diff --git a/.env.example b/.env.example index 5bc02df9c..e16e85a27 100644 --- a/.env.example +++ b/.env.example @@ -129,18 +129,27 @@ AISSTREAM_API_KEY= # 0 disables the silence watch entirely. # AISSTREAM_SILENCE_TIMEOUT_MS=120000 -# Optional: TomTom live traffic flow (BYOK freemium — free tier is ~50,000 tile -# requests/day, get a key at https://developer.tomtom.com). SERVER-SIDE ONLY: +# Optional: local ADS-B decoder feeds for the Local ADS-B layer. SERVER-SIDE +# ONLY. Comma-separated band=url entries; band is 1090 or 978 (UAT). Each host +# must be loopback, a private (RFC1918) address, localhost or a *.local name; +# the path must end in aircraft.json. Invalid entries are logged and skipped. +# See docs/LOCAL-RECEIVERS.md. +# LOCAL_RECEIVER_FEEDS=1090=http://localhost:8080/data/aircraft.json,978=http://localhost:8978/data/aircraft.json + +# Optional: TomTom live traffic flow (BYOK freemium — the free tier is 200,000 +# Traffic Flow & Incidents tile requests per MONTH, not per day; no credit card +# required. Get a key at https://developer.tomtom.com). SERVER-SIDE ONLY: # the browser fetches same-origin /api/tomtom/* and never sees the key. # Keyless fallback: the traffic layer runs its built-in simulation (white dots, # hardcoded per-road-class speeds) — no key required for the layer to work. # TOMTOM_API_KEY= -# Optional soft cap on upstream tile fetches per UTC day (default 40000) — a +# Optional soft cap on upstream tile fetches per UTC day (default 6000) — a # configurable application safety ceiling, not a guarantee of staying within # TomTom's free allowance (currently 200K tile requests/month: -# https://docs.tomtom.com/pricing/). Over the cap the proxy serves cached/stale -# tiles instead of hitting upstream. -# TOMTOM_DAILY_TILE_BUDGET=40000 +# https://docs.tomtom.com/pricing/). 6000/day keeps a 31-day month at 186K, +# inside that allowance. Over the cap the proxy serves cached/stale tiles +# instead of hitting upstream. +# TOMTOM_DAILY_TILE_BUDGET=6000 # Optional: CCTV layer tuning (advanced). Defaults are sensible — leave unset # unless you're customizing the camera source pack. diff --git a/.gitignore b/.gitignore index 491a82c15..1a64fff39 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,13 @@ node_modules dist +# Credential files. `.env` alone is not enough: Vite's loadEnv (see +# server/standalone/vite.config.js) and scripts/setup-doctor.mjs both read the +# full dotenv ladder — .env, .env.local, .env. and .env..local — +# so a key placed in any of them is live for the app. Only .env was ignored, +# leaving the other three committable. .env.example is the tracked template. .env +.env.* +!.env.example *.log screenshots/ qa-shots/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 890bad535..183c5219c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,325 @@ # Changelog +- Release CCTV media streams whose upstream falls silent after answering. The + 15-second media deadline covered only the wait for response headers, so a + camera that replied and then stopped sending held both the proxy connection + and its upstream socket open for as long as the camera host allowed; the + declared `Content-Length` ceiling was the only body bound, and a chunked or + length-less body had none. A 30-second idle deadline now bounds the gap + between upstream chunks and releases a body that has gone silent. It is + rescheduled while the response is still waiting to drain, so a viewer on a + slow link is not mistaken for a dead camera; live feeds are unaffected + (Ethan Stoner, #688). + +- Aircraft track backfill (`/api/opensky-track`, `/api/adsblol/trace`) now + answers 502 when the upstream body exceeds the 5 MB cap, instead of a 200 + whose error body the client read as an empty track. The failure is cached + like other upstream errors, so retries inside the 60 s window do not spend + OpenSky credits (Raushankumar0720, #720, #722). + +- Saving a key from Provider Settings works again on Macs where Nix or + Homebrew coreutils sit ahead of `/bin` on `PATH`. The credential hardener + now spawns Apple's `/bin/chmod -N` by absolute path; GNU `chmod` has no `-N`, + so the ACL strip failed closed and every save was refused (Arthur Bogaart, #694). + +- Render on iPad and iPhone instead of stopping with "An error occurred while + rendering." Cesium's per-vertex model atmosphere binds shader `out` + parameters directly to varyings, which Apple's Metal/ANGLE backend cannot + link, so the program failed and the render loop was torn down. The stage is + now kept out of the pipeline on affected devices by clearing + `scene.fog.renderable`, which leaves `fog.enabled` — and the fog density that + drives 3D Tiles refinement — untouched. Detection is a WebGL2 link probe of + the same pattern, so a future driver fix restores the effect with no code + change, with iOS/iPadOS detection as a backstop. Sky atmosphere and the + ground-atmosphere fragment path route through locals and are unaffected; + affected devices lose distance fog on 3D tiles and on the globe basemaps. + `src/app/atmosphereCompat.test.mjs` pins the probe, the platform matrix and + the `renderable`-not-`enabled` choice (KnottyDyes, #705). + +- Region scopes in voice analyst queries ("in the Gulf of Mexico", "over + the Alps") work again in the dev server: the bundled Natural Earth and + neighborhood packs are fetched as JSON in the browser + (`src/data/bundledJson.js`). When a region is not in the bundled packs, the + geocode and admin-boundary fallback answers `region-timeout` after 3 s + instead of holding the reply. + +- Transit and Directions rows repaint as soon as their data lands again: + `refreshLayerStats()` now lives on the layer lifecycle, not only on the + compatibility facade. `scripts/qa-radio.mjs` uses it instead of a private + panel method. +- On phones the title bar sits 16 px from the top so both Radio broadcast + waves stay on-screen. +- Keep Cyber right-rail panels mutually exclusive and Display, CCTV and Context + headers and frames fixed during content scrolling. Restore Radio's nested Context placement and compact + player. Add Cyber Sonar voice controls with settings and effect-state readback. + Keep keyboard-focus outlines visible inside Cyber's clipped map and cockpit + expand/collapse buttons, with a matching red hover border. + +- Add the opt-in Cyber HUD layout with coordinated map and cockpit panel + styling. Display exposes Sonar on/off, rings, range, power, opacity and sector. + Native point, billboard and label highlighting uses GPU draw commands; there + is no scene-dimming effect selector. Unsupported shaders retain native contact + rendering, and leaving Cyber restores the standard shell and contact treatment. + +- Add a **Recent Imagery** data layer (NASA GIBS · HLS + VIIRS, keyless). + Select a box (drag, the current view, or around a pin; up to 1,000 km a + side) and the right-rail panel lists the last 30 days of Sentinel-2 / + Landsat (30 m) and, when switched on, VIIRS daily overview imagery over it, + with thumbnails and scene cloud. Three modes: IMAGE shows one day, VS + BASEMAP swipes it against the map, A / B swipes two days; a SHOW or A / B + chip on each day card pins it, arrow keys preview the focused day while a + slot is empty, and no control moves when anything changes. While imagery is + shown on Google 3D the map switches to Esri and comes back when it is + cleared. Either image exports as a PNG; box, pins, mode and split travel in + share links; the NASA acknowledgement is in the credits and + `DATA_SOURCES.md`. The swipe is now shared with the Nepal scene + (`src/ui/imagerySplit.js`, `src/maps/imageryComparison.js`), and + `MapSourceController.subscribe()` reports every settled map switch. + +## Unreleased — local receiver feeds + +- The Local ADS-B layer also reads local 1090 MHz and 978 MHz UAT decoder + feeds: the `aircraft.json` that dump1090-fa, readsb, tar1090 or skyaware978 + serves. Configure them server-side with `LOCAL_RECEIVER_FEEDS` + (`band=url`, comma-separated); there is no feed editing in the browser. + Hosts must be loopback, RFC1918, `localhost` or `*.local`, the scheme http or + https and the path must end in `aircraft.json`; any other entry is logged at + startup, reported `invalid` and never fetched. +- Add `GET /api/local-receivers/aircraft`. It reads every configured feed in + parallel (2 s timeout, redirects refused, 2 MB body cap, about 1 s of shared + cache) and reports each feed `live`, `stale` (its own `now` is over 10 s old), + `unreachable` or `invalid`. Unconfigured, it answers + `{ configured: false }` and fetches nothing. Upstream error text is never + returned. +- The layer merges browser-SDR and feed aircraft by ICAO, keeping the newest + position, polls the route every second only while it is enabled, and remembers + which bands and sources heard each aircraft in the last 60 s. The click card + names them (for example "Heard by your receiver · 978 MHz UAT · decoder + feed"); aircraft heard only on 978 MHz carry a thin ring. The row status + covers both inputs ("2 feeds live · 14 heard", "feed 978 unreachable"), and + the Local RTL-SDR card shows a read-only decoder-feed line. +- While any input is producing aircraft (the browser receiver streaming, or a + feed live), the Local ADS-B row stays ON and lists feeds that are not live as + a trailing note ("3 heard · USB 5.8 msg/s · feed 1090 stale") instead of + showing DEGRADED. +- Records carry `band` (`1090`/`978`) and `source` (`webusb`/`feed`). +- See `docs/LOCAL-RECEIVERS.md`. + +## Unreleased — local RTL-SDR and Local ADS-B + +- Add a Local RTL-SDR card to the Radio panel. It connects a USB RTL-SDR in + desktop Chrome or Edge through WebUSB and receives broadcast FM (tune, seek, + volume) or 1090 MHz ADS-B. Local FM and internet-radio playback never play + together: starting one stops the other. +- Add a gain control: AUTO or a manual R820T step, remembered per mode. ADS-B + defaults to 28.0 dB (the earlier 20.7 dB gave about 1 msg/s against about 9 + at 28.0 dB on the same antenna; a stored choice still wins), FM to AUTO; + changes apply without reconnecting. In + ADS-B mode the card shows CRC-valid messages per second, aircraft heard, + aircraft positioned and the IQ level. +- Prefer the ADS-B/1090 MHz channel of a dual-channel receiver, remember an + explicitly chosen device per mode, and add CHANGE DEVICE to reopen the + WebUSB picker. +- Add the Local ADS-B layer (`local-adsb`, off by default, not part of share + links). Aircraft heard by the receiver draw in magenta beside public Flights; + a marker drops when its position is 60 s old and the aircraft is forgotten + after 60 s without a message. Clicking one opens a card; markers are not + camera-followed. Voice `set_layer_visibility` accepts `local-adsb`. +- Normalize local ADS-B into one record shape, with a pure adapter for + dump1090/readsb `aircraft.json` documents. +- Add `@jtarrio/webrtlsdr` and `@jtarrio/signals` (Apache-2.0); see + `THIRD_PARTY_NOTICES.md`. + +## Unreleased — weather review + +- On 3D Tiles, draw a 4096×2048 detail window around the view on each + observed-weather shell except global infrared, sampled by the shell's own + surface. It follows the view on camera move end, keeps its place while the + view stays near its centre, and hides until its image is ready after a move; + an older frame's detail stays over at most one newer frame. The image proxy + accepts a 2:1 `bbox` inside the product bounds, rounded to 0.25°. + Lightning's whole-extent image is now 4096×2048; each shell caches up to + 128 MiB of decoded images. + +- On 3D Tiles, show observed weather and the wind color field as raised, + translucent shells (5.0–6.6 km, lightning highest) with one full-extent image + per frame instead of draping onto tiles; they show at any camera height. + Globe hosts are unchanged. The weather image proxy serves every product + (radar and regional infrared up to 4096×2048, lightning and global infrared + up to 2048×1024) with a size parameter and a 16 MiB cap. Accept bounded tile + sizes in the proxy with separate immutable cache entries. + +- Cache exact-time weather images and tiles for 24 hours. Retain up to 6 decoded + global mosaics per renderer and warm the next observation during playback; + tile prefetch is bounded to eight requests and cancels when suspended. + +- Move weather times, coverage, legends and cyclone advisory details into keyed + right-rail cards; left rows keep status and configuration. Use one native + observed-history timeline with local preview and coalesced drag commits. +- Add reusable rail card and timeline components. Keep panel collapse, count, + hidden-empty behavior and first-appearance expansion. +- Show wind unit controls beside speed legends and inside inspection readings; + changing units preserves the sampled location and open reading. +- Name satellite imagery Satellite clouds, with Clouds only / Full image modes + and explicit regional coverage. Existing share parameters are unchanged. + +- Share one observed history clock across radar, infrared and lightning. Step + through their union timeline with bounded nearest-at-or-before selection; + hide products without an eligible frame. Latest uses each product's newest + observation; playback waits for all frame loads to settle before advancing. +- Label wind as a forecast that does not follow observed history. Keep history + transient and product readouts synchronized. + +- Keep Google 3D Tiles drawing while draped weather imagery loads and retain the + old observation until the replacement has rendered. +- Decode one bounded global infrared mosaic per frame on both map hosts, then + crop local tiles to avoid request-dependent brightness seams. +- Add Clouds only / Full image controls and share-link state. Filtered mode uses + a soft linear-brightness alpha ramp from 0.40 to 0.70 around the old 0.55 cut. + +- Dock the weather summary in the right rail with standard panel collapse and drag chrome. + +- Filter infrared brightness so cold cloud tops stand out; this is a display + filter, not a cloud mask. +- Retry throttled weather tiles up to three times per tile. + +- Cull regional wind batches per frame, fade curves below 60 km, and stop idle + rendering when no curve is visible. +- Fade the wind color field below ~1,200 km camera height and hide it at 200 km. + On 3D Tiles, update alpha in 0.1 steps only at camera move end or installation; + globe imagery keeps its smooth per-frame fade. + +- Hide cyclone markers, labels, tracks and cones beyond the horizon on every map source. +- Reserve stable weather status space and coalesce panel refreshes per frame. + +- Add keyless NOAA/NHC cyclone advisory positions, coherent forecast tracks and + uncertainty cones, plus NOAA's observed 15-minute lightning density imagery. + Preserve source clocks, basin coverage and explicit pending/stale states. +- Make wind default to trails, preserve earlier share-link appearance, retain + geometry across scalar changes, and show a compact weather summary with a + location marker and selected-field emphasis for forecast inspection. + +- Add keyless NOAA observed rain radar and infrared satellite layers to Weather, + with explicit coverage/freshness, recent observation playback and native Cesium tiles. +- Increase desktop wind density to 7,200 paths and improve temperature contrast + while retaining the 1,200-path narrow-screen budget and unchanged forecast values. + +- Expand Wind into a surface-weather prototype: globe-draped speed shading, + optional same-run 2 m temperature and mean sea-level pressure, GFS/ECMWF model + selection, a numeric legend, wind units, Pause, and a dismissible map-center + reading. Keep wind visible when an optional field is unavailable; respect + reduced motion and stop animation while hidden or disabled. Bake bounded + forecast-following curves once per field and animate their phase on the GPU, + with a canvas fallback and globe view lighting owned only while Wind is enabled. + Display lift does not + change the 10 m forecast level; this adds no cloud volume, radar or forecast-time + playback. Native hardware GPU behavior remains unverified. + +Add feed provenance to analyst/view answers and HUD context while retaining existing response fields and runner ownership (Matt Van Horn, #347). + +Analyst records for loaded satellites, datacenters and dams, with explicit bounded count/rank coverage (Matt Van Horn, #351). +- 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 + keyless feature service with truncation paging. Clicking a perimeter shows + an incident card (acreage, containment, cause, behavior, personnel, county, + cost, complex membership) and, when the incident has a state- and + recency-verified InciWeb page, a click-through link to it. Recency uses + incident page origin and update times because the publication API was retired. + The layer is reachable from the panel, voice control, share links (token `2`), and the + analyst query engine. WFIGS and InciWeb requests use a capped, cached + same-origin proxy with timeouts and a per-client limit. Unchanged refreshes + retain geometry; incident-link checks abort on disable or selection change, + and the row includes a containment legend. + +- Remove the spurious scrollbars that appeared on both panel stacks at narrow + widths (720px and below) as soon as a panel was expanded. The stacks scroll + vertically there, and each panel's decorative glow, absolutely positioned + with a negative inset, became 18–20px of scrollable overflow on both axes: a + horizontal scrollbar band under the expanded CCTV, Context, Data Layers or + Scenes panel plus a vertical scrollbar that scrolled nothing but glow. The + narrow-screen rules now pin the glow to its panel box; the stacks still + scroll for genuinely tall content such as an expanded DISPLAY panel, and the + Context radio popover is not clipped. `src/ui/panelRails.test.mjs` pins the + rule against every 720px media block. + +- Enable responsive trackpad pinch zoom on the globe. Browser pixel-mode + `Ctrl+wheel` pinch gestures now reach Cesium with bounded amplification, + while ordinary wheel, line-mode and touch-pinch inputs retain their existing + behavior; the listener is removed with the application scene. + +- Report AIS speed and course that carry the standard "not available" code as + unknown instead of 102.3 knots and 360 degrees. Genuine readings, including a + stopped vessel's zero and the highest encodable values, are unchanged. + +- Render native `` controls declare a dark colour scheme and explicit option +colours, so the browser-painted option list matches the panel it drops out of. +The scheme is declared on the controls rather than on the document root, so +hand-tuned scrollbar and text-input skins are unchanged. Applies to the HUD +layout, Scenes, CCTV camera, Radio filter and Draw colour menus. + +Vessel snapshot completeness is separate from freshness. A current snapshot with +rejected or duplicate records shows PARTIAL with accepted/received counts; stale +or unknown freshness and transport failures retain their warnings. Partial +snapshots still retain missing contacts within the existing age and row limits. +A complete successful snapshot clears the partial indicator. + +Director imports now open a non-mutating preview before Apply. EDIT DETAILS +authors validated anchor, camera, pack and interaction drafts; SHARE SCENE exports +a selected scene or a bounded bundle of explicitly chosen pack files. Bundled +bytes remain in memory until replacement/teardown and require reimport after a +page reload. Stop releases rendering while retaining replay bytes. Cancellation +and stale drafts cannot replace newer project state. See [authoring and sharing](DIRECTOR-SHARING.md). + +Director version-6 documents add bounded, scene-local feature actions. Settled +LOAD/seek exposes keyboard-accessible text/source cards, anchor focus, explicit +shot transitions and admitted layer state changes. Pointer claims take priority; +Stop/replacement/teardown cancel pending actions and release handlers and UI. +Same-shot seeks rebuild selected packs and restore declared layer baselines. +See [scene actions](DIRECTOR-INTERACTIONS.md). Existing scenes/assets and credit remain. + +Director version-5 documents add scene-local data-pack manifests and per-shot +selection. Registered sources acquire bounded, cancellable assets separately from +GeoJSON, PNG and manually played media presentation. Storage paths, attribution +and geographic placement remain distinct; Stop/replacement releases resources. +Import acquires nothing. See [data packs](DIRECTOR-DATA-PACKS.md). Existing scene +content, assets and credit remain unchanged. + +Director version-4 documents add named geographic anchors and optional explicit +camera moves with easing, duration and holds. Playback and seek share one +coordinate sampler; navigation/manual input revokes authored motion and pending +holds. Anchor heights and explicit endpoints require the WGS84 ellipsoid +reference. Legacy projects retain their ordinary flights, content and edits. +See [camera directions](DIRECTOR-CAMERA.md). + +Realtime voice composes separate connection, response/tool, Radio handoff, input +and audio-meter, cost, viewport-context and diagnostic owners. The existing +controller exports and session/backend contracts remain available. Tool protocol, +response wording, push-to-talk timing, model preferences and Radio confirmation +order are preserved. Stopped connections, stale offers and delayed captures cannot affect a +replacement session; audio meters release failed initialization and reject revoked +frames. Delayed action results and post-capture continuations cannot resume a +stopped conversation or send output into a replacement. See [voice ownership](VOICE-OWNERSHIP.md). + +The application shell composes focused state owners for navigation, destination +lookup/orbit, Cockpit, visual settings, panel layout, aircraft display and layer +bindings. Keyboard/display subscriptions have a separate lifetime; existing +layer, scene and voice methods remain available through a delegation facade. +Disposal settles pending globe resets and removes camera-entry listeners before +asynchronous restoration; replacing a manager detaches its old Directions +services. See [UI ownership](UI-OWNERSHIP.md). + +Director's ordered shot runner is exported independently of rendering, UI, +storage and scene content. The existing scene controller supplies an adapter for +visual/layer state, camera travel, media holds and release. Playback cancellation, +preview cleanup, saved projects and all scene assets/attribution are preserved. +Pure authored-time/seek calculations and a playback clock now own timing, +hold deadlines and subscriptions. Stop immediately clears timers and settles +holds; stale tick callbacks cannot publish into a replacement. Registered pack +rules own presentation overrides and Nepal map fallback without changing saved +shots or content. Scene-document validation and legacy migration now have separate +owners. Invalid imports preserve the current project; unreadable saved projects +are protected from fallback writes. Version 6 is the export format, with +zero pitch, low camera heights, scope and detection edits preserved. See [the document contract](SCENE-DOCUMENT.md); +see [Director](DIRECTOR.md) for camera, pack, action and sharing support. + Search framing and annotations request semantic map features from an explicit source. The Overpass adapter owns bounded queries, member/tag decoding and request deadlines; callers retain candidate ranking, outline caching, deferred retries and scene placement. Empty, transient and throttled outcomes remain distinct. Traffic sources return road records and installation sources return mapped records with freshness/saturation metadata, so their layers no longer decode upstream elements. ALPR already normalizes its records in the source. Default providers, footprints, road directions, exact-viewport retries and source attribution are unchanged. Nepal media preloads survive repeated camera-flight updates, but Stop, event disable and replacement remove abandoned frames and revoke pending Facebook sessions. Fallback evidence-card clicks respect the shared drawing-tool pointer lease. +In the Pinokio browser shell, Nepal provider embeds and hidden preloads are +disabled before creating frames or loading provider SDKs, because the shell can +redirect iframe navigation to an external browser. Existing source-linked cards +remain available, and Open Original is an explicit action. Optional approved +local clips still use the existing fallback; the public pack bundles no witness +clips. Chrome and Safari retain embeds even when visiting a Pinokio-launched +server. This compatibility fallback does not repair Pinokio's navigation handler. + Nepal flood lines classify the active terrain or photoreal surface, and the surge marker follows that surface. Geographic route coordinates are unchanged; dynamic lines do not rely on unsupported depth-failure materials. Later media-only shots keep their completed source-path history throughout arrival and card reveal. Scene Stop, replacement, seek, and teardown revoke the Upper Valley locator's delayed camera approach and orbit while preserving its visible callout. A revoked timer or camera callback cannot start another flight or interfere with a newer shot. @@ -20,7 +331,7 @@ The Nepal overview route and lake-shot trail share the river-centerline starting The event panel omits the WITNESS shortcut. Shot media, source attribution, Open Original links and corridor navigation remain available. -The Mailung Bazzar, Dandaguan YouTube embed follows the provider's playback clock through 0:07, then the scene advances after its 0.65-second media exit. The controller reconciles provider state and source time when the API attaches and while waiting for playback, including missed PLAYING notifications and an already-ended clip. Startup is bounded to five seconds, and stalled playback has a bounded timeout; unavailable or blocked media cannot strand the scene. The authored estimate remains seven seconds plus the exit, replacing older saved holds at runtime without rewriting them. Stop, replacement and teardown revoke pending playback callbacks. +The Mailung Bazzar, Dandaguan YouTube embed follows the provider's playback clock through 0:07, then the scene advances after its 0.65-second media exit. The controller reconciles provider state and source time when the API attaches and while waiting for playback, including missed PLAYING notifications and an already-ended clip. Startup is bounded to five seconds, and stalled playback has a bounded timeout; unavailable or blocked media cannot strand the scene. When the host deliberately suppresses provider playback and there is no approved local clip, the source card instead uses the authored 7.65-second dwell before the next shot. The authored estimate replaces older saved holds at runtime without rewriting them. Autoplay requires transient Director ownership from Play Scene or Play Shot; LOAD, restoration and seek remain passive. Stop, replacement and teardown revoke that ownership and pending playback callbacks. Persistent media-led Nepal shots preserve their completed upstream flood path during camera travel. The next reach still reveals after arrival; direct loads reconstruct the prefix and backward replay trims downstream history. @@ -38,7 +349,7 @@ Source factories have dedicated `layers//source` exports. ALPR and earth Voice controls bind to a protocol-independent session factory. The default WebRTC adapter preserves the existing Realtime connection, push-to-talk, cost controls and radio handoff. Session subscriptions expose state, transcript, action call/result, interruption and completion events; stopping or replacing a session cancels pending actions. Alternate adapters can use the same controls and action runner. -Voice action argument schemas have one portable owner under `src/voice/actionSchemas.js`. The Realtime provider builds the same 28 tools using separate description-only metadata. Description customization cannot replace argument types, enum values or required fields. +Voice action argument schemas have one portable owner under `src/voice/actionSchemas.js`. The Realtime provider builds 29 tools, retaining the existing 28 names and argument contracts apart from the three additive analyst-layer enum values using separate description-only metadata. Description customization cannot replace argument types, enum values or required fields. Portable source exports provide Radio Browser station normalization, CCTV feed types and regional records independently of HTTP middleware. Radio normalization accepts an explicit URL policy; the standalone directory retains its existing HTTPS rules. Tile coordinate validation accepts explicit zoom bounds with unchanged traffic defaults. Cache, request and rendering owners remain unchanged. @@ -67,7 +378,6 @@ owns disclosure, docking and Cockpit panel snapshots. Each takes explicit operations and reads instead of the complete shell. Existing controls, share formats and one-application-per-page behavior are preserved. - Layer lifecycle transactions are owned by `data/lifecycle`, which has no panel, render-governor or detection imports. Application composition mounts a separate layer presentation owner that reacts to status, accepted visibility/parameter @@ -76,7 +386,6 @@ rendered detection set. The legacy manager retains panel helper compatibility; registration sealing, restoration order and failed-transition rollback remain unchanged. - Application scene setup owns request services, terrain/floor caches and annotation lookup state. Controls, layers and voice share those owners, and cancellation clears caches and removes map-stack listeners. Standalone setup supplies the @@ -85,7 +394,6 @@ framing and annotation boundaries receive their service instances explicitly. Compatibility entrypoints retain defaults for direct callers; normal startup does not change global service slots. Analyst follow-up memory belongs to its voice runner. - Application startup constructs fresh layer instances from explicit source objects. Standalone composition selects the existing providers. Controls, launch orbit lookups, Contacts voice answers and ISS pass queries use the registered catalog. @@ -93,7 +401,6 @@ Aircraft classification is catalog-owned and cancelled with application teardown scene engines still support one application per page. Compatibility data entrypoints remain for direct callers, but normal startup does not configure global sources. - Application data setup receives an ordered layer catalog and serialization metadata. Controls use the same instances. The standalone composition selects the existing default catalog, and restoration starts only after all registrations are sealed. @@ -112,7 +419,6 @@ transports and cancellation through response parsing. Stop and application teardown abort pending connections; reconnect requests a new client secret. Microphone, radio handoff, tool schemas and default model behavior are preserved. - Geospatial lookups are composed through `src/search`: forward/reverse geocoding, text/nearby search and routing use configurable providers/endpoints. Annotation, HUD and voice consumers share the configured service. Existing Google/Photon @@ -120,7 +426,6 @@ selection, route/direct-line honesty and tool schemas are preserved. Node Google, OSRM and Nominatim adapters accept trusted construction-time configuration; request parameters cannot choose arbitrary upstream URLs. See APPLICATION.md. - The optional **ALPR Cameras** layer shows community-mapped OpenStreetMap locations, not camera footage or plate records. City-scale queries use the existing Overpass provider, with capped results, retry, cached-data and incomplete-coverage notices. @@ -224,7 +529,6 @@ Selection changes, disable and destruction cancel pending trail requests; late responses cannot refill a cleared or replacement trail. Heading and course, sea-surface placement, click ownership and card selection policy are unchanged. - ## Military-flight components and aircraft mechanics `gods-eye-view/layers/military` exports `createMilitaryFlightLayer`. It uses the @@ -281,7 +585,6 @@ messages; arbitrary HTTP response bodies are not surfaced as diagnostics. Sources receive cancellation signals and check them after body parsing. The layer's existing lifecycle and selection guards continue to reject late work. - ## State and action outcomes Share preferences, place lookups and Scene playback expose immutable snapshots @@ -330,7 +633,6 @@ retained Cockpit actions cannot restart a disposed controller. Input, subscripti and queued panel work stop before asynchronous layer restoration; final camera and portal cleanup follows that restoration. - ## Context coordination Context controls own Contacts/Space Missions state, entry and exit transactions, @@ -340,7 +642,6 @@ presentation work stop during disposal; layer restoration retains its existing compensation and latest-intent rules. Clear Selected Layers shares this owner, so an older restore cannot replay over a newer Clear action. - ## Camera panel ownership CCTV controls receive the existing camera port and explicit application actions. @@ -351,7 +652,6 @@ calibration edit. Failed refreshes preserve settled pixels for the same camera, while a newly selected camera never shows the prior camera's image. Disposal releases listeners, subscriptions, image handlers, summary timers and chip-hide timers. - ## UI disposal UI disposal releases the CCTV subscription, command-dock observer, legacy drag @@ -393,7 +693,6 @@ and result presentation. Existing search providers and camera handoff policy are preserved. Replacing or closing a POI row cancels its pending expansion frame; destruction releases listeners, pending searches and the orbit indicator. - ## Layer panel ownership Layer rows, feed feedback, counts, focus-preserving chips and toggle listeners @@ -402,6 +701,24 @@ snapshots, lifecycle actions and row descriptors. Remount and teardown remove listeners and row subscriptions; obsolete completions do not repaint old rows. The clear control presents busy state while its existing action owns the transaction. +## Model atmosphere on Apple Metal + +Cesium's per-vertex model atmosphere is kept out of the pipeline on devices +whose driver cannot link it. `AtmosphereStageVS` binds shader `out` parameters +directly to varyings, which ANGLE's Metal backend rejects at link time, tearing +down the render loop on iPadOS and iOS. `ModelSceneGraph.configurePipeline` +attaches that stage only when `fog.enabled && fog.renderable`, so the viewer +clears `scene.fog.renderable` and leaves `fog.enabled` — and the fog density +that drives 3D Tiles screen-space-error scaling — intact. Sky atmosphere and the +ground-atmosphere fragment path route through locals and are unaffected. +Affected devices lose distance fog on 3D tiles and on globe basemaps (Esri, +Bing, keyless), since the globe fog shader uses the same `renderable` flag. +The probe releases its throwaway WebGL2 context immediately. + +Detection is a WebGL2 link probe of the same out-parameter/varying pattern, so a +future driver fix restores the effect with no code change; iOS/iPadOS platform +detection is the backstop for when no probe context can be created. Applied +during viewer construction, before any tile builds a draw command. ## Map Source control ownership @@ -454,7 +771,6 @@ panel, and honors keyboard focus on the right. Mobile layout still releases desktop allocation styles. Stable Display allocation avoids unnecessary style writes. This extraction does not change panel positions or layout defaults. - ## Surface keyboard lifecycle `ui/surfaces` owns the capture-phase keyboard listener, Tab cycling and return @@ -466,7 +782,6 @@ preferences. Provider Settings retains its existing visibility and save policy. Initial focus, transitions and DOM content remain with each screen. This component does not add modal semantics or make the map inert. - ## Panel disclosure lifecycle Panel collapse buttons, nested Escape handling and dock hover/focus timing now @@ -476,7 +791,6 @@ Location draft cleanup and Map Source selection remain with their existing callers. Listener and timer cleanup is synchronous when controls are replaced or disposed, preventing old hover or focus work from changing a later view. - ## Military feed cooldown and loading guidance The adsb.lol military proxy reuses its last response during upstream 429/5xx @@ -490,7 +804,6 @@ Mapped-installation zoom guidance appears in the layer row without counting as a global loading failure. Guidance statuses do not suppress independent refresh errors. - ## Places and CCTV request bounds With a Google key configured, nearby and text search reject missing, blank, @@ -500,21 +813,20 @@ their `configured: false` response. CCTV media waits at most 15 seconds for upstream response headers and returns 504 on timeout. Its timer stops when headers arrive, so live bodies can continue -streaming; body idle deadlines are separate from this header deadline. Error -responses are cancelled. Buffered snapshots have a 16 MiB streaming cap; an -oversized image remains an upstream miss and uses the normal fallback chain. -The existing declared media size ceiling remains 64 MiB. - +streaming; a separate 30-second idle deadline then bounds the gap between +upstream chunks and releases a body that has gone silent. A response that is +still waiting to drain reschedules that deadline, so a slow client does not read +as a stalled upstream. Error responses are cancelled. Buffered snapshots have a +16 MiB streaming cap; an oversized image remains an upstream miss and uses the +normal fallback chain. The existing declared media size ceiling remains 64 MiB. ## GBFS upstream bounds The station reader addresses the proxy as `/api/gbfs/`; the -feed address is read from the path, and a query-string form is refused with a -400. GBFS refuses upstream redirects and enforces its 5 MiB response cap while +feed address is read from the path, and a query-string form is refused with a 400. GBFS refuses upstream redirects and enforces its 5 MiB response cap while streaming. The 12-second deadline includes reading the body, and rejected or stalled downloads are cancelled. Development and preview use the same handler. - ## Remaining local service modules Overpass query validation, geometry simplification, disk caching and upstream @@ -547,7 +859,6 @@ preview returns JSON 404 for those endpoints. Server credentials come from the local environment; browser keys are captured at build time. Rebuild after changing a browser key. Preview is for local build verification, not a production server. - ## CCTV and radio provider modules CCTV catalog acquisition, source normalization and frame/media delivery now live @@ -657,7 +968,6 @@ supported. `.env.example` and `pinokio/_ENVIRONMENT` document both entries. The Street View headings tool uses the same server-first selection after resolving environment overrides per variable; its explicit `--key` wins. - ## Infrastructure marker visibility Datacenter/dam registration uses fresh reusable factories with the application's @@ -777,7 +1087,7 @@ Non-object or array-valued properties reject the response instead of being treat Launch payloads with missing records now say PAYLOAD DATA UNAVAILABLE. Missing names use Unnamed payload; absent or invalid mass stays unknown instead of appearing as 0 KG. -Updated: September 15, 2026 +Updated: September 23, 2026 ## Aircraft and vessel server modules @@ -795,7 +1105,6 @@ The existing aircraft normalizer is separately available through the portable `gods-eye-view/sources/adsb-lol` export. Provider URLs, local credentials, cache policy, fallback behavior, response shapes and rendering remain unchanged. - ## Control names for assistive technology Scope, Bloom, Sharpen and location search have explicit accessible names. @@ -890,7 +1199,7 @@ fetching, trailing-24-hour filtering and partial-success caching are unchanged. > durable in this app (`gev:layer-state:v2`, written by > `LayerStateCoordinator._commitExplicit` only for origin `user`/`voice`/`tool`). > A mission enables **its own** layers at `origin: 'user'` — durable, exactly as -> clicking those rows is, because picking the mission *is* that choice. The two +> clicking those rows is, because picking the mission _is_ that choice. The two > Context missions also expand the Context panel, as the visible tabs do; the > globe missions open no panel. Everything else is off limits: detection > mode/density, `gev:detection-allocation:v1`, 3D models, feather, and above all @@ -914,7 +1223,7 @@ fetching, trailing-24-hour filtering and partial-success caching are unchanged. > rule by a unit pin), and session-dismisses rather than contesting the key; if > one is already up at init it **waits** instead of appearing over it. (2) A > surface can take the screen with **no class to watch** — the Cesium attribution -> lightbox is full-screen at `z-index: 200` against the card's `175`, which left +> lightbox is at `z-index: 200` against the card's `175`, which left > the launcher measurable (`getClientRects()` non-empty) and buried, so ESC > dismissed a card nobody could see and burned the session flag. `isTopmost()` > therefore also **hit-tests the card's own centre** with `elementFromPoint`; any @@ -925,7 +1234,7 @@ fetching, trailing-24-hour filtering and partial-success caching are unchanged. > `stopImmediatePropagation()`, and the launcher skips `defaultPrevented` events. > `stopPropagation()` alone does **not** stop later listeners on the same > `document` — that is exactly how the compact Radio disclosure made one key -> close the disclosure *and* dismiss the launcher. +> close the disclosure _and_ dismiss the launcher. > > **Accepted:** a surface class that never clears means no launcher for that page > load, with no timeout. None of the four classes is restored at startup, so an @@ -981,6 +1290,7 @@ This is the current runtime/source-of-truth snapshot for the project. > [!IMPORTANT] > **Delta since the July-2 body below** (the detailed sections are still accurate > for everything they describe; these landed after): +> > - **"Never answered yet" is a THIRD state, distinct from empty (2026-08-23):** > `sourceState` in `src/data/militaryAwareness.js` treats a dependency that is > busy AND has never produced an answer (`loading === true && !lastUpdate`) as @@ -1003,7 +1313,6 @@ This is the current runtime/source-of-truth snapshot for the project. > samples, `enabling` throughout, panel non-numeric) and across a failing > one. Its `status: 'idle'` is not what saves it — the lifecycle is; the > module has no `loading` status at all. -> > Any new dependency that can be slow must report `loading` and `lastUpdate` > honestly for the contract to hold, and must be pinned against the shape its > own module really returns — a fixture that invents a status the module cannot @@ -1208,7 +1517,7 @@ This is the current runtime/source-of-truth snapshot for the project. > 1,000,000,000 m, plus finite components — not a null check, because a depth > read over empty sky can return a Cartesian that Cesium mishandles three > different ways: non-finite throws `DeveloperError: normalized result is not -> a number`, exactly `(0,0,0)` returns undefined, and a near-center value such +a number`, exactly `(0,0,0)` returns undefined, and a near-center value such > as `(500,0,0)` converts SILENTLY into a point 6,378 km underground that > reverse-geocodes as 0°, 0°. The floor sits ~346 km below the smallest real > surface magnitude (WGS84 polar radius 6,356,752 m); the ceiling is ~24× @@ -1266,17 +1575,17 @@ This is the current runtime/source-of-truth snapshot for the project. > supersession, and run teardown abort it — the data manager rolls an aborted > enable back through the module's own `disable()`, so no layer is left on > carrying stale params. Visuals: `styleManager.applyVisualState(state, { -> isCurrent })` gates BOTH halves of the map-stack switch, which is its only -> suspension point. The switch is a *mutation*, not just a wait, and +isCurrent })` gates BOTH halves of the map-stack switch, which is its only +> suspension point. The switch is a _mutation_, not just a wait, and > `mapStackController` invalidates a switch only when another `setStack()` > arrives — a winning state that omits `mapStack` (every normalized shot does) > never issues one, so a stale switch would otherwise stand on the globe. > So: an already-superseded caller never starts the switch, and one superseded -> *during* it puts the globe back to the stack the winner inherited — but only +> _during_ it puts the globe back to the stack the winner inherited — but only > while `getSwitchGeneration()` shows no newer switch has claimed it, because > a newer switch is a live intent that must not be stomped. The shader-uniform > commit after the await keeps its own gate. Precisely: a stale LOAD's -> *synchronous* prelude (style/bloom/HUD) can still have landed before it was +> _synchronous_ prelude (style/bloom/HUD) can still have landed before it was > superseded, and is then overwritten by the newer state; what cannot survive > is its map stack, its uniform commit, its layers, or its camera flight. > Post-`await` flag checks remain as a backstop. Known remainder: run cleanup @@ -1396,7 +1705,7 @@ This is the current runtime/source-of-truth snapshot for the project. > - **AIS feed watchdog (2026-08-18):** feed liveness is judged by DATA, not > socket state — AISStream can complete the handshake and then deliver > nothing forever. `/api/ais-live` reports `live | stale | reconnecting | -> down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with +down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with > `silentForMs`, `reconnectAttempt` and `nextAttemptAt`. Silence is REPORTED > at 120s and ACTED ON at 300s; recovery walks a 5s/15s/60s/300s ladder and > then stops at a terminal `down` with a slow 15-min retry running behind it @@ -1726,7 +2035,7 @@ This is the current runtime/source-of-truth snapshot for the project. > - **Compact data-attribution panel:** the complete Cesium credit inventory > remains available without taking over the viewport. Its expanded desktop > panel is capped at 70dvh/36rem, the wrapped 12px credit list scrolls inside -> it, and narrow screens retain Cesium's full-screen surface with an internal +> it, and narrow screens retain Cesium's surface with an internal > scroller. The title, close control, links, and persistent Google/Cesium line > remain unchanged and visible. > - **Distant-aircraft recession:** both civilian and military billboard fleets @@ -1941,8 +2250,7 @@ This is the current runtime/source-of-truth snapshot for the project. > at `z-index:5`**, not into `#world-overlay-root`: the root is a stacking > context (`z-index:6`), i.e. an isolated blending group, and a surface inside > it has its `mix-blend-mode: screen` silently discarded by the browser -> instead of compositing against the WebGL scene. z-index (5 under the root's -> 6) keeps it beneath ambient-through-tracked host paint. +> instead of compositing against the WebGL scene. z-index (5 under the root's 6) keeps it beneath ambient-through-tracked host paint. > The >22 ms odd-frame relief valve is restored: the host does not clear the > detection surface on a held frame, while unrelated shared lanes repaint, > and `throttleSkipCount` remains a live diagnostic. Detection `data-*` fields @@ -2036,7 +2344,7 @@ This is the current runtime/source-of-truth snapshot for the project. > Identity stays `icao24` on every keyed surface (`getNearby().icao24`, the > detection `sourceId` declutter hashes, and the `id` that `trackById` and the > Context cohorts resolve) — only the displayed string follows the chain. -> Because adsbdb enrichment can answer *after* selection, the Context subject +> Because adsbdb enrichment can answer _after_ selection, the Context subject > re-resolves its label each refresh (`resolveSubjectLabel()`) instead of > freezing the selection-time snapshot. > - **Phase 5 tracked military aircraft label:** The military tracking entity @@ -2154,7 +2462,7 @@ This is the current runtime/source-of-truth snapshot for the project. > active camera is excluded from the 40-card ambient quota and has no host > card by default: its monitor plane is the active representation. The > product option `cctvLayer.setCardPresentationOptions({ -> activeCameraCardEnabled: true })` may publish it through the retained +activeCameraCardEnabled: true })` may publish it through the retained > protected path. CCTV leaders use the source cyan, remain vertical at the > camera anchor except for the off-card edge clamp, and counter-scale to one > CSS pixel through the altitude transform. Card hits come from @@ -2336,7 +2644,7 @@ This is the current runtime/source-of-truth snapshot for the project. > sprites/trails, OpenSky credit governor). The 2026-07-08 CHANGELOG entry > records the subsystem's architecture, invariants, residuals, and verification. > - **Height-datum test surface:** `npm test` 184 unit · `npm run -> test:track` 43 tracking invariants · headless QA harnesses under +test:track` 43 tracking invariants · headless QA harnesses under > `scripts/qa-*.mjs` incl. `qa-height-datum.mjs` (numeric heights) and > `qa-floor-verify.mjs` (any-airport ground-truth oracle). > - **2026-08-19 — display-time ground floor (flights layer).** A grounded @@ -2402,7 +2710,7 @@ This is the current runtime/source-of-truth snapshot for the project. > ISS pass prediction, and per-layer data attribution. Gate at close: unit 98/98, build clean, > track 19/19, + five QA harnesses (heading 16/16, sprites 9/9, cctv 5/5, failstate 5/5, > attribution 18/18). New modules: `src/data/{motionModel,aircraftMeta,aircraftClass,aircraftIcons,issPass,routePlausible,dataCredits}.js`. -> The live runtime now declares 28 voice tools; the 17→20 count above is retained only as milestone history. +> The live runtime now declares 29 voice tools; the 17→20 count above is retained only as milestone history. ## Canonical Docs Order @@ -2439,25 +2747,29 @@ nearby place—always use station selection. Unqualified “turn on/start the ra requests use Play; a qualified Play-shaped tool call is normalized to Select so its criteria cannot be silently ignored. -| Layer | Source | File | Proxy | Update Interval | -|-------|--------|------|-------|-----------------| -| Live Flights ✈️ | OpenSky Network; bounded adsb.lol regional fallback | `src/data/flights.js` | `/api/opensky` (OAuth + fallback) | 30s | -| Military Flights 🎖️ | adsb.lol /v2/mil | `src/data/militaryFlights.js` | `/api/adsblol/mil` | 15s | -| Live AIS Vessels 🚢 | AISStream websocket | `src/data/aisLiveVessels.js` | `/api/ais-live` | 60s (+800ms visibility pass) | -| Mapped Installations ⌖ | OpenStreetMap mapped context; on-demand Google Maps Places supplement | `src/data/militaryInstallations.js` | `/api/military-installations`, `/api/google/text-search` | viewport-driven + user search; while unavailable, auto-retry 30 s → 240 s backoff | -| Earthquakes | USGS | `src/data/earthquakes.js` | — | 60s | -| Satellites | CelesTrak | `src/data/satellites.js` | `/api/celestrak` | 120s | -| Space Missions (30d) | Launch Library 2 + CelesTrak | `src/data/rocketLaunches.js` | `/api/launches` + `/api/celestrak/active` | 5 min | -| Traffic | OSM Overpass (+ optional TomTom live flow) | `src/data/traffic.js` | `/api/overpass` + `/api/tomtom` | viewport-driven | -| CCTV | Austin + Caltrans (CA) + TfL London + Ontario 511 + Fintraffic (FI) + DriveBC (BC) + TxDOT (TX) + Estonia (Tallinn, Tarktee) + Live Traffic NSW + Open Calgary Open Data + Street View fallback | `src/data/cctv.js` | `/api/cctv` | 10s (active) | -| Radio | Radio Browser (public-domain station directory) | `src/data/radio.js` | `/api/radio/stations`, `/api/radio/click/:uuid` | 45 min directory refresh | -| Bikeshare 🚲 | GBFS (Lyft + BCycle) | `src/data/bikeshare.js` | `/api/gbfs` | 60s | -| Directions 🧭 | OSRM on FOSSGIS servers (OpenStreetMap) | `src/data/directions.js` | `/api/route` (`steps=1`) | on placement / mode change | -| Transit 🚌 | Operator GTFS-Realtime VehiclePositions (7 keyless regions, `src/data/transitFeeds.js`) | `src/layers/transit/` via `src/app/layers/transit.js` | `/api/transit` | 15s (poll + delayed playback) | -| Datacenters ▣ | OSM extract (bundled) | `src/data/localLayers.js` | — | static | -| Dams ▰ | OpenInfraMap/OSM extract (bundled) | `src/data/localLayers.js` | — | static | -| Submarine Cables ◠ | TeleGeography public map (bundled) | `src/data/telegeographySubmarineCables.js` | — | static | -| FIRMS Active Fires ▲ | NASA FIRMS live (VIIRS ×3 NRT, trailing 24h) | `src/data/firmsHeatmap.js` | `/api/firms` (`FIRMS_MAP_KEY`) | 10 min (proxy TTL 30 min) | +| Layer | Source | File | Proxy | Update Interval | +| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | -------------------------------------------------------- | --------------------------------------------------------------------------------- | +| Live Flights ✈️ | OpenSky Network; bounded adsb.lol regional fallback | `src/data/flights.js` | `/api/opensky` (OAuth + fallback) | 30s | +| Military Flights 🎖️ | adsb.lol /v2/mil | `src/data/militaryFlights.js` | `/api/adsblol/mil` | 15s | +| Live AIS Vessels 🚢 | AISStream websocket | `src/data/aisLiveVessels.js` | `/api/ais-live` | 60s (+800ms visibility pass) | +| Mapped Installations ⌖ | OpenStreetMap mapped context; on-demand Google Maps Places supplement | `src/data/militaryInstallations.js` | `/api/military-installations`, `/api/google/text-search` | viewport-driven + user search; while unavailable, auto-retry 30 s → 240 s backoff | +| Earthquakes | USGS | `src/data/earthquakes.js` | — | 60s | +| Satellites | CelesTrak | `src/data/satellites.js` | `/api/celestrak` | 120s | +| Space Missions (30d) | Launch Library 2 + CelesTrak | `src/data/rocketLaunches.js` | `/api/launches` + `/api/celestrak/active` | 5 min | +| Traffic | OSM Overpass (+ optional TomTom live flow) | `src/data/traffic.js` | `/api/overpass` + `/api/tomtom` | viewport-driven | +| CCTV | Austin + Caltrans (CA) + TfL London + Ontario 511 + Fintraffic (FI) + DriveBC (BC) + TxDOT (TX) + Estonia (Tallinn, Tarktee) + Live Traffic NSW + Open Calgary Open Data + Street View fallback | `src/data/cctv.js` | `/api/cctv` | 10s (active) | +| Radio | Radio Browser (public-domain station directory) | `src/data/radio.js` | `/api/radio/stations`, `/api/radio/click/:uuid` | 45 min directory refresh | +| Transit 🚌 | Operator GTFS-Realtime VehiclePositions (7 keyless regions, `src/data/transitFeeds.js`) | `src/layers/transit/` via `src/app/layers/transit.js` | `/api/transit` | 15s (poll + delayed playback) | +| Bikeshare 🚲 | GBFS (Lyft + BCycle) | `src/data/bikeshare.js` | `/api/gbfs` | 60s | +| Directions 🧭 | OSRM on FOSSGIS servers (OpenStreetMap) | `src/data/directions.js` | `/api/route` (`steps=1`) | on placement / mode change | +| Datacenters ▣ | OSM extract (bundled) | `src/data/localLayers.js` | — | static | +| Dams ▰ | OpenInfraMap/OSM extract (bundled) | `src/data/localLayers.js` | — | static | +| Submarine Cables ◠ | TeleGeography public map (bundled) | `src/data/telegeographySubmarineCables.js` | — | static | +| FIRMS Active Fires ▲ | NASA FIRMS live (VIIRS ×3 NRT + MODIS NRT, trailing 24h) | `src/data/firmsHeatmap.js` | `/api/firms` (`FIRMS_MAP_KEY`) | 10 min (proxy TTL 30 min) | +| Wind 🌬 | NOAA GFS 10 m wind (keyless, 0.25°→1° grid; animated particles) | `src/data/wind.js` | `/api/wind` | 1 h (forecast cycle) | +| Fire Perimeters 🔥 | NIFC WFIGS current interagency perimeters (keyless, paged past the 2000-record cap); InciWeb catalog + incident page origin and update time checks for verified incident-page links | `src/layers/perimeters/` via `src/app/layers/perimeters.js` | `/api/fire-perimeters` + `/api/fire-perimeters/inciweb/*` | 5 min (server caches: catalog 1 h; publication 30 min) | + +Fire Perimeters uses capped, timed server reads with stale-on-error caching and a per-client limit. Unchanged snapshots retain geometry; link checks cancel on disable or selection change, and the row legend shows reported containment. Directions is a keyless front end to the routing the voice agent already uses. Its row chips are the whole interface: DRIVE / WALK / BIKE pick the @@ -2513,7 +2825,7 @@ tool holds the pointer. FLY runs through the UI shell's immediate-navigation facade — the same camera authority validated voice destinations use — and is handed the shared ground-floor read and corridor warm, so the dolly does not fly a mountain corridor at sea level. A reroute (SWAP, or a profile change), -CLEAR, disable and destroy stop the flight *this layer started* and only that +CLEAR, disable and destroy stop the flight _this layer started_ and only that one: `flyRoute` returns a motion id and `interruptCameraMotionIfActive` refuses to stop a motion someone else began. @@ -2541,7 +2853,9 @@ What a card needs is a resolved ground anchor: a step whose ground cell has not answered yet opens nothing rather than a card hanging at sea level. The cells are re-read for up to 90 seconds, which outlasts a cold terrain round trip; reroute, CLEAR and disable cancel that. -Transit is off by default, and share links use token `j`. The layer polls +Transit is off by default, and share links use token `j`. The movement panel order +places Transit directly after Street Traffic and before Bike Share. Cameras and +utilities retain their own groups. The layer polls registered feeds near the camera every 15 seconds, below a 3,000 km altitude gate. Seven keyless regions are available: Boston, Austin, Minneapolis–St Paul, Helsinki, the Netherlands, Norway and South East Queensland. Mode silhouettes @@ -2566,10 +2880,19 @@ clipped to the displayed time. The browser retains up to 15 minutes and 128 fixes per vehicle, under a global 32 MiB history budget. Capacity pressure may shorten that history. Only the selected vehicle has a trail: completed segments are batched primitives, and a small moving head ends at the marker. Trail -geometry is bounded to 2,048 prepared vertices; history changes rebuild the -body, while ordinary playback updates the head and segment visibility. -Both normal and depth-fail instance colours follow the age ramp once per display -second or style change. Subdivision crossings update only changed visibility +geometry is bounded to 640 prepared vertices, prioritizing the active corridor +and shortening the oldest geometry first. Active and future marker corridors +retain their own 640-vertex budget; long report intervals use coarser subdivisions +than 25 m instead of dropping an admitted vehicle. Supported scenes use ground polylines +classified against both terrain and 3D tiles, including after map-stack changes, +with per-segment age colours. History changes rebuild the body. The head is one +short draped corridor, clipped to displayed time by a material uniform; only +subdivision crossings rebuild it. Ordinary frames upload no head geometry. +Without ground-polyline support, ordinary primitives retain a mode-coloured +0.55-alpha depth-fail path, including the head, without dimming it to near-black. +Instance attribute updates write back the same typed array returned by Cesium; +its getters return copies, so reading a second time discards a visibility or colour edit. +Normal instance colours follow the age ramp once per display second or style change. Subdivision crossings update only changed visibility attributes. Deselecting releases selection geometry; marker paths retain only active and future corridors. @@ -2587,22 +2910,27 @@ ingestion, eviction uses receipt-ordered queues, and capacity loss is disclosed when history is recreated. **Surface and route limitations.** Heights are aligned to work with Google 3D -tiles. Unknown historical surfaces leave gaps in a trail. Sparse reports can +tiles. Draped history is prepared on selection even while marker floors are unresolved; +Cesium resolves its surface. Without ground-polyline support, unknown historical +surfaces leave gaps. A selected body follows layer enablement and vehicle existence, +so an off-screen head does not hide an on-screen tail. Sparse reports can cut across corners; these paths are not surveyed route geometry. Subway markers are projected to street level because the feed does not provide depth, and the selected card explains that choice. Actual street-level views still require visual inspection. **Appearance.** Normal fleet frames are 20 px, growing to 30 px on selection; -NVG, thermal and noir frames are 30/36 px. Source rasters are 48/96 px before padding. -External halos are 1/1.5 px in normal and 3/3 px in sensors, calculated from the +CRT, NVG, thermal and noir frames are 26/39 px. Source rasters are 48/96 px before padding. +External halos are 1/1.5 px in normal, 1.25/1.25 px in CRT and 2/2 px in sensors, calculated from the final unpadded display size. Six modes, two sizes and three profiles cap the raster cache at 36 variants. Normal mode colours are bus `#5EF08A`, tram `#FFC24A`, subway `#FF4538`, rail `#D9A6FF`, ferry `#5FD6FF`, and unknown -`#D8DDE5`. Selection keeps the mode colour. Sensor bodies use solid rounded envelopes with at least 60% opaque white coverage -of the padded display footprint, without interior panel lines. Sensor input is opaque white with a -fully opaque black halo; black-hot reverses the contrast through the -thermal effect. Creation, mode changes, selection, deselection, map presets and +`#D8DDE5`. Selection keeps the mode colour. Sensors reuse each normal silhouette's exact +outer path, filled opaque white without interior panel lines, with an opaque +`#05080C` halo. Only the external padding grows; the unpadded silhouette remains +at CRT size. There is no envelope body. Black-hot reverses the contrast and +Ironbow maps the white input to its hottest palette entry through the thermal +effect; sprite code never applies a red tint. Creation, mode changes, selection, deselection, map presets and Cockpit vision use the same sprite styling function. Sensor signatures remain in-scene. The thresholds in `qaMetrics.js` require @@ -2612,14 +2940,17 @@ of its phosphor peak white (0.65992 from RGB 0.16/1/0.22), halo minimum ≤0.25 with the centre minus sampled background reported without gating. Each preset needs at least six verified, unobscured sprites; insufficient coverage is UNEXERCISED. The sampler excludes overlapping footprints, including otherwise ineligible -sprites, and verifies pick ownership across all nine sampled core pixels. +sprites, and chooses nine source-raster points in the widest solid white band, avoiding +window/panel gaps. Equal-width tram bands prefer the upper solid body over the +geometric centre; the nine-point spacing and all thresholds remain unchanged. +The sampler then verifies pick ownership at all nine points. Noir samples also exclude its deliberately vignetted outer field, using shader settings and screen position rather than observed brightness. Selected-trail diagnostics report every condition even when selection fails. Transit brackets use the normal-composite overlay surface: a 1.25 px mode-colour stroke over 3.25 px dark backing. Other contact themes retain their existing -behavior. The selected trail uses a 2 px core over 4 px backing, mode-coloured +behavior. The selected trail uses a 3 px core over 5 px backing, mode-coloured in normal and white input in sensors. Alpha falls linearly from 0.80 at the head to 0.45 at two minutes, 0.20 at ten minutes and 0.08 at fifteen minutes. @@ -2642,7 +2973,10 @@ heights, and reuses caller-owned sample and segment storage. collections above CCTV and Bikeshare. Traffic, Bikeshare and Transit share camera sensitivity claims; the original sensitivity returns after the last release. Visibility checks combine the camera frustum and ellipsoid occlusion at no more -than 4 Hz; missing map bounds do not admit the globe's far side. Frame work +than 4 Hz; missing map bounds do not admit the globe's far side. Camera arrivals +rebuild an unprepared or cold marker corridor during that visibility sweep, +adopt a loaded surface, and update both heightPending and surfaceReady diagnostics. +A resolved display sample clears its pending-height gate without waiting for a poll. Frame work visits moving visible vehicles, up to 64 pending height changes, and the selected head. Rotation visits visible membership at 5 Hz, with selected rotation per frame. The transit render hold exists only for visible positional or orientation @@ -2656,6 +2990,15 @@ destruction also releases collections and registrations. QA_BASE_URL=http://localhost:4305 QA_TAG=keyless node scripts/qa-transit.mjs ``` +`QA_BASE_URL=http://localhost:4305 node scripts/qa-transit-recovery.mjs` is the +focused keyless camera-arrival regression. With destination tiles loaded, it +injects nine disclosed moving-bus reports and delays their floor acquisition, +selects the hidden vehicle, then releases the floor and calls camera.setView. +Within two seconds it requires a visible marker, a prepared visible body and +at least six of eight paired off/on trail pixel samples. It uses production +selection, visibility and geometry owners and writes screenshots plus JSON; +it does not establish Google 3D acceptance. + The full run samples completed frames at 1920×1080 CSS pixels, records DPR, and measures moving fleets of 800 and 3,000 vehicles with 128 fixes each and DETECT on. Street/metro targets are respectively: transit frame CPU p95 ≤1/4 ms, frame @@ -2686,6 +3029,30 @@ injected playback independently of live fleet activity. Thermal checks verify style activation before reading generated controls; DETECT checks set density and exercise the real OFF/restore button. Cesium render errors fail selection acceptance. +The `trail-visible` section requires a visible Google 3D tileset. It selects a +scripted straight bus with CapMetro metadata under the isolated `qa-trail-capmetro` +feed ID, with nine retained fixes, runs for 20 seconds at each +300/600/900 m view (55/45/45 degrees), then freezes playback and waits for sustained tile and primitive readiness. +It captures off/on/off/on framebuffer patches at eight distinct projected surface +points outside the padded sprite and selection bracket. `Google 3D selected trail visible at 6 of 8 projected samples` +prints the selected key, fix count, elapsed display time, path length, hit count, +per-point coordinates/hits and renderer strategy. At least six points need a +repeatably changed green core or dark backing at the same pixels. Repeated off +and on channels and their contrast deltas must agree within 8 RGB levels; +background refinement, overlapping samples and unchanged dark roads fail. The dark +backing must reduce summed RGB by at least 40%, and either match needs RGB +distance of at least 40, so a faint depth-fail wash cannot satisfy visibility. Artifacts are +`-m-trail-visible.jpg` and matching JSON. Run the same harness +against the base and patched keyed builds; partial runs remain diagnostic. +Node checks run Cesium's final geometry pipeline, including batch IDs and +position encoding: 1,576 bytes per head subdivision and 2,014,128 bytes for the +1,278-instance body. The body plus a separate 81,792-byte instance reserve totals +2,095,920 bytes, below the 2 MiB body limit; the head remains below its separate +2 KiB/frame geometry limit. Ordinary frames upload no head geometry. These are +pipeline buffer measurements, not measured GPU time or instance-texture uploads. The same 20-second browser interval scopes +WebGL uploads to the trail body/head, forces one body rebuild, reports head CPU +p95/max, and gates body uploads at 2 MiB and head uploads at 2 KiB/frame. + Required empty or unexercised checks fail acceptance. The passing final line is `HARNESS: PASS (0 unexercised)`. A `QA_SECTIONS` subset is diagnostic only and cannot claim full acceptance. @@ -3035,7 +3402,7 @@ silently demoting every later lookup for the session. COVERAGE ON enable creates the active/visible 14-camera cohort, and activation always creates the selected frustum even with COVERAGE OFF. **Field validation passed 2026-07-04** (core look + downtown no-clip confirmed); that round fixed three findings: the - ground clamp now lifts the cap *center* only so the wireframe stays a true pyramid welded to + ground clamp now lifts the cap _center_ only so the wireframe stays a true pyramid welded to the plane (was a flattened fan / the ~47.5 m divergence — RESOLVED), re-selecting the active camera is a no-op (killed a click-flash), and texture swaps gate on canvas content (killed a periodic white flash). Coverage is now **metro-wide: 250 cameras** (`CCTV_AUSTIN_MAX_SOURCES` @@ -3047,7 +3414,7 @@ silently demoting every later lookup for the session. poses, and the layer is stills-first. sources. Fintraffic Finland road weather cameras (2026-09-13; cap 300, `CCTV_FINTRAFFIC_MAX_SOURCES`, kill switch `CCTV_FINTRAFFIC_ENABLED=0`) are the fourth pack: one keyless GeoJSON station list - covering the whole country, where one *preset* (a station's fixed view) is one camera — 806 + covering the whole country, where one _preset_ (a station's fixed view) is one camera — 806 GATHERING stations carry 2,256 in-collection presets, prioritized to 300 against seven anchors on the main road spine. `CCTV_MAX_SOURCES` is a 4,000 catalog-wide ceiling shared round-robin across packs, so a lower global cap thins every region instead of starving the last pack. @@ -3100,7 +3467,7 @@ silently demoting every later lookup for the session. `activeCameraCardEnabled` presentation option can publish the retained protected-card path. Disable tears the tier down completely. Coverage/viewshed semantics unchanged. -- **Satellites**: orbit rings rotate about Earth's Z by ΔGMST every ~1s (exact inertial→ECEF compensation; no SGP4 re-runs); the tracked satellite propagates per frame with one shared epoch for dot/label/camera. Verified: ISS holds <1km perpendicular to its ring while tracked. +- **Satellites**: orbit rings rotate about Earth's Z by ΔGMST every ~1s (exact inertial→ECEF compensation; no SGP4 re-runs); the tracked satellite propagates per frame with one shared epoch for dot/label/camera. Verified: ISS holds <1km perpendicular to its ring while tracked. Pass prediction (`src/data/satellitePass.js`; `getNextSatellitePass`, `getNextIssPass`) scans at 20s, bisects rise/set to ~0.2s, fits the peak with a parabola, and marks a pass visible when the satellite is outside a cylindrical Earth shadow while the observer's Sun is at or below −6°. `next_iss_pass` preserves its geometric-pass ordering and appends visibility metadata. General `next_satellite_pass` accepts a loaded NORAD ID or unambiguous name, searches 24 hours and optionally requires estimated visibility. These estimates do not account for weather or satellite brightness. - **Space Missions (30d)**: recent launches render as bounded shared-host, horizon-occluded mission markers using Launch Library 2 v2.3 detailed records. Enabling the layer selects the unified right-side Context panel's Space Missions mode and enables the required satellite layer. Before applying its temporary dense/hidden Satellite mode, Space Missions snapshots the complete standalone Satellite parameter set and exact enabled-layer set. Disabling Space Missions from either Context or the left Data Layers rail restores those parameters and the exact prior enabled state, so a Satellite layer that was already on stays on while a mode-owned dependency returns off; enabling Satellites by itself remains independent. Selecting a mission isolates its launch-to-orbit transfer and dashed satellite orbit, fills that same panel with navigation/details, and animates a small phase-colored marker along the exact displayed Cartesian samples. Marker hit testing drill-picks through photorealistic tiles so the depth-test-free tactical dot remains reliably selectable; its text is non-interactive shared-host presentation. The selected pad is the camera's zoom pivot: the overview remains centered on its launch site, wheel zoom approaches that site instead of drifting elsewhere, and camera pitch progressively changes from global nadir to an oblique close 3D view. Its protected shared-host callout remains visible and expands to include both mission and launch-site names. `FOCUS` flies directly to a 12 km oblique frame around the selected launch site and retains the same anchored zoom/orbit behavior. `REPLAY ASCENT` resets the selected marker at the pad, frames it from an oblique third-person angle, and follows it through the mission-specific compressed ascent directly into one orbital lap at the default `1×` rate. A live `0.25×`–`4×` slider changes ascent and orbit playback speed; adjusting it mid-replay preserves the current path position and historical mission timestamp. Re-entry/recovery cannot be inserted into replay. At orbit insertion the camera smoothly pulls back over the first fifth of the orbital replay and pitches to a globe-scale nadir view while continuing to target the moving replay point. Replay Cancel, mission navigation, deselection, layer disable, and data refresh all release camera ownership. Reconstructed paths are one continuous 128-sample geodetic curve: horizontal departure begins near zero while altitude rises quickly, then the climb progressively bends toward insertion without the former hard 120 km corner. Unmatched orbit fallbacks are smooth planar inclined rings rather than longitude/latitude ground-track curves. The panel lists disclosed payload names, types, operators/manufacturers, mass, multiplicity, and destination when supplied; an empty LL2 payload collection is shown as `CLASSIFIED / MULTI-PAYLOAD`. Launcher, spacecraft, and recoverable payload stages appear in a compact stage table with serial/flight/reuse details, recovery outcome/type, destination, and final coordinates when those records exist; an empty recovery collection omits the section. Stage recoveries with confirmed coordinates use those coordinates; return-to-launch-site records use the pad; downrange-only records receive an explicitly labeled estimated endpoint along the ascent azimuth. Available endpoints render as static 2 px dashed descent/recovery paths with a fixed final-position dot and an estimated atmospheric-interface segment when applicable. The ascent is geodetically densified above the ellipsoid toward the orbit's nearest insertion point, then rendered with `ArcType.NONE`, so it neither cuts through Earth nor separates from the marker. Because LL2 does not normally supply continuous ascent telemetry, pad-to-insertion paths without upstream trajectory samples are labeled `RECONSTRUCTED ESTIMATE` / `ASCENT ESTIMATE`; only supplied trajectory samples receive the replay wording. Selected-orbit framing fits the complete ring, rear-side linework uses normal scene depth occlusion, and current distance, speed, and callout data come only from a launch-year-validated satellite match. Speed is the magnitude of the SGP4 inertial velocity vector at the same propagation epoch as position, displayed in km/s with km/h available as hover detail. Unavailable operator, site, launch-time, orbit, current-altitude, and speed values omit their detail rows instead of reserving panel space with placeholders. Newly launched payloads absent from the core operational groups use CelesTrak's cached active TLE feed as a lookup-only fallback; weak constellation-name matches are rejected. The replay callout maps compressed animation progress onto Launch Library's mission-relative timeline, showing the historical UTC date/time at the marker's current path position; unavailable timelines remain explicit. Matched live satellite positions propagate at one-second cadence and use a distinct green dot/callout with the current UTC date/time. When no mission is selected, the Context panel presents a scrollable newest-first roster of every launch in the rolling window, including the smaller 5 px operator-colored marker, provider, and launch date. Hovering or keyboard-focusing a row shows four compact cyan corner brackets on both that roster row and its corresponding globe dot, rotates the globe at the current zoom to center it, and gives its label declutter priority without selecting it; the globe label remains unbracketed. Selecting a roster row invokes the same mission isolation and full-orbit framing as clicking its globe marker. The replay vehicle is one screen-space SVG/CSS HUD overlay rather than separate Cesium billboard, label, and reticle graphics. It is hidden during ordinary Focus and manual close views, where the standard selected launch-site label remains visible, and exists only while ascent replay is active. Its fixed pixel scale is shared by ascent and insertion, so camera range never resizes the rocket on screen before the phase boundary. Generic Launch Library pad names are reduced to their identifying suffix, and replay timestamps use a cyan state title over unprefixed white UTC date/time values. `REPLAY ASCENT` holds the unframed cyan/white rocket at the pad for a real-time `T−10` countdown, transitions through `LIFTOFF`, and attaches six tapered cyan/white ellipse waves directly below it from liftoff through insertion to convey thrust without adding scene geometry. While replay is active, the single start button is replaced by compact Play, Pause, and Cancel icon controls. Pause freezes countdown or mission time, vehicle/stage positions, camera target, labels, and thrust-wave animation; Play resumes from that exact frame, and Cancel releases replay camera ownership. The rocket and thrust group rotates from the path's live screen-space tangent, so its nose follows the visible ascent curve while the adjacent text remains upright. The camera begins as a close oblique launch chase, then smoothly widens between roughly 120 and 420 km vehicle altitude into a higher oblique context view that keeps the moving rocket targeted while exposing the ascent bend and orbit connection. At insertion the rocket/thrust glyph is replaced by the fixed-size cyan orbit dot, which the camera follows through the existing globe-scale orbit pullback. The chase camera limits per-frame yaw changes across heading wraps so it cannot abruptly cross in front of the vehicle and make ascent read in reverse; the replay-speed slider affects mission playback but not countdown duration. Mission world text has no native `LabelGraphics`: overview launch markers publish at most 48 ambient candidates for a 24-winner budget, while selecting a mission clears that overview source and publishes its launch-site callout, stage re-entry annotations, live/estimated payload-position readout, and orbit annotation as protected selected-lane entries. The source retains the exact former strings and colors. Static anchors reuse the Cartesian values used to build their mission geometry; the moving payload entry reads the layer's per-frame live-position cache; catalog-backed orbit annotation positions are cached in the same one-second matrix update that realigns the orbit primitive. Keyhole edge fade, horizon culling, final collision placement, and UI exclusion are owned by the shared host. Deselect restores the bounded overview, and refresh, disable, and destroy replace or clear both mission sources. @@ -3235,7 +3602,8 @@ silently demoting every later lookup for the session. - **Token flow**: browser fetches a short-lived client secret from `/api/realtime/token`; the Vite middleware holds `OPENAI_API_KEY` and posts the full session config (instructions, tool schemas, VAD, truncation) to `api.openai.com/v1/realtime/client_secrets`. SDP exchange goes directly to `api.openai.com/v1/realtime/calls` with the ephemeral token. - **Session defaults** (env-tunable): model `gpt-realtime-2` (or `gpt-realtime-2.1-mini` when the MINI tier is selected — see the model-tier entry below), voice `marin`, reasoning effort `low`, semantic VAD with low eagerness, no response interruption, context window truncated to ~3,000 post-instruction tokens with 0.5 retention ratio — the conversational window stays short because map state is fetched live per turn. -- **Twenty-eight tools** (schemas defined server-side in `vite.config.js`, executed client-side in `src/voice/gevActions.js`): `fly_to_location`, `select_nearest_aircraft`, `adjust_camera_zoom`, `zoom_to_globe`, `set_layer_visibility`, `show_data_layers_menu`, `set_panel_open`, `set_visual_style`, `get_entity_context`, `get_current_view_state`, `set_hud`, `set_detection`, `set_map_stack`, `set_post_processing`, `control_scene`, `control_cctv`, `set_context_mode`, `control_cockpit`, `control_radio`, `track_entity`, `stop_tracking`, `frame_overhead`, `annotate_map`, `clear_annotations`, `move_camera`, `fly_route`, `analyst_query`, and `next_iss_pass`. +- **Twenty-nine tools** (argument schemas in `src/voice/actionSchemas.js`, served with their descriptions by `server/providers/openai/tools.js`, executed client-side in `src/voice/gevActions.js`): `fly_to_location`, `select_nearest_aircraft`, `adjust_camera_zoom`, `zoom_to_globe`, `set_layer_visibility`, `show_data_layers_menu`, `set_panel_open`, `set_visual_style`, `get_entity_context`, `get_current_view_state`, `set_hud`, `set_detection`, `set_map_stack`, `set_post_processing`, `control_scene`, `control_cctv`, `set_context_mode`, `control_cockpit`, `control_radio`, `track_entity`, `stop_tracking`, `frame_overhead`, `annotate_map`, `clear_annotations`, `move_camera`, `fly_route`, `analyst_query`, `next_iss_pass`, and `next_satellite_pass`. + > **Reading `npm test` totals:** the count depends on the Node major. The two > GC-bracketed allocation microbenchmarks (`src/data/focusAllocations.test.mjs` > = 1 test, `src/overlays/worldOverlayAllocation.test.mjs` = 13) only RUN on the @@ -3265,15 +3633,15 @@ silently demoting every later lookup for the session. - **Tier selection.** `standard` = `gpt-realtime-2` (default), `mini` = `gpt-realtime-2.1-mini` (~3× cheaper per audio token). The client sends `?tier=` to `/api/realtime/token`; the endpoint resolves it through the shared registry, so an unknown, empty, or hostile value falls back to `standard` rather than reaching OpenAI as a model id. Responses echo `X-GEV-Voice-Tier` / `X-GEV-Voice-Model` (plus `X-GEV-Voice-Tier-Fallback: 1` when a bogus tier was downgraded). Persisted at `godsEyeView.voiceCost.tier`. - **Applies NEXT session.** The model is fixed when the ephemeral token is minted, so a live session always keeps the model it connected with; toggling mid-session only records the preference (the button title says so). The cost tracker's lifetime is the session's lifetime and its model binding is immutable from `start()` to `stop()` — rebuilding it on toggle would erase accrued spend and let repeated toggles bypass the cap. The tracker may only be replaced once the session is FULLY SETTLED (`isVoiceSessionSettled()`: not active **and** no data channel **and** no peer connection) — `!isActive()` alone is not enough, because the `error` status reports inactive while the transport can still deliver a late `response.done`. The toggle itself reads and writes only the persisted preference, never the live tracker. - **Env overrides.** `OPENAI_REALTIME_MODEL` / `OPENAI_REALTIME_MODEL_MINI` remain authoritative per tier, so a drifted upstream model id is a `.env` fix rather than a code change. Because an override can point a tier at any model, the client prices against the model id the server actually echoed, **not** the tier it requested. An unrecognised id is billed at the most expensive known rates plus one console warning — under-metering is what lets a cap be overrun. - - **Metering.** Token usage from each `response.done` is folded into a per-session estimate. Cached tokens are subtracted from their modality totals; any aggregate-minus-details residual (and any payload with no detail at all) is attributed to audio rates, so uncertainty always resolves *upward*. + - **Metering.** Token usage from each `response.done` is folded into a per-session estimate. Cached tokens are subtracted from their modality totals; any aggregate-minus-details residual (and any payload with no detail at all) is attributed to audio rates, so uncertainty always resolves _upward_. - **Thresholds** (one object, persisted at `godsEyeView.voiceCost.limits`): soft warning at **$2** — amber readout plus exactly one console line; hard cap at **$5** — the session ends through the ordinary stop path (data channel and peer connection closed, mic tracks stopped) and the readout reads `Session ended — cost cap`. `0`/negative disables a threshold and round-trips through storage as an `'off'` sentinel (raw `Infinity` would JSON-serialize to `null` and silently restore the default); a corrupt entry falls back to the defaults rather than disarming the cap. - - **Cap semantics — in-flight tools COMPLETE and are NOT rolled back.** A session-ending latch (`isSessionEnding()`) is checked at the tool-dispatch site, so no *new* tool is dispatched once the cap trips. `extractFunctionCalls` yields at most one call per event, so that single check covers the whole batch. A tool already executing may still finish its map mutation (a camera flight, a layer toggle, an annotation). This is deliberate: unwinding a partially applied map change has no safe general implementation, and a half-reverted camera/layer/annotation state is worse than a completed one. + - **Cap semantics — in-flight tools COMPLETE and are NOT rolled back.** A session-ending latch (`isSessionEnding()`) is checked at the tool-dispatch site, so no _new_ tool is dispatched once the cap trips. `extractFunctionCalls` yields at most one call per event, so that single check covers the whole batch. A tool already executing may still finish its map mutation (a camera flight, a layer toggle, an annotation). This is deliberate: unwinding a partially applied map change has no safe general implementation, and a half-reverted camera/layer/annotation state is worse than a completed one. - **In-flight response at teardown → the accounting is INCOMPLETE.** Usage only arrives with `response.done`, which never comes for a response cut off by teardown (`stop()` closes the peer connection, and the server cancels rather than completes it). Rather than invent a token count for it, the tracker is marked `incomplete`: the chip shows a trailing `*` (`~$1.00*`) as a see-note mark and the tooltip carries the reason. Deliberately **not** presented as a lower bound — the estimate can also run high (residuals and unrecognised models bill at worst-case rates, and sub-cent totals round up), so it is partial rather than directional. (A bounded teardown drain was tried and removed: `pc.close()` closes the data channels a drain would listen on, so it was structurally dead.) - **⚠️ Model ids and rates are external facts** read from OpenAI's model + pricing pages on 2026-08-18 and marked VERIFY-AT-RELEASE in `voiceCost.js`. - **Reliability**: tool-call dedupe (2.5s window across call/item/args keys); response-create queueing that respects active responses and defers follow-ups when the user starts speaking; per-tool follow-up instructions so the agent confirms only what actually happened (zoom confirms only on `ok=true`). - **Aircraft identity honesty:** “What is this aircraft?” reads callsign, operator, registration, type, and route only from the selected contact context. Missing operator, route, or type enrichment is named explicitly rather than silently omitted or inferred from the callsign. - **Diagnostics**: every client/server event is posted to `/api/realtime/debug-log` and appended to `.gev-logs/realtime-conversations.jsonl` (gitignored) with secret/image redaction; last 30 errors persist in `localStorage` (`gev-realtime-errors`); `window.__gevVoiceCommands.getDiagnostics()` in the console. -- **Counting semantics ("near")** — a CONTRACT; new count-bearing tool work inherits it. Three honest numbers exist for one question: the Contacts cohort (250 km around the subject, what the panel shows), `analyst_query`'s count of *currently-loaded* records for the requested scope, and the layer-wide loaded total in `coverage.layersQueried[].records`. They diverge legitimately — the flights layer loads by viewport, so after a camera dive the loaded set can hold a fraction of the cohort (field case: panel 42, analyst 8). The contract: +- **Counting semantics ("near")** — a CONTRACT; new count-bearing tool work inherits it. Three honest numbers exist for one question: the Contacts cohort (250 km around the subject, what the panel shows), `analyst_query`'s count of _currently-loaded_ records for the requested scope, and the layer-wide loaded total in `coverage.layersQueried[].records`. They diverge legitimately — the flights layer loads by viewport, so after a camera dive the loaded set can hold a fraction of the cohort (field case: panel 42, analyst 8). The contract: 1. **Contacts ACTIVE** → "near / nearby / how many aircraft" means the **Contacts window** — the panel's numbers, spoken verbatim. Mechanism: `contactsWindow` (`{centeredOn, radiusKm, flights, military, vessels}`), carried by both `analyst_query` and `get_current_view_state`, derived by `contactsWindowFromSnapshot()` from the same snapshot the panel renders so the two cannot drift. A cohort whose feed cannot answer reports `'unknown'`, never a confident zero. 2. **Contacts OFF** → "nearby" means **in view**; "near \" means a radius around that place. A radius query with Contacts active and no explicit centre is centred on the **active contact**, not the camera. 3. **Every count names its scope in words** — "42 in your window", "8 in view", "about 30 within 250 km of Austin" — never a bare number. `analyst_query` returns `scopeLabel` so this is mechanical. Two different numbers with named scopes are not a contradiction. @@ -3364,6 +3732,18 @@ are omitted rather than framing the wrong part of the globe. - Pure half: `src/annotations/drawMode.js` (session, minimum vertices, double-click de-dup at 0.5 m, vertex ceiling, degenerate-geometry refusal, ring closing, dateline-safe length/area/centroid, hint text). Regression surface: `src/annotations/drawMode.test.mjs` and `src/data/inputOwnership.test.mjs` (pure), `src/annotations/drawToolBehaviour.test.mjs` (the tool driven against DOM and viewer doubles — leases, borrowed input actions, teardown, the Enter key, preview heights), `src/annotations/drawTool.test.mjs` (structural: where files live, which ids the markup carries, what the docs may claim), and the rendered harness `scripts/qa-draw-tool.mjs`. - The annotation tree is a declared ownership group: `./annotations` → `src/annotations/index.js` in `package.json`, with its module graph listed in `scripts/package-boundaries.json`, so an annotation module reaching outside that graph is a gate failure rather than a surprise in a layer's bundle. `drawMode.js`, `drawTool.js` and their tests are in `scripts/format-scope.json`. +### Recent Imagery (September 2026) + +- The layer sits in the Data Layers panel's Cameras group beside Cameras (CCTV); Mapped ALPR Cameras moved to the Infrastructure group to make room. +- DATA ▸ **Recent Imagery** (`recent-imagery`, `src/layers/recentImagery/`) lists the last 30 UTC days of imagery for a selected box and drapes the days you pick: HLS S30 (Sentinel-2) and L30 (Landsat 8/9) at 30 m, and the VIIRS NOAA-21 daily overview at 250 m. Keyless and browser-direct: NASA CMR for which days have HLS granules in the box (`catalog.js`, both collections concurrently, paged with `CMR-Search-After` up to 2,000 records each, `truncated` against CMR `hits`), GIBS WMTS for tiles, Worldview Snapshots for thumbnails and exports. Worldview's `Data-Present` header is the only availability signal: GIBS answers an empty tile with HTTP 200, and the JPEG overview would drape black, so a day confirmed empty never drapes. +- **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side, on one side of the dateline and inside the Web-Mercator limit (`validateBox`). A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height. +- **Modes, pins and the preview.** The mode is explicit: `image` (one pinned day, slot `a`), `basemap` (that day on the left of a swipe, the basemap on the right: slot `a` splits LEFT and there is no second layer) and `ab` (day `a` left, day `b` right). `setAssignment(slot, key | null)` / `toggleAssignment(slot, key)` pin and unpin; a day is in one slot at most (pinning it in the other slot moves it) and an empty day cannot be pinned. `setMode()` keeps both pins; `b` only drapes in `ab`. While the mode's first empty slot exists the focused day previews in it: a click at once, arrow keys after 250 ms of quiet (`FOCUS_DEBOUNCE_MS`, one timer, last day wins); an unprobed day is followed and previews when its probe says present, an empty or unknown day never drapes and the previous preview stays. A pin change drops the preview until focus moves again, and unpinning takes that layer off at once. `rankLatest` picks START HERE coverage first (a present HLS day whose footprints cover the box, or have none, beats a newer sliver), then newest with all granules ≤ 20% known cloud, then newest; slivers only as `partial`; else the newest non-empty VIIRS day; it is focused and previewed after each search when nothing is pinned. Escape clears the preview (`clearPreview()`), then cancels the box tool, then blurs — with SELECT BOX armed too, through the tool's `onEscape` interceptor wired in `createApplicationTools`. Pins, mode, box and split changes made in the panel are published with `adoptLayerParams`, never while a share link is being applied. +- **Rendering.** `rendering.js` owns at most two GIBS layers on the host `src/maps/imageryHost.js` resolves: `viewer.imageryLayers` while the globe shows, the photoreal tileset's `imageryLayers` while it is hidden, or none (the panel says so). Layers are rebuilt on a new host, never re-parented. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. Thumbnails: three fetches at once, sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes. +- **Esri surface and the swipe.** While any image is on the map (a preview included) the layer holds the map lease (`acquireImageryComparison`, owner `recent-imagery`, `esri-if-photoreal`): on Google 3D the map switches to Esri, because 30 m pixels over 3D buildings do not read, and Cesium's split only works on the globe. The lease is handed back, and Google 3D restored unless the operator changed maps meanwhile, when the last image leaves the map or the layer is disabled; the notice line says so while it holds. While a day is shown the imagery keeps Esri: a manual switch that lands on Google 3D is answered at once with a new lease under the same policy (`keepEsri`), the notice reads `Imagery stays on Esri · CLEAR to use Google 3D`, and the divider never suspends because of a map switch. It re-leases once per switch generation and only for a manual one (`MapSourceController#getSwitchOrigin()` is `manual` for an outside `setStack`, `automatic` for the controller's own fallback or recovery), never for the lease's own switch and never while releasing, so CLEAR and disable still return to Google 3D; a lease another owner holds stays refused. When Esri fails and the controller falls back to Google 3D on its own, the layer lets the lease go without restoring anything, both days drape on the tileset without a swipe and the guidance reads `Esri map unavailable · no swipe`; only the next manual switch to Google 3D takes Esri again, so a failing Esri map is never retried in a loop. Switching between globe stacks (Esri, OSM, Bing) only rebinds. On a tileset host both images drape without a swipe. The split control (`createImagerySplit`, labels A / B, or IMAGE / BASEMAP) exists only while a swipe is live, recentres on every new comparison (not while scrubbing the second day), except once for a split restored from a link. There is no keyboard shortcut (Space is the app's push-to-talk): SWAP (`#ri-swap`, in the controls row, its slot reserved and the button disabled while no swipe is live) trades the two sides, A to the right and B to the left, or the image to the right of the basemap, and a second click restores; the hint reads `Drag the divider · SWAP trades sides`. The swap is not in the share link, and every new comparison starts unswapped. One opacity applies to both drapes. Another owner holding the lease is reported and the images still drape. +- **Panel.** `#recent-imagery-panel` is static rail markup in `src/ui/templates/context.html` beside `#weather-panel`, registered in `PanelLayoutController`, `PanelChrome` and the share panel state (`ui` token `i`), hidden while the layer is off and opened on first appearance unless a stored or shared collapse choice exists (`dataset.collapsedPreference`). `LayerPanel.attachRecentImagery(factory)` mounts the readout (`createRecentImageryPanel` in `src/ui/recentImagery.js`) into its `data-rail-scroller` body, as the weather readout is mounted. The body is a fixed stack in which no block changes height and no control moves in any state: `#ri-actions` (SELECT BOX · USE VIEW · CLEAR, rail-card actions), `#ri-notice` (one line: `#ri-notice-text` with the refusal, error, CLEAR notice or the Esri note, and `#ri-zoom-in` in a fixed slot at its right end, reserved unless an oversized box or view can be fitted), `#ri-strip` (day cards newest first: thumbnail, date, sensor, cloud, START HERE, PREVIEW, and a SHOW chip or A and B chips; ← → Home End move, S / A / B pin, Enter previews), `#ri-hint` (one line: the next step), `#ri-selection` (`#ri-mode` IMAGE · VS BASEMAP · A / B, then `#ri-slot-a` and `#ri-slot-b` with `#ri-unpin-a` / `#ri-unpin-b` kept in place when empty), `#ri-controls` (`#ri-opacity`, EXPORT / EXPORT A and EXPORT B) and `#ri-details`, a collapsed rail card holding the focused day's acquisition, coverage and granules, catalog notes, the empty-days toggle and the imagery credit. Absent controls are reserved (invisible), never removed. Every render preserves the body's `scrollTop`. +- **Share links.** Layer options (token `1`): box edges as integers at degrees × 100000, pins `a` and `b` as compact days (`S20260918`), `m` mode (0 image, 1 basemap, 2 A / B), `p` split percent (share-link only: never stored locally) and `v` for the daily overview. Row chips: `MORE DETAIL · 30 m` (on) and `DAILY OVERVIEW · 250 m` (off). +- Regression surface: the colocated `*.test.mjs` beside each module (shared doubles in `src/layers/recentImagery/testDoubles.mjs`; `src/ui/recentImagery.test.mjs` includes a DOM-structure guard: every control keeps its place in the tree, nothing is hidden, and every fixed-height block keeps the class the stylesheet fixes its height by; it has no layout, so it cannot see movement), `src/ui/layerPanel.test.mjs` (mount), `src/maps/controller.test.mjs` (`subscribe`), `src/data/layerState.test.mjs` (codec), `src/sharelink.celestial.test.mjs` (panel token), and the live gate `scripts/qa-recent-imagery.mjs`, which also measures every control's rect across the transitions within 1 px; that measurement is the real layout-shift check. + ### 3D Aircraft + Tracking (June 2026) - **The TRACKED contact's 2D↔3D handoff is DEFAULT behaviour (2026-08-19), driven by camera distance alone.** It does NOT consult the DISPLAY-rail `3D` toggle, which continues to own the FLEET (the un-instanced draw-call budget stays the operator's decision). Policy lives in `src/data/trackedModelRegime.js` and is shared by both layers: enter below `TRACKED_MODEL_ENTER_ALT_M` = 150,000 m and hand back to the billboard only above `TRACKED_MODEL_EXIT_ALT_M` = 172,500 m. **The swap distance was set by playtesting on 2026-08-20:** a first pass at 1,000,000 m switched too early; 2D reads correctly at ~600 km and the handoff belongs at ~150 km. **Consequence, recorded on purpose:** the tracked contact now enters 3D NEARER than the FLEET does (`MODEL_ALT_CEIL_M` = 800,000 m, unchanged), so with the DISPLAY-rail `3D` toggle on, 150–800 km draws surrounding contacts as models while the selected one is still a glyph. Nothing double-draws (the fleet pass skips the tracked icao) and aligning the two is a fleet-side decision, deliberately out of scope. **The two thresholds are asymmetric on purpose:** a single threshold makes a tracked orbit sitting ON the boundary strobe billboard↔model as the camera's altitude wobbles across it. Do not collapse them. The latch is scoped per selection, so a new target re-evaluates against the ENTER ceiling rather than inheriting the previous target's exit band. Exactly ONE model is involved; it loads on demand when the regime opens, is HIDDEN (not released) on regime exit so re-entry has no load gap, and is released by the existing teardown on deselect/re-track/destroy. Cockpit and TR-3B suppression are unchanged. **Two invariants around it:** (a) the hysteresis latch AND the load-failure latch are per-selection state cleared by `_resetTrackedSelectionState()` in the tracking lifecycle (deselect / re-track / cross-layer / init / destroy) — the predicate's icao-change guard is defence only, since it needs a drawn frame while nothing is selected and the render governor's idle mode does not promise one; (b) on-demand loading is bounded at 3 attempts per selection with a 1.5 s backoff and one console warning naming the asset — the driver runs every `scene.preUpdate`, so an unbounded catch means a missing GLB spins load→reject at frame rate. The billboard stays the visual throughout a failed load. @@ -3431,6 +3811,7 @@ are omitted rather than framing the wrong part of the globe. - Build gate: `npm run build` - Network access: local-only by default (`HOST=localhost` in dev-fresh.sh); LAN is an explicit opt-in via `HOST=0.0.0.0` (launcher prints a key-exposure warning + LAN URL; see SECURITY.md) - OpenSky default mode: OAuth (`OPENSKY_AUTH_MODE=oauth`; `anon` works without credentials) +- Setup doctor resolves `OPENSKY_AUTH_MODE` from the environment and dotenv files. Explicit `anon` and OAuth mode without a client pair report keyless anonymous access (rate-limited); a complete OAuth pair retains the existing presence-only capability wording. Basic and auto modes report the selected mode without guessing which credentials runtime will accept. The proxy's auth behavior is unchanged. - Google key expected in Keychain service `google-maps-api` (or `GOOGLE_MAPS_API_KEY`, or `.env`) - OpenSky credentials expected in Keychain service `opensky-network` (or env, or `.env`); `OPENSKY_AUTH_MODE` and `OPENSKY_CREDENTIALS_FILE` read from `.env` too - Optional-key precedence in `dev-fresh.sh` is uniform — explicit shell env, then `.env`, then Keychain: `OPENAI_API_KEY` (Keychain `openai-api`/`api-key` — voice + HUD summary), `AISSTREAM_API_KEY` (`aisstream-api`/`api-key` — live vessels), `CESIUM_ION_TOKEN` (`cesium-ion`/`token` — Bing stacks), `TOMTOM_API_KEY` (`tomtom-api`/`api-key` — live traffic flow), `FIRMS_MAP_KEY` (`firms-map`/`map-key` — live fires), `LL2_API_TOKEN` (`.env` only) @@ -3446,6 +3827,7 @@ are omitted rather than framing the wrong part of the globe. - A cold OpenSky failure uses the current camera subpoint only to request a cached adsb.lol point fallback capped at 250 nm. A fresh OpenSky response or last-good cache wins; a nominally successful worldwide snapshot more than two minutes old prefers viewport-scoped adsb.lol when available, otherwise the stale source is reported honestly. The fallback is visibly source-labeled and is never presented as a worldwide snapshot. - GBFS proxy refuses upstream redirects (`redirect: 'manual'`; any 3xx becomes a 502 and the redirect target is logged server-side only) and enforces its 5 MB response cap while the body streams, cancelling the upstream read past the cap; CCTV health map is bounded. - Proxy error payloads are sanitized (no internal error details returned to clients). +- That holds for the OpenAI and CCTV media paths too: `/api/openai/hud-summary` never relays OpenAI's own `error.message`, `/api/realtime/token` passes successful ephemeral-token responses through but answers with a fixed error when minting fails or upstream rejects the request, and a failed CCTV media fetch stores a fixed camera health `message` — `GET /api/cctv/health` serializes that field and the CCTV panel renders it as a status label, so it is a client surface as much as the response body is. - `OPENAI_API_KEY` is server-side only; the browser receives ephemeral Realtime client secrets from `/api/realtime/token`. - `AISSTREAM_API_KEY` is server-side only; the browser reads the same-origin `/api/ais-live` cache. - `/api/google/nearby-places` keeps the Google key out of Places requests issued for voice scene context. @@ -3455,9 +3837,14 @@ are omitted rather than framing the wrong part of the globe. - `/api/route` proxies bounded OSRM route requests for annotation routes, with profile allowlisting, distance caps, response caps, caching, and sanitized "no route found" errors. - Track endpoints: `/api/ais-live/track?mmsi=` (server-accumulated ring buffers; sub-route handled before the rows snapshot), `/api/opensky-track?icao24=` (OAuth, 60s cache, sanitized errors, independent OpenSky credit bucket), `/api/adsblol/trace?hex=` (60s cache, 5MB cap, ODbL attribution required in UI). - Realtime debug logs redact API keys, bearer tokens, client secrets, and image data URLs before writing to disk; request bodies are size-capped. +- `/api/realtime/debug-log` enforces an always-on 120-per-client/400-global one-minute limiter (not the opt-in `GEV_RATELIMIT_OPENAI_PER_MIN` bucket the cost-bearing OpenAI routes share), appends asynchronously through a serialized queue, and rotates `realtime-conversations.jsonl` at 32 MB keeping one prior generation, so the sink is bounded at twice that regardless of session length. A malformed record answers 400 and a failed write 500, both with a fixed message. ## UI/UX Runtime Defaults +- Trackpad pinch zoom is registered as Cesium's `Ctrl+wheel` camera input. + Pixel-mode pinch deltas receive bounded amplification before reaching the + canvas; ordinary wheel, line/page-mode and native touch-pinch paths are left + unchanged. The application scene owns and removes the relay listener. - Z ladder: panels promote within 100–139 (renormalized on wrap), voice pill 150, toast 200, clean-view exit 300. - Panel POSITION keys are versioned `v8` (`godsEyeView.v8.panelPos.`); collapsed-state keys remain `v6`. The one-time position reset clears stale DISPLAY placements that could overlap the Context rail. - Map Source lives in the bottom Visual Presets tray. The left accordion contains no MAP STACK panel, and the `k` panel token that addressed it is gone from the share registry, so legacy `ui=k...` state takes the ordinary unknown-token skip. @@ -3466,6 +3853,7 @@ are omitted rather than framing the wrong part of the globe. - The desktop right rail (`#right-context-rail`) owns `DISPLAY`, `CCTV`, its active parameter controls, and `GLOBAL CONTEXT` as one fixed responsive stack in that order. Its compact buttons use the same 176 px width as the left accordion and one consistent 50 px height, share the left stack's 52 px edge inset and measured top baseline across HUD variants, then constrain themselves against visible HUD/chrome rectangles and the remaining vertical corridor. `DISPLAY` is no longer draggable and legacy saved coordinates are ignored. - The right rail is labeled **DISPLAY** (formerly "MOVE") and groups, in order, HUD, DETECT, Bloom, Sharpen, 3D, Clean-UI (HUD + DETECT promoted to the top). Its expanded controls retain the same compact 176 px width as the right-side tabs instead of growing to the wider Context detail-card width. It starts expanded on first run and respects the user's later `v6` collapse choice. Collapses/expands with directional chevrons (`◀` collapsed, `▶` expanded). - Display and Context use matching 330 px expanded widths and matching compact tab dimensions. The parameter panel is part of Display's expanded content. DISPLAY may remain open beside one contextual panel; CCTV and Context are mutually exclusive. In Tactical HUD, expanding CCTV or Context hides the other contextual launcher while DISPLAY remains independently available. The most recently opened right-rail panel owns the constrained lane even when it appears later in DOM order; passive restoration and automatic disclosure do not replace that explicit owner. Minimal and other HUD layouts retain the collapsed launchers; when their active panel exceeds the measured corridor, the rail reserves sibling heights and gaps and scrolls the active panel internally. +- At 720px and below both panel stacks (`#left-panel-stack`, `#right-context-rail`) go edge-to-edge and scroll vertically. Every hosted panel's decorative `.panel-glow` is pinned to its panel box there (`inset: 0` in `src/ui/styles/responsive.css`): on desktop the glow overhangs the panel by 18–20 px as harmless paint, but inside a scroll container that overhang is scrollable overflow on both axes and drew a horizontal scrollbar band plus a vertical scrollbar that scrolled nothing but glow whenever CCTV, Context, Data Layers or Scenes was expanded. The glow's blur is ink overflow and never scrolls, so the look is unchanged. Do not fix this by clipping the stacks: `overflow-x: clip` would also clip the Context radio popover and would not remove the vertical scrollbar. Pinned by `src/ui/panelRails.test.mjs` against every `(max-width: 720px)` block in the flattened stylesheet. - `STYLE PRESETS` and `LOCATIONS` start collapsed, expand on intentional hover/click, and auto-collapse after hover leave delay. - Collapsed mini-status indicators show active style and active location/landmark. - Detection mode is user-controlled and should persist when switching styles. Since 2026-08-22 it also STARTS on — Dense @ 75% for every style on a first run, Normal included — as a `GLOBAL_POST_DEFAULTS` baseline that does NOT set `_detectionUserOverridden`. Exception (unchanged): selecting a military style (CRT/NVG/FLIR) auto-enables the same Dense preset, but only until the user manually changes detection this session (`_detectionUserOverridden` gate), after which style switches never touch it. @@ -3540,7 +3928,7 @@ are omitted rather than framing the wrong part of the globe. - **Aircraft course slew:** civilian and military 3D models retain the 60°/s course limiter, but each rendered frame can consume at most 250 ms of accumulated slew time. A long tile/render stall therefore catches up over multiple visible frames instead of turning one delayed frame into a heading snap. - **Manual-first cockpit briefing:** the right-side Live Signals / Regional News / Local Info carousel does not advance automatically on page load. Previous, Next, and direct page controls remain available; the visible `CYCLE OFF` / `CYCLE ON` toggle explicitly starts or stops the nine-second page cycle, which still pauses on hover/focus and while collapsed, hidden, or outside cockpit mode. Live signal data continues refreshing in either state. - **Photoreal horizon blend:** Cesium's sky atmosphere remains enabled behind the hidden base globe, but its light intensity, saturation, and brightness are reduced from the library defaults so the distant Google Photorealistic 3D Tiles boundary blends into the sky instead of producing a bright cyan horizon seam. - - **Cockpit direction and speed tapes:** plausible destination metadata now drives one translucent, isometric visor chevron labeled directly below with the estimated geographic bearing; the prior full geodesic dashed path is not rendered. A mirrored live ground-speed tape follows the inside-left keyhole rim using the same responsive curve, end fades, fixed pointer, and fractional tick motion as the altitude tape on the right. Speed values scroll upward as they increase while altitude values scroll downward. Its tick endpoints and current-speed pointer share the rail's inset-circle origin, so the markings stay attached to the visible curve rather than drifting inward with the text-label gutter. + - **Cockpit direction and speed tapes:** plausible destination metadata now drives one translucent, isometric visor chevron labeled directly below with the estimated geographic bearing; the prior full geodesic dashed path is not rendered. A mirrored live ground-speed tape follows the inside-left keyhole rim using the same responsive curve, end fades, fixed pointer, and fractional tick motion as the altitude tape on the right. Speed values scroll upward as they increase while altitude values scroll downward. Its tick endpoints and current-speed pointer share the rail's inset-circle origin, so the markings stay attached to the visible curve rather than drifting inward with the text-label gutter. - Voice control UI (`#gev-voice-control`) shows status states OFF / CONNECTING / LISTENING / EXECUTING / ERROR. ### Current Global Post Defaults @@ -3688,7 +4076,8 @@ easier to meet (detection is now on more often), but does not create it. - Traffic runs in `sim` mode (white dots, hardcoded speeds) unless `TOMTOM_API_KEY` is configured (env or Keychain `tomtom-api`/`api-key`), which enables `live` mode: TomTom flow vector tiles via the budget-governed `/api/tomtom` proxy - (`.gev-cache/tomtom/`, 120 s TTL, `TOMTOM_DAILY_TILE_BUDGET` default 40k/day), + (`.gev-cache/tomtom/`, 120 s TTL, `TOMTOM_DAILY_TILE_BUDGET` default 6k/day, + sized so a 31-day month stays inside TomTom's 200K/month free allowance), decoded client-side (`flowTiles.js`), matched onto Overpass roads (`flowMatch.js`), and rendered as green/amber/red dot color + speed/density scaling (`trafficFlowStyle.js`); closures spawn no dots; unmatched roads stay @@ -3782,7 +4171,6 @@ frames. Typing fields, modified keys and key repeats do not toggle it. The readout starts hidden each session and releases its timer and frame listener when hidden or when the application is disposed. - ## Radio components The radio entry composes one layer from directory ingestion, station queries, @@ -3793,6 +4181,134 @@ Existing catalog validation, category filters, tuning and voice playback behavio remain unchanged. Audio connects directly to the broadcaster after an explicit play action; the source does not relay or record streams. +## Local RTL-SDR and Local ADS-B + +The Radio panel holds a Local RTL-SDR card below internet radio. One browser +WebUSB session (`src/sdr/controller.js`) drives a USB RTL-SDR in desktop Chrome +or Edge on localhost or HTTPS; nothing opens until CONNECT. Demodulation and +Mode S decoding run in a worker; FM audio plays through an audio worklet. +Local FM and internet radio are one listening surface: starting local FM stops +internet-radio playback, and starting internet radio stops local FM. ADS-B +reception does not interrupt internet radio. + +- **Modes.** FM (87.5–108 MHz, tune, seek, volume) or ADS-B at 1090 MHz. + With a receiver open, selecting ADS-B enables the Local ADS-B layer; + selecting FM disables it. + Enabling the layer switches the receiver to ADS-B; disabling it leaves the + receiver mode unchanged. +- **Gain.** AUTO (tuner AGC) or a manual R820T step from 0.0 to 49.6 dB, + stored per mode in `gev:sdr:gain:v1`. Defaults: ADS-B 28.0 dB, FM AUTO. + Changes apply to the open receiver without reconnecting. +- **Receiver stats (ADS-B).** CRC-valid messages per second, aircraft heard, + aircraft with a fresh position and the IQ level. +- **Devices.** An already-authorized receiver opens without the WebUSB + picker. ADS-B prefers a device whose product name matches ADS-B or 1090 (the + 1090 MHz channel of a dual-channel board); FM avoids ADS-B/UAT channels. + A device chosen in the picker is remembered per mode by vendor, product, + product name and serial in `gev:sdr:device:v1`. CHANGE DEVICE reopens the + picker. LOCATE uses browser location for receiver-relative CPR decoding. + +The Local ADS-B layer (`local-adsb`, `src/layers/localAdsb/`) is off by default +and registered as local-only: it never enters share links or stored layer +state. Its aircraft get the public Flights treatment in magenta, alongside +the public Flights layer. Public Flights renders about one poll interval +(~30 s) behind for smooth interpolation while local aircraft are shown as +heard, so a local marker usually leads its public twin; both markers are drawn +on purpose: + +- **Class.** Each aircraft is classified with `aircraftClass.js` from its + ADS-B emitter category (dump1090 strings: `A1` light, `A3` large, `A7` + rotorcraft; set A/B/C/D = type code 4/3/2/1) and, once known, its adsbdb + ICAO type. Silhouette and per-class scale come from `aircraftIcons.js` + (×0.8 on the ground), tinted magenta. +- **3D.** The DISPLAY rail's 3D toggle and its proximity/all mode apply: the + layer reads the Flights layer's `models3d` params and uses the same ceiling, + caps, add/keep radii, visible-first eligibility + (`src/data/modelEligibility.js`) and per-class GLB + (`src/layers/flights/modelSpec.js`), tinted magenta through the same MIX + colour blend Flights uses for military amber. Heights are barometric + + geoid N, as Flights renders a contact without a geometric altitude; a + grounded model rides the one-shot ground snap and belly offset. +- **Motion.** No display delay. The marker is extrapolated forward from the + newest fix with `motionModel.js` (arc extrapolation, path-derived course + blended over the reported track, rate-limited slew); a new fix is absorbed + by a correction that decays over 900 ms. Coasting continues while messages + arrive and stops 10 s after the last one (60 s at most). +- **Sanity filter.** For airborne positions the browser decoder prefers a + fresh even/odd pair, then a frame decoded relative to the aircraft's own + position (under 10 minutes old), then the receiver location. Surface + positions are stricter: a single surface frame decodes only against the + aircraft's own recent fix, and only when that fix is provably within 45 NM + (it could not have gone farther since at its speed limit); the receiver + location never decodes a lone surface frame and only picks the quadrant of + a surface pair. Without an existing suitable fix for that aircraft + (airborne or surface, provably within 45 NM), surface acquisition + requires an even/odd pair. Every fix + must be reachable from the last accepted one at 1.5 × reported ground + speed + 50 kt (1,000 kt without a speed, 350 kt for A1/A7/B1/B4) over the + elapsed time + 1 s, plus 500 m. + Refused fixes are counted (`positionsRejected` in the SDR state; the layer + applies the same check to merged feed records and reports the total as + `rejectedPositions` in its stats). Three refusals in a row re-anchor. +- **Trail.** A selected aircraft draws a magenta trail of the positions the + receiver heard (up to 10 minutes / 600 fixes, dropped with the aircraft), + with the tracked-flight trail look and a live head segment. No network + backfill. +- **Enrichment.** Only the selected aircraft (type + route) and aircraft + about to render as models (type) are looked up, through the Flights + source's cached adsbdb proxy with the same once-per-session, four-in-flight, + 200 ms drip rules. + +A marker drops once its newest position is 60 s old; an aircraft is forgotten +after 60 s without a message. Clicking a marker opens a readout card (ICAO, +callsign, class and category, adsbdb operator/type and a plausible route when +known, altitude, ground speed, track, vertical rate, position age, message +count, "Heard by your receiver"); markers are not camera-followed. Positioned +aircraft join detection boxes, labelled only with a decoded callsign. + +Receivers publish one record shape from `src/sources/adsbRecords.js` +(`icao`, `callsign`, `category`, `onGround`, `lat`, `lon`, `altitudeFt`, +`groundSpeedKt`, `trackDeg`, `verticalRateFpm`, `lastPositionAt`, +`lastMessageAt`, `messageCount`, `rssiDbfs`, `band`, `source`). `band` is `1090` or `978`; `source` is +`webusb` (browser SDR) or `feed` (decoder feed). +`normalizeDump1090Aircraft(json, nowMs, { band })` maps a dump1090/readsb/ +skyaware978 `aircraft.json` document into the same records. Voice +`set_layer_visibility` accepts `local-adsb` ("local ADS-B", "my receiver", +"my antenna"). + +**Decoder feeds.** The layer's second input is the server route +`GET /api/local-receivers/aircraft` +(`server/providers/local-receivers.js`), configured only by the +`LOCAL_RECEIVER_FEEDS` environment value (`band=url`, comma-separated, e.g. +`1090=http://localhost:8080/data/aircraft.json`). Every host must pass +`parseTapAddress` (loopback, RFC1918, `localhost`, `*.local`), the scheme must +be http(s) and the path must end in `aircraft.json`; an invalid entry is logged +at startup, reported `invalid` and never fetched. The route reads all feeds in +parallel (2 s timeout, redirects refused, 2 MB cap, single-flight with a 1 s +cache) and returns `{ configured, generatedAt, feeds: [{ band, label, status, +aircraft, ageMs }], records }`, where a feed is `live`, `stale` (its own `now` +is over 10 s old), `unreachable` or `invalid`. Labels name the band only; +addresses and upstream error text stay on the server. Unconfigured, it returns +`{ configured: false, feeds: [], records: [] }` without fetching. + +The browser session (`src/layers/localAdsb/feeds.js`) polls the route every +second only while the layer is enabled and only while the route reports +`configured`; the Local RTL-SDR card makes one probe request at startup to show +its read-only "Decoder feeds: 1090 live · 978 live" line. Feed records are +rebased to the browser clock and kept up to 60 s after their last message. +`mergeLocalAdsbRecords` merges both inputs by ICAO, keeping the newest position +(tie: newest message) and the bands/sources heard in the last 60 s; the card's +receiver line names them ("Heard by your receiver · 1090 MHz + 978 MHz UAT · +browser SDR + decoder feed"). Aircraft heard only on 978 MHz UAT draw with a +thin light-magenta ring. With feeds configured the row status reads "2 feeds +live · 14 heard" when every feed is live. While any input is producing (the +browser receiver streaming, or a feed live) the row stays nominal and names the +other feeds as a trailing note ("3 heard · USB 5.8 msg/s · feed 1090 stale"), +since a decoder stopped so the browser can take the dongle is not a fault. With +nothing producing, every readable feed stale reads STALE and anything else is +an error. Without feeds it keeps the WebUSB statuses. See +`docs/LOCAL-RECEIVERS.md`. + ## Bundled geography and submarine cable components Submarine cables use separate source, geometry, rendering, interaction and @@ -3825,3 +4341,55 @@ releases imagery layers/listeners on replacement. Destroy invalidates pending work and releases owned resources, including late factory results. Supplied 3D tilesets remain owned by the caller; tilesets created through the controller's factory are added to its viewer and removed on destruction. + +## Live CCTV integration candidate (#489) + +Daniel Slay's shared-decoder panel/projection feature is adapted to bounded +HTTP(S) HLS. DelDOT uses official HTTPS HLS URLs; RTMP/ffmpeg remux is excluded +because subprocess transport does not inherit the Node redirect policy. Server +sessions reserve synchronously, cap memory and response bytes, reject redirects, +and abort on release/shutdown. No disk store or background sweep exists while +inactive. The panel paints the same video at at most 640px/15 fps; collapse stops +its paint loop. Camera deactivation destroys the decoder, and fatal playback +errors revert to the labeled frame fallback. Camera changes clear the old panel +frame. hls.js is imported only when an HLS camera starts. Two live sessions may +coexist with at most eight independent consumer leases each; no-access lease +expiry is 15 seconds. Closing one consumer leaves other consumers running. Encrypted/fMP4/byte-range playlists fail +closed. Performance and live agency reliability require recorded validation. + +## Wind forecast models + +Wind supports selectable GFS/IFS models with persisted model choice. Each fetch chooses the available cycle and forecast step nearest the current time; rows show both issue and valid UTC timestamps. Grid identities include model, cycle, forecast step and any requested scalar field. The six model/field cache slots each retain the last two issued grids for manifest/grid rollover, coalesce concurrent requests, retain last-good data on failures and retry no faster than once per minute. Model changes clear the old field immediately, cancel old acquisition and ignore superseded results. + +### Local Weather review candidate + +Weather combines the GFS/ECMWF surface forecast with three observation layers: +NOAA Rain radar (CONUS), Satellite clouds (regional GOES or slower global infrared), +and 15-minute lightning density (Americas and Pacific). One transient observed +clock drives all enabled observation rows. Earlier/Later use the sorted union of +non-suspended products' advertised times; each product selects its nearest frame +at or before the requested UTC time, never a future frame or an interpolation. +The maximum gap is 30 minutes for radar, regional infrared and lightning, and +3 hours for hourly global infrared. A missing eligible frame hides that product +and reports the gap; rows show actual displayed UTC time with synced/nearest labels. +Manifest rollover preserves the requested history time, even when frames expire. + +Latest follows each product's own newest frame, so its timestamps can differ. +Playback advances two seconds after all products settle, wraps, and stops with +fewer than two union times or when all products are suspended. Hidden documents, +reduced motion and unavailable imagery hosts suspend products. Re-enabling or +restoring a host joins the retained history target. The wind row explicitly says +“Forecast · does not follow history” while the observed clock is in history mode. +The catalog exposes `weatherClock` and destroys it with its lifetime signal. + +Source, opacity, coverage navigation and transport controls live in the WEATHER +panel's cards and timeline, not in the rows. The viewer clock is untouched. +Observation layers are off by default; share/persist includes appearance and product, while history +is transient and shared links open latest. Rendering retains the previous frame +when an incoming frame fails; no eligible historical frame instead hides imagery. + +Desktop wind now allows 7,200 baked native GPU paths (narrow viewports remain at +1,200). This doubles the maximum desktop geometry budget, not forecast resolution. +Temperature uses stronger fixed −40..50°C colors; the underlying 1° forecast and +numeric inspection values are unchanged. No volumetric cloud height or local rain +arrival prediction is claimed. NOAA source limits are documented in DATA_SOURCES. diff --git a/docs/DIRECTOR-CAMERA.md b/docs/DIRECTOR-CAMERA.md new file mode 100644 index 000000000..2481ba296 --- /dev/null +++ b/docs/DIRECTOR-CAMERA.md @@ -0,0 +1,110 @@ +# Director camera directions + +Version 4 scene documents can name geographic anchors and describe an explicit +camera move followed by a hold. Existing camera-pose shots still use the ordinary +camera flight. Import, playback, Load, Replay and seek accept the new directions; +[EDIT DETAILS](DIRECTOR-SHARING.md) captures anchors and move starts; a graphical +path editor remains a later extension. + +```json +{ + "version": 4, + "scenes": [{ + "id": "austin", + "title": "Across Austin", + "anchors": [ + { "id": "west", "title": "West viewpoint", "lat": 30.2672, + "lon": -97.76, "alt": 6000, "altitudeReference": "ellipsoid" }, + { "id": "east", "title": "East viewpoint", "lat": 30.2672, + "lon": -97.73, "alt": 7000, "altitudeReference": "ellipsoid" } + ], + "shots": [{ + "id": "crossing", + "title": "Cross the city", + "durationSec": 4, + "holdSec": 2, + "camera": { "anchorId": "east", "heading": 10, "pitch": -45, "roll": 0 }, + "move": { + "from": { "anchorId": "west", "heading": 350, "pitch": -45, "roll": 0 }, + "easing": "cubic-in-out" + }, + "visual": { "style": "normal" }, + "layers": {} + }] + }] +} +``` + +## One owner for each authored value + +An anchor is a scene-local geographic position, with a stable `id`, optional +`title`, latitude, longitude, height and explicit altitude reference. Each scene +accepts at most 1,024 anchors. IDs must be unique within that scene. References to +missing anchors fail validation before replacing a project. + +The shot's `camera` is its destination. It can be an inline pose or an +`anchorId` plus orientation. The optional `move.from` uses the same pose/reference +shape. References cannot also carry inline coordinates. They do not form chains. +Heading, pitch and roll belong to each camera pose, so two shots can look in +different directions from the same geographic anchor. Omitted orientation uses +heading 0, pitch −35 and roll 0 degrees. + +An explicit move requires `move.from`, `move.easing`, `durationSec` and `holdSec`. +Its duration is 0.2–86,400 seconds; the hold is 0–86,400 seconds. The destination +is not copied into another field. `linear` and `cubic-in-out` are the supported +easings. A shot without `move` retains the existing ordinary flight, even in a +version-4 file. Its destination may also reference an anchor. + +Capture continues to create ordinary camera-pose shots. Update Shot stores the +current viewport as an inline destination, preserving an explicit move's start +and easing; it does not change a shared anchor and thereby move other shots. +Editing imported directions and anchors currently means editing the scene JSON. + +## Coordinates and altitude + +Latitude/longitude use WGS84 degrees. Orientation uses the application's Cesium +heading/pitch/roll convention in degrees: heading rotates from local north, +negative pitch looks down, and zero pitch is horizontal. Camera positions use +meters above the WGS84 ellipsoid, matching `Cartesian3.fromDegrees` and captured +camera poses. These heights are not mean-sea-level elevations or heights above +the visible surface. + +Every anchor and every inline endpoint of an explicit move must say +`"altitudeReference": "ellipsoid"`. Ordinary legacy poses without that field +already use the same reference. Terrain-relative and mean-sea-level references +are rejected; no terrain request, default ground estimate or implicit conversion +is made. Authors must provide ellipsoidal heights with enough clearance for their +scene. The format does not promise collision avoidance or terrain following. + +During an explicit move, latitude and altitude interpolate between endpoints. +Longitude takes the shortest signed arc across the dateline; heading and roll +also take their shortest signed arcs. An exact 180-degree tie takes the negative +arc. This is an authored coordinate interpolation, not a geodesic or a camera +flight with an automatically raised arc. Endpoints are exact, including zero +pitch. Curved paths and look-at targets are later extensions. + +## Time, seeking and cancellation + +Load and Replay of an explicit move start at its authored `from` pose, regardless +of the current viewport. Play uses that same start. Both live playback and seek +use `sampleCameraMove`; a seek into the hold uses the exact destination. Backward +seeks do not depend on a prior camera position. Existing scene-pack media/reveal +rules can extend holds as before. + +Each active explicit move owns one animation-frame callback. Stop, replacement, +import, teardown, a navigation handoff or manual pointer/wheel input revokes that +callback and settles the move. Navigation also cancels a run during an authored +hold, so the next shot cannot retake the camera. Camera claims still respect +Cockpit's refusal. Already queued callbacks cannot move a replacement scene. +The timing diagnostic includes the active authored camera animation. + +The renderer-independent `gods-eye-view/director` export provides +`resolveCameraPose(scene, camera)`, `resolveCameraMove(scene, shot)` and +`sampleCameraMove(move, progress)`. These expect validated/normalized data. +Rendering and frame ownership live in `src/scenes/cameraMotion.js`; the existing +scene controller supplies camera application and lifecycle cancellation. + +Version-1/2/3 projects migrate to version 4 without converting their ordinary +shots into explicit moves. IDs, positions, durations, visual settings, packs and +source attribution survive. The bloom scale remains independent of the document +version; version-3 bloom is never interpreted as the older inverted scale. diff --git a/docs/DIRECTOR-DATA-PACKS.md b/docs/DIRECTOR-DATA-PACKS.md new file mode 100644 index 000000000..bf64efd0b --- /dev/null +++ b/docs/DIRECTOR-DATA-PACKS.md @@ -0,0 +1,115 @@ +# Director data packs + +Version-5 scene documents can declare `dataPacks` on a scene and select them by +`dataPackIds` on each shot. Import validates declarations without loading assets. +Loading, seeking or playing a shot acquires only its selected packs. A shot with +no pack IDs clears the preceding shot's packs. Existing scene recipes and assets +keep their current paths, notices and behavior. + +A pack manifest is version 1 and requires an ID, format, source, attribution and +placement. Sources describe storage; placement describes geography. Source names +refer to trusted application registrations, never scripts to import. A document +cannot supply request headers, keys, cookies, endpoints or executable handlers. + +```json +{ + "version": 5, + "scenes": [{ + "id": "example", + "title": "My geographic notes", + "dataPacks": [{ + "id": "notes", + "version": 1, + "format": "geojson", + "source": { "adapter": "assets", "path": "my-scene/notes.geojson" }, + "attribution": { "text": "Your name", "license": "Your asset's actual license" }, + "placement": { "altitudeReference": "ellipsoid" } + }], + "shots": [{ + "id": "overview", + "camera": { "lat": 30.2672, "lon": -97.742, "alt": 2600, "pitch": -70 }, + "durationSec": 4, + "holdSec": 2, + "dataPackIds": ["notes"] + }] + }] +} +``` + +For the standalone application, put that asset at +`public/scene-assets/my-scene/notes.geojson`. The registered `assets` source has +an explicit `/scene-assets/` base on the application's origin. Importing a file +from disk does not grant access to adjacent local files or infer a remote base. +Relative paths cannot contain traversal, query strings, fragments, URL syntax, +percent escapes or empty segments. Asset directories are served as static files; +this is not a new arbitrary-URL proxy. + +## Formats and placement + +- **`geojson`:** a UTF-8 `FeatureCollection`, served as `application/geo+json` or + `application/json`. Each feature needs a unique string `id`. Point, LineString + and Polygon (including holes) are supported. Coordinates are WGS84 + `[longitude, latitude, ellipsoidHeightMeters]`; missing height means zero, + which can be underground. Supply appropriate heights. Geometry properties + are ignored: they cannot select external icons, HTML, styling or scripts. + Placement is `{ "altitudeReference": "ellipsoid" }`. +- **`image`:** PNG served as `image/png`, at most 4096×4096 pixels, checked before + decoding. Placement is `{ "bounds": [west, south, east, north], "height": 300, + "altitudeReference": "ellipsoid" }`. Bounds must increase and cannot cross + the dateline. The image is a horizontal geographic rectangle at that height. +- **`media`:** MP4/WebM video or MPEG/Ogg/WAV/WebM audio, with the matching standard + MIME type. Placement is `{ "anchorId": "media-location" }`, referring to a + scene-local anchor with explicit ellipsoid height. A labelled marker locates + the media; an attribution card provides native, user-operated playback + controls. Media never autoplays. Codec support depends on the browser. D5 does + not synchronize media time with scene time or embed third-party players. + +Pack attribution always includes nonempty `text` and `license`; an optional +HTTPS `url` opens as a source link with no opener/referrer. Importing or sharing +an asset never changes its license. D5 adds no third-party content and preserves +all existing Nepal content and contributor notices. + +Optional `byteLength` specifies the exact expected byte count; optional `sha256` +is a lowercase hexadecimal SHA-256 digest checked before rendering. There are at +most 8 packs per scene, 8 MiB per asset, and 32 MiB of selected assets per shot. +GeoJSON additionally allows at most 2,000 features and 50,000 positions. +Transforms, terrain-relative placement, terrain collision avoidance, arbitrary +GeoJSON styles and archive extraction are not implemented. Explicit local files +can be shared through [JSON asset bundles](DIRECTOR-SHARING.md). + +## Loading and resource ownership + +The `director` package export provides `createAssetDirectorySource` and +`createDataPackSession`. The former receives an explicit trusted HTTP(S) +directory `baseUrl` and optional `fetchImpl`; it confines every relative asset +path to that directory. Cross-origin directories require CORS. Requests omit +credentials and referrers, reject redirects, and use `cache: 'no-store'`. +There is no persistent pack cache, offline fallback or silent substitute. A +missing, invalid, oversized or integrity-mismatched asset fails the shot's pack +load, removes partial results and reports a stable error without exposing a URL. +Successful loading leaves the attribution cards visible with the assets. + +`createApplicationTools({ sceneDataPacks: { sources } })` and +`new SceneDirector(viewer, style, data, { dataPacks: { sources } })` accept a +registry of source functions. Each receives `{ path, signal, maxBytes }` and +returns `{ bytes: Uint8Array, mimeType }`. Custom transports must honor the +signal, bound reads and return the real MIME type. They remain application code, +not scene document fields. Without registrations, referenced sources fail closed. + +The portable session receives format adapters separately. Each adapter receives +`{ pack, asset, anchors, signal }` and returns a resource with an idempotent +`dispose()`. Core's scene composition supplies Cesium geometry/image rendering +and text-only attribution/native media controls. The session applies a 15-second +load deadline and rejects late results, even when an adapter ignores abort. + +Stop, replacement, next-shot selection, scene release and destruction cancel +pending work, remove owned entities/cards, stop media and revoke object URLs. +Run completion releases packs with its run signal. Direct LOAD and seek retain +packs until the next operation or Stop. Resources are reacquired per shot; +there are no disabled pack refresh loops. `getDataPackState()` returns copied +status and resource counts for lifecycle diagnostics. + +Run `node scripts/qa-director-packs.mjs` against a credentialed local server to +exercise the real import/load/seek/Stop path with self-authored synthetic assets. +See [actions](DIRECTOR-INTERACTIONS.md) and [authoring/sharing](DIRECTOR-SHARING.md) +for the controls built on this manifest/loading boundary. diff --git a/docs/DIRECTOR-INTERACTIONS.md b/docs/DIRECTOR-INTERACTIONS.md new file mode 100644 index 000000000..10168078c --- /dev/null +++ b/docs/DIRECTOR-INTERACTIONS.md @@ -0,0 +1,66 @@ +# Director scene actions + +Version-6 scene documents can attach actions to stable GeoJSON feature IDs in a +shot's selected data packs. Existing versions 1–5 migrate without adding actions. +Import validates data and references; it does not load assets or execute actions. + +Add `interactions` to a shot, for example: + +```json +{ + "id": "read-outline", + "label": "About this outline", + "target": { "packId": "outline", "featureId": "boundary" }, + "action": { + "type": "card", + "text": "An authored explanation, displayed as plain text.", + "url": "https://example.org/source" + } +} +``` + +The target must be a feature in a GeoJSON pack selected by that shot. Points, +lines and polygons retain stable pack/feature identities. Assets load before +feature existence is checked; a missing feature refuses the entire action set. +Images and native media are not interaction targets in this version. + +| Action | Fields | Behavior | +| --- | --- | --- | +| `card` | `text`, optional `url` | Show plain text and an optional HTTPS source link; never HTML | +| `focus` | `anchorId` | Set a top-down camera pose at a scene anchor through camera ownership arbitration | +| `shot` | `shotId` | Load another shot in the same scene at its authored start | +| `layer` | `layerId`, boolean `enabled` | Request an explicit state through the ordinary layer admission path | + +There are at most 64 interactions per shot. Card text is limited to 4,096 +characters; source links cannot contain credentials, query strings or fragments. +No script, module, arbitrary fetch endpoint or request header is accepted. + +Actions appear after LOAD or seek finishes. Click a pack feature to select its +actions and focus the first button; choose a button explicitly to execute it. +Tab traverses buttons and Enter/Space activates them. The selected buttons have +visible outlines, and status feedback is announced to assistive technology. +There are no global keyboard shortcuts to collide with navigation or typing. +Drawing ownership blocks both pointer selection and action execution. Camera +focus uses existing navigation admission, including Cockpit restrictions. + +Actions are inactive during automatic playback and camera travel. They do not +introduce automatic branching or loops. A chain of user-triggered shot changes +is limited to 64 transitions; an explicit LOAD starts a new chain. Import/Stop, +replacement, playback and teardown remove selection, cards and picking handlers, +and abort pending layer requests. No per-frame interaction loop runs. + +A layer action must name a layer with an explicit baseline in the current shot. +A target shot must declare a baseline for every layer the departing shot can +change. LOAD and seek reapply those baselines and clear selection. Stop cancels +pending transitions; already completed layer changes remain visible, consistent +with ordinary scene controls. Camera focus is an immediate anchor pose, not a +new timeline segment; seek restores the authored camera pose. Scene JSON is not +modified by executing an action. + +The portable interaction session owns action admission/cancellation. The scene +interaction owner supplies accessible DOM and picking; pack renderers own the +feature identities and release them with their geometry. Layer/source admission +and camera arbitration remain with their existing owners. + +Author actions in scene JSON or the validated EDIT DETAILS draft. +[Import preview and file sharing](DIRECTOR-SHARING.md) preserve those declarations. Existing content, assets, notices and contributor credit are preserved. diff --git a/docs/DIRECTOR-SHARING.md b/docs/DIRECTOR-SHARING.md new file mode 100644 index 000000000..7748b2eb2 --- /dev/null +++ b/docs/DIRECTOR-SHARING.md @@ -0,0 +1,96 @@ +# Director authoring and file sharing + +Open Scenes and select a scene and shot. Existing capture, update, playback and +whole-project export controls remain available. Authored scene content, source +links, assets and contributor credit are preserved. + +## Review imports before applying + +IMPORT accepts scene JSON (including older supported versions) or a +`.gevbundle.json` asset bundle. A preview lists scenes, shots, data-pack attribution, +configured or unavailable sources, missing layer IDs and bundled bytes. Preview +makes no asset requests and does not change the current project. Configured +sources do not guarantee that a file exists: ordinary assets are checked on LOAD. +Bundle preview verifies the manifest and byte integrity; format decoding and +geometry limits are still enforced when rendering. + +Apply replaces the current project after validation and playback cleanup. Export +your current project first if you want to keep both. Cancel or Escape discards +the staged import. A changed project invalidates an open draft rather than being +overwritten. Invalid files leave the existing project and browser save intact. +The programmatic `importProjectFile(file)` API still applies trusted callers' +imports directly; the installed file chooser supplies the review step. + +## Edit scene details + +EDIT DETAILS provides validated JSON fields for: + +- Scene anchors and data-pack manifests. +- The selected shot's camera, optional move, duration, hold, pack IDs and actions. + +Capture camera as anchor adds a named geographic position to the draft. Set move +start to current camera creates a pose-to-pose move ending at the shot's existing +camera; Use ordinary flight removes that explicit move. Heights are meters above +the WGS84 ellipsoid. Apply details validates the complete project, preserves IDs, +layer declarations and content notices, and keeps the selected shot. Cancel +leaves the project unchanged. See [camera directions](DIRECTOR-CAMERA.md), +[data packs](DIRECTOR-DATA-PACKS.md) and [actions](DIRECTOR-INTERACTIONS.md) for +field definitions. This is a basic draft editor, not a node graph or path editor. + +## Share a selected scene + +SHARE SCENE exports only the selected scene. Download scene JSON preserves its +camera, timing, layers, anchors, manifests, interactions and attribution, but +contains no asset bytes. The recipient needs the referenced source registrations +and files. Existing EXPORT PRESETS continues to export the entire project. + +For a bundle, select the declared pack files or a folder, then Download asset +bundle. Folder paths match a manifest path either directly or after removing the +chosen root directory. Individual filenames must be unambiguous across all pack +sources; ambiguous or missing matches fail without downloading a partial bundle. +Previously imported bundle files can be reused. Export never automatically fetches +remote files or copies registered recipe media. Existing integrity declarations +must match the files you supply. + +Bundles include only declared data-pack files. Registered scene content, linked +media, map tiles and live data are not included. Source notices and licenses remain +in the document; packaging a file does not grant permission to redistribute it. + +## Bundle format and limits + +A bundle is uncompressed JSON with these fields: + +```json +{ + "format": "gev-scene-bundle", + "version": 1, + "project": { "version": 6, "scenes": [] }, + "assets": [] +} +``` + +Each asset contains `path`, `mimeType`, `base64` and lowercase hexadecimal `sha256`. +Export copies the document and rewrites pack references to the reserved +`scene-bundle` source, adding exact `byteLength` and `sha256`. Paths are confined +relative names; URLs, traversal, duplicate or unreferenced assets, unknown fields, +missing packs and mismatched hashes are rejected. Scene documents remain bounded +at 5 MiB. A bundle allows 50 MiB of JSON, 64 files, 8 MiB per file and 32 MiB of +asset bytes in total. Supported MIME types are JSON/GeoJSON, PNG, MP4/WebM video +and MPEG/Ogg/WAV/WebM audio. Normal pack format and geometry checks still apply. +There are no executable modules, request headers or credentials in the format. + +Imported bytes stay in memory for the current project and session. Stop releases +rendered resources while retaining these bytes for replay. Project replacement +or application teardown releases them. Only scene JSON is saved in browser +storage: **reimport the bundle after reloading the app**. Missing bundle bytes +fail explicitly, with no network fallback. This is file sharing, not a storage +service or an offline basemap. + +Portable helpers are exported through `gods-eye-view/director`: `parseSceneShare`, +`readSceneShare`, `createSceneBundle`, `createBundleAssets`, `describeSceneShare`, +`editSceneDetails` and `selectSceneDocument`. Loading and UI remain separate owners. +`getSharingState()` reports copied dialog/asset counts for lifecycle diagnostics. + +Run `node scripts/qa-director-sharing.mjs` against the local server for installed +controls, cancellation, stale drafts, export/import round trips, resource cleanup +and narrow-screen acceptance. Fixtures are synthetic and carry their own notices. diff --git a/docs/DIRECTOR.md b/docs/DIRECTOR.md new file mode 100644 index 000000000..a2ca13da7 --- /dev/null +++ b/docs/DIRECTOR.md @@ -0,0 +1,108 @@ +# Director: reusable scene playback + +Director is the scene playback system. Ordered shot execution, authored timing and playback clocks are separated +from the scene editor and application rendering. This document +records implemented camera directions, data packs, declarative interactions and +file sharing, along with the remaining extensions. + +## Implemented boundary + +`src/director/playback.js`, exported as `gods-eye-view/director`, provides: + +- `buildPlaybackQueue(scenes, startSceneId, { single })`: ordered scenes/shots, + retaining the existing round-robin behavior. +- `playSceneQueue(queue, { token, adapter, previousScene, releaseOnFinish })`: + sequential execution, cancellation checks and scene release. + +The runner imports no renderer, UI, storage, recipe or dataset. An adapter supplies +these phases, in order: `selectShot`, `applyVisual`, `applyLayers`, `travel`, +`settle`, `hold`, `completeShot`. Each receives `{ scene, shot, index, total, +token }`. It also supplies `releaseScene(scene, token?)` and optionally `complete()`. +Callbacks may return promises. Each playback invocation requires its own adapter +state and token; the caller owns camera arbitration and concurrent-run refusal. + +The runner checks cancellation after each phase. Adapters must also pass the +abort signal or liveness predicate into pending work: a check between phases +cannot stop a camera flight or network request already in progress. Cleanup +between scenes and on preview exit runs without an aborted token. A refused +initial handoff starts no shot. Final cleanup runs on completion, Stop or failure; +`releaseOnFinish: false` retains the final scene for ordinary playback. Exceptions +propagate so the caller can restore its controls. Empty/already-cancelled queues +acquire no resources. This low-level API expects normalized scene objects; +untrusted file validation belongs at the import boundary. + +`src/scenes/playbackAdapter.js` connects this runner to the existing +`SceneDirector`. The latter still owns editor state, saved-project import/export, +camera ownership and asynchronous load/seek arbitration. Pure seek calculations +live in `src/director/timeline.js`; `src/director/clock.js` owns the run/load/shot +tickers, hold deadlines, snapshots and clock subscriptions. Stop settles pending +holds immediately, and revoked tick callbacks cannot affect a replacement clock. +`getPlaybackTimingState()` exposes copied snapshots and an active-timer count for +lifecycle diagnostics without exposing timer handles. + +The `director` export also provides `sceneTimingForShot`, `sceneSeekState`, +`cameraAtProgress` and `createPlaybackClock`. Timeline functions receive duration +and hold resolvers; the clock receives timing, running-state and progress callbacks. +They import no renderer, storage, recipe or dataset. + +`src/scenes/shotPresentation.js` prepares layer/seek context and resolves holds +and map preferences through a scene-pack registry. The `scenes` export provides +`createScenePackRegistry({ recipes, adapters })`; pass the result as `scenePacks` +in the SceneDirector constructor options. Trusted adapters can supply +`minimumHoldSec(states)`, `resolveVisual(shot, visual, isMapStackAvailable)` and +`cancelMotion(getLayerModule)`. Default composition registers the existing Nepal +presentation rules. These are code-level composition hooks, not executable +modules imported from scene files. Existing media-owner waits remain bounded. + +All authored scenes, assets, IDs, source links, attribution and existing JSON +projects are preserved. The Nepal sequence remains the contribution introduced +by @manjunath22466 in #590. Its clips use source links/embeds; comparison images +and river coordinates are bundled. See the +[event pack provenance](../public/events/bhote-koshi-2026/README.md). + +## Next changes, in order + +1. **Timeline and content separation — implemented.** Pure duration/seek + calculations, an owned clock and registered presentation rules preserve + existing recipes and content. Tests cover direct load, forward/backward seek, + replay, bounded media waits and cancellation at pending transitions. +2. **Versioned scene document — implemented for existing camera-pose shots.** + [The scene document](SCENE-DOCUMENT.md) preserves version-1/2/3 imports. Bounded validation + rejects malformed files before replacing current state; legacy migration + preserves IDs, pack bindings and visual edits. Unreadable saved files are + protected from fallback writes. Camera anchors, pack manifests and actions + receive stable IDs with their respective later format extensions. +3. **Camera directions — implemented for pose-to-pose moves.** + [Version 4](DIRECTOR-CAMERA.md) adds scene-local geographic anchors, explicit + start/destination poses, easing, duration and holds. Playback and seek share + the same sampler. Ellipsoidal heights are explicit; terrain-relative input + is rejected. Existing shots retain ordinary flights. Basic anchor/move authoring is available through EDIT DETAILS; curved paths and + look-at targets remain later extensions. +4. **Data packs and placement — implemented for bounded assets.** + [Version 5](DIRECTOR-DATA-PACKS.md) defines a pack manifest with format/version, + source, attribution/license and optional integrity/size metadata. It distinguishes + registered asset directories from geographic coordinates, image bounds and + media anchors. GeoJSON, PNG and native media adapters load with byte/time + limits and explicit ellipsoid heights. Stop and replacement release resources. + Paths resolve against a trusted directory base; missing/offline assets fail + explicitly. File bundles are available; transforms and terrain-relative placement + remain future extensions. Scene files carry no credentials or executable modules. +5. **Declarative interactions — implemented.** [Version 6](DIRECTOR-INTERACTIONS.md) + connects selected feature IDs to accessible text/source cards, anchor focus, + shot seek and admitted layer changes. References are validated and pending + actions cancel on Stop, replacement or teardown. Scene files contain no + JavaScript or arbitrary HTML; actions require explicit user input. +6. **Sharing and basic authoring — implemented.** [Authoring and sharing](DIRECTOR-SHARING.md) + adds import preview, missing-source/layer diagnostics, validated scene/shot + drafts and selected-scene JSON or explicit-file bundles. Pack attribution is + preserved. Bundle bytes last for the session and must be reimported after a + reload. A future node graph can author the same document without becoming a + playback or format requirement. + +Each step must preserve existing scene editing, keyboard playback, camera +arbitration, layer cleanup, media timing and provider fallback. Acceptance includes +portable runner tests, existing Director regressions and browser playback with +Stop/seek/replay, plus tracking and voice checks. Use reproducible local fixtures +for failures and cancellation, alongside live visual checks for actual content. + +Declarative actions are implemented in version 6; see [scene actions](DIRECTOR-INTERACTIONS.md) for supported targets, execution and reset semantics. diff --git a/docs/INFRASTRUCTURE-LAYERS.md b/docs/INFRASTRUCTURE-LAYERS.md index d29e356f9..76567e605 100644 --- a/docs/INFRASTRUCTURE-LAYERS.md +++ b/docs/INFRASTRUCTURE-LAYERS.md @@ -36,7 +36,8 @@ const layers = createInfrastructureLayers({ | `governorRequestRender` | `(reason)`; request a frame through the existing render scheduler | Each returned layer supports `init(viewer)`, `enable(viewer)`, `disable(viewer)`, -`update(viewer)`, `destroy(viewer)`, `getStats()` and `getLodDiagnostics()`. +`update(viewer)`, `destroy(viewer)`, `getStats()`, `getLodDiagnostics()` and +`getAnalystRecords()`. Use the same viewer for the instance's entire lifetime. Each viewer/context/overlay host permits one live instance per layer ID; destroy an old instance before replacing it. Separate applications may use identical IDs with separate hosts. diff --git a/docs/KNOWN-ISSUES.md b/docs/KNOWN-ISSUES.md index 92c92c1f9..e41623cc6 100644 --- a/docs/KNOWN-ISSUES.md +++ b/docs/KNOWN-ISSUES.md @@ -1,6 +1,6 @@ # KNOWN ISSUES -Updated: July 8, 2026 +Updated: September 22, 2026 This file tracks active runtime issues only. @@ -78,6 +78,56 @@ Status: Open (owner-accepted 2026-07-08, documented) --- +### Weather layers: coverage and meaning +Status: Open (source limits, by design) + +- **Rain radar covers the contiguous United States only.** It shows MRMS + reflectivity in dBZ, not rainfall rate or a forecast; a gap in coverage does not + mean no precipitation. +- **Lightning density is a ground-network grid, not GLM flashes.** It is NOAA's + 15-minute density product derived from Vaisala NLDN/GLD360 on an approximately + 8 km grid, for the Americas and Pacific only (110°E across the dateline to 0°, + 25°S–80°N). It is not a live strike counter or an all-clear. +- **Cyclone advisories cover NOAA's basins only:** the Atlantic and the + eastern/central North Pacific (NHC and CPHC). Storms elsewhere do not appear. + The cone is forecast-center uncertainty, not storm size. +- **Satellite clouds:** global infrared is hourly with typically 2–3 hours of + source latency. Clouds only is a brightness filter, not a cloud mask. +- **Wind is a forecast.** The animation flows through one forecast on an + approximately 1° grid and does not advance forecast time or follow the + observed-history timeline. +- **History is not shared.** Share links carry the weather layers and their + settings but open at Latest. +- **3D Tiles detail window during history playback:** when a frame's detail image + is slow to arrive, the window may fall back to the coarser full-extent image + until it does. +- Native hardware GPU behavior of the wind and weather renderers is not yet + verified. + +--- + +### Satellite passes and analyst answers +Status: Open (by design) + +- Pass predictions search the next 24 hours for satellites in the loaded catalog. + Visibility is a geometric estimate (satellite sunlit, observer's Sun at or + below −6°); it ignores weather, satellite brightness and orbital-element age. +- Analyst counts and ranks cover a bounded set of loaded records (by default + 2,000 per layer for satellites, datacenters and dams), so omitted records can + change a nearest or count answer. Satellite distance is ground distance. + +--- + +### Live camera video (HLS) +Status: Open (limits) + +- At most two live-video sessions run at once. RTMP-only sources and encrypted, + fMP4 or byte-range playlists are not supported. +- When live video fails, the camera falls back to its labeled still, Street View + or placeholder frame, which is not live video. + +--- + ## Closed / Intentional (for clarity) ### Proxy SSRF and error-surface hardening gaps @@ -118,5 +168,14 @@ Context: converted to **live NASA FIRMS data** on 2026-07-16: the `/api/firms` proxy merges three VIIRS NRT sources (trailing 24 h, 30 min cache, serve-stale-on-failure) and the bundled snapshot was deleted. Requires a free server-side `FIRMS_MAP_KEY`; without it - the layer shows a KEY REQUIRED state. -- Weather radar is still held out of OSS v1 after QA found the previous overlay did not provide reliable visible value. + the layer row reads "Needs FIRMS_MAP_KEY — add it in Provider Settings". + +--- + +### Weather radar held out of the open-source release +Status: Closed — observed rain radar shipped (September 2026) + +Context: +- Rain radar, Satellite clouds, Lightning density, Wind and Cyclone advisories + are in the Weather group of Data Layers. Their current limits are listed under + "Weather layers: coverage and meaning" above. diff --git a/docs/LOCAL-RECEIVERS.md b/docs/LOCAL-RECEIVERS.md new file mode 100644 index 000000000..ee75d9a70 --- /dev/null +++ b/docs/LOCAL-RECEIVERS.md @@ -0,0 +1,82 @@ +# Local receivers + +The Local ADS-B layer draws aircraft heard by your own receivers. It has two +inputs, and it can use both at once. + +| Input | What it is | Bands | +| ------------ | ----------------------------------------------------------------------------------------------------------------------------------- | -------------------- | +| Browser SDR | A USB RTL-SDR opened by the browser through WebUSB (Radio panel, Local RTL-SDR card). Decoding runs in the page. | 1090 MHz | +| Decoder feed | The `aircraft.json` served by a decoder you run: dump1090-fa, readsb or tar1090 (1090 MHz), or dump978-fa + skyaware978 (978 MHz). | 1090 MHz, 978 MHz UAT | + +Aircraft from both inputs are merged by ICAO address. The newest position +wins, and the click card names every band and source that heard the aircraft +in the last 60 s. Aircraft heard only on 978 MHz UAT draw with a thin ring. + +Local aircraft usually lead their public twins. The public Flights layer +renders positions about one poll interval (~30 s) behind so it can interpolate +smoothly between fixes, while local receiver aircraft are shown as heard. An +aircraft in both layers therefore draws twice, the magenta local marker ahead +of the public one; both markers are drawn on purpose. + +## Which to use + +- **One plain RTL-SDR dongle, desktop Chrome or Edge:** use the browser SDR. + Nothing else to install. +- **A dual-band board, a Raspberry Pi feeder, or a dongle already used by a + decoder:** use a decoder feed. A USB dongle can be opened by only one program + at a time, so a dongle that dump1090 or dump978 owns cannot also be opened by + the browser. + +## Configuring feeds + +Feeds are set in the server environment only (`.env`), never in the browser: + +```sh +LOCAL_RECEIVER_FEEDS=1090=http://localhost:8080/data/aircraft.json,978=http://localhost:8978/data/aircraft.json +``` + +Each entry is `band=url`, where `band` is `1090` or `978`. The URL must: + +- use `http` or `https`; +- point at loopback, a private (RFC1918) address, `localhost` or a `*.local` + name. Public addresses, link-local addresses (including `169.254.169.254`), + IPv6 and other host names are refused; +- have a path ending in `aircraft.json`, with no credentials, query or + fragment. + +An entry that breaks a rule is logged when the server starts, shown as +`invalid` and never fetched. Restart the server after changing the value. + +The server reads every feed about once a second while the Local ADS-B layer is +on. A feed is `live`, `stale` (its own `now` is more than 10 s old, usually a +stopped decoder), `unreachable` or `invalid`. The Layers panel row and the +Local RTL-SDR card show these states. + +## Example: dump1090-fa and dump978-fa on macOS or Linux + +Write each decoder's JSON to a directory, then serve the directory on +localhost. Each command keeps running, so start each in its own terminal: + +```sh +# 1090 MHz +dump1090-fa --device-index 0 --write-json /tmp/adsb1090 +python3 -m http.server 8080 --bind 127.0.0.1 --directory /tmp/adsb1090 + +# 978 MHz UAT: dump978-fa decodes, skyaware978 writes aircraft.json +dump978-fa --sdr driver=rtlsdr,rtl=1 --raw-port 30978 +skyaware978 --connect localhost:30978 --json-dir /tmp/adsb978 +python3 -m http.server 8978 --bind 127.0.0.1 --directory /tmp/adsb978 +``` + +```sh +LOCAL_RECEIVER_FEEDS=1090=http://localhost:8080/aircraft.json,978=http://localhost:8978/aircraft.json +``` + +A board with two identical-serial channels, such as the Nooelec FlyCatcher, +cannot be told apart by serial number. Select each channel by index: +`--device-index ` for dump1090-fa and `--sdr driver=rtlsdr,rtl=` for +dump978-fa. `rtl_test` lists the indexes. + +A tar1090 or readsb install on a Raspberry Pi already serves +`http:///tar1090/data/aircraft.json`. Use the Pi's private address +or its `.local` name. diff --git a/docs/SCENE-DOCUMENT.md b/docs/SCENE-DOCUMENT.md new file mode 100644 index 000000000..f6dc66636 --- /dev/null +++ b/docs/SCENE-DOCUMENT.md @@ -0,0 +1,105 @@ +# Scene document format + +Scenes exports a UTF-8 JSON project. Version 5 adds [data packs](DIRECTOR-DATA-PACKS.md) +and is the write format. Versions 1, 2, 3, 4 and unversioned legacy files migrate on +import without converting their existing shots into authored moves. Unknown versions or unsupported fields are rejected with +a field path before the current project, selection or saved bytes change. + +```json +{ + "version": 5, + "scenes": [{ + "id": "my-scene", + "title": "My scene", + "shots": [{ + "id": "my-shot", + "title": "Arrival", + "durationSec": 4, + "holdSec": 1, + "camera": { "lat": 51.5, "lon": -0.12, "alt": 800, + "heading": 0, "pitch": -35, "roll": 0 }, + "visual": { "style": "normal" }, + "layers": { "traffic": { "enabled": true } } + }] + }] +} +``` + +## Fields and migration + +The root requires `scenes` (an array, which may be empty). Optional root fields +are `version`, `createdAt`, `updatedAt` and `installedBuiltInSceneIds` (string IDs). +Each scene requires a `shots` array; optional fields are `id`, `title`, +`releaseLayerIds`, `appliedShotPacks` and version-4 `anchors`. A pack marker has `id`, optional numeric +`version` and `shotBindings` (original shot title to saved shot ID). These markers +retain the editor's existing pack-update and rename behavior. + +Shots accept `id`, `title`, `durationSec`, `holdSec`, `camera`, `visual`, `layers`, +`sourcePackId`, `sourcePackVersion` and version-4 `move`. Scene IDs are unique within the project; +shot IDs are unique within their scene. Existing IDs and pack bindings survive +migration. Missing IDs are generated once and persisted by the next save/export. +Missing titles and optional camera/visual fields receive the editor's defaults. +Empty scenes and intentionally empty projects remain empty. + +Camera latitude/longitude and heading/pitch/roll use degrees. Altitude uses +meters above the WGS84 ellipsoid. Import preserves finite heights below +100 meters and zero pitch, which previously fell through to defaults. Anchors and explicit moves require the `ellipsoid` altitude reference; +terrain-relative inputs are rejected. See the camera contract for exact semantics. +Flight durations retain the editor's minimum of 0.2 seconds and its 4-second +fallback for zero; holds may be zero. + +Visual fields are `style`, `mapStack`, `styleParams`, `bloom`, `sharpen`, `hud`, and +`detection`, and `scope`. Bloom has `enabled`, `intensity`, `version`; sharpen has `enabled`, +`intensity`; HUD has `visible`, `variant`; detection has `mode`, `density`, +`allocation`, `fadePct` and `outsideOpacityPct`. Scope has `enabled`, `featherPct`. +The latter settings were written by Update Shot but previously lost during +normalization; they now survive import and capture. +Version-1/2 bloom without an explicit scale version uses the original inverted +scale and migrates once to scale 2. The scene document and bloom scale versions +are separate. Legacy numeric strings are accepted for numeric fields. + +Layer entries accept a boolean shorthand or `{ "enabled": true, "params": {} }`. +Parameters and style parameters retain nested JSON data. They are interpreted by +already registered components; importing a file does not fetch its URLs, register +modules, evaluate code or apply its layers. Unsupported structural fields are +rejected instead of silently dropping potential edits. Map-stack selection +retains the existing registered-stack behavior. + +## Validation limits + +`gods-eye-view/director` exports `parseSceneDocument(text)`, +`validateSceneDocument(project)`, `stringifySceneDocument(project)`, +`SceneDocumentError`, `SCENE_DOCUMENT_VERSION` and `SCENE_DOCUMENT_LIMITS`. +Validation is independent of the renderer, storage and recipes. Parsing checks +UTF-8 size before JSON decoding; the file importer also checks file size before +reading it. Migration/defaults live separately in `src/scenes/project.js`. + +Limits are 5 MiB, 256 scenes, 10,000 total shots, 10,000 entries per collection, +24 levels of nesting, 200,000 visited values, 65,536 characters per JSON string, +256 characters per field/ID, and 4,096 characters per title. Numeric values must +be finite. Camera limits are latitude ±90, longitude ±180, altitude −12,000 to +1 billion meters, heading/roll ±360 and pitch ±90; durations/holds are at most +86,400 seconds. Post-processing values are bounded and normalized to the existing +slider ranges. Object prototype keys are refused at every depth. + +An invalid import leaves the current project and playback untouched. A valid +import cancels and settles pending playback before replacing the project. If +multiple files are read concurrently, only the newest request can replace it. +Disposal prevents a pending import from publishing. + +The browser storage key remains `godsEyeView.sceneProject.v2` for compatibility; +that key's suffix is not the document version. An unreadable saved project stays +in storage. The app supplies temporary defaults and a visible warning, but blocks +saving over the original bytes until a valid file is explicitly imported. Export +can preserve temporary edits. Storage writes use the same validation before replacing saved bytes; invalid +edits and storage write failures surface an unsaved toast. + +Only authored project fields belong in this file. Runtime clocks, camera flights, +loading progress and run diagnostics remain separate. Camera anchors and authored +moves arrived in version 4; data packs follow in version 5. Declarative +interactions remain a planned extension. No scene assets, source links, licenses or contributor attribution +change with this document boundary. + +Version 5 additionally accepts scene `dataPacks` and shot `dataPackIds`, as +defined in [data packs](DIRECTOR-DATA-PACKS.md). Version-4 camera documents +continue to import without adding any packs. diff --git a/docs/UI-OWNERSHIP.md b/docs/UI-OWNERSHIP.md new file mode 100644 index 000000000..8d24215c7 --- /dev/null +++ b/docs/UI-OWNERSHIP.md @@ -0,0 +1,35 @@ +# Application UI ownership + +`src/ui/applicationShell.js` constructs controls, connects their explicit inputs +and coordinates shutdown. `shellFacade.js` preserves the methods used by layers, +scene playback and voice. It delegates; new behavior belongs with its owner. + +| Owner | Responsibility | +| --- | --- | +| `navigationController.js` | Navigation generation, tracking release and camera authority | +| `locationNavigation.js` | Destination lookup/selection, orbit, world jumps and globe-reset completion | +| `cockpitCoordinator.js` | Cockpit entry/rollback, readouts and the single Display portal | +| `visualSettings.js` | Effects, detection overrides, visual restoration and render-loop lifetime | +| `panelChrome.js` | Disclosure, docking, layout and Cockpit panel restoration | +| `aircraftDisplay.js` | Shared commercial/military 3D display preferences and controls | +| `layerBindings.js` | Data-manager attachment, selected-tracker adoption and camera-entry listeners | +| `displayBindings.js` | Keyboard/display subscriptions and frame-rate monitor lifetime | +| `shareRestoration.js` | Initial share/layer restoration and cancellation | +| `shellFeedback.js` | Loading feedback, notices and toast lifetime | + +Owners receive named services, elements, operations and readers. They do not +receive the application shell itself. Readers resolve a replaceable collaborator +at use time; operations cross an ownership boundary without copying its state. +The facade exposes existing properties as delegates rather than duplicate state. + +Shutdown has two phases. First revoke input, deferred navigation, camera-entry +listeners, lookups, timers and rendering work. Then await Context restoration, +release sensor overrides while the manager is still attached, detach layer +services and destroy scene resources. Late callbacks cannot acquire the camera. +Manager replacement also releases subscriptions and the previous Directions +module even if the replacement does not provide a Directions layer. + +Source-contract tests follow both sides of delegated wiring. Lifecycle tests +exercise pending reset cancellation, stale camera callbacks, replacement and +idempotent teardown. Browser acceptance covers the composed application, including +share restoration, scene commands, navigation, Cockpit, display and voice. diff --git a/docs/VOICE-OWNERSHIP.md b/docs/VOICE-OWNERSHIP.md new file mode 100644 index 000000000..d5553df00 --- /dev/null +++ b/docs/VOICE-OWNERSHIP.md @@ -0,0 +1,48 @@ +# Realtime voice ownership + +`realtimeController.js` composes the session and owns its status, UI bindings and +overall lifetime. It coordinates startup and shutdown. `realtimeFacade.js` +preserves existing methods and properties by delegation, without copying state. +The session adapter, action runner and backend interfaces remain unchanged. + +| Owner | State and responsibility | +| --- | --- | +| `realtimeConnection.js` | Start generation, request cancellation, peer/data channel, acquired microphone stream and playback element | +| `realtimeTurns.js` | Active and superseded responses, pending confirmations, deduplicated calls and action cancellation | +| `realtimeRadio.js` | Speaker ducking, prepared playback, stronger-action reservations and playback observers | +| `realtimeInput.js` | Physical Space gesture, microphone mute, input/output meters and their frame/listener lifetime | +| `realtimeCost.js` | Next-session preferences and the current session's model-bound meter | +| `realtimeViewport.js` | One retained image, bounded deletion identities and capture generation | +| `realtimeDiagnostics.js` | Bounded error history and sanitized optional diagnostics | + +Pure input policy, preferences and protocol-response policy have separate modules. +Owners receive named readers, operations or focused collaborators. Cross-owner +cancellation uses operations; response handling does not own Radio's reservations +or viewport deletion bookkeeping. + +Shutdown first invalidates acquisition and action work, then closes transport, +stops audio analysis, releases media and clears conversation/input state. Full +removal also detaches UI, keyboard, annotation and Radio observers. Radio takeover +retains confirmed playback through that same shutdown path. A late offer, peer callback, +viewport capture or cancelled meter frame cannot enter a replacement session. +Action and post-capture continuations retain their conversation identity before +publishing output, queueing a response or changing status. + +Behavioral invariants remain in force: a 500 ms Space hold claims push-to-talk; +short control taps and text entry remain native; a click-started session stays +open-mic. Every accepted or refused tool call receives its terminal output once. +New typed input supersedes old intent. Radio waits for the spoken confirmation and +verified muted playback. A live cost meter stays bound to its negotiated model, +even when the next-session preference changes. + +Run the unit suite and both live recorded-audio modes against a configured local +server: + +```sh +node scripts/qa-voice-wav.mjs http://localhost:4173 +node scripts/qa-voice-wav.mjs http://localhost:4173 --push-to-talk +``` + +The second mode uses the actual Space shortcut, verifies microphone acquisition +and release, and checks the same globe/Radio outcome. Tracking and scene-control +acceptance exercise voice's shared application operations separately. diff --git a/package-lock.json b/package-lock.json index c24590e4a..17bb0691e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,9 +9,13 @@ "version": "0.1.1", "license": "MIT", "dependencies": { + "@jtarrio/signals": "^0.10.0", + "@jtarrio/webrtlsdr": "^3.0.6", "@mapbox/vector-tile": "^3.0.0", + "@meri-imperiumi/eccodes-wasm": "^2.48.2", "cesium": "^1.124.0", "egm96-universal": "^1.1.1", + "hls.js": "^1.7.3", "mgrs": "^2.1.0", "pbf": "^5.1.2", "satellite.js": "^6.0.2" @@ -1059,6 +1063,22 @@ "url": "https://opencollective.com/libvips" } }, + "node_modules/@jtarrio/signals": { + "version": "0.10.1", + "resolved": "https://registry.npmjs.org/@jtarrio/signals/-/signals-0.10.1.tgz", + "integrity": "sha512-X6tJOugEATYH9KJy6j2feEBVCUmRv1U9SSbg9ITQZCx/Qruw2fE2zsS1HKH3yOsxrZBE+eQTGM+d0roX4xuDdw==", + "license": "Apache-2.0" + }, + "node_modules/@jtarrio/webrtlsdr": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/@jtarrio/webrtlsdr/-/webrtlsdr-3.0.6.tgz", + "integrity": "sha512-+P8dsbXQ/6Mwru/vV613yHH68nHFyUJ9zPK68hE/Hh2F3jwyirUAjjBtIAfN/MlJbFioMJ3NS6dMGrRj9deFvw==", + "license": "Apache-2.0", + "dependencies": { + "@jtarrio/signals": "^0.10.0", + "@types/w3c-web-usb": "^1.0.10" + } + }, "node_modules/@mapbox/point-geometry": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@mapbox/point-geometry/-/point-geometry-1.1.0.tgz", @@ -1076,6 +1096,24 @@ "pbf": "^5.0.0" } }, + "node_modules/@meri-imperiumi/eccodes-wasm": { + "version": "2.48.2", + "resolved": "https://registry.npmjs.org/@meri-imperiumi/eccodes-wasm/-/eccodes-wasm-2.48.2.tgz", + "integrity": "sha512-Z7rD3xInomPG7FS97ORD1UGKAdgeeRP9ofa9k4m8d+k2sDfDQeAjTzvs9UOndyaZovaSbEQeIoNX8gTmQNhiSA==", + "cpu": [ + "x64", + "arm64" + ], + "license": "Apache-2.0", + "os": [ + "darwin", + "linux", + "win32" + ], + "engines": { + "node": ">=24.0.0" + } + }, "node_modules/@puppeteer/browsers": { "version": "3.2.2", "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-3.2.2.tgz", @@ -1518,6 +1556,12 @@ "license": "MIT", "optional": true }, + "node_modules/@types/w3c-web-usb": { + "version": "1.0.14", + "resolved": "https://registry.npmjs.org/@types/w3c-web-usb/-/w3c-web-usb-1.0.14.tgz", + "integrity": "sha512-Qu3Nn6JFuF4+sHKYl+IcX9vYiI40ogleXzFFSxoE1W94rG98o/kXs8uJ0QSfFzuwBCZWlGfUGpPkgwuuX4PchA==", + "license": "MIT" + }, "node_modules/@zip.js/zip.js": { "version": "2.8.18", "resolved": "https://registry.npmjs.org/@zip.js/zip.js/-/zip.js-2.8.18.tgz", @@ -1944,6 +1988,12 @@ "integrity": "sha512-bzh50DW9kTPM00T8y4o8vQg89Di9oLJVLW/KaOGIXJWP/iqCN6WKYkbNOF04vFLJhwcpYUh9ydh/+5vpOqV4YQ==", "license": "MIT" }, + "node_modules/hls.js": { + "version": "1.7.3", + "resolved": "https://registry.npmjs.org/hls.js/-/hls.js-1.7.3.tgz", + "integrity": "sha512-MsPlx6yVW4Qv4C7mEVou4/gk/5cN2dVxOTnrNjPSmyH2f0Ln+/UkG10Ax1PE6OvrmTVPKgQYozTtBaPOuCzq7A==", + "license": "Apache-2.0" + }, "node_modules/http-errors": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", diff --git a/package.json b/package.json index a919399a1..3e80dc55e 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "gods-eye-view", "private": true, "version": "0.1.1", - "description": "A real-time intelligence console for planet Earth \u2014 photorealistic 3D globe, live aircraft/ships/satellites/earthquakes/CCTV, and hands-free voice control. Runs in a browser.", + "description": "A real-time intelligence console for planet Earth — photorealistic 3D globe, live aircraft/ships/satellites/earthquakes/CCTV, and hands-free voice control. Runs in a browser.", "type": "module", "license": "MIT", "author": "Bilawal Sidhu", @@ -47,9 +47,13 @@ "qa:transit": "node scripts/qa-transit.mjs" }, "dependencies": { + "@jtarrio/signals": "^0.10.0", + "@jtarrio/webrtlsdr": "^3.0.6", "@mapbox/vector-tile": "^3.0.0", + "@meri-imperiumi/eccodes-wasm": "^2.48.2", "cesium": "^1.124.0", "egm96-universal": "^1.1.1", + "hls.js": "^1.7.3", "mgrs": "^2.1.0", "pbf": "^5.1.2", "satellite.js": "^6.0.2" @@ -142,6 +146,7 @@ "./ui/scenes": "./src/ui/scenes.js", "./ui/shell": "./src/ui/applicationShell.js", "./ui/styles": "./src/ui/styles.js", + "./director": "./src/director/playback.js", "./scenes": "./src/scenes/director.js", "./sources/live": "./src/sources/live/index.js", "./layers/flights": "./src/layers/flights/index.js", @@ -149,6 +154,8 @@ "./aircraft": "./src/layers/aircraft/index.js", "./layers/vessels": "./src/layers/vessels/index.js", "./layers/earthquakes": "./src/layers/earthquakes/index.js", + "./layers/recent-imagery": "./src/layers/recentImagery/index.js", + "./layers/perimeters": "./src/layers/perimeters/index.js", "./sources/firms-csv": "./src/data/firmsCsv.js", "./layers/firms": "./src/layers/firms/index.js", "./layers/satellites": "./src/layers/satellites/index.js", @@ -220,6 +227,7 @@ "./layers/bikeshare/source": "./src/layers/bikeshare/source.js", "./layers/cctv/source": "./src/layers/cctv/source.js", "./layers/earthquakes/source": "./src/layers/earthquakes/source.js", + "./layers/perimeters/source": "./src/layers/perimeters/source.js", "./layers/firms/source": "./src/layers/firms/source.js", "./layers/installations/source": "./src/layers/installations/source.js", "./layers/launches/source": "./src/layers/launches/source.js", diff --git a/scripts/check-import-directions.mjs b/scripts/check-import-directions.mjs index d84bc18ac..a5e61f039 100644 --- a/scripts/check-import-directions.mjs +++ b/scripts/check-import-directions.mjs @@ -35,9 +35,12 @@ const portableExport = (key) => /^\.\/layers\/(?:flights|military|vessels)\/(?:records|ingestion)$/.test( key, ) || - ['./voice/action-schemas', './voice/session', './data/lifecycle'].includes( - key, - ); + [ + './director', + './voice/action-schemas', + './voice/session', + './data/lifecycle', + ].includes(key); /** Check every runtime file, plus transitive portable/source graphs, independently of bundler reachability. */ export function checkImportDirections(root) { diff --git a/scripts/check-package-boundaries.mjs b/scripts/check-package-boundaries.mjs index 3655cd998..28627e4ac 100644 --- a/scripts/check-package-boundaries.mjs +++ b/scripts/check-package-boundaries.mjs @@ -89,6 +89,10 @@ export async function checkPackageBoundaries(root) { const seen = new Set(); await build({ root, + // Keep this gate out of a running dev server's dependency cache + // (node_modules/.vite): a build there re-optimizes dependencies and the + // dev server's workers then fail with 504 "Outdated Optimize Dep". + cacheDir: path.join(root, 'node_modules/.vite-boundaries'), configFile: false, envFile: false, publicDir: false, @@ -115,7 +119,12 @@ export async function checkPackageBoundaries(root) { assetsInlineLimit: 0, rollupOptions: { input, - external: group.external, + // A declared dependency also owns its package subpath exports + // (for example `@jtarrio/webrtlsdr/rtlsdr.js`). + external: (id) => + group.external.some( + (name) => id === name || id.startsWith(`${name}/`), + ), // Unused imports must still obey ownership; tree shaking is not a boundary. treeshake: false, preserveEntrySignatures: 'strict', diff --git a/scripts/format-scope.json b/scripts/format-scope.json index 145739fb1..eee546dd5 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -31,6 +31,7 @@ "src/app/mapLifecycle.test.mjs", "src/app/startupCamera.test.mjs", "src/app/viewer.js", + "src/app/atmosphereCompat.test.mjs", "src/standalone/application.js", "src/standalone/controls.js", "src/standalone/data.js", @@ -99,6 +100,8 @@ "src/tooling/previewServing.test.mjs", "server/providers/common/request.js", "server/providers/common/source-root.js", + "src/data/tapAddress.test.mjs", + "src/data/tapAddress.js", "server/providers/local.js", "server/providers/military-installations.js", "server/providers/military-installations/cache.js", @@ -142,6 +145,8 @@ "src/keylessGeocoder.js", "src/standalone/placeSearch.js", "src/ui/panelDisclosure.js", + "src/ui/imagerySplit.js", + "src/ui/imagerySplit.test.mjs", "src/ui/surfaceKeyboard.js", "src/ui/surfaceKeyboard.test.mjs", "src/ui/panelRails.js", @@ -181,6 +186,7 @@ "src/ui/layers.js", "src/ui/layerPanel.js", "src/ui/layerKeyRequirement.test.mjs", + "src/ui/layerPanel.test.mjs", "src/ui/clearLayersControl.js", "scripts/qa-layer-panel.mjs", "scripts/qa-directions.mjs", @@ -333,6 +339,16 @@ "src/layers/earthquakes/model.js", "src/layers/earthquakes/source.js", "src/layers/earthquakes/ownership.test.mjs", + "src/layers/perimeters/index.js", + "src/layers/perimeters/records.js", + "src/layers/perimeters/source.js", + "src/layers/perimeters/cards.js", + "src/layers/perimeters/inciweb.js", + "src/layers/perimeters/records.test.mjs", + "src/layers/perimeters/source.test.mjs", + "src/layers/perimeters/cards.test.mjs", + "src/layers/perimeters/inciweb.test.mjs", + "src/layers/perimeters/ownership.test.mjs", "src/data/firmsHeatmap.js", "src/data/fireAnchors.js", "src/layers/firms/anchors.js", @@ -382,6 +398,10 @@ "src/layers/launches/model.js", "src/layers/launches/selection.js", "src/layers/launches/camera.js", + "src/data/localGeojson.analyst.test.mjs", + "src/data/satellites.analyst.test.mjs", + "src/data/layerSnapshot.test.mjs", + "src/data/satellitePass.test.mjs", "src/data/satellites.js", "src/data/rocketLaunches.js", "src/layers/satellites/source.test.mjs", @@ -494,6 +514,7 @@ "src/layers/cctv/source.test.mjs", "src/data/alprCameras.js", "src/data/alprCameras.test.mjs", + "src/data/dataCredits.test.mjs", "src/layers/alpr/index.js", "src/layers/alpr/model.js", "src/layers/alpr/policy.js", @@ -542,11 +563,13 @@ "src/data/telegeographySubmarineCables.test.mjs", "src/data/naturalEarthRegions.js", "src/data/neighborhoodPolygons.js", + "src/data/bundledJson.js", "src/layers/submarineCables/bundledSource.test.mjs", "src/maps/availability.js", "src/maps/catalog.js", "src/maps/controller.js", "src/maps/controller.test.mjs", + "src/maps/imageryComparison.js", "src/maps/credits.js", "src/maps/defaultSources.js", "src/maps/google3d.js", @@ -594,6 +617,7 @@ "src/app/layers/flights.js", "src/app/layers/radio.js", "src/app/layers/earthquakes.js", + "src/app/layers/perimeters.js", "src/app/layers/cctv.js", "src/app/layers/firms.js", "src/app/layers/satellites.js", @@ -702,6 +726,7 @@ "src/layers/transit/viewport.js", "src/layers/transit/lifecycle.test.mjs", "scripts/qa-transit.mjs", + "scripts/qa-transit-heading.mjs", "src/tooling/transitProvider.test.mjs", "src/app/layers/transit.js", "src/data/transitIcons.js", @@ -724,7 +749,95 @@ "scripts/qa-transit-controls.mjs", "src/tooling/transitQa.test.mjs", "scripts/qa-transit-browser.mjs", + "scripts/qa-transit-recovery.mjs", "scripts/format-runtime.json", "src/tooling/transitService.test.mjs", - "src/sources/overpassFeatures.test.mjs" + "src/sources/overpassFeatures.test.mjs", + "src/data/cctvHlsStream.test.mjs", + "src/layers/cctv/videoPlayback.test.mjs", + "src/ui/cctvVideo.test.mjs", + "src/ui/styles/weather.css", + "src/layers/weather/index.js", + "src/layers/weather/clock.js", + "src/layers/weather/clock.test.mjs", + "src/layers/weather/rendering.js", + "src/layers/weather/shellRendering.js", + "src/layers/weather/shellRendering.test.mjs", + "src/layers/weather/infraredAlpha.js", + "src/layers/weather/infraredAlpha.test.mjs", + "src/layers/weather/infraredImage.js", + "src/layers/weather/infraredImage.test.mjs", + "src/layers/weather/source.js", + "src/layers/weather/weather.test.mjs", + "src/layers/weather/rasterTiles.test.mjs", + "src/layers/wind/rendering.test.mjs", + "src/layers/weather/source.test.mjs", + "src/data/weatherProxy.test.mjs", + "server/providers/weather.js", + "src/director/clock.test.mjs", + "src/director/timeline.test.mjs", + "src/scenes/packs/registry.test.mjs", + "scripts/qa-director-timing.mjs", + "src/director/document.test.mjs", + "src/director/camera.test.mjs", + "src/scenes/cameraMotion.test.mjs", + "scripts/qa-director-camera.mjs", + "src/director/packs/packs.test.mjs", + "scripts/qa-director-packs.mjs", + "src/scenes/dataPacks/presentation.test.mjs", + "src/director/interactions/interactions.test.mjs", + "scripts/qa-director-interactions.mjs", + "src/director/sharing/sharing.test.mjs", + "scripts/qa-director-sharing.mjs", + "src/ui/weatherPanel.js", + "src/ui/weatherPanel.test.mjs", + "src/ui/railCards.js", + "src/ui/railCards.test.mjs", + "src/ui/railTimeline.js", + "src/ui/railTimeline.test.mjs", + "src/layers/weather/imageryOrder.js", + "src/layers/weather/imageryOrder.test.mjs", + "server/providers/cyclones.js", + "server/providers/firePerimeters.js", + "src/data/cyclonesProxy.test.mjs", + "src/data/firePerimetersProxy.test.mjs", + "src/layers/cyclones/index.js", + "src/layers/cyclones/rendering.js", + "src/layers/cyclones/labels.js", + "src/layers/cyclones/source.js", + "src/layers/cyclones/rendering.test.mjs", + "src/layers/cyclones/labels.test.mjs", + "src/layers/cyclones/index.test.mjs", + "src/layers/cyclones/source.test.mjs", + "src/data/aisStreamSentinels.test.mjs", + "scripts/qa-weather-perf.mjs", + "scripts/qa-weather-journey.mjs", + "scripts/qa-weather-swap.mjs", + "scripts/qa-weather-teardown.mjs", + "src/layers/weather/imageryHost.test.mjs", + "src/sdr/adsbDecoder.test.mjs", + "src/sdr/controller.test.mjs", + "src/sdr/gain.test.mjs", + "src/sdr/spectrum.test.mjs", + "src/sdr/usbDevices.test.mjs", + "src/sources/adsbRecords.test.mjs", + "src/layers/localAdsb/index.test.mjs", + "src/ui/localSdrControls.test.mjs", + "src/ui/localSdrMarkup.test.mjs", + "src/ui/localSdrPresentation.test.mjs", + "src/data/localReceiversProxy.test.mjs", + "src/layers/localAdsb/feeds.test.mjs", + "src/ui/railScrollers.test.mjs", + "src/layers/localAdsb/motion.test.mjs", + "src/data/modelEligibility.test.mjs", + "src/layers/recentImagery/model.test.mjs", + "src/layers/recentImagery/catalog.test.mjs", + "src/maps/imageryHost.test.mjs", + "src/layers/recentImagery/rendering.test.mjs", + "src/layers/recentImagery/thumbnails.test.mjs", + "src/layers/recentImagery/index.test.mjs", + "src/ui/imageryBoxTool.test.mjs", + "src/ui/recentImagery.test.mjs", + "src/layers/recentImagery/testDoubles.mjs", + "scripts/qa-recent-imagery.mjs" ] diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 643edce10..8e9c9a61c 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -20,7 +20,7 @@ }, "viewer": { "exports": ["./application/viewer"], - "modules": ["src/app/viewer.js"], + "modules": ["src/app/viewer.js", "src/app/atmosphereCompat.js"], "external": ["cesium"] }, "vite-build": { @@ -161,6 +161,7 @@ "server/providers/cctv/normalize.js", "server/providers/cctv/range.js", "server/providers/cctv/sources.js", + "server/providers/cctv/stream.js", "server/providers/common/http.js", "src/data/directionText.js", "server/providers/common/geo.js", @@ -256,6 +257,7 @@ "runtime": "node", "exports": ["./server/providers/openai"], "modules": [ + "src/hudLayoutPolicy.js", "server/providers/common/rate-limit.js", "server/providers/common/request.js", "server/providers/common/source-root.js", @@ -268,6 +270,10 @@ "server/providers/openai/realtime.js", "server/providers/openai/tools.js", "src/hudSummaryResponse.js", + "src/data/layerSnapshot.js", + "src/data/feedState.js", + "src/loadingFeedback.js", + "src/data/installationFeedback.js", "src/voice/voiceCost.js", "src/voice/actionSchemas.js", "server/providers/openai/toolDescriptions.js", @@ -322,6 +328,7 @@ "exports": ["./ui/layout"], "modules": [ "src/ui/panelRails.js", + "src/ui/displayPanelScroll.js", "src/ui/leftPanelRail.js", "src/ui/rightPanelRail.js", "src/ui/panelMeasurement.js", @@ -375,11 +382,18 @@ "modules": [ "src/ui/layers.js", "src/ui/layerPanel.js", + "src/ui/weatherPanel.js", + "src/ui/railCards.js", + "src/ui/railCardBlocks.js", + "src/ui/chipGroup.js", + "src/ui/rowList.js", + "src/ui/railTimeline.js", "src/ui/clearLayersControl.js", "src/loadingFeedback.js", "src/data/installationFeedback.js", "src/keySetupCore.mjs", - "src/data/feedState.js" + "src/data/feedState.js", + "src/data/layerSnapshot.js" ], "external": [] }, @@ -413,6 +427,7 @@ "src/ui/cctvCalibration.js", "src/ui/cctvControls.js", "src/ui/cctvFrames.js", + "src/ui/cctvVideo.js", "src/ui/cctvPresentation.js" ], "external": [] @@ -449,6 +464,7 @@ "src/ui/cockpitContext.js", "src/ui/cockpitController.js", "src/ui/cockpitDisplayPortal.js", + "src/ui/displayPanelScroll.js", "src/ui/cockpitInput.js", "src/ui/cockpitInstruments.js", "src/ui/cockpitLayout.js", @@ -474,6 +490,10 @@ "ui-shell": { "exports": ["./ui/shell"], "modules": [ + "src/hudLayouts.js", + "src/hudLayoutPolicy.js", + "src/cyberSonar.js", + "src/ui/radioPanelPlacement.js", "src/app/stateChannel.js", "src/bloom.js", "src/cctvFocusPolicy.js", @@ -504,6 +524,9 @@ "src/styles/surveillance.js", "src/styles/thermal.js", "src/ui/applicationShell.js", + "src/ui/cyberSonarControls.js", + "src/ui/locationNavigation.js", + "src/ui/cockpitCoordinator.js", "src/ui/cameraOrientationControls.js", "src/ui/applicationShortcuts.js", "src/ui/cctv.js", @@ -511,6 +534,7 @@ "src/ui/cctvCalibration.js", "src/ui/cctvControls.js", "src/ui/cctvFrames.js", + "src/ui/cctvVideo.js", "src/ui/cctvPresentation.js", "src/ui/clearLayersControl.js", "src/ui/cockpit.js", @@ -519,6 +543,7 @@ "src/ui/cockpitContext.js", "src/ui/cockpitController.js", "src/ui/cockpitDisplayPortal.js", + "src/ui/displayPanelScroll.js", "src/ui/cockpitInput.js", "src/ui/cockpitInstruments.js", "src/ui/cockpitLayout.js", @@ -538,6 +563,12 @@ "src/ui/effects.js", "src/ui/frameRateMonitor.js", "src/ui/layerPanel.js", + "src/ui/weatherPanel.js", + "src/ui/railCards.js", + "src/ui/railCardBlocks.js", + "src/ui/chipGroup.js", + "src/ui/rowList.js", + "src/ui/railTimeline.js", "src/ui/layers.js", "src/ui/leftPanelRail.js", "src/ui/location.js", @@ -574,7 +605,16 @@ "src/ui/visualPresets.js", "src/ui/visualSettings.js", "src/worldFocus.js", - "src/data/feedState.js" + "src/data/feedState.js", + "src/data/layerSnapshot.js", + "src/ui/aircraftDisplay.js", + "src/layers/weather/imageryHost.js", + "src/ui/layerBindings.js", + "src/ui/displayBindings.js", + "src/ui/shellFacade.js", + "src/ui/localSdrControls.js", + "src/layers/localAdsb/feedNames.js", + "src/ui/localSdrPresentation.js" ], "external": ["cesium"] }, @@ -602,7 +642,32 @@ "src/ui/styles/command-dock-sliding.css", "src/ui/styles/voice-cost.css", "src/ui/styles/first-run.css", - "src/ui/styles/provider-settings.css" + "src/ui/styles/provider-settings.css", + "src/ui/styles/weather.css", + "src/ui/styles/recent-imagery.css" + ], + "external": [] + }, + "director": { + "exports": ["./director"], + "modules": [ + "src/director/playback.js", + "src/director/clock.js", + "src/director/timeline.js", + "src/director/document.js", + "src/director/documentFields.js", + "src/director/cameraDocument.js", + "src/director/camera.js", + "src/director/packs/source.js", + "src/director/packs/session.js", + "src/director/packs/geojson.js", + "src/director/packs/manifest.js", + "src/director/interactions/document.js", + "src/director/interactions/session.js", + "src/director/sharing/bundle.js", + "src/director/sharing/preview.js", + "src/director/sharing/lifetime.js", + "src/director/authoring.js" ], "external": [] }, @@ -615,6 +680,8 @@ "src/data/bhoteKoshiFloodPath.js", "src/maps/catalog.js", "src/scenes/director.js", + "src/scenes/playbackAdapter.js", + "src/director/playback.js", "src/scenes/recipes.js", "src/scenes/scenePolicy.js", "src/bloom.js", @@ -622,7 +689,36 @@ "src/ui/scenes.js", "src/ui/sceneControls.js", "src/ui/scenePresentation.js", - "src/contextModePolicy.js" + "src/contextModePolicy.js", + "src/director/clock.js", + "src/director/timeline.js", + "src/scenes/shotPresentation.js", + "src/scenes/packs/registry.js", + "src/scenes/packs/defaults.js", + "src/scenes/packs/nepal.js", + "src/director/document.js", + "src/scenes/project.js", + "src/director/documentFields.js", + "src/director/cameraDocument.js", + "src/director/camera.js", + "src/scenes/cameraMotion.js", + "src/director/packs/source.js", + "src/director/packs/session.js", + "src/director/packs/geojson.js", + "src/director/packs/manifest.js", + "src/scenes/dataPacks/controller.js", + "src/scenes/dataPacks/presentation.js", + "src/scenes/dataPacks/geometry.js", + "src/director/interactions/document.js", + "src/director/interactions/session.js", + "src/scenes/interactions.js", + "src/data/inputOwnership.js", + "src/director/sharing/bundle.js", + "src/director/sharing/preview.js", + "src/director/sharing/lifetime.js", + "src/director/authoring.js", + "src/scenes/sharing.js", + "src/ui/sceneSharing.js" ], "external": ["cesium"] }, @@ -640,6 +736,7 @@ "civil-flights": { "exports": ["./layers/flights"], "modules": [ + "src/cyberSonar.js", "src/data/aircraftClass.js", "src/data/aircraftIcons.js", "src/data/aircraftMeta.js", @@ -671,13 +768,16 @@ "src/layers/flights/records.js", "src/layers/flights/recordPolicy.js", "src/layers/flights/snapshotRenderer.js", - "src/data/inputOwnership.js" + "src/layers/flights/modelSpec.js", + "src/data/inputOwnership.js", + "src/data/modelEligibility.js" ], "external": ["cesium"] }, "military-flights": { "exports": ["./layers/military"], "modules": [ + "src/cyberSonar.js", "src/data/aircraftClass.js", "src/data/aircraftIcons.js", "src/data/aircraftMeta.js", @@ -706,7 +806,8 @@ "src/layers/military/records.js", "src/layers/military/recordPolicy.js", "src/layers/military/snapshotRenderer.js", - "src/data/inputOwnership.js" + "src/data/inputOwnership.js", + "src/data/modelEligibility.js" ], "external": ["cesium"] }, @@ -768,6 +869,18 @@ ], "external": ["cesium"] }, + "recent-imagery": { + "exports": ["./layers/recent-imagery"], + "modules": [ + "src/layers/recentImagery/index.js", + "src/layers/recentImagery/model.js", + "src/layers/recentImagery/catalog.js", + "src/layers/recentImagery/rendering.js", + "src/layers/recentImagery/thumbnails.js", + "src/maps/imageryHost.js" + ], + "external": ["cesium"] + }, "fire-layer": { "exports": ["./layers/firms"], "modules": [ @@ -796,6 +909,7 @@ "modules": [ "src/data/issPass.js", "src/data/satelliteClass.js", + "src/data/satellitePass.js", "src/layers/satellites/catalog.js", "src/layers/satellites/controls.js", "src/layers/satellites/index.js", @@ -804,6 +918,7 @@ "src/layers/satellites/labels.js", "src/layers/satellites/lifecycle.js", "src/layers/satellites/orbits.js", + "src/layers/satellites/records.js", "src/layers/satellites/policy.js", "src/layers/satellites/rendering.js", "src/layers/satellites/source.js", @@ -817,6 +932,7 @@ "launches-layer": { "exports": ["./layers/launches"], "modules": [ + "src/cyberSonar.js", "src/layers/launches/camera.js", "src/layers/launches/controls.js", "src/layers/launches/index.js", @@ -863,6 +979,7 @@ "awareness-layer": { "exports": ["./layers/awareness"], "modules": [ + "src/cyberSonar.js", "src/cockpitMath.js", "src/data/iconOrientation.js", "src/data/militaryAwarenessEngine.js", @@ -965,6 +1082,7 @@ "src/layers/cctv/policy.js", "src/layers/cctv/presentation.js", "src/layers/cctv/projection.js", + "src/layers/cctv/videoPlayback.js", "src/layers/cctv/rendering.js", "src/layers/cctv/selection.js", "src/layers/cctv/source.js", @@ -975,7 +1093,7 @@ "src/data/inputOwnership.js", "src/layers/cctv/sourcePolicy.js" ], - "external": ["cesium"] + "external": ["hls.js", "cesium"] }, "alpr-cameras": { "exports": ["./layers/alpr"], @@ -1056,6 +1174,7 @@ "modules": [ "src/data/naturalEarthRegions.js", "src/data/neighborhoodPolygons.js", + "src/data/bundledJson.js", "src/data/retryableLoad.js", "src/data/local_data/neighborhoods/san-francisco.json", "src/data/local_data/natural_earth/regions.json", @@ -1076,13 +1195,15 @@ "src/maps/availability.js", "src/maps/catalog.js", "src/maps/controller.js", + "src/maps/imageryComparison.js", "src/maps/credits.js", "src/maps/defaultSources.js", "src/maps/google3d.js", "src/maps/imagery.js", "src/maps/registry.js", "src/maps/terrain.js", - "src/keySetupCore.mjs" + "src/keySetupCore.mjs", + "src/maps/imageryHost.js" ], "external": ["cesium"] }, @@ -1105,7 +1226,18 @@ "src/voice/session.js", "src/voice/sessionCommands.js", "src/voice/realtimeSession.js", - "src/voice/realtimeEvents.js" + "src/voice/realtimeEvents.js", + "src/voice/realtimePreferences.js", + "src/voice/realtimeProtocol.js", + "src/voice/realtimeDiagnostics.js", + "src/voice/realtimeViewport.js", + "src/voice/realtimeInputPolicy.js", + "src/voice/realtimeInput.js", + "src/voice/realtimeCost.js", + "src/voice/realtimeFacade.js", + "src/voice/realtimeRadio.js", + "src/voice/realtimeTurns.js", + "src/voice/realtimeConnection.js" ], "external": [] }, @@ -1129,8 +1261,15 @@ "./standalone/catalog" ], "modules": [ + "src/cyberSonarScene.js", + "src/cyberSonar.js", + "src/hudLayouts.js", + "src/hudLayoutPolicy.js", + "src/ui/radioPanelPlacement.js", + "src/cyberSonarGpu.js", "src/scenes/nepalEvidencePack.js", "src/data/bhoteKoshiEvent.js", + "src/ui/imagerySplit.js", "src/data/bhoteKoshiEmbeddedMedia.js", "src/data/bhoteKoshiLocator.js", "src/data/bhoteKoshiIncidentPlaces.js", @@ -1174,6 +1313,7 @@ "src/app/surfaceServices.js", "src/app/tools.js", "src/app/viewer.js", + "src/app/atmosphereCompat.js", "src/bloom.js", "src/camera.js", "src/cameraVerbs.js", @@ -1208,6 +1348,19 @@ "src/data/contactMatch.js", "src/data/contextStore.js", "src/data/dataCredits.js", + "src/data/wind.js", + "src/layers/wind/index.js", + "src/layers/wind/model.js", + "src/layers/wind/fields.js", + "src/layers/wind/streamlines.js", + "src/layers/wind/gpuRendering.js", + "src/layers/wind/relief.js", + "src/layers/wind/inspection.js", + "src/layers/wind/presentation.js", + "src/layers/wind/rendering.js", + "src/layers/weather/rasterTiles.js", + "src/layers/wind/source.js", + "src/sources/windBody.js", "src/data/detection.js", "src/data/detectionCohort.js", "src/data/detectionDraw.js", @@ -1257,10 +1410,12 @@ "src/data/regionalBrief.js", "src/data/regionalModel.js", "src/data/renderAltitude.js", + "src/data/bundledJson.js", "src/data/retryableLoad.js", "src/data/rocketLaunches.js", "src/data/routePlausible.js", "src/data/satelliteClass.js", + "src/data/satellitePass.js", "src/data/satellites.js", "src/data/scenePick.js", "src/data/spriteOrder.js", @@ -1343,6 +1498,7 @@ "src/layers/cctv/policy.js", "src/layers/cctv/presentation.js", "src/layers/cctv/projection.js", + "src/layers/cctv/videoPlayback.js", "src/layers/cctv/rendering.js", "src/layers/cctv/selection.js", "src/layers/cctv/source.js", @@ -1448,6 +1604,7 @@ "src/layers/satellites/labels.js", "src/layers/satellites/lifecycle.js", "src/layers/satellites/orbits.js", + "src/layers/satellites/records.js", "src/layers/satellites/policy.js", "src/layers/satellites/rendering.js", "src/layers/satellites/source.js", @@ -1503,6 +1660,7 @@ "src/maps/availability.js", "src/maps/catalog.js", "src/maps/controller.js", + "src/maps/imageryComparison.js", "src/maps/credits.js", "src/maps/defaultSources.js", "src/maps/google3d.js", @@ -1518,6 +1676,8 @@ "src/renderGovernor.js", "src/rightRailPolicy.js", "src/scenes/director.js", + "src/scenes/playbackAdapter.js", + "src/director/playback.js", "src/scenes/recipes.js", "src/scenes/scenePolicy.js", "src/scopeMask.js", @@ -1547,6 +1707,9 @@ "src/styles/surveillance.js", "src/styles/thermal.js", "src/ui/applicationShell.js", + "src/ui/cyberSonarControls.js", + "src/ui/locationNavigation.js", + "src/ui/cockpitCoordinator.js", "src/ui/cameraOrientationControls.js", "src/ui/applicationShortcuts.js", "src/ui/cctv.js", @@ -1554,6 +1717,7 @@ "src/ui/cctvCalibration.js", "src/ui/cctvControls.js", "src/ui/cctvFrames.js", + "src/ui/cctvVideo.js", "src/ui/cctvPresentation.js", "src/ui/clearLayersControl.js", "src/ui/cockpit.js", @@ -1562,6 +1726,7 @@ "src/ui/cockpitContext.js", "src/ui/cockpitController.js", "src/ui/cockpitDisplayPortal.js", + "src/ui/displayPanelScroll.js", "src/ui/cockpitInput.js", "src/ui/cockpitInstruments.js", "src/ui/cockpitLayout.js", @@ -1582,6 +1747,12 @@ "src/ui/effects.js", "src/ui/frameRateMonitor.js", "src/ui/layerPanel.js", + "src/ui/weatherPanel.js", + "src/ui/railCards.js", + "src/ui/railCardBlocks.js", + "src/ui/chipGroup.js", + "src/ui/rowList.js", + "src/ui/railTimeline.js", "src/ui/layers.js", "src/ui/leftPanelRail.js", "src/ui/location.js", @@ -1630,6 +1801,7 @@ "src/layers/flights/records.js", "src/layers/flights/recordPolicy.js", "src/layers/flights/snapshotRenderer.js", + "src/layers/flights/modelSpec.js", "src/layers/military/records.js", "src/layers/military/recordPolicy.js", "src/layers/military/snapshotRenderer.js", @@ -1652,8 +1824,15 @@ "src/voice/realtimeEvents.js", "src/app/localGeojsonServices.js", "src/data/feedState.js", + "src/data/layerSnapshot.js", "src/layers/alpr/records.js", "src/layers/earthquakes/records.js", + "src/app/layers/perimeters.js", + "src/layers/perimeters/index.js", + "src/layers/perimeters/source.js", + "src/layers/perimeters/records.js", + "src/layers/perimeters/cards.js", + "src/layers/perimeters/inciweb.js", "src/layers/cctv/sourcePolicy.js", "src/sources/reference.js", "src/search/nominatim.js", @@ -1682,6 +1861,7 @@ "src/data/contactTrailRenderer.js", "src/data/transitProxy.js", "src/data/gtfsRealtime.js", + "src/data/modelEligibility.js", "src/layers/transit/trails.js", "src/layers/transit/movement.js", "src/layers/transit/qaMetrics.js", @@ -1691,15 +1871,99 @@ "src/sources/overpassFeaturesRecords.js", "src/sources/overpassFeatures.js", "src/sources/featureSource.js", - "src/sources/overpassRoads.js" + "src/sources/overpassRoads.js", + "src/ui/aircraftDisplay.js", + "src/ui/layerBindings.js", + "src/ui/displayBindings.js", + "src/ui/shellFacade.js", + "src/voice/realtimePreferences.js", + "src/voice/realtimeProtocol.js", + "src/voice/realtimeDiagnostics.js", + "src/voice/realtimeViewport.js", + "src/voice/realtimeInputPolicy.js", + "src/voice/realtimeInput.js", + "src/voice/realtimeCost.js", + "src/voice/realtimeFacade.js", + "src/voice/realtimeRadio.js", + "src/voice/realtimeTurns.js", + "src/voice/realtimeConnection.js", + "src/layers/weather/index.js", + "src/layers/weather/clock.js", + "src/layers/weather/rendering.js", + "src/layers/weather/shellRendering.js", + "src/layers/weather/infraredAlpha.js", + "src/layers/weather/infraredImage.js", + "src/layers/weather/source.js", + "src/director/clock.js", + "src/director/timeline.js", + "src/scenes/shotPresentation.js", + "src/scenes/packs/registry.js", + "src/scenes/packs/defaults.js", + "src/scenes/packs/nepal.js", + "src/director/document.js", + "src/scenes/project.js", + "src/director/documentFields.js", + "src/director/cameraDocument.js", + "src/director/camera.js", + "src/scenes/cameraMotion.js", + "src/director/packs/source.js", + "src/director/packs/session.js", + "src/director/packs/geojson.js", + "src/director/packs/manifest.js", + "src/scenes/dataPacks/controller.js", + "src/scenes/dataPacks/presentation.js", + "src/scenes/dataPacks/geometry.js", + "src/director/interactions/document.js", + "src/director/interactions/session.js", + "src/scenes/interactions.js", + "src/director/sharing/bundle.js", + "src/director/sharing/preview.js", + "src/director/sharing/lifetime.js", + "src/director/authoring.js", + "src/scenes/sharing.js", + "src/ui/sceneSharing.js", + "src/layers/weather/imageryOrder.js", + "src/layers/weather/imageryHost.js", + "src/layers/cyclones/index.js", + "src/layers/cyclones/rendering.js", + "src/layers/cyclones/labels.js", + "src/layers/cyclones/source.js", + "src/app/layers/localAdsb.js", + "src/layers/localAdsb/index.js", + "src/layers/localAdsb/policy.js", + "src/layers/localAdsb/card.js", + "src/layers/localAdsb/feeds.js", + "src/layers/localAdsb/status.js", + "src/layers/localAdsb/feedNames.js", + "src/layers/localAdsb/motion.js", + "src/layers/localAdsb/models.js", + "src/layers/localAdsb/enrichment.js", + "src/sources/adsbRecords.js", + "src/sdr/controller.js", + "src/sdr/spectrum.js", + "src/sdr/gain.js", + "src/sdr/usbDevices.js", + "src/ui/localSdrControls.js", + "src/ui/localSdrPresentation.js", + "src/app/layers/recentImagery.js", + "src/layers/recentImagery/index.js", + "src/layers/recentImagery/model.js", + "src/layers/recentImagery/catalog.js", + "src/layers/recentImagery/rendering.js", + "src/layers/recentImagery/thumbnails.js", + "src/maps/imageryHost.js", + "src/ui/recentImagery.js", + "src/ui/imageryBoxTool.js" ], "external": [ + "hls.js", "@mapbox/vector-tile", "cesium", "egm96-universal", "mgrs", "pbf", - "satellite.js" + "satellite.js", + "@jtarrio/webrtlsdr" ] }, "application-catalog": { @@ -1710,7 +1974,10 @@ "application-layer-construction": { "exports": ["./application/layers"], "modules": [ + "src/cyberSonar.js", "src/data/bhoteKoshiEvent.js", + "src/ui/imagerySplit.js", + "src/maps/imageryComparison.js", "src/data/bhoteKoshiEmbeddedMedia.js", "src/data/bhoteKoshiLocator.js", "src/data/bhoteKoshiIncidentPlaces.js", @@ -1720,6 +1987,16 @@ "src/annotations/resolver.js", "src/app/catalog.js", "src/app/constructCatalog.js", + "src/layers/wind/index.js", + "src/layers/wind/model.js", + "src/layers/wind/fields.js", + "src/layers/wind/streamlines.js", + "src/layers/wind/gpuRendering.js", + "src/layers/wind/relief.js", + "src/layers/wind/inspection.js", + "src/layers/wind/presentation.js", + "src/layers/wind/rendering.js", + "src/layers/weather/rasterTiles.js", "src/app/layers/aisLiveVessels.js", "src/app/layers/alprCameras.js", "src/app/layers/bikeshare.js", @@ -1767,6 +2044,7 @@ "src/data/infrastructure.js", "src/data/installationFeedback.js", "src/data/issPass.js", + "src/data/satellitePass.js", "src/data/labelArbiter.js", "src/data/layerState.js", "src/data/localGeojson.js", @@ -1784,6 +2062,7 @@ "src/data/pickRegistry.js", "src/data/radioCountry.js", "src/data/renderAltitude.js", + "src/data/bundledJson.js", "src/data/retryableLoad.js", "src/data/routePlausible.js", "src/data/satelliteClass.js", @@ -1858,6 +2137,7 @@ "src/layers/cctv/policy.js", "src/layers/cctv/presentation.js", "src/layers/cctv/projection.js", + "src/layers/cctv/videoPlayback.js", "src/layers/cctv/rendering.js", "src/layers/cctv/selection.js", "src/layers/cctv/source.js", @@ -1963,6 +2243,7 @@ "src/layers/satellites/labels.js", "src/layers/satellites/lifecycle.js", "src/layers/satellites/orbits.js", + "src/layers/satellites/records.js", "src/layers/satellites/policy.js", "src/layers/satellites/rendering.js", "src/layers/satellites/source.js", @@ -2026,6 +2307,7 @@ "src/layers/flights/records.js", "src/layers/flights/recordPolicy.js", "src/layers/flights/snapshotRenderer.js", + "src/layers/flights/modelSpec.js", "src/layers/military/records.js", "src/layers/military/recordPolicy.js", "src/layers/military/snapshotRenderer.js", @@ -2049,6 +2331,12 @@ "src/app/localGeojsonServices.js", "src/layers/alpr/records.js", "src/layers/earthquakes/records.js", + "src/app/layers/perimeters.js", + "src/layers/perimeters/index.js", + "src/layers/perimeters/source.js", + "src/layers/perimeters/records.js", + "src/layers/perimeters/cards.js", + "src/layers/perimeters/inciweb.js", "src/layers/cctv/sourcePolicy.js", "src/search/nominatim.js", "src/nominatimGeocode.js", @@ -2085,15 +2373,56 @@ "src/sources/overpassFeaturesRecords.js", "src/sources/overpassFeatures.js", "src/sources/featureSource.js", - "src/sources/overpassRoads.js" + "src/sources/overpassRoads.js", + "src/layers/weather/index.js", + "src/layers/weather/clock.js", + "src/layers/weather/rendering.js", + "src/layers/weather/shellRendering.js", + "src/layers/weather/infraredAlpha.js", + "src/layers/weather/infraredImage.js", + "src/layers/weather/source.js", + "src/layers/weather/imageryOrder.js", + "src/layers/weather/imageryHost.js", + "src/layers/cyclones/index.js", + "src/layers/cyclones/rendering.js", + "src/layers/cyclones/labels.js", + "src/layers/cyclones/source.js", + "src/app/layers/localAdsb.js", + "src/layers/localAdsb/index.js", + "src/layers/localAdsb/policy.js", + "src/layers/localAdsb/card.js", + "src/layers/localAdsb/feeds.js", + "src/layers/localAdsb/status.js", + "src/layers/localAdsb/feedNames.js", + "src/layers/localAdsb/motion.js", + "src/layers/localAdsb/models.js", + "src/layers/localAdsb/enrichment.js", + "src/sources/adsbRecords.js", + "src/sdr/controller.js", + "src/sdr/spectrum.js", + "src/sdr/gain.js", + "src/sdr/usbDevices.js", + "src/data/detection.js", + "src/data/detectionRenderDemand.js", + "src/data/detectionPresentation.js", + "src/data/modelEligibility.js", + "src/app/layers/recentImagery.js", + "src/layers/recentImagery/index.js", + "src/layers/recentImagery/model.js", + "src/layers/recentImagery/catalog.js", + "src/layers/recentImagery/rendering.js", + "src/layers/recentImagery/thumbnails.js", + "src/maps/imageryHost.js" ], "external": [ + "hls.js", "cesium", "egm96-universal", "satellite.js", "@mapbox/vector-tile", "pbf", - "mgrs" + "mgrs", + "@jtarrio/webrtlsdr" ] }, "application-operations": { @@ -2111,6 +2440,7 @@ "src/data/local_data/neighborhoods/san-francisco.json", "src/data/naturalEarthRegions.js", "src/data/neighborhoodPolygons.js", + "src/data/bundledJson.js", "src/data/retryableLoad.js", "src/data/scenePick.js", "src/keylessGeocoder.js", @@ -2156,7 +2486,11 @@ }, "ui-navigation": { "exports": ["./ui/navigation"], - "modules": ["src/navigationPolicy.js", "src/ui/navigationController.js"], + "modules": [ + "src/navigationPolicy.js", + "src/ui/navigationController.js", + "src/app/stateChannel.js" + ], "external": ["cesium"] }, "ui-share-restoration": { @@ -2174,6 +2508,10 @@ "ui-visual-settings": { "exports": ["./ui/visual-settings"], "modules": [ + "src/cyberSonar.js", + "src/hudLayouts.js", + "src/hudLayoutPolicy.js", + "src/ui/radioPanelPlacement.js", "src/bloom.js", "src/cockpitVisionPolicy.js", "src/contactsDetectionPolicy.js", @@ -2198,6 +2536,8 @@ "ui-panel-chrome": { "exports": ["./ui/panel-chrome"], "modules": [ + "src/ui/displayPanelScroll.js", + "src/ui/radioPanelPlacement.js", "src/panelStackLayout.js", "src/ui/leftPanelRail.js", "src/ui/panelChrome.js", @@ -2288,7 +2628,7 @@ }, "voice-action-schemas": { "exports": ["./voice/action-schemas"], - "modules": ["src/voice/actionSchemas.js"], + "modules": ["src/voice/actionSchemas.js", "src/hudLayoutPolicy.js"], "external": [] }, "voice-session": { @@ -2377,6 +2717,9 @@ "src/sources/reference.js", "src/layers/earthquakes/source.js", "src/layers/earthquakes/records.js", + "src/sources/httpBody.js", + "src/layers/perimeters/source.js", + "src/layers/perimeters/records.js", "src/layers/submarineCables/bundledSource.js" ], "external": [] @@ -2447,6 +2790,7 @@ "transit-standalone": { "exports": ["./layers/transit/standalone"], "modules": [ + "src/cyberSonar.js", "src/app/sourceSlot.js", "src/celestialRing.js", "src/data/cameraSensitivity.js", @@ -2572,5 +2916,26 @@ "src/sources/featureSource.js" ], "external": [] + }, + "perimeters": { + "exports": ["./layers/perimeters"], + "modules": [ + "src/layers/perimeters/index.js", + "src/sources/httpBody.js", + "src/layers/perimeters/source.js", + "src/layers/perimeters/records.js", + "src/layers/perimeters/cards.js", + "src/layers/perimeters/inciweb.js" + ], + "external": ["cesium"] + }, + "perimeters-source": { + "exports": ["./layers/perimeters/source"], + "modules": [ + "src/layers/perimeters/records.js", + "src/sources/httpBody.js", + "src/layers/perimeters/source.js" + ], + "external": [] } } diff --git a/scripts/qa-cockpit-utility.mjs b/scripts/qa-cockpit-utility.mjs index 5c3829462..607889bbe 100644 --- a/scripts/qa-cockpit-utility.mjs +++ b/scripts/qa-cockpit-utility.mjs @@ -1943,6 +1943,98 @@ try { }), ); + // Cyber relocates its collapsed briefing header into the expanded utility + // lane. Exercise actual height changes without reload and measure both cards. + await page.evaluate(() => { + const manager = window.__godsEyeView.styleManager; + manager._setHudVariant('cyber'); + manager.hud.setMode('on'); + manager._setCockpitDisclosure('display', false); + manager._setCockpitDisclosure('radio', true); + }); + const cyberRadioOrder = await page.evaluate(() => { + const manager = window.__godsEyeView.styleManager; + manager.cockpitView.syncSignalLayout(); + const display = document + .getElementById('cockpit-display-toggle-btn') + .closest('.cockpit-utility-control'); + const radio = document + .getElementById('cockpit-radio-toggle-btn') + .closest('.cockpit-utility-control'); + const displayRect = display.getBoundingClientRect(); + const radioRect = radio.getBoundingClientRect(); + return { + display: displayRect.toJSON(), + radio: radioRect.toJSON(), + displayExpanded: display.classList.contains('is-expanded'), + radioExpanded: radio.classList.contains('is-expanded'), + gap: radioRect.top - displayRect.bottom, + }; + }); + check( + 'Cyber expanding Radio preserves the authored Display-then-Radio order', + !cyberRadioOrder.displayExpanded + && cyberRadioOrder.radioExpanded + && cyberRadioOrder.display.height > 0 + && cyberRadioOrder.radio.height > 0 + && cyberRadioOrder.gap >= 7, + JSON.stringify(cyberRadioOrder), + ); + await page.screenshot({ path: path.join(shotsDir, 'cyber-radio-order.png') }); + await page.evaluate(() => { + const manager = window.__godsEyeView.styleManager; + manager._setCockpitDisclosure('radio', false); + manager._setCockpitDisclosure('display', true); + }); + const cyberStyleStates = await page.evaluate(() => { + const manager = window.__godsEyeView.styleManager; + const states = []; + for (const style of ['normal', 'surveillance', 'thermal', 'retro']) { + document.querySelector(`.style-btn[data-style="${style}"]`).click(); + states.push({ + requestedStyle: style, + activeStyle: manager.activeStyle, + hud: manager.hud.getVariant(), + theme: document.documentElement.dataset.uiTheme, + selector: document.getElementById('hud-layout-select').value, + savedHud: manager.getVisualState().hud.variant, + }); + } + return states; + }); + check('Cockpit visual-style controls retain Cyber HUD, selector, shell and saved layout', + cyberStyleStates.every(state => state.activeStyle === state.requestedStyle + && state.hud === 'cyber' && state.theme === 'cyber' + && state.selector === 'cyber' && state.savedHud === 'cyber'), + JSON.stringify(cyberStyleStates)); + for (const height of [987, 720, 640, 900]) { + await page.setViewport({ width: 1440, height, deviceScaleFactor: 1 }); + await new Promise((resolve) => setTimeout(resolve, 400)); + const geometry = await page.evaluate(() => { + const signal = document.getElementById('cockpit-signal-stream'); + const utility = document.getElementById('cockpit-utility-controls'); + const expanded = utility.querySelector('.cockpit-utility-control.is-expanded'); + const s = signal.getBoundingClientRect(); + const u = expanded.getBoundingClientRect(); + const toggle = document.getElementById('cockpit-signal-toggle'); + const t = toggle.getBoundingClientRect(); + const hit = document.elementFromPoint(t.x + t.width / 2, t.y + t.height / 2); + return { height: innerHeight, theme: document.documentElement.dataset.uiTheme, + collapsed: signal.dataset.collapsed, signal: s.toJSON(), utility: u.toJSON(), + reachable: Boolean(hit && toggle.contains(hit)), + contained: u.bottom <= s.top - 7 && s.bottom < innerHeight, + }; + }); + check(`Cyber collapsed Live Signals remains visible and reachable after resize to ${height}px`, + geometry.theme === 'cyber' && geometry.collapsed === 'true' + && geometry.signal.width > 0 && geometry.signal.height > 0 + && geometry.reachable && geometry.contained, JSON.stringify(geometry)); + if (height === 640 || height === 900) { + await page.screenshot({ path: path.join(shotsDir, `cyber-resize-${height}.png`) }); + } + } + await page.evaluate(() => window.__godsEyeView.styleManager._setHudVariant('operator')); + const signalTransition = await page.evaluate(() => { const manager = window.__godsEyeView.styleManager; const cockpit = manager.cockpitView; @@ -2171,7 +2263,8 @@ try { ); const resetResult = await page.evaluate(() => { - const manager = window.__godsEyeView.styleManager; + // Both the UI and compatibility facade delegate to this navigation owner. + const manager = window.__godsEyeView.styleManager._locationNavigation; const awareness = window.__godsEyeView.dataManager.layers.get('military-awareness')?.module; window.__qaCockpitReset = { calls: 0, @@ -2203,7 +2296,7 @@ try { const awareness = gev.dataManager.layers.get('military-awareness')?.module; const subjectId = awareness?.getContextSnapshot?.()?.subject?.id || null; const height = gev.viewer.camera.positionCartographic?.height; - gev.styleManager.resetToGlobeView = qa.original; + gev.styleManager._locationNavigation.resetToGlobeView = qa.original; delete window.__qaCockpitReset; return { calls: qa.calls, diff --git a/scripts/qa-director-camera.mjs b/scripts/qa-director-camera.mjs new file mode 100644 index 000000000..62f0af5ff --- /dev/null +++ b/scripts/qa-director-camera.mjs @@ -0,0 +1,210 @@ +#!/usr/bin/env node +/** Verify imported camera directions through real rendering and camera authority handoffs. */ +import fs from 'node:fs'; +import path from 'node:path'; +import puppeteer from 'puppeteer'; +const output = path.resolve('qa-shots/director-camera'); +fs.mkdirSync(output, { recursive: true }); +const browser = await puppeteer.launch({ + headless: true, + args: ['--no-sandbox', '--disable-dev-shm-usage'], +}); +const page = await browser.newPage(); +const errors = []; +page.on('pageerror', (error) => errors.push(error.message)); +let failed = 0; +function check(name, passed) { + console.log(`[${passed ? 'PASS' : 'FAIL'}] ${name}`); + if (!passed) failed++; +} +try { + await page.setViewport({ width: 1440, height: 900 }); + await page.goto( + `${process.env.QA_BASE_URL || 'http://localhost:4173'}/?welcome=0`, + { waitUntil: 'domcontentloaded' }, + ); + await page.waitForFunction( + () => + window.__godsEyeView?.sceneDirector && + document.getElementById('loading-screen')?.classList.contains('hidden'), + { timeout: 60000 }, + ); + const result = await page.evaluate(async () => { + const { sceneDirector: d, styleManager: style } = window.__godsEyeView; + const file = { + version: 4, + scenes: [ + { + id: 'directions', + title: 'Camera directions', + anchors: [ + { + id: 'start', + title: 'Austin west', + lat: 30.2672, + lon: -97.76, + alt: 6000, + altitudeReference: 'ellipsoid', + }, + { + id: 'end', + title: 'Austin east', + lat: 30.2672, + lon: -97.73, + alt: 7000, + altitudeReference: 'ellipsoid', + }, + ], + shots: [ + { + id: 'move', + title: 'Across Austin', + durationSec: 1, + holdSec: 0.2, + camera: { anchorId: 'end', heading: 10, pitch: -45, roll: 0 }, + move: { + from: { anchorId: 'start', heading: 350, pitch: -45, roll: 0 }, + easing: 'linear', + }, + layers: {}, + visual: { style: 'normal' }, + }, + ], + }, + ], + }; + await d.importProjectFile( + new File([JSON.stringify(file)], 'directions.json'), + ); + const scene = d._project.scenes[0]; + const shot = scene.shots[0]; + const imported = + scene.anchors.length === 2 && shot.camera.anchorId === 'end'; + await d.seekScene(scene.id, 0.5 / 1.2); + const middle = style.getCameraState(); + const seekMidpoint = + Math.abs(middle.lon - -97.745) < 1e-6 && + Math.abs(middle.alt - 6500) < 0.01; + await d.seekScene(scene.id, 0); + const back = style.getCameraState(); + const backward = Math.abs(back.lon - -97.76) < 1e-6; + const replay = await d.replayShot(scene.id, shot.id); + const end = style.getCameraState(); + const replayEnd = + replay?.started && + Math.abs(end.lon - -97.73) < 1e-6 && + Math.abs(end.alt - 7000) < 0.01; + d.stopScene(); + await d.startScene(scene.id, { single: true, preview: false }); + const completed = + !d.running && d.getPlaybackTimingState().activeTimers === 0; + const settled = Math.abs(style.getCameraState().lon - -97.73) < 1e-6; + // Updating the target creates an explicit inline pose while retaining the authored start. + d.updateSelectedShot(); + const saved = JSON.parse( + localStorage.getItem('godsEyeView.sceneProject.v2'), + ); + const updated = + saved.scenes[0].shots[0].camera.altitudeReference === 'ellipsoid' && + saved.scenes[0].shots[0].move.from.anchorId === 'start'; + shot.durationSec = 30; + const run = d.startScene(scene.id, { single: true, preview: false }); + const deadline = Date.now() + 10000; + while (!d._cameraMotion.active && Date.now() < deadline) + await new Promise((r) => setTimeout(r, 20)); + const started = d._cameraMotion.active; + style.runImmediateNavigation('location', () => true); + await run; + const revoked = + started && + !d.running && + !d._cameraMotion.active && + d.getPlaybackTimingState().activeTimers === 0; + const stoppedPose = style.getCameraState(); + await new Promise((r) => setTimeout(r, 150)); + const stable = + Math.abs(style.getCameraState().lon - stoppedPose.lon) < 1e-7; + return { + imported, + seekMidpoint, + backward, + replayEnd, + completed, + settled, + updated, + revoked, + stable, + }; + }); + for (const [name, passed] of Object.entries(result)) check(name, passed); + await new Promise((r) => setTimeout(r, 6000)); + await page.screenshot({ path: path.join(output, 'austin.png') }); + await page.evaluate(() => { + const d = window.__godsEyeView.sceneDirector; + const pose = d.styleManager.getCameraState(); + d._setCameraView({ ...pose, heading: pose.heading + 25, pitch: -60 }); + d.viewer.scene.requestRender(); + }); + await new Promise((r) => setTimeout(r, 3000)); + await page.screenshot({ path: path.join(output, 'angle.png') }); + const inputStarted = await page.evaluate(async () => { + const d = window.__godsEyeView.sceneDirector; + const scene = d._project.scenes[0]; + window.__qaCameraRun = d.startScene(scene.id, { + single: true, + preview: false, + }); + const deadline = Date.now() + 10000; + while (!d._cameraMotion.active && Date.now() < deadline) + await new Promise((r) => setTimeout(r, 20)); + return d._cameraMotion.active; + }); + const canvas = + (await page.$('canvas.cesium-widget-canvas')) || + (await page.$('.cesium-widget canvas')); + const rect = await canvas.boundingBox(); + await page.mouse.move(rect.x + rect.width / 2, rect.y + rect.height / 2); + await page.mouse.down(); + await page.mouse.up(); + const input = + inputStarted && + (await page.evaluate(async () => { + await window.__qaCameraRun; + const d = window.__godsEyeView.sceneDirector; + return !d.running && d.getPlaybackTimingState().activeTimers === 0; + })); + check('manual canvas input revokes the move and releases clocks', input); + const hold = await page.evaluate(async () => { + const { sceneDirector: d, styleManager: style } = window.__godsEyeView; + const scene = d._project.scenes[0]; + const shot = scene.shots[0]; + shot.durationSec = 0.2; + shot.holdSec = 30; + const run = d.startScene(scene.id, { single: true, preview: false }); + const deadline = Date.now() + 10000; + while ( + (!d._activeSceneTravel || !d.running || d._cameraMotion.active) && + Date.now() < deadline + ) + await new Promise((r) => setTimeout(r, 20)); + const holding = d.running && !d._cameraMotion.active; + const began = performance.now(); + style.runImmediateNavigation('location', () => true); + await run; + return ( + holding && + performance.now() - began < 1000 && + d.getPlaybackTimingState().activeTimers === 0 + ); + }); + check('navigation during an authored hold settles immediately', hold); + + if (errors.length) + console.error( + errors.map((message) => message.replace(/https?:\/\/\S+/g, '[URL]')), + ); + check('no uncaught browser errors', errors.length === 0); +} finally { + await browser.close(); +} +if (failed) process.exitCode = 1; diff --git a/scripts/qa-director-interactions.mjs b/scripts/qa-director-interactions.mjs new file mode 100644 index 000000000..6c04f4b80 --- /dev/null +++ b/scripts/qa-director-interactions.mjs @@ -0,0 +1,364 @@ +#!/usr/bin/env node +/** Real pointer/keyboard acceptance using a synthetic, self-authored feature pack. */ +import fs from 'node:fs'; +import puppeteer from 'puppeteer'; +const output = 'qa-shots/director-interactions'; +fs.mkdirSync(output, { recursive: true }); +const browser = await puppeteer.launch({ + headless: true, + args: ['--no-sandbox', '--disable-dev-shm-usage'], +}); +const page = await browser.newPage(); +let failures = 0; +const errors = []; +const check = (name, ok) => { + console.log(`[${ok ? 'PASS' : 'FAIL'}] ${name}`); + if (!ok) failures++; +}; +page.on('pageerror', (e) => errors.push(e.message)); +await page.setRequestInterception(true); +page.on('request', (request) => { + if (new URL(request.url()).pathname === '/scene-assets/qa/actions.json') + void request + .respond({ + status: 200, + contentType: 'application/geo+json', + body: JSON.stringify({ + type: 'FeatureCollection', + features: [ + { + type: 'Feature', + id: 'point', + geometry: { type: 'Point', coordinates: [-97.742, 30.2672, 600] }, + }, + ], + }), + }) + .catch(() => {}); + else void request.continue().catch(() => {}); +}); +const action = (id) => `[data-director-action="${id}"]`; +const load = () => + page.evaluate(() => + window.__godsEyeView.sceneDirector.loadShot('interactive', 'one', { + flyDuration: 0.2, + }), + ); +try { + await page.setViewport({ width: 1440, height: 900 }); + await page.goto( + `${process.env.QA_BASE_URL || 'http://localhost:4173'}/?welcome=0`, + { waitUntil: 'domcontentloaded' }, + ); + await page.waitForFunction( + () => + window.__godsEyeView?.sceneDirector && + document.getElementById('loading-screen')?.classList.contains('hidden'), + { timeout: 60000 }, + ); + await page.evaluate(async () => { + const d = window.__godsEyeView.sceneDirector; + const camera = { + lat: 30.2672, + lon: -97.742, + alt: 4000, + heading: 0, + pitch: -90, + roll: 0, + altitudeReference: 'ellipsoid', + }; + const target = { packId: 'data', featureId: 'point' }; + const interaction = (id, label, action) => ({ id, label, target, action }); + window.__interactionProject = { + version: 6, + scenes: [ + { + id: 'interactive', + title: 'Interactive fixture', + anchors: [ + { + id: 'view', + lat: 30.27, + lon: -97.74, + alt: 5000, + altitudeReference: 'ellipsoid', + }, + ], + dataPacks: [ + { + id: 'data', + version: 1, + format: 'geojson', + source: { adapter: 'assets', path: 'qa/actions.json' }, + attribution: { text: 'Synthetic fixture', license: 'CC0-1.0' }, + placement: { altitudeReference: 'ellipsoid' }, + }, + ], + shots: [ + { + id: 'one', + title: 'Choose an action', + camera, + durationSec: 0.2, + holdSec: 0, + move: { + from: { ...camera, alt: 4100, altitudeReference: 'ellipsoid' }, + easing: 'linear', + }, + visual: { style: 'normal', mapStack: 'photoreal' }, + layers: { traffic: false }, + dataPackIds: ['data'], + interactions: [ + interaction('card', 'Read source', { + type: 'card', + text: 'Plain text only', + url: 'https://example.org/source', + }), + interaction('focus', 'Focus anchor', { + type: 'focus', + anchorId: 'view', + }), + interaction('layer', 'Show traffic', { + type: 'layer', + layerId: 'traffic', + enabled: true, + }), + interaction('next', 'Next shot', { + type: 'shot', + shotId: 'two', + }), + ], + }, + { + id: 'two', + title: 'Next', + camera: { ...camera, heading: 30 }, + durationSec: 0.2, + holdSec: 0, + layers: { traffic: false }, + }, + ], + }, + ], + }; + await d.importProjectFile( + new File([JSON.stringify(window.__interactionProject)], 'actions.json'), + ); + }); + check( + 'import installs no action handlers or UI', + await page.evaluate( + () => + !window.__godsEyeView.sceneDirector.getInteractionState().active && + !document.querySelector('[data-director-interactions]'), + ), + ); + await load(); + check( + 'settled LOAD activates four actions', + await page.evaluate( + () => + window.__godsEyeView.sceneDirector.getInteractionState().count === 4, + ), + ); + await page.waitForFunction( + () => window.__godsEyeView.tileset?.tilesLoaded === true, + { timeout: 60000 }, + ); + await new Promise((r) => setTimeout(r, 2000)); + const point = await page.evaluate(async () => { + const d = window.__godsEyeView.sceneDirector; + const entity = d.viewer.entities.values.find( + (e) => e.name === 'data / point', + ); + const pos = entity.position.getValue(d.viewer.clock.currentTime); + const screen = d.viewer.scene.cartesianToCanvasCoordinates(pos); + const rect = d.viewer.scene.canvas.getBoundingClientRect(); + return { x: screen.x + rect.left, y: screen.y + rect.top }; + }); + await page.mouse.click(point.x, point.y); + check( + 'real globe pick selects the feature and focuses its keyboard action', + await page.evaluate( + () => + document.activeElement?.dataset.directorAction === 'card' && + document + .querySelector('[data-director-interactions] [role=status]') + .textContent.includes('point'), + ), + ); + await page.keyboard.press('Enter'); + check( + 'Enter shows literal text and a safe source link', + await page.evaluate(() => { + const card = document.querySelector('[data-director-action-card]'); + return ( + card?.textContent.includes('Plain text only') && + !card.querySelector('b') && + card.querySelector('a')?.rel === 'noopener noreferrer' + ); + }), + ); + await page.screenshot({ path: `${output}/selected.png` }); + fs.writeFileSync( + `${output}/report.json`, + JSON.stringify( + await page.evaluate(() => ({ + tilesSettled: window.__godsEyeView.tileset?.tilesLoaded === true, + })), + null, + 2, + ), + ); + await page.keyboard.press('Tab'); + await page.keyboard.press('Space'); + check( + 'Tab/Space focuses the authored anchor through camera ownership', + await page.evaluate( + () => + Math.abs( + window.__godsEyeView.sceneDirector.viewer.camera.positionCartographic + .height - 5000, + ) < 1, + ), + ); + await page.screenshot({ path: `${output}/anchor.png` }); + const sourceBase = process.env.QA_SOURCE_BASE || '/src'; + // Resolve ownership from the same module graph as the active application. + await page.evaluate(async (base) => { + window.__inputOwner = await import(`${base}/data/inputOwnership.js`); + window.__lease = window.__inputOwner.claimPointer('qa-draw'); + }, sourceBase); + await page.click(action('card')); + check( + 'drawing ownership refuses actions', + await page.evaluate(() => + document + .querySelector('[data-director-interactions] [role=status]') + .textContent.includes('unavailable'), + ), + ); + await page.evaluate(() => window.__inputOwner.releasePointer(window.__lease)); + // Hold the actual manager admission call to exercise Stop before an enable settles. + await page.evaluate(() => { + const d = window.__godsEyeView.sceneDirector, + m = d.dataManager; + window.__originalEnable = m.setEnabled; + m.setEnabled = function (id, enabled, options) { + if (id !== 'traffic' || !enabled) + return window.__originalEnable.call(this, id, enabled, options); + window.__actionSignal = options.signal; + return new Promise((resolve) => { + window.__lateAction = () => resolve(true); + options.signal.addEventListener('abort', () => resolve(false), { + once: true, + }); + }); + }; + }); + await page.click(action('layer')); + await page.waitForFunction(() => window.__actionSignal); + await page.evaluate(() => window.__godsEyeView.sceneDirector.stopScene()); + check( + 'Stop aborts pending layer admission and removes handlers/cards/selection', + await page.evaluate( + () => + window.__actionSignal.aborted && + !window.__godsEyeView.sceneDirector.getInteractionState().active && + !document.querySelector('[data-director-interactions]'), + ), + ); + await page.evaluate(() => { + window.__lateAction(); + window.__godsEyeView.sceneDirector.dataManager.setEnabled = + window.__originalEnable; + }); + await load(); + await page.evaluate(() => + window.__godsEyeView.sceneDirector.seekScene('interactive', 0.1), + ); + check( + 'same-shot seek restores pack geometry and resets action state', + await page.evaluate( + () => + window.__godsEyeView.sceneDirector.getInteractionState().count === 4 && + window.__godsEyeView.sceneDirector.getInteractionState().selected === + null && + window.__godsEyeView.sceneDirector.getDataPackState().count === 1, + ), + ); + await page.evaluate(() => { + window.__oldActionButton = document.querySelector( + '[data-director-action=card]', + ); + }); + await page.click(action('next')); + await page.waitForFunction( + () => window.__godsEyeView.sceneDirector._selectedShotId === 'two', + ); + check( + 'explicit shot transition replaces resources and removes actions', + await page.evaluate( + () => + !window.__godsEyeView.sceneDirector.getInteractionState().active && + window.__godsEyeView.sceneDirector.getDataPackState().count === 0, + ), + ); + await load(); + await page.evaluate(() => window.__oldActionButton.click()); + check( + 'detached buttons cannot invoke replacement actions with the same ID', + await page.evaluate( + () => + window.__godsEyeView.sceneDirector.getInteractionState().selected === + null && + !document.querySelector('[data-director-action-card]').textContent, + ), + ); + await page.evaluate(() => { + window.__godsEyeView.sceneDirector._interactionTransitions = 64; + }); + await page.click(action('next')); + check( + 'bounded transition chain cannot take another branch', + await page.evaluate( + () => window.__godsEyeView.sceneDirector._selectedShotId === 'one', + ), + ); + await load(); + await page.evaluate(async () => { + const p = structuredClone(window.__interactionProject); + p.scenes[0].shots[0].interactions[0].target.featureId = 'missing'; + const d = window.__godsEyeView.sceneDirector; + await d.importProjectFile(new File([JSON.stringify(p)], 'missing.json')); + await d.loadShot('interactive', 'one', { flyDuration: 0.2 }); + }); + check( + 'unknown loaded feature refuses the whole action set', + await page.evaluate( + () => + !window.__godsEyeView.sceneDirector.getInteractionState().active && + !document.querySelector('[data-director-interactions]'), + ), + ); + await page.evaluate(async () => { + const d = window.__godsEyeView.sceneDirector; + await d.importProjectFile( + new File([JSON.stringify(window.__interactionProject)], 'restore.json'), + ); + await d.loadShot('interactive', 'one', { flyDuration: 0.2 }); + await d.destroy(); + }); + check( + 'teardown releases interactive resources', + await page.evaluate( + () => + window.__godsEyeView.sceneDirector.getInteractionState().count === 0 && + !document.querySelector('[data-director-interactions]'), + ), + ); + check('no uncaught browser errors', errors.length === 0); +} finally { + await browser.close(); +} +process.exitCode = failures ? 1 : 0; diff --git a/scripts/qa-director-packs.mjs b/scripts/qa-director-packs.mjs new file mode 100644 index 000000000..9ef68d420 --- /dev/null +++ b/scripts/qa-director-packs.mjs @@ -0,0 +1,359 @@ +#!/usr/bin/env node +/** Synthetic, self-authored assets exercise import, rendering and pack resource lifetime. */ +import fs from 'node:fs'; +import path from 'node:path'; +import puppeteer from 'puppeteer'; +import sharp from 'sharp'; +const output = path.resolve('qa-shots/director-packs'); +fs.mkdirSync(output, { recursive: true }); +const png = await sharp({ + create: { + width: 64, + height: 64, + channels: 4, + background: { r: 255, g: 80, b: 30, alpha: 0.65 }, + }, +}) + .png() + .toBuffer(); +const wav = Buffer.alloc(44 + 16000); +wav.write('RIFF'); +wav.writeUInt32LE(wav.length - 8, 4); +wav.write('WAVEfmt ', 8); +wav.writeUInt32LE(16, 16); +wav.writeUInt16LE(1, 20); +wav.writeUInt16LE(1, 22); +wav.writeUInt32LE(8000, 24); +wav.writeUInt32LE(16000, 28); +wav.writeUInt16LE(2, 32); +wav.writeUInt16LE(16, 34); +wav.write('data', 36); +wav.writeUInt32LE(16000, 40); +const geojson = { + type: 'FeatureCollection', + features: [ + { + type: 'Feature', + id: 'point', + geometry: { type: 'Point', coordinates: [-97.742, 30.27, 450] }, + }, + { + type: 'Feature', + id: 'line', + geometry: { + type: 'LineString', + coordinates: [ + [-97.745, 30.268, 400], + [-97.735, 30.268, 400], + ], + }, + }, + { + type: 'Feature', + id: 'polygon', + geometry: { + type: 'Polygon', + coordinates: [ + [ + [-97.746, 30.265, 300], + [-97.74, 30.265, 300], + [-97.74, 30.267, 300], + [-97.746, 30.265, 300], + ], + ], + }, + }, + ], +}; +const browser = await puppeteer.launch({ + headless: true, + args: ['--no-sandbox', '--disable-dev-shm-usage'], +}); +const page = await browser.newPage(); +const errors = [], + requests = []; +let pending, + failures = 0; +const check = (name, passed) => { + console.log(`[${passed ? 'PASS' : 'FAIL'}] ${name}`); + if (!passed) failures++; +}; +page.on('pageerror', (e) => errors.push(e.message)); + +await page.setRequestInterception(true); +page.on('request', (request) => { + const url = new URL(request.url()); + if (!url.pathname.startsWith('/scene-assets/')) + return void request.continue(); + requests.push(url.pathname); + if (url.pathname.endsWith('/slow.json')) { + pending = request; + return; + } + const reply = url.pathname.endsWith('/outline.json') + ? { contentType: 'application/geo+json', body: JSON.stringify(geojson) } + : url.pathname.endsWith('/image.png') + ? { contentType: 'image/png', body: png } + : url.pathname.endsWith('/audio.wav') + ? { contentType: 'audio/wav', body: wav } + : { status: 404, body: 'missing' }; + void request.respond(reply).catch(() => {}); +}); +try { + await page.setViewport({ width: 1440, height: 900 }); + await page.goto( + `${process.env.QA_BASE_URL || 'http://localhost:4173'}/?welcome=0`, + { waitUntil: 'domcontentloaded' }, + ); + await page.waitForFunction( + () => + window.__godsEyeView?.sceneDirector && + document.getElementById('loading-screen')?.classList.contains('hidden'), + { timeout: 60000 }, + ); + await page.evaluate(async () => { + const d = window.__godsEyeView.sceneDirector; + const manifest = (id, format, file, placement) => ({ + id, + version: 1, + format, + source: { adapter: 'assets', path: `qa/${file}` }, + attribution: { text: 'Synthetic QA fixture', license: 'CC0-1.0' }, + placement, + }); + const camera = { + lat: 30.2672, + lon: -97.742, + alt: 4000, + heading: 0, + pitch: -90, + roll: 0, + }; + const project = { + version: 5, + scenes: [ + { + id: 'packs', + title: 'Data packs QA', + anchors: [ + { + id: 'media', + lat: 30.269, + lon: -97.737, + alt: 450, + altitudeReference: 'ellipsoid', + }, + ], + dataPacks: [ + manifest('outline', 'geojson', 'outline.json', { + altitudeReference: 'ellipsoid', + }), + manifest('image', 'image', 'image.png', { + bounds: [-97.738, 30.264, -97.732, 30.267], + height: 300, + altitudeReference: 'ellipsoid', + }), + manifest('media', 'media', 'audio.wav', { anchorId: 'media' }), + manifest('slow', 'geojson', 'slow.json', { + altitudeReference: 'ellipsoid', + }), + manifest('missing', 'geojson', 'missing.json', { + altitudeReference: 'ellipsoid', + }), + ], + shots: ['all', 'empty', 'slow', 'missing'].map((id) => ({ + id, + title: id, + camera, + durationSec: 0.3, + holdSec: 0.2, + visual: { style: 'normal', mapStack: 'photoreal' }, + layers: {}, + dataPackIds: + id === 'all' + ? ['outline', 'image', 'media'] + : id === 'empty' + ? [] + : [id], + })), + }, + ], + }; + await d.importProjectFile( + new File([JSON.stringify(project)], 'packs.json'), + ); + window.__packBaseline = d.viewer.entities.values.length; + window.__packPrimitiveBaseline = d.viewer.scene.primitives.length; + window.__packRevoked = []; + const revoke = URL.revokeObjectURL.bind(URL); + URL.revokeObjectURL = (url) => { + window.__packRevoked.push(url); + revoke(url); + }; + }); + check('import does not acquire unselected assets', requests.length === 0); + const loaded = await page.evaluate(async () => { + const d = window.__godsEyeView.sceneDirector; + const result = await d.loadShot('packs', 'all', { flyDuration: 0.3 }); + window.__packMaterials = Array.from( + { + length: + d.viewer.scene.primitives.length - window.__packPrimitiveBaseline, + }, + (_, i) => + d.viewer.scene.primitives.get(window.__packPrimitiveBaseline + i) + .appearance?.material, + ).filter(Boolean); + return { + started: result?.started, + state: d.getDataPackState(), + count: d.viewer.entities.values.length - window.__packBaseline, + primitives: + d.viewer.scene.primitives.length - window.__packPrimitiveBaseline, + cards: document.querySelectorAll('[data-director-pack]').length, + paused: document.querySelector('[data-director-pack] audio')?.paused, + }; + }); + check( + 'GeoJSON, PNG and media load only through registered sources', + loaded.started && loaded.state.count === 3 && requests.length === 3, + ); + check( + 'geometry and image batches plus anchored markers render separately', + loaded.count === 2 && loaded.primitives === 3, + ); + check( + 'attribution is visible and media does not autoplay', + loaded.cards === 3 && loaded.paused === true, + ); + await page.waitForFunction( + () => window.__godsEyeView.mapStackController.getActiveId() === 'photoreal', + { timeout: 15000 }, + ); + await new Promise((r) => setTimeout(r, 5000)); + await page.waitForFunction( + () => window.__godsEyeView.tileset?.tilesLoaded === true, + { timeout: 60000 }, + ); + const evidence = await page.evaluate(() => ({ + mapStack: window.__godsEyeView.mapStackController.getActiveId(), + tilesSettled: window.__godsEyeView.tileset?.tilesLoaded === true, + })); + fs.writeFileSync( + path.join(output, 'report.json'), + JSON.stringify(evidence, null, 2), + ); + check( + 'static geometry is ready before visual acceptance', + await page.evaluate(() => { + const primitives = window.__godsEyeView.viewer.scene.primitives; + return Array.from( + { length: primitives.length - window.__packPrimitiveBaseline }, + (_, i) => primitives.get(window.__packPrimitiveBaseline + i), + ).every((p) => p.ready !== false); + }), + ); + await page.screenshot({ path: path.join(output, 'packs.png') }); + await page.evaluate(() => { + const d = window.__godsEyeView.sceneDirector; + d._setCameraView({ + ...d.styleManager.getCameraState(), + heading: 30, + pitch: -85, + }); + }); + await page.waitForFunction( + () => window.__godsEyeView.tileset?.tilesLoaded === true, + { timeout: 60000 }, + ); + await new Promise((r) => setTimeout(r, 2000)); + await page.screenshot({ path: path.join(output, 'angle.png') }); + const life = await page.evaluate(async () => { + const d = window.__godsEyeView.sceneDirector; + const media = document.querySelector('[data-director-pack] audio'); + await media.play(); + const played = !media.paused; + await d.loadShot('packs', 'empty', { flyDuration: 0.3 }); + const cleared = + d.getDataPackState().count === 0 && + !document.querySelector('[data-director-packs]') && + d.viewer.entities.values.length === window.__packBaseline && + d.viewer.scene.primitives.length === window.__packPrimitiveBaseline && + media.paused && + !media.getAttribute('src') && + window.__packRevoked.length === 2 && + window.__packMaterials.length === 1 && + window.__packMaterials.every((material) => material.isDestroyed()); + await d.seekScene('packs', 0.1); + const seek = d.getDataPackState().count === 3; + d.stopScene(); + const stopped = + d.getDataPackState().count === 0 && + d.viewer.entities.values.length === window.__packBaseline; + const missing = await d.loadShot('packs', 'missing', { flyDuration: 0.3 }); + return { + played, + cleared, + seek, + stopped, + missing: missing?.started === false && d.getDataPackState().count === 0, + }; + }); + for (const [name, passed] of Object.entries(life)) check(name, passed); + await page.evaluate(() => { + window.__pendingPack = window.__godsEyeView.sceneDirector.loadShot( + 'packs', + 'slow', + ); + }); + const deadline = Date.now() + 15000; + while (!pending && Date.now() < deadline) + await new Promise((r) => setTimeout(r, 50)); + check('pending transport reached', !!pending); + const cancelled = await page.evaluate(async () => { + const d = window.__godsEyeView.sceneDirector; + const start = performance.now(); + d.stopScene(); + await window.__pendingPack; + return performance.now() - start < 1000 && d.getDataPackState().count === 0; + }); + check('Stop promptly settles a pending transport', cancelled); + if (pending) + await pending + .respond({ + contentType: 'application/json', + body: JSON.stringify(geojson), + }) + .catch(() => {}); + check( + 'late response cannot reintroduce entities', + await page.evaluate( + () => + window.__godsEyeView.viewer.entities.values.length === + window.__packBaseline && + window.__godsEyeView.viewer.scene.primitives.length === + window.__packPrimitiveBaseline, + ), + ); + await page.evaluate(async () => { + const d = window.__godsEyeView.sceneDirector; + await d.loadShot('packs', 'all', { flyDuration: 0.3 }); + await d.importProjectFile( + new File([JSON.stringify({ version: 5, scenes: [] })], 'empty.json'), + ); + }); + check( + 'replacement import clears every pack resource', + await page.evaluate( + () => + window.__godsEyeView.sceneDirector.getDataPackState().count === 0 && + !document.querySelector('[data-director-packs]'), + ), + ); + check('no uncaught browser errors', errors.length === 0); + if (errors.length) + console.error(errors.map((e) => e.replace(/https?:\/\/\S+/g, '[URL]'))); +} finally { + await browser.close(); +} +if (failures) process.exitCode = 1; diff --git a/scripts/qa-director-sharing.mjs b/scripts/qa-director-sharing.mjs new file mode 100644 index 000000000..bfc76ed93 --- /dev/null +++ b/scripts/qa-director-sharing.mjs @@ -0,0 +1,482 @@ +#!/usr/bin/env node +/** Sharing/authoring acceptance with local synthetic assets and real installed controls. */ +import fs from 'node:fs'; +import path from 'node:path'; +import puppeteer from 'puppeteer'; +const output = path.resolve('qa-shots/director-sharing'); +fs.mkdirSync(output, { recursive: true }); +const geometry = { + type: 'FeatureCollection', + features: [ + { + type: 'Feature', + id: 'point', + geometry: { type: 'Point', coordinates: [-97.742, 30.2672, 500] }, + }, + ], +}; +fs.writeFileSync(path.join(output, 'data.geojson'), JSON.stringify(geometry)); +const camera = { + lat: 30.2672, + lon: -97.742, + alt: 4000, + heading: 0, + pitch: -90, + roll: 0, +}; +const project = { + version: 6, + scenes: [ + { + id: 'share', + title: 'Sharing fixture', + dataPacks: [ + { + id: 'data', + version: 1, + format: 'geojson', + source: { adapter: 'assets', path: 'example/data.geojson' }, + attribution: { text: 'Synthetic fixture', license: 'CC0-1.0' }, + placement: { altitudeReference: 'ellipsoid' }, + }, + ], + shots: [ + { + id: 'shot', + title: 'First', + camera, + durationSec: 0.3, + holdSec: 0, + visual: { style: 'normal', mapStack: 'photoreal' }, + layers: {}, + dataPackIds: ['data'], + interactions: [ + { + id: 'info', + label: 'Read fixture', + target: { packId: 'data', featureId: 'point' }, + action: { type: 'card', text: 'Synthetic scene note' }, + }, + ], + }, + ], + }, + { id: 'second', title: 'Other scene', shots: [] }, + ], +}; +const file = path.join(output, 'project.json'); +fs.writeFileSync(file, JSON.stringify(project)); +const browser = await puppeteer.launch({ + headless: true, + args: ['--no-sandbox', '--disable-dev-shm-usage'], +}); +const page = await browser.newPage(); +let failures = 0; +const errors = [], + requests = []; +const check = (name, ok) => { + console.log(`[${ok ? 'PASS' : 'FAIL'}] ${name}`); + if (!ok) failures++; +}; +page.on('pageerror', (e) => errors.push(e.message)); +page.on('request', (r) => { + if (new URL(r.url()).pathname.startsWith('/scene-assets/')) + requests.push(r.url()); +}); +async function click(label) { + const handle = await page.evaluateHandle( + (label) => + [...document.querySelectorAll('button')].find( + (b) => b.textContent === label, + ), + label, + ); + await handle.asElement().click(); + await handle.dispose(); +} +async function value(label, text) { + await page.$eval( + `[aria-label="${label}"]`, + (node, text) => { + node.value = text; + node.dispatchEvent(new Event('input', { bubbles: true })); + }, + text, + ); +} +try { + await page.setViewport({ width: 1440, height: 900 }); + await page.goto( + `${process.env.QA_BASE_URL || 'http://localhost:4173'}/?welcome=0`, + { waitUntil: 'domcontentloaded' }, + ); + await page.waitForFunction( + () => + window.__godsEyeView?.sceneDirector && + document.getElementById('loading-screen')?.classList.contains('hidden'), + { timeout: 60000 }, + ); + await page.click('[data-collapse-target="scene-panel"]'); + const before = await page.evaluate(() => + JSON.stringify(window.__godsEyeView.sceneDirector._project), + ); + const input = await page.$('#scene-import-file'); + await input.uploadFile(file); + await page.waitForSelector('[data-director-apply-import]'); + check( + 'preview parses metadata without acquiring assets or replacing the current project', + requests.length === 0 && + (await page.evaluate( + (before) => + JSON.stringify(window.__godsEyeView.sceneDirector._project) === + before, + before, + )), + ); + check( + 'preview renders author attribution as literal text', + await page.evaluate( + () => + document + .querySelector('[data-director-dialog]') + .textContent.includes('Synthetic fixture') && + !document.querySelector('[data-director-dialog] b'), + ), + ); + await page.keyboard.press('Escape'); + check( + 'Escape cancels preview without altering saved work', + await page.evaluate( + (before) => + !document.querySelector('[data-director-dialog]') && + JSON.stringify(window.__godsEyeView.sceneDirector._project) === before, + before, + ), + ); + await input.uploadFile(file); + await page.waitForSelector('[data-director-apply-import]'); + await page.click('[data-director-apply-import]'); + await page.waitForFunction( + () => !document.querySelector('[data-director-dialog]'), + ); + check( + 'Apply import replaces metadata but does not start playback or fetch a pack', + requests.length === 0 && + (await page.evaluate( + () => + window.__godsEyeView.sceneDirector._project.scenes.length === 2 && + !window.__godsEyeView.sceneDirector.running, + )), + ); + await click('EDIT DETAILS'); + await click('Capture camera as anchor'); + await page.waitForFunction(() => + document + .querySelector('[data-director-dialog] [role=status]') + .textContent.includes('Anchor added'), + ); + await click('Set move start to current camera'); + await page.waitForFunction(() => + document + .querySelector('[data-director-dialog] [role=status]') + .textContent.includes('Move added'), + ); + const draft = await page.$eval( + '[aria-label="Shot camera, timing, packs and actions"]', + (n) => n.value, + ); + const bad = JSON.parse(draft); + bad.camera.lat = 91; + await value('Shot camera, timing, packs and actions', JSON.stringify(bad)); + const saved = await page.evaluate(() => + localStorage.getItem('godsEyeView.sceneProject.v2'), + ); + await page.click('[data-director-apply-details]'); + await page.waitForFunction(() => + document + .querySelector('[data-director-dialog] [role=status]') + .textContent.includes('camera.lat'), + ); + check( + 'invalid draft preserves saved bytes and existing authored content', + await page.evaluate( + (saved) => localStorage.getItem('godsEyeView.sceneProject.v2') === saved, + saved, + ), + ); + await value('Shot camera, timing, packs and actions', draft); + await page.click('[data-director-apply-details]'); + await page.waitForFunction( + () => !document.querySelector('[data-director-dialog]'), + ); + check( + 'author controls preserve selected shot, pack attribution and action definitions', + await page.evaluate(() => { + const d = window.__godsEyeView.sceneDirector, + s = d._getSelectedScene(); + return ( + d._selectedShotId === 'shot' && + s.anchors.length === 1 && + s.shots[0].move.easing === 'cubic-in-out' && + s.shots[0].interactions.length === 1 && + s.dataPacks[0].attribution.license === 'CC0-1.0' + ); + }), + ); + await page.evaluate(() => { + window.__shareExports = []; + const create = URL.createObjectURL.bind(URL); + URL.createObjectURL = (blob) => { + if (blob.type === 'application/json') + window.__shareExports.push(blob.text()); + return create(blob); + }; + }); + await click('SHARE SCENE'); + await click('Download scene JSON'); + const exported = await page.evaluate(async () => + JSON.parse(await window.__shareExports.at(-1)), + ); + check( + 'scene JSON exports only the selected scene and keeps its credit', + exported.scenes.length === 1 && + exported.scenes[0].dataPacks[0].attribution.license === 'CC0-1.0', + ); + await click('Download asset bundle'); + await page.waitForFunction(() => + document + .querySelector('[data-director-dialog] [role=status]') + .textContent.includes('Could not complete'), + ); + check( + 'missing explicit files produce no partial download or network fallback', + requests.length === 0 && + (await page.evaluate(() => window.__shareExports.length === 1)), + ); + const files = await page.$('[aria-label="Choose data-pack files"]'); + await files.uploadFile(path.join(output, 'data.geojson')); + await click('Download asset bundle'); + await page.waitForFunction( + () => + document.querySelector('[data-director-dialog] [role=status]') + .textContent === 'Asset bundle downloaded', + ); + const bundle = await page.evaluate( + async () => await window.__shareExports.at(-1), + ); + const bundleFile = path.join(output, 'scene.gevbundle.json'); + fs.writeFileSync(bundleFile, bundle); + check( + 'bundle contains the selected bytes and preserves attribution', + JSON.parse(bundle).assets.length === 1 && + JSON.parse(bundle).project.scenes[0].dataPacks[0].attribution.license === + 'CC0-1.0', + ); + await page.keyboard.press('Escape'); + await input.uploadFile(bundleFile); + await page.waitForSelector('[data-director-apply-import]'); + check( + 'bundle preview verifies bytes and explains session-only storage', + await page.evaluate( + () => + document + .querySelector('[data-director-dialog]') + .textContent.includes('bundled bytes verified') && + window.__godsEyeView.sceneDirector.getSharingState().assets.count === 0, + ), + ); + await page.screenshot({ path: path.join(output, 'preview.png') }); + await page.click('[data-director-apply-import]'); + await page.waitForFunction( + () => !document.querySelector('[data-director-dialog]'), + ); + await page.evaluate(() => + window.__godsEyeView.sceneDirector.loadShot('share', 'shot', { + flyDuration: 0.3, + }), + ); + check( + 'imported bundle renders and enables feature actions with zero asset requests', + requests.length === 0 && + (await page.evaluate( + () => + window.__godsEyeView.sceneDirector.getDataPackState().count === 1 && + window.__godsEyeView.sceneDirector.getInteractionState().count === 1, + )), + ); + await page.waitForFunction( + () => window.__godsEyeView.tileset?.tilesLoaded === true, + { timeout: 60000 }, + ); + await page.screenshot({ path: path.join(output, 'rendered.png') }); + fs.writeFileSync( + path.join(output, 'report.json'), + JSON.stringify( + await page.evaluate(() => ({ + tilesSettled: window.__godsEyeView.tileset?.tilesLoaded === true, + })), + ), + ); + await page.evaluate(() => window.__godsEyeView.sceneDirector.stopScene()); + check( + 'Stop releases rendered resources while retaining reusable project bytes', + await page.evaluate(() => { + const d = window.__godsEyeView.sceneDirector; + return ( + d.getDataPackState().count === 0 && + d.getSharingState().assets.count === 1 + ); + }), + ); + await page.evaluate(() => + window.__godsEyeView.sceneDirector.seekScene('share', 0), + ); + check( + 'seek reloads the bundle without a network fallback', + requests.length === 0 && + (await page.evaluate( + () => window.__godsEyeView.sceneDirector.getDataPackState().count === 1, + )), + ); + await click('EDIT DETAILS'); + await page.evaluate(() => { + window.__godsEyeView.sceneDirector._project.scenes[0].title = 'Newer edit'; + }); + await page.click('[data-director-apply-details]'); + check( + 'stale author draft cannot overwrite a newer edit', + await page.evaluate( + () => + window.__godsEyeView.sceneDirector._project.scenes[0].title === + 'Newer edit', + ), + ); + await page.keyboard.press('Escape'); + await click('SHARE SCENE'); + await page.setViewport({ width: 390, height: 844 }); + check( + 'modal remains within a narrow viewport', + await page.$eval('[data-director-dialog]', (n) => { + const r = n.getBoundingClientRect(); + return ( + r.left >= 0 && + r.right <= innerWidth && + r.top >= 0 && + r.bottom <= innerHeight + ); + }), + ); + await page.screenshot({ path: path.join(output, 'narrow.png') }); + await page.keyboard.press('Escape'); + const pending = await page.evaluate(async () => { + const d = window.__godsEyeView.sceneDirector; + let finish; + const work = d._sharing.preview({ + name: 'pending.json', + text: () => new Promise((r) => (finish = r)), + }); + d._sharing.close(); + await work; + finish(JSON.stringify({ version: 6, scenes: [] })); + return !d.getSharingState().open; + }); + check( + 'cancel settles a pending file read and suppresses its late completion', + pending, + ); + const cancelledApply = await page.evaluate(async () => { + const d = window.__godsEyeView.sceneDirector; + const before = JSON.stringify(d._project); + const saved = JSON.stringify({ ...localStorage }); + let finish; + const pendingWork = new Promise((resolve) => (finish = resolve)); + d._pendingWork.add(pendingWork); + const owner = new AbortController(); + const work = d.importProjectFile( + { name: 'cancelled.json' }, + { + prepared: { project: { version: 6, scenes: [] }, assets: new Map() }, + expectedProject: JSON.stringify(d._project, null, 2), + signal: owner.signal, + }, + ); + owner.abort(); + finish(); + const applied = await work; + d._pendingWork.delete(pendingWork); + return ( + applied === false && + JSON.stringify(d._project) === before && + JSON.stringify({ ...localStorage }) === saved && + d.getSharingState().assets.count === 1 + ); + }); + check( + 'cancelling Apply during pending scene cleanup preserves saved project and bundle bytes', + cancelledApply, + ); + await click('EDIT DETAILS'); + await page.evaluate(() => { + const fields = [ + ...document.querySelectorAll('[data-director-dialog] textarea'), + ]; + const scene = JSON.parse(fields[0].value), + shot = JSON.parse(fields[1].value); + scene.dataPacks = []; + shot.dataPackIds = []; + shot.interactions = []; + fields[0].value = JSON.stringify(scene); + fields[1].value = JSON.stringify(shot); + }); + await page.click('[data-director-apply-details]'); + await page.waitForFunction( + () => !document.querySelector('[data-director-dialog]'), + ); + check( + 'removing a pack through authoring releases its retained bytes', + await page.evaluate( + () => + window.__godsEyeView.sceneDirector.getSharingState().assets.count === 0, + ), + ); + await page.evaluate( + (text) => + window.__godsEyeView.sceneDirector.importProjectFile( + new File([text], 'again.gevbundle.json'), + ), + bundle, + ); + await page.evaluate(() => + window.__godsEyeView.sceneDirector.importProjectFile( + new File([JSON.stringify({ version: 6, scenes: [] })], 'empty.json'), + ), + ); + check( + 'replacement releases stored bundle bytes', + await page.evaluate( + () => + window.__godsEyeView.sceneDirector.getSharingState().assets.count === 0, + ), + ); + await page.evaluate(async () => { + const d = window.__godsEyeView.sceneDirector; + void d._sharing.preview({ + name: 'pending.json', + text: () => new Promise(() => {}), + }); + await d.destroy(); + }); + check( + 'teardown removes pending dialogs and authoring controls', + await page.evaluate( + () => + !document.querySelector('[data-director-dialog]') && + !document.querySelector('[data-director-authoring]') && + !window.__godsEyeView.sceneDirector.getSharingState().open, + ), + ); + check('no uncaught browser errors', errors.length === 0); +} finally { + await browser.close(); +} +process.exitCode = failures ? 1 : 0; diff --git a/scripts/qa-director-timing.mjs b/scripts/qa-director-timing.mjs new file mode 100644 index 000000000..1361a8dcb --- /dev/null +++ b/scripts/qa-director-timing.mjs @@ -0,0 +1,137 @@ +#!/usr/bin/env node +/** Exercise scene-clock ownership and authored seek behavior in the composed browser app. */ +import fs from 'node:fs'; +import path from 'node:path'; +import puppeteer from 'puppeteer'; +const shots = path.resolve('qa-shots/director-timing'); +fs.mkdirSync(shots, { recursive: true }); +const browser = await puppeteer.launch({ + headless: true, + args: ['--no-sandbox', '--disable-dev-shm-usage'], +}); +const page = await browser.newPage(); +const errors = []; +page.on('pageerror', (error) => errors.push(error.message)); +let failures = 0; +function check(name, passed) { + console.log(`[${passed ? 'PASS' : 'FAIL'}] ${name}`); + if (!passed) failures++; +} +try { + await page.setViewport({ width: 1440, height: 900 }); + await page.goto( + `${process.env.QA_BASE_URL || 'http://localhost:4173'}/?welcome=0`, + { waitUntil: 'domcontentloaded' }, + ); + await page.waitForFunction( + () => + window.__godsEyeView?.sceneDirector && + document.getElementById('loading-screen')?.classList.contains('hidden'), + { timeout: 60000 }, + ); + const result = await page.evaluate(async () => { + const director = window.__godsEyeView.sceneDirector; + const camera = director.styleManager.getCameraState(); + const visual = director.styleManager.getVisualState(); + const scene = { + id: 'timing-qa', + title: 'Timing QA', + shots: [0, 1].map((index) => ({ + id: `timing-${index}`, + title: `Timing ${index}`, + durationSec: 0.4, + holdSec: 0.3, + camera: { ...camera, lon: camera.lon + index * 0.002 }, + visual, + layers: {}, + })), + }; + director._project.scenes.push(scene); + const load = await director.loadShot(scene.id, scene.shots[0].id, { + flyDuration: 0.3, + }); + const forward = await director.seekScene(scene.id, 0.9); + const forwardSnapshot = director.getPlaybackTimingState().snapshot; + const backward = await director.seekScene(scene.id, 0.1); + const backwardSnapshot = director.getPlaybackTimingState().snapshot; + const replay = await director.replayShot(scene.id, scene.shots[1].id); + director.stopScene(); + await director.startScene(scene.id, { single: true, preview: false }); + const completed = + !director.running && director.getPlaybackTimingState().activeTimers === 0; + scene.shots[0].holdSec = 60; + const run = director.startScene(scene.id, { single: true, preview: false }); + const deadline = Date.now() + 10000; + while ( + director.getPlaybackTimingState().activeTimers < 3 && + Date.now() < deadline + ) + await new Promise((resolve) => setTimeout(resolve, 25)); + const holding = director.getPlaybackTimingState().activeTimers >= 3; + const stoppedAt = performance.now(); + director.stopScene('QA Stop during hold'); + await run; + const stoppedPromptly = performance.now() - stoppedAt < 1000; + const noTimers = director.getPlaybackTimingState().activeTimers === 0; + director._project.scenes = director._project.scenes.filter( + ({ id }) => id !== scene.id, + ); + return { + loaded: load?.started, + forward: forward && forwardSnapshot.shotId === 'timing-1', + backward: backward && backwardSnapshot.shotId === 'timing-0', + replay: replay?.started, + completed, + holding, + stoppedPromptly, + noTimers, + }; + }); + for (const [name, passed] of Object.entries(result)) check(name, passed); + const content = await page.evaluate(async () => { + const d = window.__godsEyeView.sceneDirector; + const scene = d._project.scenes.find(({ title }) => + /Nepal Flood Incident/i.test(title), + ); + if (!scene) return { exists: false }; + const shot = + scene.shots.find(({ title }) => /Regional Approach/i.test(title)) || + scene.shots[0]; + const loaded = await d.loadShot(scene.id, shot.id, { flyDuration: 0.3 }); + return { + exists: true, + shots: scene.shots.length, + loaded: loaded?.started === true, + }; + }); + check( + 'existing Nepal scene and authored shots load', + content.exists && content.shots >= 25 && content.loaded, + ); + await new Promise((resolve) => setTimeout(resolve, 2500)); + await page.screenshot({ path: path.join(shots, 'nepal-regional.png') }); + await page.evaluate(() => { + const g = window.__godsEyeView; + g.sceneDirector.stopScene(); + const pose = g.styleManager.getCameraState(); + g.sceneDirector._setCameraView({ + ...pose, + heading: pose.heading + 45, + pitch: -55, + }); + }); + await new Promise((resolve) => setTimeout(resolve, 1000)); + await page.screenshot({ path: path.join(shots, 'nepal-angle.png') }); + check( + 'no pending clocks after Stop', + await page.evaluate( + () => + window.__godsEyeView.sceneDirector.getPlaybackTimingState() + .activeTimers === 0, + ), + ); + check('no browser exceptions', errors.length === 0); +} finally { + await browser.close(); +} +if (failures) process.exitCode = 1; diff --git a/scripts/qa-layer-panel.mjs b/scripts/qa-layer-panel.mjs index 453009929..1282c6b50 100644 --- a/scripts/qa-layer-panel.mjs +++ b/scripts/qa-layer-panel.mjs @@ -23,13 +23,17 @@ try { `${process.env.QA_BASE_URL || 'http://localhost:4173'}/?welcome=0`, { waitUntil: 'domcontentloaded' }, ); - await page.waitForFunction( - () => window.__godsEyeView?.dataManager?._layerPanel, - { timeout: 60000 }, - ); + await page.waitForFunction(() => window.__godsEyeView?.dataManager, { + timeout: 60000, + }); const results = await page.evaluate(async () => { const manager = window.__godsEyeView.dataManager; - const container = manager._toggleContainer; + const entry = document.querySelector( + 'script[type="module"][src*="/src/main.js"]', + ); + const { application } = await import(entry.src); + const { presentation } = application.getComponents().data; + const container = presentation.panel._toggleContainer; const id = 'qa-panel-lifecycle'; let listener = null; let enabled = 0; @@ -54,7 +58,7 @@ try { }); const result = []; try { - manager.buildTogglePanel(container); + presentation.mount(container); const row = () => container.querySelector(`[data-layer-id="${id}"]`); const first = row().querySelector('.data-toggle-btn'); result.push([ @@ -66,7 +70,7 @@ try { 'row subscription is installed', typeof listener === 'function', ]); - manager.buildTogglePanel(container); + presentation.mount(container); first.click(); await Promise.resolve(); result.push([ @@ -97,7 +101,7 @@ try { ]); await manager.setEnabled(id, true); const final = row().querySelector('.data-toggle-btn'); - manager._layerPanel.destroy(); + presentation._panel.destroy(); final.click(); await Promise.resolve(); result.push([ @@ -109,10 +113,10 @@ try { manager.isEnabled(id), ]); } finally { - manager._layerPanel?.destroy(); - manager._layerPanel = null; + presentation._panel?.destroy(); + presentation._panel = null; await window.__gevQaUnregisterLayer(manager, id); - manager.buildTogglePanel(container); + presentation.mount(container); } result.push([ 'ordinary layer rows return after reassembly', diff --git a/scripts/qa-nepal-media-playback.mjs b/scripts/qa-nepal-media-playback.mjs new file mode 100644 index 000000000..87dc5d64f --- /dev/null +++ b/scripts/qa-nepal-media-playback.mjs @@ -0,0 +1,204 @@ +#!/usr/bin/env node +// Composed-app media policy/lifecycle checks. Pinokio UA is a policy fixture, +// not native-host acceptance; the YouTube SDK clock below is deterministic. +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import puppeteer from 'puppeteer'; + +const output = path.resolve( + process.env.QA_OUTPUT_DIR || 'qa-shots/nepal-media', +); +fs.mkdirSync(output, { recursive: true }); +const browser = await puppeteer.launch({ + headless: process.env.QA_HEADFUL !== '1', + args: process.env.QA_HEADFUL === '1' ? ['--use-angle=metal'] : [], +}); +let assertions = 0; +const check = (name, value) => { + assert.ok(value, name); + assertions++; + console.log(`[PASS] ${name}`); +}; +try { + for (const pinokio of [true, false]) { + const page = await browser.newPage(); + await page.setViewport({ width: 1440, height: 900 }); + if (pinokio) + await page.setUserAgent((await browser.userAgent()) + ' Pinokio/8.0.40'); + const popups = []; + page.on('popup', (popup) => popups.push(popup.url())); + // Do not depend on provider availability to prove our startup/trim/exit handoff. + await page.setRequestInterception(true); + page.on('request', (request) => { + if (/youtube(?:-nocookie)?\.com\/embed\//.test(request.url())) { + void request.respond({ + status: 200, + contentType: 'text/html', + body: '

Player clock fixture

', + }); + } else void request.continue(); + }); + await page.evaluateOnNewDocument(() => { + window.__mediaFixture = { starts: [], stops: [] }; + window.YT = { + Player: class { + constructor(_frame, { events }) { + this.events = events; + this.began = null; + this.stoppedAt = null; + this.timer = setTimeout( + () => events.onReady({ target: this }), + 1200, + ); + } + mute() {} + playVideo() { + if (this.began != null) return; + this.began = Date.now(); + window.__mediaFixture.starts.push(this.began); + this.events.onStateChange({ target: this, data: 1 }); + } + getCurrentTime() { + return this.began == null + ? 0 + : ((this.stoppedAt || Date.now()) - this.began) / 1000; + } + getPlayerState() { + return this.began == null ? -1 : this.stoppedAt ? 2 : 1; + } + pauseVideo() { + if (this.began != null && !this.stoppedAt) { + this.stoppedAt = Date.now(); + window.__mediaFixture.stops.push(this.getCurrentTime()); + } + } + destroy() { + clearTimeout(this.timer); + this.pauseVideo(); + } + }, + }; + }); + await page.goto( + `${process.env.QA_BASE_URL || 'http://localhost:4173'}/?welcome=0`, + { waitUntil: 'domcontentloaded' }, + ); + await page.waitForFunction( + () => + window.__godsEyeView?.sceneDirector && + document.querySelector('#loading-screen')?.classList.contains('hidden'), + { timeout: 60000 }, + ); + const result = await page.evaluate(async (pinokio) => { + const d = window.__godsEyeView.sceneDirector; + const scene = d._project.scenes.find((s) => /Nepal/.test(s.title)); + const shot = scene.shots.find((s) => /Mailung Bazzar/.test(s.title)); + const following = scene.shots[scene.shots.indexOf(shot) + 1]; + const previous = scene.shots[scene.shots.indexOf(shot) - 1]; + const frames = () => + [...document.querySelectorAll('iframe')].map((f) => f.src); + const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + await d.loadShot(scene.id, scene.shots[0].id, { flyDuration: 0.1 }); + const openingFrames = frames(); + await d.loadShot(scene.id, shot.id, { flyDuration: 0.1 }); + const passiveFrames = frames(); + const started = Date.now(); + const run = d.startScene(scene.id, { + single: true, + afterShotId: previous.id, + preview: false, + }); + let advanced = null; + while (Date.now() - started < 25000) { + if (d._selectedShotId === following.id) { + advanced = Date.now() - started; + break; + } + if (!d.running) break; + await sleep(100); + } + const runningAtAdvance = d.running; + const clipStops = [...window.__mediaFixture.stops]; + const status = document.querySelector('#scene-status')?.textContent; + d.stopScene(); + await run; + await sleep(250); + const stoppedFrames = frames(); + let replayAutoplay = false; + let replacementSilent = false; + if (!pinokio) { + await d.replayShot(scene.id, shot.id); + replayAutoplay = frames().some((src) => /autoplay=1/.test(src)); + await d.loadShot(scene.id, scene.shots[0].id, { flyDuration: 0.1 }); + const starts = window.__mediaFixture.starts.length; + await sleep(1600); + replacementSilent = + frames().length === 0 && + starts === window.__mediaFixture.starts.length; + } + const gl = d.viewer.scene.context._gl; + const info = gl.getExtension('WEBGL_debug_renderer_info'); + return { + openingFrames, + passiveFrames, + advanced, + runningAtAdvance, + status, + clipStops, + stoppedFrames, + replayAutoplay, + replacementSilent, + renderer: info + ? gl.getParameter(info.UNMASKED_RENDERER_WEBGL) + : gl.getParameter(gl.RENDERER), + }; + }, pinokio); + console.log(JSON.stringify({ pinokioPolicyFixture: pinokio, ...result })); + check( + 'opening shot creates no unrelated provider frames', + result.openingFrames.length === 0, + ); + check( + 'passive LOAD never requests autoplay', + result.passiveFrames.every((src) => !/autoplay=1/.test(src)), + ); + check( + 'actual next-shot identity reached while scene remains running', + result.advanced > 0 && result.runningAtAdvance, + ); + check('no scene timeout', !/timed out|Error:/i.test(result.status || '')); + check('Stop removes provider resources', result.stoppedFrames.length === 0); + check('no automatic external window', popups.length === 0); + if (pinokio) { + check( + 'suppressed providers allocate no iframe', + result.passiveFrames.length === 0, + ); + check( + 'fallback keeps authored dwell', + result.advanced >= 7500 && result.advanced < 18000, + ); + } else { + check( + 'supported clip follows seven-second source clock', + result.clipStops.some((sec) => sec >= 7 && sec < 7.6), + ); + check( + 'explicit Play Shot still requests autoplay', + result.replayAutoplay, + ); + check( + 'replacement disowns pending player startup', + result.replacementSilent, + ); + } + await page.screenshot({ + path: path.join(output, pinokio ? 'pinokio-policy.png' : 'chrome.png'), + }); + await page.close(); + } + console.log(`PASS: ${assertions} assertions`); +} finally { + await browser.close(); +} diff --git a/scripts/qa-radio.mjs b/scripts/qa-radio.mjs index c5629d2f4..c30a17ee0 100644 --- a/scripts/qa-radio.mjs +++ b/scripts/qa-radio.mjs @@ -374,7 +374,7 @@ async function main() { enabled: true, uncertain: true, }); - gev.dataManager._refreshTogglePanel(); + gev.dataManager.refreshLayerStats(); const staticResult = module.setTuningStatic(true); const filterBefore = module.getUIState().filter; const filterControl = document.getElementById('radio-filter'); @@ -447,7 +447,7 @@ async function main() { enabled: true, uncertain: false, }); - gev.dataManager._refreshTogglePanel(); + gev.dataManager.refreshLayerStats(); module.cancelTuning(); camera.flyTo = originalFlyTo; return result; @@ -4048,7 +4048,13 @@ async function main() { const { getOverlayPaintRect, getWorldOverlayDiagnostics } = await import('/src/overlays/worldOverlay.js'); const expectedEntryId = `selected:${selected.id}`; let painted = null; - for (let attempt = 0; attempt < 20 && !painted?.rect; attempt += 1) { + // Radio's horizon pass reveals the selected entity on its own timer + // after the camera jump, so a stationary view waits for both to settle. + for ( + let attempt = 0; + attempt < 20 && !(painted?.rect && selectedEntity?.show === true); + attempt += 1 + ) { painted = await new Promise((resolve) => { let removePostRender = null; const timeout = setTimeout(() => { diff --git a/scripts/qa-recent-imagery.mjs b/scripts/qa-recent-imagery.mjs new file mode 100644 index 000000000..1460ed3b5 --- /dev/null +++ b/scripts/qa-recent-imagery.mjs @@ -0,0 +1,1480 @@ +#!/usr/bin/env node +/** + * Rendered acceptance for DATA ▸ Recent Imagery against the real NASA + * endpoints (CMR catalog, GIBS tiles, Worldview snapshots): the rail panel, + * USE VIEW and the live preview, the three modes (IMAGE, VS BASEMAP, A / B) + * with their pins, the divider and the Esri surface on Google 3D, Escape + * order, the oversized-view refusal and ZOOM IN, CLEAR, the share link, + * map-switch rebind (a manual switch to Google 3D keeps the imagery on + * Esri), CCTV stability at 900 and 700 px, scroll preservation, a + * layout-shift measurement across every transition, and disable. + * + * Run: start the app (`./scripts/dev-fresh.sh`) and + * node scripts/qa-recent-imagery.mjs + * Env: QA_BASE_URL (default http://localhost:4173), QA_SHOT_DIR (default + * qa-shots/recent-imagery), QA_HEADFUL=1. Every wait is bounded. Without + * network access to NASA the run skips with exit code 0. + */ +import fs from 'node:fs'; +import path from 'node:path'; +import puppeteer from 'puppeteer'; + +const BASE_URL = process.env.QA_BASE_URL || 'http://localhost:4173'; +const SHOT_DIR = process.env.QA_SHOT_DIR || 'qa-shots/recent-imagery'; +const HEADFUL = process.env.QA_HEADFUL === '1'; +const STEP_TIMEOUT = 20_000; +const AUSTIN = { lon: -97.74, lat: 30.27, height: 12_000 }; +const PANEL = '#recent-imagery-panel'; + +async function networkAvailable() { + try { + const response = await fetch( + 'https://cmr.earthdata.nasa.gov/search/collections.json?page_size=1', + { signal: AbortSignal.timeout(8_000) }, + ); + return response.ok; + } catch { + return false; + } +} + +if (!(await networkAvailable())) { + console.log( + 'SKIP: cmr.earthdata.nasa.gov is unreachable — the live Recent Imagery gate needs network access.', + ); + process.exit(0); +} + +const browser = await puppeteer.launch({ + headless: !HEADFUL, + ...(HEADFUL + ? { + executablePath: + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', + } + : {}), + args: [ + '--no-sandbox', + '--disable-background-timer-throttling', + '--disable-renderer-backgrounding', + ...(HEADFUL ? ['--window-size=1280,860'] : []), + ...(process.platform === 'darwin' + ? ['--use-angle=metal', '--enable-gpu'] + : ['--use-gl=angle', '--use-angle=swiftshader']), + ], +}); +const page = await browser.newPage(); +const errors = []; +page.on('pageerror', (error) => errors.push(`pageerror: ${error.message}`)); +let failures = 0; +let checks = 0; +function check(name, passed, detail = '') { + checks += 1; + console.log( + `[${passed ? 'PASS' : 'FAIL'}] ${name}${detail ? ` — ${detail}` : ''}`, + ); + if (!passed) failures++; +} +fs.mkdirSync(SHOT_DIR, { recursive: true }); +const shots = []; +const shot = async (name) => { + const file = path.join(SHOT_DIR, `${name}.jpg`); + await page.screenshot({ path: file, type: 'jpeg', quality: 82 }); + shots.push(file); +}; +const panelShot = async (name) => { + const panel = await page.$(PANEL); + if (!panel) return; + const file = path.join(SHOT_DIR, `${name}.png`); + await panel.screenshot({ path: file }); + shots.push(file); +}; +const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +/** Poll a page predicate; false on timeout instead of throwing. */ +async function until(fn, arg, timeout = STEP_TIMEOUT) { + try { + await page.waitForFunction(fn, { timeout, polling: 250 }, arg); + return true; + } catch { + return false; + } +} + +/** + * Page-side helpers every predicate can use: the layer handle, GIBS layers + * per host with their split directions, and whether a header is on screen. + */ +function installPageHelpers() { + window.__riQa = { + layer: () => window.__gevRecentImagery.layer, + snap: () => window.__gevRecentImagery.layer.getSnapshot(), + owned: () => window.__gevRecentImagery.layer.diagnostics().ownedCount, + gibs(collection) { + const out = []; + for (let i = 0; i < (collection?.length || 0); i += 1) { + const layer = collection.get(i); + if ( + String(layer?.imageryProvider?.url || '').includes( + 'earthdata.nasa.gov', + ) + ) + out.push(layer.splitDirection); + } + return out; + }, + hosts() { + const gev = window.__godsEyeView; + const globe = this.gibs(gev.viewer.imageryLayers); + const tileset = this.gibs(gev.tileset?.imageryLayers); + return { + globe: globe.length, + tileset: tileset.length, + splits: [...globe, ...tileset], + globeShown: gev.viewer.scene.globe.show, + }; + }, + splitShown() { + const line = document.getElementById('recent-imagery-split-line'); + return Boolean(line && !line.hidden); + }, + headerOnScreen(id) { + const element = document.getElementById(id); + const header = + element?.querySelector('.panel-header, .pp-header-row') || element; + const rect = header?.getBoundingClientRect(); + return rect + ? rect.height > 0 && rect.top >= 0 && rect.bottom <= window.innerHeight + : false; + }, + activeStack: () => + window.__godsEyeView.mapStackController?.getActiveId?.() ?? null, + }; +} + +const state = () => + page.evaluate(() => { + const qa = window.__riQa; + const snapshot = qa.snap(); + const gev = window.__godsEyeView; + const split = document.getElementById('recent-imagery-split-line'); + const text = (id) => document.getElementById(id)?.textContent || ''; + const hosts = qa.hosts(); + return { + box: snapshot.box, + boxError: snapshot.boxError, + mode: snapshot.mode, + candidates: snapshot.candidates.map((c) => ({ + key: c.key, + drapable: c.drapable, + })), + focus: snapshot.focus?.key || null, + pinA: snapshot.pins.a.key, + pinB: snapshot.pins.b.key, + preview: snapshot.preview.key, + shown: snapshot.shown, + notice: snapshot.notice, + comparison: snapshot.comparison, + borrowedEsri: snapshot.borrowedEsri, + error: snapshot.error, + diagnostics: qa.layer().diagnostics(), + cards: document.querySelectorAll('#recent-imagery-panel .ri-card').length, + panelHidden: document.getElementById('recent-imagery-panel')?.hidden, + noticeText: text('ri-notice-text'), + hintText: text('ri-hint'), + rowA: text('ri-slot-a'), + rowB: text('ri-slot-b'), + splitVisible: Boolean( + split && !split.hidden && split.getBoundingClientRect().height > 0, + ), + splitLabels: split + ? [ + split.querySelector('span.before')?.textContent, + split.querySelector('span.after')?.textContent, + ] + : null, + splitLeft: split ? split.getBoundingClientRect().left : null, + splitPosition: gev.viewer.scene.splitPosition, + canvasWidth: gev.viewer.scene.canvas.clientWidth, + activeStack: qa.activeStack(), + gibsOnGlobe: hosts.globe, + gibsOnTileset: hosts.tileset, + gibsSplits: hosts.splits, + }; + }); +const hostsDetail = (s) => + `owned=${s.diagnostics.ownedCount} host=${s.diagnostics.host} globe=${s.gibsOnGlobe} tileset=${s.gibsOnTileset} splits=${s.gibsSplits}`; + +/** Put the camera straight down over a point at a height, no flight. */ +const setView = (view) => + page.evaluate((target) => { + const viewer = window.__godsEyeView.viewer; + viewer.camera.cancelFlight?.(); + viewer.scene.tweens?.removeAll?.(); + viewer.camera.setView({ + destination: viewer.scene.globe.ellipsoid.cartographicToCartesian({ + longitude: (target.lon * Math.PI) / 180, + latitude: (target.lat * Math.PI) / 180, + height: target.height, + }), + orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, + }); + viewer.scene.requestRender(); + }, view); + +/** Ground width of the camera's view rectangle, in km (0 without one). */ +const viewWidthKm = () => + page.evaluate(() => { + const rect = window.__godsEyeView.viewer.camera.computeViewRectangle?.(); + if (!rect) return 0; + const lat = (rect.south + rect.north) / 2; + return Math.abs(rect.east - rect.west) * 6371 * Math.cos(lat); + }); + +const click = (selector) => + page.evaluate((target) => { + const button = document.querySelector(target); + if (!button || button.disabled || button.hidden) return false; + button.click(); + return true; + }, selector); +const clickAction = (id) => click(`${PANEL} [data-action-id="${id}"]`); +const clickMode = (mode) => click(`${PANEL} .ri-mode-btn[data-mode="${mode}"]`); +const focusStrip = () => + page.evaluate(() => + document.getElementById('ri-strip')?.focus({ preventScroll: true }), + ); +const pressOnStrip = async (key) => { + await focusStrip(); + await page.keyboard.press(key); +}; + +/** Average colour of the canvas centre — the inside of a centred 10 km box. */ +async function probe() { + const base64 = await page.screenshot({ + clip: { x: 540, y: 330, width: 200, height: 200 }, + type: 'png', + encoding: 'base64', + }); + return page.evaluate(async (data) => { + const bitmap = await createImageBitmap( + await (await fetch(`data:image/png;base64,${data}`)).blob(), + ); + const canvas = new OffscreenCanvas(bitmap.width, bitmap.height); + const context = canvas.getContext('2d'); + context.drawImage(bitmap, 0, 0); + const pixels = context.getImageData(0, 0, bitmap.width, bitmap.height).data; + const sum = [0, 0, 0]; + for (let i = 0; i < pixels.length; i += 4) + for (let c = 0; c < 3; c += 1) sum[c] += pixels[i + c]; + return sum.map((value) => Math.round(value / (pixels.length / 4))); + }, base64); +} + +const tilesSettled = () => + until(() => { + const gev = window.__godsEyeView; + if (gev.viewer.scene.globe.show) return gev.viewer.scene.globe.tilesLoaded; + return !gev.tileset || gev.tileset.tilesLoaded; + }); +const backOnPhotoreal = () => + until(() => window.__riQa.activeStack() === 'photoreal'); +const onEsri = () => + until(() => window.__riQa.activeStack() === 'esri-imagery'); +const ownedIs = (count) => + until((n) => window.__riQa.owned() === n, count, 10_000); + +// ── layout-shift measurement ──────────────────────────────────────────────── +const CONTROLS = { + 'select-box': `${PANEL} [data-action-id="select-box"]`, + 'use-view': `${PANEL} [data-action-id="use-view"]`, + clear: `${PANEL} [data-action-id="clear"]`, + notice: '#ri-notice', + 'zoom-in': '#ri-zoom-in', + strip: '#ri-strip', + hint: '#ri-hint', + 'mode-image': `${PANEL} .ri-mode-btn[data-mode="image"]`, + 'mode-basemap': `${PANEL} .ri-mode-btn[data-mode="basemap"]`, + 'mode-ab': `${PANEL} .ri-mode-btn[data-mode="ab"]`, + 'row-a': '#ri-slot-a', + 'row-b': '#ri-slot-b', + 'unpin-a': '#ri-unpin-a', + 'unpin-b': '#ri-unpin-b', + opacity: '#ri-opacity', + swap: '#ri-swap', + 'export-a': `${PANEL} [data-action-id="export-a"]`, + 'export-b': `${PANEL} [data-action-id="export-b"]`, + details: '#ri-details .rail-card-header', +}; +const measure = () => + page.evaluate((controls) => { + const body = document.getElementById('recent-imagery-panel-body'); + const out = { bodyScroll: body?.scrollTop ?? null, rects: {} }; + for (const [name, selector] of Object.entries(controls)) { + const rect = document.querySelector(selector)?.getBoundingClientRect(); + out.rects[name] = rect + ? [rect.left, rect.top, rect.width, rect.height].map( + (v) => Math.round(v * 10) / 10, + ) + : null; + } + return out; + }, CONTROLS); +let layoutBaseline = null; +/** Every control's rect matches the baseline within 1 px. */ +async function checkLayout(label) { + await wait(150); + const now = await measure(); + if (!layoutBaseline) { + layoutBaseline = now; + check( + `layout baseline recorded (${label})`, + Object.values(now.rects).every(Boolean), + JSON.stringify(now.rects), + ); + return; + } + const moved = Object.entries(now.rects).filter(([name, rect]) => { + const base = layoutBaseline.rects[name]; + return ( + !rect || !base || rect.some((value, i) => Math.abs(value - base[i]) > 1) + ); + }); + check( + `no control moves: ${label}`, + moved.length === 0, + moved + .map( + ([name, rect]) => + `${name} ${JSON.stringify(layoutBaseline.rects[name])}→${JSON.stringify(rect)}`, + ) + .join(' '), + ); +} + +try { + await page.setViewport({ width: 1280, height: 860 }); + await page.goto(`${BASE_URL}/?welcome=0`, { waitUntil: 'domcontentloaded' }); + const booted = await until( + () => + window.__gevRecentImagery && + window.__godsEyeView && + document.getElementById('loading-screen')?.classList.contains('hidden'), + null, + 90_000, + ); + check('the app boots with the Recent Imagery handle', booted); + if (!booted) throw new Error('boot timeout'); + await page.evaluate(installPageHelpers); + + await setView(AUSTIN); + await tilesSettled(); + const initialStack = await page.evaluate(() => window.__riQa.activeStack()); + const photoreal = initialStack === 'photoreal'; + console.log(`initial map stack: ${initialStack}`); + const onPhotorealOnly = (name, passed, detail) => + photoreal + ? check(name, passed, detail) + : console.log(`[SKIP] ${name} — the boot stack is ${initialStack}`); + + // ── enable: the panel in the rail, per the rail readout pattern ───────── + const layerToggle = '[data-layer-id="recent-imagery"] .data-toggle-btn'; + check( + 'the data panel carries a Recent Imagery toggle', + await click(layerToggle), + ); + check( + 'the layer enables from its toggle', + await until(() => + window.__godsEyeView.dataManager.isEnabled('recent-imagery'), + ), + ); + check( + 'the panel appears on the right rail once enabled', + await until( + () => document.getElementById('recent-imagery-panel')?.hidden === false, + ), + ); + const railPlacement = await page.evaluate(() => { + const rail = document.getElementById('right-context-rail'); + const panel = document.getElementById('recent-imagery-panel'); + const body = document.getElementById('recent-imagery-panel-body'); + const order = [...rail.children].map((child) => child.id); + const at = (id) => order.indexOf(id); + return { + inRail: panel?.parentElement === rail, + beforeContext: at('recent-imagery-panel') < at('global-context-panel'), + afterWeather: at('weather-panel') < at('recent-imagery-panel'), + collapsed: panel?.classList.contains('collapsed'), + scroller: body?.hasAttribute('data-rail-scroller'), + readoutInBody: body?.firstElementChild?.classList.contains( + 'recent-imagery-readout', + ), + body: body?.offsetHeight, + title: panel?.querySelector('.panel-title')?.textContent, + order, + }; + }); + check( + 'the panel sits in the rail after WEATHER and before CONTEXT, expanded on first appearance', + railPlacement.inRail && + railPlacement.beforeContext && + railPlacement.afterWeather && + railPlacement.collapsed === false && + railPlacement.body > 0, + JSON.stringify(railPlacement), + ); + check( + 'the body is a rail scroller holding the readout, under a RECENT IMAGERY header', + railPlacement.scroller && + railPlacement.readoutInBody && + railPlacement.title === 'RECENT IMAGERY', + JSON.stringify(railPlacement), + ); + const listOf = (selector, key) => + page.evaluate( + (sel, field) => + [...document.querySelectorAll(sel)] + .map((node) => node.dataset[field] || node.id) + .join(','), + selector, + key, + ); + check( + 'the data-panel row carries only the two source chips', + (await listOf( + '[data-layer-id="recent-imagery"] .data-toggle-chip', + 'chipId', + )) === 'hls,viirs', + ); + const actionIds = await listOf( + `${PANEL} .ri-actions-row [data-action-id]`, + 'actionId', + ); + check( + 'the actions row holds SELECT BOX, USE VIEW and CLEAR', + actionIds === 'select-box,use-view,clear', + actionIds, + ); + const blocks = await listOf(`${PANEL} .recent-imagery-readout > *`, 'none'); + check( + 'the body is the fixed stack: actions, notice, strip, hint, selection, controls, details', + blocks === + 'ri-actions,ri-notice,ri-strip,ri-hint,ri-selection,ri-controls,ri-details', + blocks, + ); + let current = await state(); + check( + 'before a box: CLEAR is disabled, the hint says what to do, IMAGE is the mode', + (await page.evaluate( + () => + document.querySelector('#recent-imagery-panel [data-action-id="clear"]') + ?.disabled, + )) === true && + current.hintText === 'Select a box or use the view' && + current.mode === 'image', + `${current.hintText} ${current.mode}`, + ); + await checkLayout('empty'); + await panelShot('01-enabled-panel'); + + // ── USE VIEW at 12 km: days and the live preview ──────────────────────── + const beforeColour = await probe(); + const viewKm = await viewWidthKm(); + check('USE VIEW is clickable', await clickAction('use-view')); + const searched = await until(() => { + const snapshot = window.__riQa.snap(); + return !snapshot.searching && snapshot.candidates.length > 0; + }); + current = await state(); + check( + `USE VIEW at 12 km (${viewKm.toFixed(1)} km wide) sets a box and the catalog returns days within 20 s`, + searched && Boolean(current.box), + `${current.candidates.length} candidates, error=${current.error} boxError=${current.boxError}`, + ); + check( + 'the strip renders one card per day', + current.cards === current.candidates.length && current.cards > 0, + `${current.cards} cards`, + ); + const countText = await page.evaluate( + () => document.getElementById('recent-imagery-panel-count')?.textContent, + ); + check( + 'the header count reads the day count', + /^\d+ DAYS?$/.test(countText), + countText, + ); + const startHere = await page.evaluate(() => + [...document.querySelectorAll('#recent-imagery-panel .ri-card-start')] + .filter((node) => !node.hidden) + .map((node) => node.closest('.ri-card').dataset.key), + ); + check( + 'exactly one card wears START HERE', + startHere.length === 1, + startHere.join(','), + ); + check( + 'the START HERE day previews on its own', + await until(() => { + const snap = window.__riQa.snap(); + return ( + Boolean(snap.preview.key) && + snap.preview.slot === 'a' && + window.__riQa.owned() === 1 + ); + }), + ); + current = await state(); + check( + 'row A reads the previewed day, row B reads the basemap', + /^IMAGE.+ · preview×$/.test(current.rowA) && current.rowB === 'VSBasemap×', + `${current.rowA} | ${current.rowB}`, + ); + onPhotorealOnly( + 'on Google 3D a shown image borrows the Esri surface', + await onEsri(), + ); + const esriNote = await until( + () => + document.getElementById('ri-notice-text')?.textContent === + 'Imagery on Esri · Google 3D returns when cleared', + undefined, + 5_000, + ); + current = await state(); + onPhotorealOnly( + 'the notice says the imagery is on Esri until cleared', + esriNote, + current.noticeText, + ); + check( + 'one owned imagery layer on the globe, no divider', + current.diagnostics.ownedCount === 1 && + current.gibsOnGlobe + current.gibsOnTileset === 1 && + !current.splitVisible, + hostsDetail(current), + ); + check( + 'at least one thumbnail settles (present/empty/error)', + await until(() => + window.__riQa + .snap() + .candidates.some((c) => c.thumbnail.status !== 'unknown'), + ), + ); + await tilesSettled(); + let changedColour = null; + for (let deadline = Date.now() + STEP_TIMEOUT; Date.now() < deadline;) { + const colour = await probe(); + if (Math.hypot(...colour.map((c, i) => c - beforeColour[i])) > 6) { + changedColour = colour; + break; + } + await page.evaluate(() => + window.__godsEyeView.viewer.scene.requestRender(), + ); + await wait(1000); + } + check( + 'the rendered frame inside the box changes once the preview drapes', + Boolean(changedColour), + `before=${beforeColour} after=${changedColour || (await probe())}`, + ); + await checkLayout('preview'); + await shot('02-preview'); + await panelShot('02-preview-panel'); + + // ── arrow keys: the preview follows the focus ─────────────────────────── + await until(() => { + const snap = window.__riQa.snap(); + return snap.candidates.some( + (c) => c.key !== snap.preview.key && c.drapable, + ); + }); + current = await state(); + const targetIndex = current.candidates.findIndex( + (c) => c.key !== current.preview && c.drapable, + ); + check( + 'a present day other than the preview is reachable', + targetIndex >= 0, + String(targetIndex), + ); + const targetKey = current.candidates[targetIndex]?.key; + await focusStrip(); + await page.keyboard.press('Home'); + for (let i = 0; i < targetIndex; i += 1) + await page.keyboard.press('ArrowRight'); + const pressedAt = Date.now(); + check( + 'arrow keys move focus at once', + await until( + (key) => window.__riQa.snap().focus?.key === key, + targetKey, + 2_000, + ), + targetKey, + ); + const followed = await until( + (key) => window.__riQa.snap().preview.key === key, + targetKey, + 1_500, + ); + const elapsed = Date.now() - pressedAt; + check( + 'the focused present day previews within 1 s', + followed && elapsed <= 1_250, + `preview after ${elapsed} ms`, + ); + current = await state(); + check( + 'still a single owned layer while scrubbing', + current.diagnostics.ownedCount === 1, + hostsDetail(current), + ); + const flag = await page.evaluate( + (key) => + document.querySelector( + `#recent-imagery-panel .ri-card[data-key="${key}"] .ri-card-flag`, + )?.textContent, + targetKey, + ); + check('the previewed card wears PREVIEW', flag === 'PREVIEW', flag); + + // ── IMAGE: S pins the focused day; focus no longer moves the map ──────── + await pressOnStrip('s'); + current = await state(); + check( + 'S pins the focused day and its SHOW chip lights', + current.pinA === targetKey && + (await page.evaluate( + (key) => + document + .querySelector( + `#recent-imagery-panel .ri-card[data-key="${key}"] .ri-chip[data-slot="a"]`, + ) + ?.getAttribute('aria-pressed'), + targetKey, + )) === 'true', + current.pinA, + ); + check( + 'row A reads the pinned day without "preview"', + /^IMAGE.+×$/.test(current.rowA) && !/preview/.test(current.rowA), + current.rowA, + ); + await checkLayout('pinned'); + await page.keyboard.press(targetIndex > 0 ? 'ArrowLeft' : 'ArrowRight'); + await wait(700); + current = await state(); + check( + 'with the image pinned, focus moves without changing the map', + current.focus !== targetKey && current.shown.a === targetKey, + `focus=${current.focus} shown=${current.shown.a}`, + ); + await page.evaluate(() => { + const slider = document.getElementById('ri-opacity'); + slider.value = '60'; + slider.dispatchEvent(new Event('input', { bubbles: true })); + }); + current = await state(); + check( + 'OPACITY sets the draped alpha', + Math.abs((await page.evaluate(() => window.__riQa.snap().alpha)) - 0.6) < + 1e-9, + ); + await checkLayout('opacity'); + + // ── VS BASEMAP: the pinned day swipes against the basemap ─────────────── + check('VS BASEMAP is one click', await clickMode('basemap')); + const basemapSwipe = await until( + () => + window.__riQa.snap().shown.swipe === 'basemap' && + window.__riQa.splitShown(), + ); + current = await state(); + check( + 'VS BASEMAP shows the divider, labelled IMAGE / BASEMAP', + basemapSwipe && + JSON.stringify(current.splitLabels) === '["IMAGE","BASEMAP"]', + JSON.stringify(current.splitLabels), + ); + check( + 'the image is on the left and the basemap on the right: one layer, split LEFT', + current.diagnostics.ownedCount === 1 && + JSON.stringify(current.gibsSplits) === '[-1]', + hostsDetail(current), + ); + check( + 'the divider starts centred', + Math.abs(current.splitPosition - 0.5) < 0.01 && + Math.abs(current.splitLeft - current.canvasWidth / 2) <= 2, + `splitPosition=${current.splitPosition} left=${current.splitLeft} canvas=${current.canvasWidth}`, + ); + check( + 'row B reads the basemap, lit', + current.rowB === 'VSBasemap×' && + (await page.evaluate(() => + document.getElementById('ri-slot-b').classList.contains('lit'), + )), + current.rowB, + ); + onPhotorealOnly( + 'the swipe runs on Esri', + current.activeStack === 'esri-imagery', + current.activeStack, + ); + check( + 'the hint says SWAP trades the sides (VS BASEMAP)', + current.hintText === 'Drag the divider · SWAP trades sides', + current.hintText, + ); + await checkLayout('vs basemap'); + await tilesSettled(); + await shot('03-vs-basemap'); + await panelShot('03-vs-basemap-panel'); + + // ── A / B: pin A, preview then pin B, swipe, SWAP, unpin ──────────────── + check('A / B is one click', await clickMode('ab')); + current = await state(); + check( + 'A / B keeps the pin as A and waits for B', + current.mode === 'ab' && + current.pinA === targetKey && + !current.splitVisible && + /^A.+×$/.test(current.rowA) && + current.rowB === 'BNot set×', + `${current.rowA} | ${current.rowB}`, + ); + const chipLabels = await page.evaluate( + (key) => + [ + ...document.querySelectorAll( + `#recent-imagery-panel .ri-card[data-key="${key}"] .ri-chip`, + ), + ].map((chip) => chip.textContent), + targetKey, + ); + check( + 'the cards now carry A and B chips', + JSON.stringify(chipLabels) === '["A","B"]', + JSON.stringify(chipLabels), + ); + await checkLayout('A / B, A pinned'); + const secondIndex = (await state()).candidates.findIndex( + (c) => c.key !== targetKey && c.drapable, + ); + const secondKey = current.candidates[secondIndex]?.key; + await focusStrip(); + await page.keyboard.press('Home'); + for (let i = 0; i < secondIndex; i += 1) + await page.keyboard.press('ArrowRight'); + check( + 'arrows preview the other day as B against A', + await until( + (key) => { + const snap = window.__riQa.snap(); + return snap.preview.key === key && snap.preview.slot === 'b'; + }, + secondKey, + 3_000, + ), + secondKey, + ); + await page.keyboard.press('b'); + const abSwipe = await until( + (key) => + window.__riQa.snap().pins.b.key === key && + window.__riQa.snap().shown.swipe === 'ab' && + window.__riQa.splitShown(), + secondKey, + ); + current = await state(); + check( + 'B pins the second day and the divider reads A / B', + abSwipe && JSON.stringify(current.splitLabels) === '["A","B"]', + JSON.stringify(current.splitLabels), + ); + check( + 'two owned layers: A left, B right', + current.diagnostics.ownedCount === 2 && + JSON.stringify([...current.gibsSplits].sort()) === '[-1,1]', + hostsDetail(current), + ); + check( + 'the divider recentres for the new comparison', + Math.abs(current.splitPosition - 0.5) < 0.01, + String(current.splitPosition), + ); + check( + 'row B reads the pinned day', + /^B.+×$/.test(current.rowB) && !/Not set/.test(current.rowB), + current.rowB, + ); + onPhotorealOnly( + 'the A / B swipe runs on Esri', + current.activeStack === 'esri-imagery', + current.activeStack, + ); + check( + 'the hint says SWAP trades the sides (A / B)', + current.hintText === 'Drag the divider · SWAP trades sides', + current.hintText, + ); + await checkLayout('A / B, both pinned'); + await tilesSettled(); + await shot('04-ab'); + await panelShot('04-ab-panel'); + // SWAP trades the sides (Space is push-to-talk, so no key does this). + const splitBeforeSwap = current.splitPosition; + check('SWAP is one click while the swipe is live', await click('#ri-swap')); + const swapped = await until( + () => + window.__riQa.snap().swapped === true && + document.querySelector('#recent-imagery-split-line span.before') + ?.textContent === 'B', + ); + current = await state(); + check( + 'SWAP trades the divider labels to B / A and keeps the divider where it was', + swapped && + JSON.stringify(current.splitLabels) === '["B","A"]' && + JSON.stringify([...current.gibsSplits].sort()) === '[-1,1]' && + Math.abs(current.splitPosition - splitBeforeSwap) < 0.01, + `${JSON.stringify(current.splitLabels)} ${hostsDetail(current)} split=${current.splitPosition}`, + ); + await checkLayout('A / B, swapped'); + check('SWAP again is one click', await click('#ri-swap')); + const restored = await until( + () => + window.__riQa.snap().swapped === false && + document.querySelector('#recent-imagery-split-line span.before') + ?.textContent === 'A', + ); + current = await state(); + check( + 'SWAP again restores A / B', + restored && JSON.stringify(current.splitLabels) === '["A","B"]', + JSON.stringify(current.splitLabels), + ); + check('B unpins from its ×', await click('#ri-unpin-b')); + const singleA = await until( + () => + window.__riQa.owned() === 1 && + !document.getElementById('recent-imagery-split-line'), + ); + current = await state(); + check( + 'unpinning B drops its layer at once: A alone, no divider', + singleA && current.shown.a === targetKey && !current.shown.b, + hostsDetail(current), + ); + check( + 'without a swipe SWAP keeps its slot, disabled and invisible', + await page.evaluate(() => { + const swap = document.getElementById('ri-swap'); + return Boolean( + swap?.disabled && + swap.classList.contains('is-reserved') && + getComputedStyle(swap).visibility === 'hidden', + ); + }), + ); + onPhotorealOnly( + 'A alone stays on Esri', + current.activeStack === 'esri-imagery', + current.activeStack, + ); + await checkLayout('B unpinned'); + check('A unpins from its ×', await click('#ri-unpin-a')); + check('with nothing shown, no layer remains', await ownedIs(0)); + onPhotorealOnly( + 'with nothing shown, Google 3D comes back', + await backOnPhotoreal(), + ); + await checkLayout('A unpinned'); + + // ── the share link carries the pins and the mode ──────────────────────── + await clickMode('basemap'); + await pressOnStrip('a'); + const shared = await until( + () => { + const params = new URLSearchParams(window.location.hash.slice(1)); + const layers = (params.get('l') || '').split('.'); + const options = params.get('lo') || ''; + return ( + layers.includes('1') && + /(^|_)1\.a\.[SLV]\d{8}/.test(options) && + /(^|_)1\.m\.1(_|$)/.test(options) && + /(^|_)1\.w\.-?\d+/.test(options) + ); + }, + undefined, + 8_000, + ); + check( + 'the share link carries the layer, the box, the pin and the mode', + shared, + await page.evaluate(() => window.location.hash.slice(0, 400)), + ); + + // ── Escape order: preview, then the box tool ──────────────────────────── + await click('#ri-unpin-a'); + await clickMode('image'); + await ownedIs(0); + await focusStrip(); + await page.keyboard.press('ArrowRight'); + check( + 'a focus move previews again', + await until( + () => Boolean(window.__riQa.snap().preview.key), + undefined, + 5_000, + ), + ); + check( + 'SELECT BOX arms the box tool', + (await clickAction('select-box')) && + (await until(() => window.__gevRecentImagery.tool.isActive())), + ); + await page.keyboard.press('Escape'); + const escapedPreview = await until( + () => !window.__riQa.snap().preview.key, + undefined, + 3_000, + ); + const stillArmed = await page.evaluate(() => + window.__gevRecentImagery.tool.isActive(), + ); + check( + 'Escape clears the preview first and leaves SELECT BOX armed', + escapedPreview && stillArmed, + `preview cleared=${escapedPreview} toolActive=${stillArmed}`, + ); + await page.keyboard.press('Escape'); + check( + 'the next Escape cancels the box tool', + await until(() => !window.__gevRecentImagery.tool.isActive()), + ); + onPhotorealOnly( + 'with the preview cleared Google 3D comes back', + await backOnPhotoreal(), + ); + + // ── oversized USE VIEW → refusal in the notice line ───────────────────── + let refusalWidth = 0; + for (const height of [400_000, 900_000, 1_800_000]) { + await setView({ ...AUSTIN, height }); + await wait(300); + refusalWidth = await viewWidthKm(); + if (refusalWidth > 1_100) break; + } + const boxBefore = JSON.stringify((await state()).box); + await clickAction('use-view'); + const refused = await until( + () => + /^View is/.test( + document.getElementById('ri-notice-text')?.textContent || '', + ), + undefined, + 5_000, + ); + current = await state(); + check( + `an oversized USE VIEW (${Math.round(refusalWidth)} km) is refused in the notice line`, + refused && + /^View is [\d,]+ km wide · limit 1,000 km$/.test(current.noticeText), + current.noticeText, + ); + check( + 'the hint says to zoom in or draw a smaller box', + current.hintText === 'Zoom in or draw a smaller box', + current.hintText, + ); + check('the refusal keeps the box', JSON.stringify(current.box) === boxBefore); + const refusalLine = await page.evaluate(() => { + const text = document.getElementById('ri-notice-text'); + const chip = document.getElementById('ri-zoom-in'); + const line = document.getElementById('ri-notice').getBoundingClientRect(); + const rect = chip.getBoundingClientRect(); + return { + fits: text.scrollWidth <= text.clientWidth, + scrollWidth: text.scrollWidth, + clientWidth: text.clientWidth, + chipVisible: + getComputedStyle(chip).visibility === 'visible' && + !chip.disabled && + rect.width > 0, + chipAtEnd: Math.abs(rect.right - line.right) <= 1, + lineHeight: line.height, + }; + }); + check( + 'the refusal fits the notice line without an ellipsis', + refusalLine.fits, + JSON.stringify(refusalLine), + ); + check( + 'ZOOM IN shows at the right end of the notice line, which keeps its height', + refusalLine.chipVisible && + refusalLine.chipAtEnd && + Math.abs(refusalLine.lineHeight - 14) <= 0.5, + JSON.stringify(refusalLine), + ); + await checkLayout('refused'); + await panelShot('05-refused-panel'); + // ZOOM IN: straight down to the height whose view is 400 km wide. + const fitHeight = await page.evaluate(() => { + const viewer = window.__godsEyeView.viewer; + const canvas = viewer.scene.canvas; + const halfWidth = + Math.tan(viewer.camera.frustum.fovy / 2) * + (canvas.clientWidth / canvas.clientHeight); + return Math.min(400, Math.max(5, 400 / (2 * halfWidth))) * 1000; + }); + check('ZOOM IN is clickable', await click('#ri-zoom-in')); + const zoomed = await until( + (target) => + Math.abs( + window.__godsEyeView.viewer.camera.positionCartographic.height - target, + ) <= + target * 0.01, + fitHeight, + 2_000, + ); + const zoomedHeight = await page.evaluate( + () => window.__godsEyeView.viewer.camera.positionCartographic.height, + ); + check( + `ZOOM IN flies to ${Math.round(fitHeight / 1000)} km within 2 s`, + zoomed, + `height=${Math.round(zoomedHeight)} target=${Math.round(fitHeight)}`, + ); + await tilesSettled(); + const fittedWidth = await viewWidthKm(); + await clickAction('use-view'); + const fitted = await until( + () => { + const snap = window.__riQa.snap(); + return Boolean(snap.box) && !snap.boxError && !snap.zoomToFit; + }, + undefined, + 5_000, + ); + current = await state(); + check( + `the next USE VIEW (${Math.round(fittedWidth)} km) succeeds and ZOOM IN is reserved again`, + fitted && + (await page.evaluate(() => + document.getElementById('ri-zoom-in').classList.contains('is-reserved'), + )), + `boxError=${current.boxError} notice=${current.noticeText}`, + ); + await checkLayout('fitted'); + + // ── CLEAR ──────────────────────────────────────────────────────────────── + await setView(AUSTIN); + await pressOnStrip('ArrowRight'); + await until(() => window.__riQa.owned() === 1, undefined, 5_000); + await clickAction('clear'); + const clearedAll = await until(() => { + const snap = window.__riQa.snap(); + return ( + !snap.box && + !snap.pins.a.key && + !snap.pins.b.key && + !snap.preview.key && + window.__riQa.owned() === 0 + ); + }); + current = await state(); + check( + 'CLEAR empties the box, the pins and the preview', + clearedAll && current.noticeText === 'Box and images cleared', + `box=${JSON.stringify(current.box)} owned=${current.diagnostics.ownedCount} notice=${current.noticeText}`, + ); + onPhotorealOnly('CLEAR hands Google 3D back', await backOnPhotoreal()); + await wait(1_500); + onPhotorealOnly( + 'after CLEAR the layer does not take Esri again', + (await page.evaluate(() => window.__riQa.activeStack())) === 'photoreal', + ); + await checkLayout('cleared'); + + // ── map-switch rebind ─────────────────────────────────────────────────── + await tilesSettled(); + await page.evaluate( + (view) => window.__riQa.layer().boxFromPinAt(view.lon, view.lat), + AUSTIN, + ); + const redraped = await until(() => { + const snap = window.__riQa.snap(); + return ( + !snap.searching && + Boolean(snap.preview.key) && + window.__riQa.owned() === 1 + ); + }); + check('a 10 km box previews the START HERE day again', redraped); + const stacks = await page.evaluate(() => + window.__godsEyeView.mapStackController + .getStacks() + .filter((s) => s.available) + .map((s) => s.id), + ); + const setStack = (id) => + page.evaluate( + (stack) => window.__godsEyeView.mapStackController.setStack(stack), + id, + ); + /** Wait for the one GIBS drape to sit on the given host only. */ + const drapeOn = (host) => + until( + (where) => { + const hosts = window.__riQa.hosts(); + return where === 'globe' + ? hosts.globeShown && hosts.globe === 1 && hosts.tileset === 0 + : !hosts.globeShown && hosts.globe === 0 && hosts.tileset === 1; + }, + host, + 10_000, + ); + if (photoreal && stacks.includes('esri-imagery')) { + check('the preview sits on the Esri globe', await drapeOn('globe')); + // While a day is shown the imagery keeps Esri: a manual switch to + // Google 3D is answered at once with a new lease. + await setStack('photoreal'); + const kept = (await onEsri()) && (await drapeOn('globe')); + current = await state(); + check( + 'switching to Google 3D by hand while a day is shown keeps the imagery on the Esri globe', + kept && current.diagnostics.host === 'globe', + `${hostsDetail(current)} stack=${current.activeStack}`, + ); + check( + 'the notice says the imagery stays on Esri until CLEAR, and fits', + current.noticeText === 'Imagery stays on Esri · CLEAR to use Google 3D' && + (await page.evaluate(() => { + const text = document.getElementById('ri-notice-text'); + return text.scrollWidth <= text.clientWidth; + })), + current.noticeText, + ); + await wait(1_500); + check( + 'Esri holds after the re-lease: no switch loop', + (await page.evaluate(() => window.__riQa.activeStack())) === + 'esri-imagery', + ); + // The divider survives a manual switch too. + await clickMode('basemap'); + await until(() => window.__riQa.splitShown(), undefined, 10_000); + await setStack('photoreal'); + const dividerKept = + (await onEsri()) && + (await until( + () => + window.__riQa.splitShown() && window.__riQa.snap().comparison.active, + undefined, + 10_000, + )); + current = await state(); + check( + 'a manual switch to Google 3D during VS BASEMAP keeps the divider', + dividerKept && + current.shown.swipe === 'basemap' && + !current.comparison.suspended, + `${hostsDetail(current)} stack=${current.activeStack} comparison=${JSON.stringify(current.comparison)}`, + ); + await tilesSettled(); + await shot('06-google-3d-kept-on-esri'); + await clickMode('image'); + await until(() => !window.__riQa.splitShown(), undefined, 5_000); + } else { + const other = stacks.find( + (id) => id !== initialStack && id !== 'photoreal', + ); + if (other) { + await setStack(other); + check( + `switching to ${other} keeps the drape on the globe`, + await drapeOn('globe'), + ); + await setStack(initialStack); + } else { + console.log('[SKIP] map-switch rebind — no second map stack available'); + } + } + + // ── collapse / expand, CCTV stability, DISPLAY + CONTEXT reachable ────── + /** Click a panel's collapse button; resolves to whether it is expanded. */ + const togglePanel = (id) => + page.evaluate((panelId) => { + const button = document.querySelector( + `.panel-collapse-btn[data-collapse-target="${panelId}"]`, + ); + if (!button) return null; + button.click(); + return !document.getElementById(panelId)?.classList.contains('collapsed'); + }, id); + const imageryPanel = 'recent-imagery-panel'; + const collapsedNow = (await togglePanel(imageryPanel)) === false; + await wait(400); + const headerOnly = await page.evaluate(() => ({ + panel: document.getElementById('recent-imagery-panel')?.offsetHeight, + body: document.getElementById('recent-imagery-panel-body')?.offsetHeight, + })); + check( + 'collapsing the panel leaves a header bar only', + collapsedNow && + headerOnly.body === 0 && + headerOnly.panel > 0 && + headerOnly.panel <= 80, + JSON.stringify(headerOnly), + ); + const expandedAgain = await togglePanel(imageryPanel); + await wait(400); + const bodyBack = await page.evaluate( + () => document.getElementById('recent-imagery-panel-body')?.offsetHeight, + ); + check( + 'expanding the panel brings the body back', + expandedAgain === true && bodyBack > 0, + `body=${bodyBack}`, + ); + + /** Sample both panel heights for 2 s; settled = the tail never changes. */ + const settledHeights = async () => { + const samples = []; + for (let i = 0; i < 20; i += 1) { + samples.push( + await page.evaluate(() => ({ + imagery: document.getElementById('recent-imagery-panel') + ?.offsetHeight, + cctv: document.getElementById('cctv-panel')?.offsetHeight, + })), + ); + await wait(100); + } + const tail = (key) => new Set(samples.slice(8).map((s) => s[key])); + return { + settled: tail('imagery').size === 1 && tail('cctv').size === 1, + detail: `imagery=${samples.map((s) => s.imagery).join(',')} cctv=${samples.map((s) => s.cctv).join(',')}`, + }; + }; + const railFit = () => + page.evaluate(() => { + const px = (element) => + parseFloat( + element?.style.getPropertyValue('--right-panel-allocated-height'), + ); + const cctv = document.getElementById('cctv-panel'); + const imagery = document.getElementById('recent-imagery-panel'); + const rail = document.getElementById('right-context-rail'); + // Reachable: its header is on screen, or the rail's exclusive policy + // (an expanded panel under the tactical HUD) hid it while collapsed. + const reach = (id) => { + const element = document.getElementById(id); + return ( + window.__riQa.headerOnScreen(id) || + (rail?.classList.contains('layout-exclusive') && + element?.classList.contains('collapsed') && + element.getBoundingClientRect().height === 0) + ); + }; + return { + cctvRendered: cctv?.offsetHeight ?? null, + cctvAllocated: px(cctv), + imageryRendered: imagery?.offsetHeight ?? null, + imageryAllocated: px(imagery), + imageryCollapsed: Boolean(imagery?.classList.contains('collapsed')), + imageryDisplay: imagery ? getComputedStyle(imagery).display : null, + focus: rail?.classList.contains('layout-focus'), + exclusive: rail?.classList.contains('layout-exclusive'), + display: reach('pp-toggles'), + context: reach('global-context-panel'), + }; + }); + for (const height of [900, 700]) { + const at = `(${height} px viewport)`; + await page.setViewport({ width: 1280, height }); + await wait(600); + check( + `the CCTV panel expands from its launcher ${at}`, + (await togglePanel('cctv-panel')) === true, + ); + const expanded = await settledHeights(); + check( + `the imagery and CCTV panel heights settle with CCTV expanded ${at}`, + expanded.settled, + expanded.detail, + ); + const fit = await railFit(); + check( + `CCTV renders at its allocated height beside the imagery panel ${at}`, + !fit.focus || + (Number.isFinite(fit.cctvAllocated) && + Math.abs(fit.cctvRendered - fit.cctvAllocated) <= 2), + JSON.stringify(fit), + ); + // A collapsed panel has no allocation, so it is judged on its own terms: + // the exclusive rail (one expanded panel) hides it outright, otherwise it + // is a header bar. An expanded panel must have been allocated a height. + const imageryFits = fit.imageryCollapsed + ? fit.exclusive + ? fit.imageryRendered === 0 && fit.imageryDisplay === 'none' + : fit.imageryRendered > 0 && fit.imageryRendered <= 80 + : !fit.focus || + (Number.isFinite(fit.imageryAllocated) && + fit.imageryRendered <= fit.imageryAllocated + 2); + check( + `the imagery panel stays within its allocation, or takes no room when the exclusive rail hides it collapsed ${at}`, + imageryFits, + JSON.stringify(fit), + ); + check( + `DISPLAY and CONTEXT stay reachable ${at}`, + fit.display && fit.context, + JSON.stringify(fit), + ); + await shot(`07-cctv-expanded-${height}`); + check( + `the CCTV panel collapses again ${at}`, + (await togglePanel('cctv-panel')) === false, + ); + const collapsed = await settledHeights(); + check( + `the panel heights settle with CCTV collapsed ${at}`, + collapsed.settled, + collapsed.detail, + ); + const imageryExpanded = await page.evaluate( + () => + !document + .getElementById('recent-imagery-panel') + ?.classList.contains('collapsed'), + ); + if (imageryExpanded) await togglePanel(imageryPanel); + await wait(400); + const onScreen = await page.evaluate(() => + Object.fromEntries( + [ + 'pp-toggles', + 'global-context-panel', + 'recent-imagery-panel', + 'cctv-panel', + ].map((id) => [id, window.__riQa.headerOnScreen(id)]), + ), + ); + check( + `DISPLAY, CONTEXT, CCTV and the imagery header are all on screen once everything is collapsed ${at}`, + Object.values(onScreen).every(Boolean), + JSON.stringify(onScreen), + ); + await togglePanel(imageryPanel); + await wait(400); + } + + // ── scroll preservation (700 px viewport, body scrollable) ─────────────── + await page.evaluate(() => { + const header = document.querySelector('#ri-details .rail-card-header'); + if (header?.getAttribute('aria-expanded') !== 'true') header?.click(); + }); + await wait(300); + const bodyScroll = () => + page.evaluate(() => { + const body = document.getElementById('recent-imagery-panel-body'); + return { + top: body.scrollTop, + max: body.scrollHeight - body.clientHeight, + }; + }); + const start = await page.evaluate(() => { + const body = document.getElementById('recent-imagery-panel-body'); + const max = body.scrollHeight - body.clientHeight; + if (max > 0) body.scrollTop = Math.round(max / 2); + return { max, top: body.scrollTop }; + }); + check( + 'with DETAILS open at 700 px the body scrolls', + start.max > 0, + JSON.stringify(start), + ); + if (start.max > 0) { + await page.evaluate(() => { + const layer = window.__riQa.layer(); + layer.setAlpha(0.9); + layer.setToolActive(true); + layer.setToolActive(false); + }); + await wait(300); + const afterNotify = await bodyScroll(); + check( + 'the body scroll position survives alpha and state notifications', + Math.abs(afterNotify.top - start.top) <= 1, + `before=${start.top} after=${afterNotify.top}`, + ); + await focusStrip(); + await page.keyboard.press('ArrowRight'); + await page.keyboard.press('ArrowRight'); + await wait(600); + const afterArrows = await bodyScroll(); + check( + 'the body scroll position survives arrow navigation', + Math.abs(afterArrows.top - start.top) <= 1, + `before=${start.top} after=${JSON.stringify(afterArrows)}`, + ); + await shot('08-scrolled'); + } + await page.setViewport({ width: 1280, height: 860 }); + + // ── disable ─────────────────────────────────────────────────────────────── + await click(layerToggle); + check( + 'the layer disables from its toggle', + await until( + () => !window.__godsEyeView.dataManager.isEnabled('recent-imagery'), + ), + ); + const cleared = await until(() => { + const hosts = window.__riQa.hosts(); + return ( + window.__riQa.owned() === 0 && + hosts.globe + hosts.tileset === 0 && + !document.getElementById('recent-imagery-split-line') + ); + }); + current = await state(); + check( + 'disabling leaves zero owned layers and no split line', + cleared, + `${hostsDetail(current)} split=${current.splitVisible}`, + ); + check('the panel hides when the layer is off', current.panelHidden === true); + onPhotorealOnly('disabling hands Google 3D back', await backOnPhotoreal()); + await wait(1_500); + onPhotorealOnly( + 'disabled, the layer never takes Esri again', + (await page.evaluate(() => window.__riQa.activeStack())) === 'photoreal', + ); + await shot('09-disabled'); + + check( + 'no page errors during the run', + errors.length === 0, + errors.join(' | '), + ); +} catch (error) { + check( + 'run completed', + false, + error?.stack || error?.message || String(error), + ); +} finally { + await browser.close(); +} +console.log(`shots: ${shots.join(', ')}`); +console.log(`RESULT: ${checks} checks, ${failures} failures`); +process.exitCode = failures ? 1 : 0; diff --git a/scripts/qa-scene-controls.mjs b/scripts/qa-scene-controls.mjs index f5c18dfed..9dae69cdc 100644 --- a/scripts/qa-scene-controls.mjs +++ b/scripts/qa-scene-controls.mjs @@ -85,6 +85,9 @@ try { ); promptValue = 'QA shot'; await page.click('.scene-shot-label', { count: 2 }); + await page.waitForSelector('.scene-shot-rename', { visible: true }); + await page.type('.scene-shot-rename', promptValue); + await page.keyboard.press('Enter'); await page.waitForFunction( () => document.querySelector('.scene-shot-label')?.textContent === @@ -151,7 +154,20 @@ try { const projectFile = path.join(shots, 'project.json'); fs.writeFileSync(projectFile, JSON.stringify(fixture)); const input = await page.$('#scene-import-file'); + const beforePreview = await page.evaluate(() => + JSON.stringify(window.__godsEyeView.sceneDirector._project), + ); await input.uploadFile(projectFile); + await page.waitForSelector('[data-director-apply-import]'); + check( + 'Import preview leaves the current project untouched', + await page.evaluate( + (saved) => + JSON.stringify(window.__godsEyeView.sceneDirector._project) === saved, + beforePreview, + ), + ); + await page.click('[data-director-apply-import]'); await page.waitForFunction( () => document.getElementById('scene-status').textContent === @@ -259,8 +275,8 @@ try { await input.uploadFile(badFile); await page.waitForFunction(() => document - .getElementById('scene-status') - .textContent.includes('invalid JSON'), + .querySelector('[data-director-dialog] [role=status]') + ?.textContent.includes('invalid JSON'), ); check( 'Invalid import reports failure and preserves the current project', @@ -271,6 +287,45 @@ try { 'QA Scene', ), ); + const savedBefore = await page.evaluate(() => + localStorage.getItem('godsEyeView.sceneProject.v2'), + ); + const futureFile = path.join(shots, 'future.json'); + fs.writeFileSync(futureFile, JSON.stringify({ version: 99, scenes: [] })); + await input.uploadFile(futureFile); + await page.waitForFunction(() => + document + .querySelector('[data-director-dialog] [role=status]') + ?.textContent.includes('$.version'), + ); + check( + 'Unsupported versions leave authored state and saved bytes unchanged', + await page.evaluate( + (saved) => + localStorage.getItem('godsEyeView.sceneProject.v2') === saved && + window.__godsEyeView.sceneDirector._getSelectedScene().title === + 'QA Scene', + savedBefore, + ), + ); + const malformed = structuredClone(fixture); + malformed.scenes[0].shots[0].camera.lat = 91; + const malformedFile = path.join(shots, 'malformed.json'); + fs.writeFileSync(malformedFile, JSON.stringify(malformed)); + await input.uploadFile(malformedFile); + await page.waitForFunction(() => + document + .querySelector('[data-director-dialog] [role=status]') + ?.textContent.includes('camera.lat'), + ); + check( + 'Invalid camera field identifies its path without replacing the project', + await page.evaluate( + (saved) => localStorage.getItem('godsEyeView.sceneProject.v2') === saved, + savedBefore, + ), + ); + await page.keyboard.press('Escape'); await page.screenshot({ path: path.join(shots, 'desktop.png') }); await page.setViewport({ width: 390, height: 844 }); await page.screenshot({ path: path.join(shots, 'narrow.png') }); diff --git a/scripts/qa-transit-browser.mjs b/scripts/qa-transit-browser.mjs index 1e71e484e..eb7b59985 100644 --- a/scripts/qa-transit-browser.mjs +++ b/scripts/qa-transit-browser.mjs @@ -367,7 +367,7 @@ export async function sampleTransitPixels(page, palette) { const luma = (r, g, b) => (0.299 * r + 0.587 * g + 0.114 * b) / 255; const readLuma = (cx, cy) => { const px = Math.floor(cx * scale); - const py = Math.floor(canvas.height - 1 - cy * scale); + const py = canvas.height - 1 - Math.floor(cy * scale); const buf = new Uint8Array(4); gl.readPixels(px, py, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, buf); return luma(buf[0], buf[1], buf[2]); @@ -399,46 +399,117 @@ export async function sampleTransitPixels(page, palette) { continue; } } + // Pick nine points from a solid patch of the source silhouette, + // before examining framebuffer brightness. Avoid panels/window gaps. + let corePoints = null, + widestBand = -1; + const cosCore = Math.cos(s.rotation), + sinCore = Math.sin(s.rotation); + // A tram's parallel sides have equally wide bands. Prefer its upper + // body band over the geometric centre when those widths tie. + const offsets = + s.mode === 'tram' + ? [-0.2, 0.2, -0.1, 0.1, 0] + : [0, -0.1, 0.1, -0.2, 0.2]; + for (const offset of offsets) { + const candidates = []; + let solid = true, + bandWidth = Infinity; + // Rank source geometry, never the observed framebuffer brightness. + // A thin tram needs the widest opaque white band, with room for + // the pixel filter on each side of the sampled patch. + for (let dy = -1; dy <= 1; dy++) { + const ry = Math.floor( + ((dy + offset * s.rect.height) / s.rect.height + 0.5) * + s.raster.height, + ); + const middle = Math.floor(s.raster.width / 2); + const white = (x) => + x >= 0 && + x < s.raster.width && + [0, 1, 2, 3].every( + (c) => + s.raster.data[(ry * s.raster.width + x) * 4 + c] >= 240, + ); + let left = middle, + right = middle; + while (white(left - 1)) left--; + while (white(right + 1)) right++; + bandWidth = Math.min( + bandWidth, + white(middle) ? right - left + 1 : 0, + ); + } + for (let dx = -1; dx <= 1; dx++) + for (let dy = -1; dy <= 1; dy++) { + const localY = dy + offset * s.rect.height; + const rx = Math.floor( + (dx / s.rect.width + 0.5) * s.raster.width, + ); + const ry = Math.floor( + (localY / s.rect.height + 0.5) * s.raster.height, + ); + const i = (ry * s.raster.width + rx) * 4; + if ([0, 1, 2, 3].some((c) => s.raster.data[i + c] < 240)) + solid = false; + candidates.push( + screenPoint( + s.screenX + dx * cosCore + localY * sinCore, + s.screenY - dx * sinCore + localY * cosCore, + ), + ); + } + if (solid && bandWidth > widestBand) { + corePoints = candidates; + widestBand = bandWidth; + } + } + if (!corePoints) { + skipped.push({ + key: s.key, + reason: 'no solid silhouette interior for nine samples', + }); + continue; + } // Picking is independent of rendered brightness: an overlapping // label or sprite must not masquerade as a dim sensor signature. // Check the whole sampled core, not just its centre pick. let coreOwned = true; if (scene.pick) { const framebuffer = gl.getParameter?.(gl.FRAMEBUFFER_BINDING); - for (let dx = -1; dx <= 1; dx++) - for (let dy = -1; dy <= 1; dy++) { - let u = (s.x + dx) / width, - v = 1 - (s.y + dy) / height; - if (style === 'surveillance') { - const x = u * 2 - 1, - y = v * 2 - 1, - r2 = x * x + y * y; - const d = - 1 + r2 * intensity * 0.25 + r2 * r2 * intensity * 0.075; - u = (x * d + 1) / 2; - v = (y * d + 1) / 2; - } - if (sensor) { - const grid = 1 + (pixelation - 1) * intensity; - u += - ((Math.floor((u * canvas.width) / grid) * grid) / - canvas.width - - u) * - intensity; - v += - ((Math.floor((v * canvas.height) / grid) * grid) / - canvas.height - - v) * - intensity; - } - const picked = scene.pick( - { x: u * width, y: (1 - v) * height }, - 1, - 1, - ); - if (picked?.id !== s.key && picked?.primitive?.id !== s.key) - coreOwned = false; + for (const core of corePoints) { + let u = core.x / width, + v = 1 - core.y / height; + if (style === 'surveillance') { + const x = u * 2 - 1, + y = v * 2 - 1, + r2 = x * x + y * y; + const d = + 1 + r2 * intensity * 0.25 + r2 * r2 * intensity * 0.075; + u = (x * d + 1) / 2; + v = (y * d + 1) / 2; } + if (sensor) { + const grid = 1 + (pixelation - 1) * intensity; + u += + ((Math.floor((u * canvas.width) / grid) * grid) / + canvas.width - + u) * + intensity; + v += + ((Math.floor((v * canvas.height) / grid) * grid) / + canvas.height - + v) * + intensity; + } + const picked = scene.pick( + { x: u * width, y: (1 - v) * height }, + 1, + 1, + ); + if (picked?.id !== s.key && picked?.primitive?.id !== s.key) + coreOwned = false; + } if (gl.bindFramebuffer) gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); } @@ -451,9 +522,8 @@ export async function sampleTransitPixels(page, palette) { continue; } let centre = 0; - for (let dx = -1; dx <= 1; dx += 1) - for (let dy = -1; dy <= 1; dy += 1) - centre += readLuma(s.x + dx, s.y + dy) / 9; + for (const core of corePoints) + centre += readLuma(core.x, core.y) / corePoints.length; let ringMin = 1; let ringMax = 0; // Sample the actual rotated raster halo, not a fixed-radius circle diff --git a/scripts/qa-transit-heading.mjs b/scripts/qa-transit-heading.mjs new file mode 100644 index 000000000..a16bab9bc --- /dev/null +++ b/scripts/qa-transit-heading.mjs @@ -0,0 +1,156 @@ +import puppeteer from 'puppeteer'; + +/** 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', + args: ['--no-sandbox', '--disable-background-timer-throttling'], + }); + try { + const page = await browser.newPage(); + await page.setViewport({ width: 1280, height: 800 }); + await page.goto( + `${base}/?welcome=0#lat=42.3601&lon=-71.0589&alt=1200&heading=0&pitch=-90`, + { waitUntil: 'domcontentloaded' }, + ); + await page.waitForFunction( + () => window.__godsEyeView?.dataManager?.layers?.has('transit'), + { timeout: 90000 }, + ); + await new Promise((resolve) => setTimeout(resolve, 6000)); + await page.evaluate(async () => { + const app = window.__godsEyeView; + await app.dataManager.setEnabled('transit', true, { source: 'qa' }); + const layer = app.dataManager.layers.get('transit').module; + layer._loadTransitFleetForTest(4, { lat: 42.3601, lon: -71.0589 }, 100); + const state = layer._transitStateForTest(), + parts = layer._transitPartsForTest(); + const { destroyTrack } = await import('/src/data/contactPlayback.js'); + const { + initializePlayback, + recordFix, + updatePlayback, + attachFloorToPlace, + } = await import('/src/layers/transit/movement.js'); + // The first three are parked: held east, reported east only, unknown. + for (let i = 0; i < 3; i++) { + const entry = state._vehicles.get(`mbta:qa-${i}`); + state._moving.delete(entry); + destroyTrack(entry.track); + initializePlayback(entry, state._historyBudget); + recordFix(entry, { + t: Date.now() - 30000, + lat: entry.record.lat, + lon: entry.record.lon, + }); + attachFloorToPlace(entry, entry.record, 20); + updatePlayback(entry, Date.now(), performance.now()); + entry.courseDeg = i === 0 ? 90 : null; + entry.record.bearing = i === 1 ? 90 : null; + entry.displayPaths.clear(); + parts.rendering.placeSample(entry); + parts.rendering.schedulePlayback(entry); + } + parts.rendering.syncRenderHold(); + window.__headingErrors = []; + app.viewer.scene.renderError.addEventListener((scene, error) => + window.__headingErrors.push(error.message), + ); + }); + const pose = async (heading) => { + await page.evaluate((heading) => { + const camera = window.__godsEyeView.viewer.camera; + const C = camera.positionCartographic.constructor; + camera.setView({ + destination: C.toCartesian(C.fromDegrees(-71.0589, 42.3601, 1200)), + orientation: { heading, pitch: -Math.PI / 2, roll: 0 }, + }); + }, heading); + await new Promise((resolve) => setTimeout(resolve, 700)); + }; + const sample = () => + page.evaluate(async () => { + const app = window.__godsEyeView, + scene = app.viewer.scene; + const state = app.dataManager.layers + .get('transit') + .module._transitStateForTest(); + const mul = (m, v) => + [0, 1, 2, 3].map( + (r) => + m[r] * v[0] + + m[r + 4] * v[1] + + m[r + 8] * v[2] + + m[r + 12] * v[3], + ); + const project = (p) => { + const clip = mul( + scene.camera.frustum.projectionMatrix, + mul(scene.camera.viewMatrix, [p.x, p.y, p.z, 1]), + ); + return { + x: ((clip[0] / clip[3] + 1) * scene.canvas.clientWidth) / 2, + y: ((1 - clip[1] / clip[3]) * scene.canvas.clientHeight) / 2, + }; + }; + return [0, 1, 2, 3].map((i) => { + const entry = state._vehicles.get(`mbta:qa-${i}`); + const p = project(entry.marker.position); + return { + rotation: entry.marker.rotation, + course: entry.courseDeg, + moving: state._moving.has(entry), + visible: entry.marker.show, + x: p.x, + y: p.y, + }; + }); + }); + await pose(0); + const before = await sample(); + await pose(Math.PI / 2); + const after = await sample(); + const deltaDeg = (a, b) => + (Math.atan2(Math.sin(b - a), Math.cos(b - a)) * 180) / Math.PI; + for (const [i, label] of ['held course', 'reported bearing'].entries()) { + const delta = deltaDeg(before[i].rotation, after[i].rotation); + check( + `parked ${label} reprojects through a 90 degree camera orbit`, + before[i].visible && + after[i].visible && + !before[i].moving && + !after[i].moving && + Math.abs(delta - 90) <= 5, + JSON.stringify({ before: before[i], after: after[i], delta }), + ); + } + check( + 'unknown parked course remains screen-up', + before[2].rotation === 0 && after[2].rotation === 0, + ); + await new Promise((resolve) => setTimeout(resolve, 1200)); + const moved = (await sample())[3]; + const dx = moved.x - after[3].x, + dy = moved.y - after[3].y; + const travelRotation = Math.atan2(-dx, -dy); + const error = Math.abs(deltaDeg(travelRotation, moved.rotation)); + check( + 'moving vehicle still points along its rendered travel after orbit', + moved.visible && moved.moving && Math.hypot(dx, dy) > 0.5 && error <= 5, + JSON.stringify({ + pixels: Math.hypot(dx, dy), + error, + after: after[3], + moved, + }), + ); + check( + 'heading regression has no scene render errors', + (await page.evaluate(() => window.__headingErrors)).length === 0, + ); + } finally { + await browser.close(); + } +} diff --git a/scripts/qa-transit-recovery.mjs b/scripts/qa-transit-recovery.mjs new file mode 100644 index 000000000..e5fadda49 --- /dev/null +++ b/scripts/qa-transit-recovery.mjs @@ -0,0 +1,330 @@ +/** Camera-jump regression against an existing server; never starts a server. */ +import puppeteer from 'puppeteer'; +import { mkdir, writeFile } from 'node:fs/promises'; +import { reduceTrailPixels } from '../src/layers/transit/qaMetrics.js'; + +const base = process.env.QA_BASE_URL || 'http://localhost:4305'; +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', + args: [ + '--disable-background-timer-throttling', + '--disable-renderer-backgrounding', + ], +}); +try { + const page = await browser.newPage(); + await page.setViewport({ width: 1920, height: 1080 }); + const errors = []; + page.on('pageerror', (error) => errors.push(error.message)); + await page.goto( + `${base}/?welcome=0#lat=30.271&lon=-97.7431&alt=600&heading=0&pitch=-60`, + ); + await page.waitForFunction(() => + window.__godsEyeView?.dataManager?.layers.has('transit'), + ); + await page.evaluate(async () => { + const app = window.__godsEyeView; + await app.dataManager.setEnabled('transit', true, { source: 'qa' }); + }); + await page.waitForFunction( + () => { + const scene = window.__godsEyeView.viewer.scene; + return scene.globe.tilesLoaded && scene.globe.show; + }, + { timeout: 60000 }, + ); + await page.waitForFunction( + () => { + const cover = document.getElementById('loading-screen'); + return !cover || cover.classList.contains('hidden'); + }, + { timeout: 60000 }, + ); + await page.evaluate(() => { + const app = window.__godsEyeView, + camera = app.viewer.camera; + const C = camera.positionCartographic.constructor, + lat = 30.267 + 90 / 111320; + const floor = + app.viewer.scene.globe.getHeight(C.fromDegrees(-97.7431, lat)) || 0; + camera.setView({ + destination: C.toCartesian( + C.fromDegrees( + -97.7431, + lat - 600 / Math.tan(Math.PI / 3) / 111320, + floor + 600, + ), + ), + orientation: { heading: 0, pitch: -Math.PI / 3, roll: 0 }, + }); + }); + await new Promise((resolve) => setTimeout(resolve, 2000)); + await page.waitForFunction( + () => window.__godsEyeView.viewer.scene.globe.tilesLoaded, + { timeout: 60000 }, + ); + await new Promise((resolve) => setTimeout(resolve, 1500)); + const result = await page.evaluate(async () => { + const app = window.__godsEyeView, + scene = app.viewer.scene, + camera = app.viewer.camera; + const layer = app.dataManager.layers.get('transit').module; + const state = layer._transitStateForTest(), + parts = layer._transitPartsForTest(); + const { getRegisteredTransitFeed } = + await import('/src/data/transitFeeds.js'); + const { setRate } = await import('/src/data/contactPlayback.js'); + const C = camera.positionCartographic.constructor; + const feed = { + ...getRegisteredTransitFeed('capmetro-austin'), + id: 'qa-camera-recovery', + }; + const aim = (lat, height = 600) => + camera.setView({ + destination: C.toCartesian( + C.fromDegrees( + -97.7431, + lat - 600 / Math.tan(Math.PI / 3) / 111320, + height, + ), + ), + orientation: { heading: 0, pitch: -Math.PI / 3, roll: 0 }, + }); + parts.selection.clearSelection(); + parts.ingestion.abortAllInFlight(); + state._activeFeeds.clear(); + for (const key of state._vehicles.keys()) + parts.ingestion.removeVehicle(key); + // Model an outstanding floor lookup while reports arrive off screen. + // Only acquisition is controlled; selection, visibility, paths and rendering + // use their real owners. Release to the loaded terrain at the camera jump. + const requestHeight = parts.height.requestHeight; + parts.height.requestHeight = (lat, lon) => ({ + cell: `${lat},${lon}`, + height: null, + prior: null, + }); + aim(30.28); + const now = Date.now(); + for (let i = 0; i < 9; i++) { + const timestamp = now - 135000 + i * 15000; + parts.ingestion.applySnapshot( + feed, + { + fetchedAt: timestamp, + vehicles: [ + { + id: 'moving-bus', + routeId: '1', + tripId: 'qa', + lat: 30.267 + (i * 90) / 111320, + lon: -97.7431, + timestamp: timestamp / 1000, + timestampSource: 'vehicle', + bearing: 0, + }, + ], + }, + { stale: false }, + ); + } + const entry = state._vehicles.get(`${feed.id}:moving-bus`); + entry.qaFixture = true; // Protect this disclosed fixture from live feed eviction. + parts.rendering.sampleIdle(entry); + const before = { + shown: entry.marker.show, + heightPending: entry.heightPending, + phase: entry.sample.phase, + fixes: entry.track.count, + }; + clearTimeout(state._floorTimer); + state._floorTimer = null; + const started = performance.now(); + parts.selection.selectVehicle(entry.key); + const preparedAtSelection = !!parts.trails.diagnostics()?.body; + parts.height.requestHeight = requestHeight; + const floor = + scene.globe.getHeight( + C.fromDegrees(entry.sample.lon, entry.sample.lat), + ) || 0; + aim(entry.sample.lat, floor + 600); + const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + let trail; + while (performance.now() - started < 1400) { + trail = parts.trails.diagnostics(); + if (entry.marker.show && trail?.body?.show && trail.body.ready) break; + scene.requestRender(); + await wait(25); + } + const status = { + before, + preparedAtSelection, + markerShow: entry.marker.show, + body: !!trail?.body, + bodyShow: trail?.body?.show === true, + visibility: layer + ._transitVisibilityForTest() + .find((e) => e.key === entry.key), + recoveryMs: performance.now() - started, + }; + if (!entry.marker.show || !trail?.body?.show || !trail.body.ready) + return { + ...status, + reason: 'marker or body did not recover before pixel deadline', + }; + setRate(entry.track, 0, { + wallNowMs: Date.now(), + monoNowMs: performance.now(), + }); + parts.rendering.sampleIdle(entry); + parts.rendering.schedulePlayback(entry); + const V = entry.marker.position.constructor; + const points = entry.trailSegments + .filter((s) => s.toT <= entry.sample.displayT) + .flatMap((s) => s.positions); + const lengths = [0]; + for (let i = 1; i < points.length; i++) + lengths.push(lengths.at(-1) + V.distance(points[i - 1], points[i])); + const canvas = scene.canvas, + gl = scene.context._gl, + scale = canvas.width / canvas.clientWidth; + const mul = (m, v) => + [0, 1, 2, 3].map( + (i) => + m[i] * v[0] + m[i + 4] * v[1] + m[i + 8] * v[2] + m[i + 12] * v[3], + ); + const project = (p) => { + const q = mul( + camera.frustum.projectionMatrix, + mul(camera.viewMatrix, [p.x, p.y, p.z, 1]), + ); + return { + x: ((q[0] / q[3]) * 0.5 + 0.5) * canvas.clientWidth, + y: (0.5 - (q[1] / q[3]) * 0.5) * canvas.clientHeight, + inFront: q[3] > 0, + }; + }; + const samples = Array.from({ length: 8 }, (_, i) => { + const d = (lengths.at(-1) * (i + 1)) / 9; + let j = 1; + while (j < lengths.length - 1 && lengths[j] < d) j++; + const p = V.lerp( + points[j - 1], + points[j], + (d - lengths[j - 1]) / Math.max(0.001, lengths[j] - lengths[j - 1]), + new V(), + ); + const cart = C.fromCartesian(p); + cart.height = scene.globe.getHeight(cart) || 0; + return { + ...project(C.toCartesian(cart)), + radius: (Math.SQRT2 * Math.ceil(3 * scale)) / scale, + }; + }); + const sprite = { + ...project(entry.marker.position), + radius: Math.hypot(entry.marker.width, entry.marker.height) / 2 + 4, + }; + const read = () => + samples.map(({ x, y }) => { + const r = Math.ceil(3 * scale), + px = Math.round(x * scale), + py = Math.round(canvas.height - 1 - y * scale); + if ( + px < r || + py < r || + px + r >= canvas.width || + py + r >= canvas.height + ) + return null; + const data = new Uint8Array((2 * r + 1) ** 2 * 4); + gl.readPixels( + px - r, + py - r, + 2 * r + 1, + 2 * r + 1, + gl.RGBA, + gl.UNSIGNED_BYTE, + data, + ); + return Array.from(data); + }); + const frame = () => + new Promise((resolve, reject) => { + const timer = setTimeout(() => { + remove(); + reject(new Error('No recovery frame')); + }, 500); + const remove = scene.postRender.addEventListener(() => { + remove(); + clearTimeout(timer); + resolve(read()); + }); + scene.requestRender(); + }); + let visible = true; + const remove = scene.preRender.addEventListener(() => { + trail.body.show = visible; + if (trail.headPrimitive) + trail.headPrimitive.show = visible && trail.head.show; + }); + const captures = []; + try { + for (const show of [false, true, false, true]) { + visible = show; + await frame(); + captures.push(await frame()); + } + } finally { + remove(); + parts.trails.update(); + } + const [off, on, offAgain, onAgain] = captures; + return { + ...status, + samples, + sprite, + off, + on, + offAgain, + onAgain, + tilesReady: + scene.globe.tilesLoaded && + parts.trails.diagnostics().body === trail.body, + elapsedMs: performance.now() - started, + attributes: Array.from({ length: 4 }, (_, i) => { + const a = trail.body.getGeometryInstanceAttributes(`${i}:1`); + return { show: Array.from(a.show), color: Array.from(a.color) }; + }), + }; + }); + const pixels = reduceTrailPixels(result.on, result.off, result); + result.present = pixels.present; + result.pixelPass = pixels.pass; + result.pixelDetails = pixels; + result.errors = errors; + await page.screenshot({ 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 = + result.before?.shown === false && + result.before?.phase === 'playing' && + result.preparedAtSelection && + result.markerShow && + result.body && + result.bodyShow && + result.elapsedMs <= 2000 && + pixels.pass && + !errors.length; + console.log( + `${pass ? 'PASS' : 'FAIL'} select moving bus, setView, marker + body + >=6/8 trail pixels within 2 s`, + ); + console.log(JSON.stringify(result)); + process.exitCode = pass ? 0 : 1; +} finally { + await browser.close(); +} diff --git a/scripts/qa-transit-scenes.mjs b/scripts/qa-transit-scenes.mjs index 94ec134bb..1ceb45b22 100644 --- a/scripts/qa-transit-scenes.mjs +++ b/scripts/qa-transit-scenes.mjs @@ -1,3 +1,12 @@ +import { getRegisteredTransitFeed } from '../src/data/transitFeeds.js'; + +// Not registered or active: camera discovery and live polls never own this feed. +/** CapMetro metadata under a private QA identity for selected-trail pixels. */ +export const TRAIL_VISIBILITY_FEED = Object.freeze({ + ...getRegisteredTransitFeed('capmetro-austin'), + id: 'qa-trail-capmetro', +}); + import { reportTransitVisibility } from './qa-transit-browser.mjs'; import { writeFile } from 'node:fs/promises'; import { @@ -5,6 +14,7 @@ import { reduceMotion, reduceBackground, reduceSensorContrast, + reduceTrailPixels, } from '../src/layers/transit/qaMetrics.js'; /** CDP includes objects collected during the sample, not just surviving objects. */ @@ -581,3 +591,459 @@ export async function runBostonLive({ JSON.stringify(evidence, null, 2), ); } + +/** Google 3D proof: paired framebuffer reads reject coincidental road colours. */ +export async function runTrailVisibility({ + page, + check, + wait, + shots, + tag, + selectStyle, + altitude = 600, + pitch = 45, +}) { + const name = 'Google 3D selected trail visible at 6 of 8 projected samples'; + await selectStyle(page, 'normal'); + await page.evaluate( + async ({ altitude, pitch }) => { + const app = window.__godsEyeView; + await app.dataManager.setEnabled('transit', true, { source: 'qa' }); + if (app.mapStackController.isStackAvailable('photoreal')) + await app.mapStackController.setStack('photoreal'); + const camera = app.viewer.camera, + C = camera.positionCartographic.constructor; + camera.setView({ + destination: C.toCartesian( + C.fromDegrees( + -97.7431, + 30.26725 - altitude / Math.tan((pitch * Math.PI) / 180) / 111320, + altitude, + ), + ), + orientation: { heading: 0, pitch: (-pitch * Math.PI) / 180, roll: 0 }, + }); + }, + { altitude, pitch }, + ); + await wait(8000); + const setup = await page.evaluate( + async ({ altitude, pitch, feed }) => { + const app = window.__godsEyeView, + scene = app.viewer.scene; + const layer = app.dataManager.layers.get('transit').module; + const state = layer._transitStateForTest(), + parts = layer._transitPartsForTest(); + const google = + !!app.tileset && + app.tileset.show !== false && + app.mapStackController.getActiveId() === 'photoreal'; + if (!google) + return { google: false, reason: 'visible Google 3D tileset required' }; + const C = scene.camera.positionCartographic.constructor; + const centreLat = 30.267 + 90 / 111320; + const floor = scene.sampleHeight(C.fromDegrees(-97.7431, centreLat)); + if (Number.isFinite(floor)) + scene.camera.setView({ + destination: C.toCartesian( + C.fromDegrees( + -97.7431, + centreLat - altitude / Math.tan((pitch * Math.PI) / 180) / 111320, + floor + altitude, + ), + ), + orientation: { heading: 0, pitch: (-pitch * Math.PI) / 180, roll: 0 }, + }); + parts.selection.clearSelection(); + parts.ingestion.abortAllInFlight(); + state._activeFeeds.clear(); + for (const key of state._vehicles.keys()) + parts.ingestion.removeVehicle(key); + clearTimeout(state._cameraDebounceTimer); + state._cameraDebounceTimer = null; + const { seek, setRate } = await import('/src/data/contactPlayback.js'); + const now = Date.now(); + // Nine straight street fixes, 30 m apart. Use the production surface path. + for (let i = 0; i < 9; i++) { + const timestamp = (now - 120000 + i * 15000) / 1000; + parts.ingestion.applySnapshot( + feed, + { + fetchedAt: timestamp * 1000, + vehicles: [ + { + id: 'trail-visible', + routeId: '1', + tripId: 'trail-visible', + lat: 30.267 + (i * 30) / 111320, + lon: -97.7431, + timestamp, + timestampSource: 'vehicle', + bearing: 0, + }, + ], + }, + { stale: false }, + ); + } + const entry = state._vehicles.get(`${feed.id}:trail-visible`); + entry.qaFixture = true; + const clocks = { wallNowMs: now, monoNowMs: performance.now() }; + seek(entry.track, now - 45000, clocks); + setRate(entry.track, 1, clocks); + parts.rendering.sampleIdle(entry); + parts.height.anchorFloors(); + parts.rendering.refreshVisibility(); + parts.rendering.maintainPresentation(); + parts.selection.selectVehicle(entry.key); + return { + google, + key: entry.key, + fixes: entry.track.count, + startDisplayT: now - 45000, + startLat: entry.sample.lat, + }; + }, + { altitude, pitch, feed: TRAIL_VISIBILITY_FEED }, + ); + if (!setup.google) { + check(name, false, JSON.stringify(setup), { unexercised: true }); + return; + } + const cost = await page.evaluate(async (key) => { + const app = window.__godsEyeView, + scene = app.viewer.scene; + const layer = app.dataManager.layers.get('transit').module; + const parts = layer._transitPartsForTest(), + entry = layer._transitStateForTest()._vehicles.get(key); + const gl = scene.context._gl, + originals = new Map(), + wrapped = new Map(); + let owner = null, + headBytes = 0, + bodyBytes = 0, + headUploadMax = 0, + bodyUploadMax = 0, + frames = 0; + const headCpu = []; + const wrap = (primitive, kind) => { + if (!primitive || wrapped.has(primitive)) return; + const update = primitive.update; + wrapped.set(primitive, update); + primitive.update = function (frameState) { + const before = performance.now(); + owner = kind; + try { + return update.call(this, frameState); + } finally { + owner = null; + if (kind === 'head') headCpu.push(performance.now() - before); + } + }; + }; + for (const name of ['bufferData', 'bufferSubData']) { + const original = gl[name]; + originals.set(name, original); + gl[name] = function (...args) { + if (owner) { + const value = args[name === 'bufferData' ? 1 : 2], + offset = args[3] || 0, + length = args[4]; + const bytes = + typeof value === 'number' + ? value + : value + ? length !== undefined + ? length * (value.BYTES_PER_ELEMENT || 1) + : value.byteLength - offset * (value.BYTES_PER_ELEMENT || 1) + : 0; + if (owner === 'head') headBytes += bytes; + else bodyBytes += bytes; + } + return original.apply(this, args); + }; + } + const pre = scene.preRender.addEventListener(() => { + headBytes = bodyBytes = 0; + const trail = parts.trails.diagnostics(); + wrap(trail?.body, 'body'); + wrap(trail?.headPrimitive || trail?.head?._polylineCollection, 'head'); + }); + const post = scene.postRender.addEventListener(() => { + frames++; + headUploadMax = Math.max(headUploadMax, headBytes); + bodyUploadMax = Math.max(bodyUploadMax, bodyBytes); + }); + try { + // Include a full history upload, even if the first selection already rendered. + entry.pathRevision = -1; + parts.trails.prepareEntry(entry); + scene.requestRender(); + await new Promise((resolve) => setTimeout(resolve, 20000)); + headCpu.sort((a, b) => a - b); + return { + frames, + headUploadMax, + bodyUploadMax, + headCpuP95Ms: headCpu[Math.floor(headCpu.length * 0.95)] ?? null, + headCpuMaxMs: headCpu.at(-1) ?? null, + }; + } finally { + pre(); + post(); + for (const [name, original] of originals) gl[name] = original; + for (const [primitive, update] of wrapped) + if (!primitive.isDestroyed()) primitive.update = update; + } + }, setup.key); + const result = await page.evaluate(async (setup) => { + const app = window.__godsEyeView, + scene = app.viewer.scene; + const layer = app.dataManager.layers.get('transit').module; + const state = layer._transitStateForTest(), + parts = layer._transitPartsForTest(); + const entry = state._vehicles.get(setup.key); + const trail = parts.trails.diagnostics(); + if (!entry || !trail) + return { ...setup, present: 0, reason: 'selection disappeared' }; + const { setRate } = await import('/src/data/contactPlayback.js'); + setRate(entry.track, 0, { + wallNowMs: Date.now(), + monoNowMs: performance.now(), + }); + parts.rendering.sampleIdle(entry); + parts.rendering.schedulePlayback(entry); + parts.rendering.syncRenderHold(); + const ready = () => + app.tileset?.show !== false && + app.tileset?.tilesLoaded === true && + (scene.globe?.show === false || scene.globe?.tilesLoaded === true) && + trail.body?.ready === true && + (!trail.headPrimitive || trail.headPrimitive.ready === true); + // Require sustained readiness after freezing playback, before projecting + // onto the refined surface. Repeated captures still check pixel stability. + const tilesReady = await new Promise((resolve) => { + const started = performance.now(); + let readySince = null; + const timer = setInterval(() => { + const now = performance.now(); + readySince = ready() ? (readySince ?? now) : null; + scene.requestRender(); + if ( + (readySince !== null && now - readySince >= 500) || + now - started >= 30000 + ) { + clearInterval(timer); + resolve(readySince !== null && now - readySince >= 500); + } + }, 80); + }); + if (!tilesReady) + return { + ...setup, + present: 0, + reason: 'tiles or trail geometry did not become ready', + }; + const canvas = scene.canvas, + gl = canvas.getContext('webgl2') || canvas.getContext('webgl'); + const scale = canvas.width / canvas.clientWidth; + const points = entry.trailSegments + .filter((s) => s.toT <= entry.sample.displayT) + .flatMap((s) => s.positions); + if (trail.head?.show) points.push(...trail.head.positions); + if (points.length < 2) + return { ...setup, present: 0, reason: 'no completed path' }; + const C = scene.camera.positionCartographic.constructor; + const V = entry.marker.position.constructor; + const lengths = [0]; + for (let i = 1; i < points.length; i++) + lengths.push(lengths.at(-1) + V.distance(points[i - 1], points[i])); + const mul = (m, v) => + [0, 1, 2, 3].map( + (i) => + m[i] * v[0] + m[i + 4] * v[1] + m[i + 8] * v[2] + m[i + 12] * v[3], + ); + const samples = Array.from({ length: 8 }, (_, i) => { + const d = (lengths.at(-1) * (i + 1)) / 9; + let j = 1; + while (j < lengths.length - 1 && lengths[j] < d) j++; + const p = V.lerp( + points[j - 1], + points[j], + (d - lengths[j - 1]) / Math.max(0.001, lengths[j] - lengths[j - 1]), + new V(), + ); + const cart = C.fromCartesian(p); + const height = scene.sampleHeight( + cart, + [entry.marker, trail.body, trail.headPrimitive].filter(Boolean), + ); + if (Number.isFinite(height)) cart.height = height; + const surface = C.toCartesian(cart); + const q = mul( + scene.camera.frustum.projectionMatrix, + mul(scene.camera.viewMatrix, [surface.x, surface.y, surface.z, 1]), + ); + return { + x: ((q[0] / q[3]) * 0.5 + 0.5) * canvas.clientWidth, + y: (0.5 - (q[1] / q[3]) * 0.5) * canvas.clientHeight, + inFront: q[3] > 0, + radius: (Math.SQRT2 * Math.ceil(3 * scale)) / scale, + }; + }); + const marker = entry.marker.position; + const markerClip = mul( + scene.camera.frustum.projectionMatrix, + mul(scene.camera.viewMatrix, [marker.x, marker.y, marker.z, 1]), + ); + const sprite = { + x: ((markerClip[0] / markerClip[3]) * 0.5 + 0.5) * canvas.clientWidth, + y: (0.5 - (markerClip[1] / markerClip[3]) * 0.5) * canvas.clientHeight, + // Include the padded, rotated sprite and its selection bracket. + radius: Math.hypot(entry.marker.width, entry.marker.height) / 2 + 4, + }; + const read = () => + samples.map(({ x, y, inFront }) => { + const r = Math.ceil(3 * scale), + px = Math.round(x * scale), + py = Math.round(canvas.height - 1 - y * scale); + if ( + !inFront || + px < r || + py < r || + px + r >= canvas.width || + py + r >= canvas.height + ) + return null; + const data = new Uint8Array((2 * r + 1) ** 2 * 4); + gl.readPixels( + px - r, + py - r, + 2 * r + 1, + 2 * r + 1, + gl.RGBA, + gl.UNSIGNED_BYTE, + data, + ); + return data; + }); + const frame = () => + new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + remove(); + reject(new Error('Trail framebuffer did not render within 5 s')); + }, 5000); + const remove = scene.postRender.addEventListener(() => { + remove(); + clearTimeout(timeout); + resolve(read()); + }); + scene.requestRender(); + }); + const bodyShow = trail.body?.show, + headShow = trail.head?.show, + headPrimitiveShow = trail.headPrimitive?.show, + backingShow = trail.backing?.show; + let showTrail = false; + const applyVisibility = () => { + if (trail.body) trail.body.show = showTrail && bodyShow; + if (trail.headPrimitive) + trail.headPrimitive.show = showTrail && headPrimitiveShow; + if (trail.head) trail.head.show = showTrail && headShow; + if (trail.backing) trail.backing.show = showTrail && backingShow; + }; + // Override the layer's frame update in both states; selection stays fixed. + const removeVisibility = scene.preRender.addEventListener(applyVisibility); + const captures = []; + let captureReady = true; + try { + for (const visible of [false, true, false, true]) { + showTrail = visible; + // Let post-processing settle before each measured framebuffer. + for (let i = 0; i < 3; i++) await frame(); + captures.push(await frame()); + const current = parts.trails.diagnostics(); + captureReady &&= + ready() && + current?.body === trail.body && + current?.headPrimitive === trail.headPrimitive; + } + } finally { + removeVisibility(); + if (trail.body) trail.body.show = bodyShow; + if (trail.headPrimitive) trail.headPrimitive.show = headPrimitiveShow; + if (trail.head) trail.head.show = headShow; + if (trail.backing) trail.backing.show = backingShow; + await frame(); + } + const [off, on, offAgain, onAgain] = captures.map((patches) => + patches.map((p) => (p ? Array.from(p) : null)), + ); + return { + ...setup, + fixes: entry.track.count, + selected: state._selectedKey === setup.key, + pathMetres: lengths.at(-1), + samples, + on, + off, + onAgain, + offAgain, + sprite, + tilesReady: captureReady, + elapsedDisplayMs: entry.sample.displayT - setup.startDisplayT, + movedMetres: Math.abs(entry.sample.lat - setup.startLat) * 111320, + body: trail.body?.constructor.name, + headStrategy: trail.headStrategy || 'PolylineCollection', + headRebuilds: trail.headRebuilds ?? null, + }; + }, setup); + const pixels = reduceTrailPixels(result.on, result.off, result); + result.cost = cost; + result.altitude = altitude; + result.pitch = pitch; + result.present = pixels.present; + result.total = pixels.total; + result.samples = result.samples?.map((s, i) => ({ + ...s, + hit: pixels.hits[i], + stable: pixels.stable[i], + eligible: pixels.eligible[i], + })); + await page.screenshot({ + path: `${shots}/${tag}-${altitude}m-trail-visible.jpg`, + type: 'jpeg', + quality: 95, + }); + await writeFile( + `${shots}/${tag}-${altitude}m-trail-visible.json`, + JSON.stringify(result, null, 2), + ); + for (const key of ['on', 'off', 'onAgain', 'offAgain']) delete result[key]; + check( + name, + result.google && + result.selected && + result.fixes >= 5 && + result.pathMetres > 15 && + result.elapsedDisplayMs >= 19000 && + result.movedMetres >= 5 && + pixels.pass, + JSON.stringify(result), + ); + check( + 'selected trail stays within 2 MiB rebuild and 2 KiB/frame head uploads', + cost.frames > 30 && + cost.bodyUploadMax > 0 && + cost.bodyUploadMax <= 2 * 1024 * 1024 && + cost.headUploadMax > 0 && + cost.headUploadMax <= 2048, + JSON.stringify({ altitude, ...cost }), + ); + await page.evaluate(() => + window.__godsEyeView.dataManager.layers + .get('transit') + .module._transitPartsForTest() + .selection.clearSelection(), + ); +} diff --git a/scripts/qa-transit.mjs b/scripts/qa-transit.mjs index de09a6222..aac1d8f60 100644 --- a/scripts/qa-transit.mjs +++ b/scripts/qa-transit.mjs @@ -1,4 +1,5 @@ #!/usr/bin/env node +import { runTransitHeadingRegression } from './qa-transit-heading.mjs'; import { boundPageEvaluations, reportTransitVisibility, @@ -16,6 +17,7 @@ import { runFleetBudgets, runBostonMatrix, runBostonLive, + runTrailVisibility, } from './qa-transit-scenes.mjs'; /** * Browser proof for the Transit layer against a running app. @@ -78,6 +80,18 @@ const check = ( failures += 1; } else if (!passed) failures += 1; }; +// A focused deterministic regression can run independently of live-feed QA. +if (process.argv.includes('--heading-only')) { + try { + await runTransitHeadingRegression(BASE, check); + } catch (error) { + check('heading regression completed', false, error.stack || error.message); + } + console.log(`HEADING: ${failures ? 'FAIL' : 'PASS'} (${failures} failed)`); + process.exit(failures ? 1 : 0); +} +if (runs('heading')) await runTransitHeadingRegression(BASE, check); + const renderingSource = await readFile( new URL('../src/layers/transit/rendering.js', import.meta.url), 'utf8', @@ -1774,6 +1788,13 @@ try { selectStyle, sampleRendered, }; + if (runs('trail-visible')) + for (const [altitude, pitch] of [ + [300, 55], + [600, 45], + [900, 45], + ]) + await runTrailVisibility({ ...sceneQA, altitude, pitch }); if (runs('budgets')) await runFleetBudgets(sceneQA); if (runs('matrix')) await runBostonMatrix(sceneQA); if (runs('boston-live')) await runBostonLive(sceneQA); diff --git a/scripts/qa-voice-routing.mjs b/scripts/qa-voice-routing.mjs index 4c5c9dedc..de5f44fec 100644 --- a/scripts/qa-voice-routing.mjs +++ b/scripts/qa-voice-routing.mjs @@ -625,12 +625,27 @@ async function runBehaviorLayer() { // (4b) analyst engine end-to-end: count flights over Texas (region ring // via NE-pack/admin machinery), then a follow-up over the same set. + // A cold boundary lookup can exceed the resolver's budget; it answers + // region-timeout and keeps loading, so asking again must succeed. + let texasTimeouts = 0; r = await run('analyst_query', { layers: ['flights'], scope: { kind: 'region', name: 'Texas' }, limit: 5 }); + while (r?.code === 'region-timeout' && texasTimeouts < 8) { + texasTimeouts += 1; + await settle(5000); + r = await run('analyst_query', { layers: ['flights'], scope: { kind: 'region', name: 'Texas' }, limit: 5 }); + } report(r?.ok === true && Number.isFinite(r?.count) && r.count > 0 && String(r?.coverage?.scope || '').includes('Texas'), - 'behavior: analyst counts flights over Texas', `count=${r?.count} scope=${r?.coverage?.scope} err=${r?.error || ''}`); + 'behavior: analyst counts flights over Texas', `count=${r?.count} scope=${r?.coverage?.scope} timeouts=${texasTimeouts} err=${r?.error || ''}`); r = await run('analyst_query', { followUp: true, filters: [{ field: 'onGround', op: 'eq', value: false }], sortBy: 'altitudeM', limit: 3 }); report(r?.ok === true && r?.coverage?.followUp === true, 'behavior: analyst follow-up re-filters the remembered set', `count=${r?.count} followUp=${r?.coverage?.followUp}`); + // A marine region resolves from the bundled Natural Earth pack in the page, + // without the slower geocode fallback. + const gulfStarted = Date.now(); + r = await run('analyst_query', { layers: ['flights'], scope: { kind: 'region', name: 'Gulf of Mexico' }, limit: 5 }); + const gulfMs = Date.now() - gulfStarted; + report(r?.ok === true && String(r?.coverage?.scope || '').includes('Gulf of Mexico') && gulfMs < 3000, + 'behavior: analyst resolves the Gulf of Mexico from the bundled pack', `scope=${r?.coverage?.scope} ms=${gulfMs} err=${r?.error || ''}`); // (5) zoom_to_globe is ABSOLUTE full-earth (>12,000 km band) r = await run('zoom_to_globe', {}); diff --git a/scripts/qa-voice-wav.mjs b/scripts/qa-voice-wav.mjs index b75524e7a..f9d7f8ee9 100644 --- a/scripts/qa-voice-wav.mjs +++ b/scripts/qa-voice-wav.mjs @@ -2,7 +2,7 @@ /** * Credentialed AI voice acceptance using a prerecorded Chromium microphone. * - * Run: node scripts/qa-voice-wav.mjs http://localhost:4189 + * Run: node scripts/qa-voice-wav.mjs http://localhost:4189 [--push-to-talk] */ import { createHash } from 'node:crypto'; import fs from 'node:fs'; @@ -11,8 +11,13 @@ import { fileURLToPath } from 'node:url'; import puppeteer from 'puppeteer'; const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); -const appUrl = process.argv[2] || 'http://localhost:4189'; -const wavPath = process.argv[3] +const pushToTalk = process.argv.includes('--push-to-talk'); +const positional = process.argv.slice(2).filter(arg => arg !== '--push-to-talk'); +const targetUrl = new URL(positional[0] || 'http://localhost:4189'); +// Keep first-run focus changes outside this voice/keyboard acceptance test. +targetUrl.searchParams.set('welcome', '0'); +const appUrl = targetUrl.href; +const wavPath = positional[1] || path.join(repoRoot, 'scripts', 'fixtures', 'voice', 'full-globe-turn-on-radio.wav'); const expectedFixtureSha256 = 'b57af70db1922b72fec2c6c58348ccd3309e10aa1e8edec2890277dff26cc7bb'; @@ -60,6 +65,7 @@ try { await page.waitForFunction(() => ( window.__godsEyeView?.voiceCommands && document.getElementById('gev-voice-button') + && document.getElementById('loading-screen')?.classList.contains('hidden') ), { timeout: 30_000 }); const readState = () => page.evaluate(() => { @@ -81,7 +87,26 @@ try { }); const initial = await readState(); - await page.evaluate(() => document.getElementById('gev-voice-button').click()); + let pushToTalkStarted = false; + let microphoneReleased = false; + if (pushToTalk) { + await page.bringToFront(); + await page.focus('.cesium-widget canvas'); + await page.keyboard.down('Space'); + await page.waitForFunction(() => document.querySelector( + '[data-push-to-talk="held"][data-microphone="active"]', + ), { timeout: 30_000 }); + pushToTalkStarted = true; + // The hash-pinned fixture is 9.2 seconds long and plays once from mic acquisition. + await new Promise(resolve => setTimeout(resolve, 10_000)); + await page.keyboard.up('Space'); + microphoneReleased = await page.evaluate(() => { + const status = window.__godsEyeView.voiceCommands.status; + return status === 'idle' || Boolean(document.querySelector('[data-microphone="muted"]')); + }); + } else { + await page.click('#gev-voice-button'); + } const timeline = [initial]; let lastSignature = JSON.stringify(initial); @@ -113,10 +138,14 @@ try { } const result = { - ok: finalState.voiceStatus === 'idle' + ok: (!pushToTalk || (pushToTalkStarted && microphoneReleased)) + && finalState.voiceStatus === 'idle' && finalState.radioAudioState === 'playing' && finalState.radioVoiceDucked === false && Number(finalState.cameraHeightM) >= 10_000_000, + mode: pushToTalk ? 'push-to-talk' : 'click', + pushToTalkStarted, + microphoneReleased, fixture: wavPath, fixtureSha256, appUrl, diff --git a/scripts/qa-weather-journey.mjs b/scripts/qa-weather-journey.mjs new file mode 100644 index 000000000..75cd2c269 --- /dev/null +++ b/scripts/qa-weather-journey.mjs @@ -0,0 +1,423 @@ +#!/usr/bin/env node +/** + * qa-weather-journey — drive the Weather layers the way a person would and + * keep the evidence: numbered screenshots plus per-step layer diagnostics. + * + * Starts at the Earth view, opens Data Layers, switches Wind on from its real + * row button, cycles the wind fields/models, switches radar, satellite clouds, + * lightning and cyclones on, follows "View storm" and "View US radar", zooms + * into a regional view, a city view and a street view, replays history, and + * ends with real wheel/drag input. Every step records the enabled layers' + * diagnostics (imagery tiles loaded, shown observation time, wind geometry) + * and a 2 s `scene.postRender` count so a stalled renderer cannot pass as a + * healthy screenshot. + * + * Usage: + * node scripts/qa-weather-journey.mjs [--url http://localhost:4173] + * [--label google] [--headless] [--out qa-shots/weather-journey] + * + * Requires a running dev server. Screenshots and steps.json land in + * /