diff --git a/changelog.d/1826-space-missions-panel.md b/changelog.d/1826-space-missions-panel.md new file mode 100644 index 0000000000..bc616d611d --- /dev/null +++ b/changelog.d/1826-space-missions-panel.md @@ -0,0 +1,16 @@ +- Space Missions moves out of the Context panel into its own right-rail panel, + with its own tab on phones, and becomes an ordinary layer. It no longer + switches other layers off or refuses them while it runs, and Context leaves + it and Satellites alone, so it runs beside Contacts in either order + (Contacts no longer switches Satellites off). On desktop, opening Context or + Space Missions collapses the other. Mission labels on the globe are + clickable and select their mission, even where they sit over aircraft or + ships, and picking a mission on the globe opens the panel. The Data Layers + row gets previous and next mission controls. Share links keep the panel + open or closed (a short link made from an older long link, which does not + mention the panel, is two bytes longer), voice can open it, and Cockpit + folds it away like the other map panels. An explicit user or voice + Satellites off request made after Space Missions was switched on ends it + and keeps Satellites off afterwards; scene, story, preset and other + programmatic Satellites changes leave Space Missions running + (manjunath22466, samehkhamis, #1826). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index f96409cf09..64207f325a 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -935,10 +935,10 @@ the header narrows every list. Expanded, Context becomes a full-height column at the right edge (the left edge right to left) and the map credits stop short of it. -The Contacts and Space Missions modes and the Radio strip stay in the -panel's main tab, below the card. When Contacts follows the aircraft the -card shows, its list sits inside the card. Turning Radio or Launches on -opens Context. The Properties tab holds the Labels and 3D aircraft +The Contacts mode and the Radio strip stay in the panel's main tab, below +the card. When Contacts follows the aircraft the card shows, its list sits +inside the card. Turning Radio on opens Context. Space Missions is not part +of Context: turning it on opens its own Space Missions panel. The Properties tab holds the Labels and 3D aircraft settings from Visual while a layer they act on is on. Context does its reading only while its panel is open. Weather and news @@ -2861,13 +2861,23 @@ them. ## Context coordination -Context controls own Contacts/Space Missions state, entry and exit transactions, -layer snapshots and restoration. The application supplies the existing manager, +Context controls own Contacts state, entry and exit transactions, layer +snapshots and restoration. Space Missions is an ordinary layer outside this +owner: the launches layer keeps its own Satellites dependency +(`src/layers/launches/satelliteIntents.js`), and `SpaceMissionsControls` +(`src/ui/spaceMissionsControls.js`) connects it to its panel and store. The application supplies the existing manager, installations search and camera/panel actions. Tab listeners and pending 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. +Contacts leaves Satellites on. Contacts is being removed, so no new Contacts +behavior is added here. Only an explicit user or voice Satellites OFF requested +after Space Missions ON ends Space Missions. A scene, story, preset or other +programmatic Satellites OFF leaves Space Missions running: an automatic change +must not undo the user’s explicit choice, and the mission lifecycle remains +independent of Satellites. + ## Camera panel ownership CCTV controls receive the existing camera port and explicit application actions. @@ -2884,7 +2894,7 @@ The panel opens when a camera becomes active and collapses when the layer is switched off, from its own switch or anywhere else. The panel chrome applies the collapse, so a panel the desktop accordion only folded has its saved and shared state closed too. Clear selected data layers and Context isolation -(Contacts, Space Missions) switch the layer off without the user asking: the +(Contacts) switch the layer off without the user asking: the panel and its share preference stay as they are, and the layer comes back to an open panel. Only the switch-off isolation makes counts (`suspendsLayer`, true while `_clearLayersOutsideContextMode` switches the layer off): the user @@ -3356,8 +3366,7 @@ and military aircraft and vessels share this rule; fine pointers stay exact. Manually opening Context with a tracked civilian or military aircraft enters the existing Contacts mode when Context is off. Contacts adopts that aircraft -without restarting its tracking; an active or entering Space Missions mode is -left alone. Programmatic sheet changes and closing the tab do not activate a mode. +without restarting its tracking. Programmatic sheet changes and closing the tab do not activate a mode. Sheets borrow panels. Opening one expands its panels without persisting them or claiming a user choice, and share links keep reporting each borrowed panel's @@ -3840,9 +3849,9 @@ they do not reduce the materialized entity count or establish an FPS gain. - Display controls and shader-parameter sliders show keyboard focus in both the map panel and Cockpit Display. Arrow keys retain native range adjustment. The enabled CCTV camera dropdown shows keyboard focus as well. -- Tab reaches both Contacts and Space Missions in sequence in every Context - state. Left/Right arrows also switch them; the focused tab has a distinct ring - even when selected. +- Tab reaches the Contacts control in Context and the separate Space Missions + rail button when launches are enabled. Both keep a visible focus ring when + active. - Keyboard focus on a Space Missions roster item uses the same temporary globe rotation and mission-marker highlight as pointer hover. Focus alone does not select the mission; Enter or Space performs selection. Keyboard and pointer @@ -4546,16 +4555,10 @@ a number`, exactly `(0,0,0)` returns undefined, and a near-center value such > cannot slip through by not matching the older spelling. CCTV's > `selectedCameraId` is the one recorded keep: it raises a monitor plane and > never writes `viewer.trackedEntity` or the camera. -> (4) An **isolating Context mode is exited before a shot's layers apply**. -> Space Missions refuses every enable outside its replay bundle, so with it -> left dirty all five recipes were refused (or, for Orbital Watch, composed -> over a replay they never declared). The verdict is read off the shared guard -> (`contextLayerEnableBlockReason`), not a mode name, so a future isolating -> mode is covered — the probe id `SCENE_EXCLUSIVITY_PROBE_LAYER_ID` is -> reserved by a test against the real layer registry. The exit itself is the -> ordinary `setContextMode('off')` exact-restore path and is deliberately NOT -> abortable: leaving the mode IS the restore to the operator's pre-mode state, -> and tearing that transaction in half would strand Context. A refused +> (4) Playback leaves every Context mode alone. No mode isolates the globe +> any more (Space Missions is an ordinary layer), so the former exit of an +> isolating mode before a shot's layers apply, and its probe layer id, were +> removed with it. A refused > `setEnabled` is surfaced in the status line and a `shot_layers_refused` > telemetry event instead of being reported as success. **Mixed accepted / > refused layers are reported honestly, not rolled back** — a shot whose @@ -4876,10 +4879,10 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with > selected manager-owned data layers, including an active Context choice, > while retaining visual, HUD, map, and panel settings. A disabled layer may > still release camera work that it owns through its normal teardown. -> Direct Data Layers entry into Space Missions excludes the new mission ON -> intent from its pre-entry snapshot. Its OFF control therefore leaves Space -> Missions off and restores Satellites to their exact pre-entry visibility -> and parameter state. +> Space Missions is an ordinary layer and opens no Context session. Its OFF +> control leaves Space Missions off and restores Satellites to their +> pre-mission visibility and parameter state, keeping an explicit Satellites +> action taken while it ran. > The title and loading logos use a blue 10 px outer-eye stroke with a > translucent slate fill, while the globe-and-cage gaze travels up to 34 SVG > units toward the pointer for clearer feedback at the compact title size. @@ -4887,11 +4890,12 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with > clock goes live and the camera flies to the view the app started from (the > host's `homeView`, else its `startView`, else the whole planet), letting go > of whatever it follows as Reset Globe does (`returnToStart()`). -> - **Context, Cockpit, and Radio interaction contract:** explicit Contacts, -> Space Missions, and successful Cockpit actions reveal the Context panel, while -> restoration and replay preserve its prior collapsed state. Contacts uses the -> dedicated right-side chooser; the underlying Global Context coordinator is -> registered for lifecycle and restoration but is not duplicated in Data Layers. +> - **Context, Cockpit, and Radio interaction contract:** explicit Contacts and +> Radio actions and successful Cockpit actions can reveal Context. Contacts +> uses the dedicated right-side chooser. Space Missions has its own rail +> button and panel while launches are enabled. +> Mission teardown clears the selection shown in the panel before restoring +> the Satellites layer, so a failed restore leaves no stale mission details. > Inside Cockpit, the focused summary card is titled Contact in both visible > copy and its accessible control labels. > The top-center Cockpit vision cycle is the fixed, duplicate-free sequence @@ -5585,9 +5589,10 @@ activeCameraCardEnabled: true })` may publish it through the retained > pitch/heading instruments, altitude/speed tapes, and the signal window. > Topline vision and exit controls retain the highest in-cockpit layer. > - **Space Missions dependency shutdown:** disabling a mission dependency or -> leaving the mode closes mission context and restores the exact pre-entry -> Satellite enabled state and presentation parameters. Restored parameters -> never re-show primitives while the Satellite layer is disabled. +> switching Space Missions off restores the pre-mission Satellite enabled +> state and presentation parameters, except that an explicit Satellites action +> taken while it ran is kept. Restored parameters never re-show primitives +> while the Satellite layer is disabled. > - **Flights 3D/cockpit hardening:** the destination-direction cue is an > inline SVG rather than a remotely loaded Material Icons ligature, so a > blocked or late font can no longer expand the literal word `navigation` @@ -5628,17 +5633,13 @@ activeCameraCardEnabled: true })` may publish it through the retained > only for the synchronous selection window, history survives same-layer > reselection, and NEXT availability uses the same UNKNOWN-cohort gate as the > navigation action. Contacts entry does not wait for unrelated serialized -> layer teardown; Space Missions waits for every incompatible live/current -> layer to settle off before replay data starts. A rejected teardown keeps -> that layer authoritatively enabled, restores any siblings already stopped, -> and aborts replay entry; the isolation -> guard remains active until Rocket Launches finishes enabling. Manually enabling +> layer teardown. (Space Missions isolation, which waited for incompatible +> layers to settle off, was later removed: Space Missions is now an ordinary +> layer.) Manually enabling > another Data Layer is additive in both an active mode and the neutral shell: > it does not exit Context, and the added layer joins the pre-entry snapshot > when the session is eventually restored. Manually disabling a required mode > dependency still exits and restores that union. -> While Space Missions is active, direct incompatible enables are refused -> before initialization or polling and explain that the mode must be exited. > User entry alone owns the pre-entry snapshot; programmatic dependencies do > not replace it, and rapid re-entry snapshots the pending settled restore > target rather than partial manager state. @@ -5694,10 +5695,8 @@ activeCameraCardEnabled: true })` may publish it through the retained > enabled-layer set and every runtime parameter it changes, then clears > unrelated active Data Layers. Mode switches, required-dependency disables, direct > disable, and teardown restore that pre-entry state before control leaves -> Context. Directly switching between Flights and Space Missions remains -> supported without losing the original snapshot. Contacts waits for the -> dependency releases it owns before restoring that snapshot, so the first -> Space Missions selection completes without a stale teardown superseding it. +> Context. Contacts waits for the dependency releases it owns before +> restoring that snapshot. > - **Space Mission horizon occlusion:** mission dots and hover reticles apply > their surface-anchor horizon state before Cesium draws or picks the frame, > while shared-host labels use the same hidden-globe horizon contract. Rear-side @@ -6419,9 +6418,9 @@ start where the label would round to 10.0 km, so a 9.96 km route displays as **Keys needed: none.** Directions works on a keyless boot, and the layer is off until the operator turns it on. -**Context behavior.** Directions is not a Context layer: neither Contacts nor -Space Missions reads it, depends on it, or lists it as a companion. It is -therefore one of the layers an exclusive Context mode switches off on entry +**Context behavior.** Directions is not a Context layer: Contacts does not +read it, depend on it, or list it as a companion. It is therefore one of the +layers the exclusive Contacts mode switches off on entry (`_clearLayersOutsideContextMode`) and restores on exit, like every other non-participating layer — the route and both endpoints are cleared with it, and placing them again is the way back. Cockpit does not touch the layer either, @@ -6747,8 +6746,8 @@ Required empty or unexercised checks fail acceptance. The passing final line is cannot claim full acceptance. **Lifecycle and proxy.** Contacts temporarily disables Transit and restores its -prior state on exit; Space Missions refuses enablement while isolating replay -data. Cockpit does not need Contacts and does not independently enable Transit. +prior state on exit; Space Missions, an ordinary layer, leaves Transit as it +is. Cockpit does not need Contacts and does not independently enable Transit. The proxy fetches registered URLs only, validates redirect origins, bounds responses and decoding, caches successful snapshots, and backs off after failed refreshes. A 304 confirms contact without appending history. Missing vehicles @@ -7328,14 +7327,14 @@ silently demoting every later lookup for the session. ### Context / Contacts coordinator (July 2026) - The internal Context coordinator is available in every visual style. Its dedicated right-side `CONTEXT` chooser exposes the neutral shell; the coordinator is not duplicated in Data Layers and does not enable a live-data dependency until a mode is selected. -- The expanded `CONTEXT` view offers mutually exclusive `CONTACTS` and `SPACE MISSIONS` modes. Selecting `CONTACTS` enables the context-owned Flights, Military Flights, AIS Vessels, and Mapped Installations dependencies only when they are not already user-enabled; selecting `SPACE MISSIONS` enables the recent-launch layer and its Satellite dependency. `CONTACTS` cycles the nearest supported contact of whatever type is selected. Satellites are deliberately excluded from those Awareness cohorts and keep their own tracking UX. Selecting the active mode again returns to the neutral chooser and releases only mode-owned dependencies. +- The expanded `CONTEXT` view offers the `CONTACTS` mode. Selecting `CONTACTS` enables the context-owned Flights, Military Flights, AIS Vessels, and Mapped Installations dependencies only when they are not already user-enabled. Space Missions is not a Context mode: it is the ordinary recent-launch layer with its own panel, and it runs beside Contacts. `CONTACTS` cycles the nearest supported contact of whatever type is selected. Satellites are deliberately excluded from those Awareness cohorts and keep their own tracking UX. Selecting the active mode again returns to the neutral chooser and releases only mode-owned dependencies. - If a civilian or military aircraft is already tracked when `CONTACTS` becomes operational, that source-owned track is adopted as the Context subject before nearest-contact autofocus. Context rechecks the tracker after its dependencies settle, so a newer selection wins, while an explicit clear during activation prevents fallback from silently selecting a replacement. Cockpit entry remains unavailable until that Context transaction has settled, so its camera takeover cannot clear Cesium tracking before adoption. Adoption does not recreate tracking or transfer camera ownership; it initializes the normal 250 km ring, history, proximity results, and Cockpit Previous/Next state for the original aircraft. With no tracked aircraft, an AIS vessel already selected (the vessel layer's `getSelectedInfo()`) becomes the subject, at activation and again when a deferred dependency settles, exactly as a vessel selected while `CONTACTS` is on; no nearest flight is picked and the camera is not moved. - `SEARCH NEARBY SITES` retains the bounded OSM results and makes one user-initiated, view-biased Google Maps Places text search for “military installation.” Google results are source-stamped, deduplicated against OSM by rounded location/name, and remain mapped context rather than operational claims. If Places is unavailable or the API is not enabled for the supplied key, OSM context remains available. A view across the antimeridian is searched around its own centre, with a radius from its real width. - The Context header holds only its title and collapse control. It no longer carries a Radio shortcut or a compact Radio player: Radio is the `RADIO` section inside the panel, with its own disclosure and the single `ENABLE` power control. Cockpit keeps its own compact Radio utility. - Context is set for reading in every theme: mode, standby and action labels are 10 px, and the panel draws no glow halo. The two modes form one segmented control, the standby guidance is plain left-aligned text rather than a dashed placeholder, and the panel's section titles share the side panels' dock-label colour. - The expanded desktop header omits the redundant `ON` label; the active mode button carries state. Expanded Contact results also omit the duplicate `GLOBAL CONTEXT` / `CONTEXT ONLY` status row and begin with the selected subject and its 250 km scope. Global Context does not fabricate a selected-entity model preview: the provisional hand-authored aircraft wireframe was removed because it was not geometry extracted from the selected entity's actual asset. - Dependency ownership is reversible: disabling Global Context releases only dependencies it enabled, while user-enabled layers remain on. This also removes the Military-layer suppression handoff when Global Context owned Military, allowing an already-enabled civilian Flights layer to resume its normal mixed rendering. If OpenSky is unavailable and has no last-good cache, Flights requests a capped 250 nm adsb.lol point snapshot around the current view anchor and labels that provenance explicitly; it never relabels military-feed rows as civilian data. If both inputs fail, Flights remains `UNKNOWN`. -- Space Missions is replay-isolated: Rocket Launches and Satellites are the only Data Layers permitted while the mode is active. Direct UI and voice entry capture the same pre-entry snapshot; internal dependency and restoration enables do not create a user-owned Context session. Entry waits for incompatible layers to shut down, direct incompatible enables are blocked before lifecycle work, and the entry gate remains active through the complete Rocket Launches enable. That enable includes the first mission-index load: an HTTP error, timeout, network failure or malformed payload before any index has loaded fails the enable, so Context rolls back to the pre-entry layers instead of committing an empty, isolating mode; the camera returns to its pre-entry view unless navigation took it, and a toast says the mission index could not load. A valid empty index still enters, and a refresh failure after an index loaded keeps its records and the mode. Exiting cancels the layer's own camera flights but never one navigation started. A newer same-target ON request takes ownership of the pending entry without releasing its isolation snapshot, including when it arrives while the prior request is awaiting the adoption guard. A caller abort, resource cancellation, newer OFF, or layer teardown waits for exact manager settlement and restores that snapshot without resurrecting Rocket Launches. If an abort lands after only part of a restore settles, Context completes the same exact target without the stale caller signal and then replays newer explicit layer intent. Dedicated Voice Context cancellation reports a stable cancelled result plus the current Context state; generic layer visibility additionally exposes manager phase, reason, successor, and lifecycle details. Once an exact voice visibility intent commits, a newer voice turn cannot relabel it as cancelled while Context settlement completes; pre-commit aborts remain cancellable and final lifecycle mismatches remain failures. Clear Selected Layers reserves its complete captured OFF set before sequential teardown; a newer absolute request of any origin supersedes only its layer reservation and remains authoritative. A rejected layer teardown retains the truthful enabled state, rolls already-stopped siblings back to the captured pre-entry set, and aborts replay; rapid exit/re-entry serializes the full Satellite enabled-state and parameter restore before a new snapshot is taken. Contacts remains additive and restores user-enabled layers normally. +- Space Missions is an ordinary layer, not a Context mode. It neither isolates the globe nor refuses other layers, opens no Context session, and runs beside Contacts. Turning it on enables its Satellites dependency in the temporary dense/hidden mode and turning it off restores Satellites' exact prior visibility and parameters; an explicit Satellites action taken while it runs (by the person or by voice) is kept through that restore, and such a Satellites OFF asked for after the newest Space Missions ON ends Space Missions (request order, not settle order, decides; `src/layers/launches/satelliteIntents.js`). A scene, story, preset or other programmatic Satellites change does neither (owner decision). Contacts leaves Satellites as it is. The first mission-index load is part of the enable: an HTTP error, timeout, network failure or malformed payload before any index has loaded fails the enable, the camera returns to its pre-entry view unless navigation took it, and a toast says the mission index could not load. A valid empty index still enables, and a refresh failure after an index loaded keeps its records. Turning the layer on by hand, choosing it at first run, asking for it by voice (`set_context_mode` still accepts `space-missions` and switches the layer), or picking a mission on the globe opens the Space Missions panel; on desktop, opening it closes Context and the other right-rail panels, and opening Context closes it. Voice `set_panel_open` refuses to open the panel while the layer is off and says to turn Space Missions on first. - Enabled Data Layer controls report normalized feed health on the button (`LOADING`, `DEGRADED`, `STALE`, `FALLBACK`, or `UNAVAILABLE`) while the metadata line retains the source and reason. A partial CelesTrak group failure keeps the usable catalog and reports `DEGRADED`; a total outage keeps last-good catalog data visible but reports `UNAVAILABLE`. - On activation it focuses the nearest currently observed aircraft across the civilian and military feeds, with military winning an exact distance tie; if none are available, it focuses an observed AIS vessel. The aircraft search is deliberately uncapped and one refresh-tick retry handles initially empty feeds. This is an attention-priority navigation shortcut, not a high-risk, affiliation, or threat classification. - A selected aircraft, AIS vessel, or mapped installation gets a 250 km **context window** with nearby cohort counts, nearest examples, source labels, and stale/unavailable reasons. It emits `NEARBY` or `UNKNOWN`; no detection, engagement, affiliation, or sensor-activity conclusion is calculated. @@ -7492,8 +7491,8 @@ silently demoting every later lookup for the session. protected-card path. Disable tears the tier down completely. Coverage/viewshed semantics unchanged. - **Satellites**: every point moves every frame. Each satellite's SGP4 sample (position, velocity, gravity and its rate of change; `src/layers/satellites/motion.js`) is reckoned forward or back to the world time and turned into the Earth-fixed frame, so points glide at any play speed instead of stepping once a second. Core satellites take a fresh sample every second, or as soon as the world time is 30 s from their sample (fast play, a seek), which keeps every point within about 10 m of SGP4; Starlink extras are sampled round-robin, more per frame the faster time plays, and a point more than two minutes from its sample waits for the next one. Hidden points are not moved until shown. 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. Both the loaded-catalog and active-TLE lookups read the launch year from the TLE international designator through one parser (`src/sources/tle.js`); a blank or malformed designator is an unknown year, which skips the year check rather than rejecting the 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. +- **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 reveals its own right-rail button and roster and enables the required satellite layer; it does not touch Context. 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 Data Layers hides its rail button and panel and 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. An explicit user or voice Satellites OFF requested after Space Missions ON exits Space Missions, including after returning from Stories; scene, story, preset and other programmatic Satellites changes do not. The controls under the Space Missions row cycle through available launches. Selecting a mission isolates its launch-to-orbit transfer and dashed satellite orbit, fills the Space Missions panel with details, navigation, and replay controls, 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. Clicking the launch name on the globe selects and focuses the same mission as its dot. 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. Both the loaded-catalog and active-TLE lookups read the launch year from the TLE international designator through one parser (`src/sources/tle.js`); a blank or malformed designator is an unknown year, which skips the year check rather than rejecting the 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 Space Missions 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. A selected mission renders its orbit as four repeating tactical sectors, each containing one prominent cyan dot followed by one hundred thin translucent dashes. The bright dots act as orbit anchors while the subdued dash field remains depth-tested against the globe and is shown only for the selected mission. Close selected-pad views add one static 500 m-radius cyan launch-zone ring with a low-opacity translucent fill over the sampled photoreal launch-site surface. The single scene primitive is created only for the visible selected site and is otherwise dormant. It appears during Focus, sufficiently close manual zoom, and the replay countdown, but is suppressed above 120 km camera altitude, beyond 180 km direct camera-to-pad range, for unselected missions, and whenever Space Missions is inactive. Focus establishes a launch-site-centered camera transform once; subsequent manual heading and pitch changes remain centered on that site without an automated per-frame correction. Surface mission markers and labels use an additional conservative globe-limb margin before the exact ellipsoid occluder boundary, preventing near-horizon visibility from alternating between frames. diff --git a/docs/SHARE-LINK-FORMAT.md b/docs/SHARE-LINK-FORMAT.md index 4ebbbc343a..888c3a91e3 100644 --- a/docs/SHARE-LINK-FORMAT.md +++ b/docs/SHARE-LINK-FORMAT.md @@ -282,6 +282,7 @@ reserved: a decoder ignores that entry, as for collapsed 0. | 8 | `global-context-panel` | `g` | collapsed | | 9 | `pp-toggles` | `p` | collapsed | | 10 | `param-slider-panel` | `m` | expanded | +| 11 | `space-missions-panel` | `n` | collapsed | ### Style parameters (field 27) diff --git a/scripts/format-scope.json b/scripts/format-scope.json index 630a9bc51f..78f3edbf24 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -297,6 +297,9 @@ "src/ui/contextControls.js", "src/ui/contextControls.test.mjs", "src/ui/contextLayerChanges.js", + "src/ui/spaceMissionsControls.js", + "src/ui/spaceMissionsControls.test.mjs", + "src/ui/stores/spaceMissions.js", "src/ui/contextPresentation.js", "src/ui/contextSession.js", "src/ui/contextSubscriptions.js", @@ -521,6 +524,10 @@ "src/layers/launches/source.test.mjs", "src/layers/launches/ingestion.test.mjs", "src/layers/launches/failedEntry.test.mjs", + "src/layers/launches/labelClick.test.mjs", + "src/layers/launches/missionCycler.test.mjs", + "src/layers/launches/satelliteIntents.js", + "src/layers/launches/satelliteIntents.test.mjs", "src/layers/installations/lifecycle.js", "src/layers/installations/viewport.js", "src/layers/installations/controls.js", diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index e837a81d1a..8910282ebc 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -130,6 +130,7 @@ "src/ui/radioTunerModel.js", "src/ui/views/panels/MissionDetail.vue", "src/ui/views/panels/MissionRoster.vue", + "src/ui/views/panels/SpaceMissionsPanel.vue", "src/ui/views/panels/AwarenessPanel.vue", "src/ui/views/panels/AwarenessNames.vue", "src/ui/views/DisplayControlsView.vue", @@ -163,6 +164,7 @@ "src/ui/stores/cctv.js", "src/ui/stores/radio.js", "src/ui/stores/context.js", + "src/ui/stores/spaceMissions.js", "src/ui/stores/cockpit.js", "src/ui/stores/locale.js", "src/ui/stores/providerSettings.js", @@ -1449,6 +1451,7 @@ "src/ui/contextSession.js", "src/ui/contextSubscriptions.js", "src/ui/contextTransactions.js", + "src/ui/spaceMissionsControls.js", "src/ui/displayControls.js", "src/ui/effects.js", "src/ui/frameRateMonitor.js", @@ -1577,6 +1580,7 @@ "src/ui/stores/cctv.js", "src/ui/stores/radio.js", "src/ui/stores/context.js", + "src/ui/stores/spaceMissions.js", "src/ui/stores/cockpit.js", "src/ui/stores/locale.js", "src/ui/stores/providerSettings.js", @@ -2875,6 +2879,7 @@ "src/data/entityRecords.js", "src/render/cesium/follow.js", "src/layers/launches/ingestion.js", + "src/layers/launches/satelliteIntents.js", "src/layers/launches/launchPad.js", "src/layers/launches/lifecycle.js", "src/layers/launches/model.js", @@ -4534,6 +4539,7 @@ "src/layers/launches/controls.js", "src/layers/launches/index.js", "src/layers/launches/ingestion.js", + "src/layers/launches/satelliteIntents.js", "src/layers/launches/launchPad.js", "src/layers/launches/lifecycle.js", "src/layers/launches/model.js", @@ -4765,6 +4771,7 @@ "src/ui/contextSession.js", "src/ui/contextSubscriptions.js", "src/ui/contextTransactions.js", + "src/ui/spaceMissionsControls.js", "src/ui/displayControls.js", "src/ui/effects.js", "src/ui/frameRateMonitor.js", @@ -5327,6 +5334,7 @@ "src/ui/stores/cctv.js", "src/ui/stores/radio.js", "src/ui/stores/context.js", + "src/ui/stores/spaceMissions.js", "src/ui/stores/cockpit.js", "src/ui/stores/locale.js", "src/ui/stores/providerSettings.js", @@ -5815,6 +5823,7 @@ "src/layers/launches/controls.js", "src/layers/launches/index.js", "src/layers/launches/ingestion.js", + "src/layers/launches/satelliteIntents.js", "src/layers/launches/launchPad.js", "src/layers/launches/lifecycle.js", "src/layers/launches/model.js", diff --git a/scripts/qa-cockpit-utility.mjs b/scripts/qa-cockpit-utility.mjs index 21d20a06f1..3ca0e81773 100644 --- a/scripts/qa-cockpit-utility.mjs +++ b/scripts/qa-cockpit-utility.mjs @@ -193,41 +193,74 @@ try { }); const contactMissionHandoff = await page.evaluate(async () => { const { styleManager, dataManager } = window.__godsEyeView; + // Launch Library is not contacted: the layer's own work is stubbed so the + // check covers only how Space Missions sits beside Context. + const stubMissions = (rocketEntry) => { + const original = { + initialized: rocketEntry.initialized, + lifecycleState: rocketEntry.lifecycleState, + init: rocketEntry.module.init, + enable: rocketEntry.module.enable, + update: rocketEntry.module.update, + disable: rocketEntry.module.disable, + }; + rocketEntry.initialized = true; + rocketEntry.module.init = async () => true; + rocketEntry.module.enable = async () => true; + rocketEntry.module.update = async () => true; + rocketEntry.module.disable = async () => true; + return () => { + rocketEntry.initialized = original.initialized; + rocketEntry.lifecycleState = original.lifecycleState; + rocketEntry.module.init = original.init; + rocketEntry.module.enable = original.enable; + rocketEntry.module.update = original.update; + rocketEntry.module.disable = original.disable; + }; + }; const originalShowToast = styleManager._showToast; const toasts = []; styleManager._showToast = (message) => { toasts.push(String(message)); }; + const restoreMissions = stubMissions(dataManager.layers.get('rocket-launches')); try { if (styleManager._contextControls._contextMode) await styleManager._contextControls._selectContextMode(null); const contactsResult = await styleManager._contextControls._selectContextMode('flights'); - const missionResult = await styleManager._contextControls._selectContextMode('space-missions'); - const switched = { + const missionResult = await dataManager.setEnabled('rocket-launches', true, { origin: 'user' }); + await styleManager._waitForContextLayerSettlement(); + const together = { contactsResult, missionResult, mode: styleManager._contextControls._contextMode, missionsEnabled: dataManager.isEnabled('rocket-launches'), toasts: [...toasts], }; + const missionOff = await dataManager.setEnabled('rocket-launches', false, { origin: 'user' }); + await styleManager._waitForContextLayerSettlement(); + const modeAfterMissions = styleManager._contextControls._contextMode; const exitResult = await styleManager._contextControls._selectContextMode(null); return { - ...switched, + ...together, + missionOff, + modeAfterMissions, exitResult, modeAfterExit: styleManager._contextControls._contextMode, - missionsOffAfterExit: !dataManager.isEffectivelyEnabled('rocket-launches'), }; } finally { + restoreMissions(); styleManager._showToast = originalShowToast; } }); check( - 'Contacts hands off to Space Missions on the first request without a failure toast', + 'Space Missions runs beside Contacts, and switching it off leaves Contacts on', contactMissionHandoff.contactsResult === true && contactMissionHandoff.missionResult === true - && contactMissionHandoff.mode === 'space-missions' + && contactMissionHandoff.mode === 'flights' && contactMissionHandoff.missionsEnabled && contactMissionHandoff.toasts?.length === 0 + && contactMissionHandoff.missionOff === true + && contactMissionHandoff.modeAfterMissions === 'flights' && contactMissionHandoff.exitResult === true - && contactMissionHandoff.modeAfterExit === null - && contactMissionHandoff.missionsOffAfterExit, + && contactMissionHandoff.modeAfterExit === null, JSON.stringify(contactMissionHandoff), ); const cancelledMissionEntry = await page.evaluate(async () => { @@ -330,7 +363,7 @@ try { } }); check( - 'cancelled direct Space Missions entry restores its exact isolated sibling state', + 'a cancelled Space Missions start leaves its sibling layer on and opens no Context session', cancelledMissionEntry.exercised && cancelledMissionEntry.transitionResult === false && !cancelledMissionEntry.timedOut @@ -341,214 +374,45 @@ try { JSON.stringify(cancelledMissionEntry), ); check( - 'successful Space Missions cancellation rollback stays silent', + 'a cancelled Space Missions start stays silent', cancelledMissionEntry.exercised && cancelledMissionEntry.toasts?.length === 0, JSON.stringify(cancelledMissionEntry.toasts || []), ); - const replacementMissionEntry = await page.evaluate(async () => { - const styleManager = window.__godsEyeView.styleManager; - const dataManager = window.__godsEyeView.dataManager; - const rocketEntry = dataManager.layers.get('rocket-launches'); - if (!rocketEntry || dataManager.isEffectivelyEnabled('rocket-launches')) { - return { exercised: false, reason: 'Space Missions was not in a clean OFF state' }; - } - const siblingId = 'qa-cockpit-replacement-sibling'; - window.__gevQaRegisterLayer(dataManager, { - id: siblingId, - name: 'QA replacement sibling', - icon: 'science', - source: 'QA', - updateInterval: -1, - async init() { return true; }, - async enable() { return true; }, - async update() { return true; }, - async disable() { return true; }, - async destroy() {}, - getStats() { return { count: 1, status: 'live' }; }, - }); - await dataManager.setEnabled(siblingId, true, { origin: 'programmatic' }); - const original = { - siblingInitialized: dataManager.layers.get(siblingId)?.initialized, - initialized: rocketEntry.initialized, - lifecycleState: rocketEntry.lifecycleState, - init: rocketEntry.module.init, - enable: rocketEntry.module.enable, - update: rocketEntry.module.update, - disable: rocketEntry.module.disable, - showToast: styleManager._showToast, - }; - let firstUpdate = true; - let releaseUpdate; - let markUpdateStarted; - const updateStarted = new Promise((resolve) => { markUpdateStarted = resolve; }); - const updateGate = new Promise((resolve) => { releaseUpdate = resolve; }); - const toasts = []; - rocketEntry.initialized = true; - rocketEntry.module.enable = async () => true; - rocketEntry.module.update = async () => { - if (!firstUpdate) return true; - firstUpdate = false; - markUpdateStarted(); - await updateGate; - return true; - }; - rocketEntry.module.disable = async () => true; - styleManager._showToast = (message) => { toasts.push(String(message)); }; - try { - const entry = styleManager._contextControls._selectContextMode('space-missions'); - await updateStarted; - const replacement = dataManager.setEnabled('rocket-launches', true, { origin: 'programmatic' }); - releaseUpdate(); - const [entryResult, replacementResult] = await Promise.all([entry, replacement]); - const committed = { - entryResult, - replacementResult, - mode: styleManager._contextControls._contextMode, - entering: styleManager._contextControls._contextModeEntering, - snapshotRetained: Boolean(styleManager._contextControls._contextSessionSnapshot), - siblingIsolated: !dataManager.isEffectivelyEnabled(siblingId), - missionEnabled: dataManager.isEnabled('rocket-launches'), - missionEffective: dataManager.isEffectivelyEnabled('rocket-launches'), - toasts: [...toasts], - }; - const exitResult = await styleManager._contextControls._selectContextMode(null); - return { - exercised: true, - ...committed, - exitResult, - siblingRestored: dataManager.isEnabled(siblingId), - missionRestoredOff: !dataManager.isEffectivelyEnabled('rocket-launches'), - }; - } finally { - styleManager._showToast = original.showToast; - rocketEntry.module.init = original.init; - rocketEntry.module.enable = original.enable; - rocketEntry.module.update = original.update; - rocketEntry.module.disable = original.disable; - rocketEntry.initialized = original.initialized; - rocketEntry.lifecycleState = original.lifecycleState; - await dataManager.setEnabled(siblingId, false, { origin: 'programmatic' }); - await window.__gevQaUnregisterLayer(dataManager, siblingId); - } - }); - check( - 'right-rail Space Missions adopts a newer authoritative ON without stale restoration', - replacementMissionEntry.exercised - && replacementMissionEntry.entryResult === true - && replacementMissionEntry.replacementResult === true - && replacementMissionEntry.mode === 'space-missions' - && replacementMissionEntry.entering === null - && replacementMissionEntry.snapshotRetained - && replacementMissionEntry.siblingIsolated - && replacementMissionEntry.missionEnabled - && replacementMissionEntry.missionEffective - && replacementMissionEntry.toasts?.length === 0 - && replacementMissionEntry.exitResult === true - && replacementMissionEntry.siblingRestored - && replacementMissionEntry.missionRestoredOff, - JSON.stringify(replacementMissionEntry), - ); - const supersededMissionEntry = await page.evaluate(async () => { - const styleManager = window.__godsEyeView.styleManager; - const dataManager = window.__godsEyeView.dataManager; - const rocketEntry = dataManager.layers.get('rocket-launches'); - if (!rocketEntry || dataManager.isEffectivelyEnabled('rocket-launches')) { - return { exercised: false, reason: 'Space Missions was not in a clean OFF state' }; - } - const siblingId = 'qa-cockpit-superseded-sibling'; - window.__gevQaRegisterLayer(dataManager, { - id: siblingId, - name: 'QA superseded sibling', - icon: 'science', - source: 'QA', - updateInterval: -1, - async init() { return true; }, - async enable() { return true; }, - async update() { return true; }, - async disable() { return true; }, - async destroy() {}, - getStats() { return { count: 1, status: 'live' }; }, - }); - await dataManager.setEnabled(siblingId, true, { origin: 'programmatic' }); - const original = { - initialized: rocketEntry.initialized, - lifecycleState: rocketEntry.lifecycleState, - init: rocketEntry.module.init, - enable: rocketEntry.module.enable, - update: rocketEntry.module.update, - disable: rocketEntry.module.disable, - showToast: styleManager._showToast, - }; - let releaseUpdate; - let markUpdateStarted; - const updateStarted = new Promise((resolve) => { markUpdateStarted = resolve; }); - const updateGate = new Promise((resolve) => { releaseUpdate = resolve; }); - const toasts = []; - rocketEntry.initialized = true; - rocketEntry.module.enable = async () => true; - rocketEntry.module.update = async () => { - markUpdateStarted(); - await updateGate; - return true; - }; - rocketEntry.module.disable = async () => true; - styleManager._showToast = (message) => { toasts.push(String(message)); }; - try { - const entry = styleManager._runUserFacingContextAction( - (notificationToken) => styleManager._contextControls._selectContextMode( - 'space-missions', - { notificationToken }, - ), - 'Space Missions could not complete the requested transition; try again', - ); - await updateStarted; - const supersedingOff = dataManager.setEnabled('rocket-launches', false, { - origin: 'programmatic', - }); - releaseUpdate(); - const [entryResult, offResult] = await Promise.all([entry, supersedingOff]); - return { - exercised: true, - entryResult, - offResult, - mode: styleManager._contextControls._contextMode, - entering: styleManager._contextControls._contextModeEntering, - snapshotRetained: Boolean(styleManager._contextControls._contextSessionSnapshot), - siblingRestored: dataManager.isEnabled(siblingId), - missionEffective: dataManager.isEffectivelyEnabled('rocket-launches'), - toasts, - }; - } finally { - styleManager._showToast = original.showToast; - rocketEntry.module.init = original.init; - rocketEntry.module.enable = original.enable; - rocketEntry.module.update = original.update; - rocketEntry.module.disable = original.disable; - rocketEntry.initialized = original.initialized; - rocketEntry.lifecycleState = original.lifecycleState; - await dataManager.setEnabled(siblingId, false, { origin: 'programmatic' }); - await window.__gevQaUnregisterLayer(dataManager, siblingId); - } - }); - check( - 'right-rail Space Missions superseded by OFF restores exactly without a failure toast', - supersededMissionEntry.exercised - && supersededMissionEntry.entryResult === null - && supersededMissionEntry.mode === null - && supersededMissionEntry.entering === null - && !supersededMissionEntry.snapshotRetained - && supersededMissionEntry.siblingRestored - && !supersededMissionEntry.missionEffective - && supersededMissionEntry.toasts?.length === 0, - JSON.stringify(supersededMissionEntry), - ); - const voiceMissionEntry = await page.evaluate(async () => { + const ordinaryMissionLayer = await page.evaluate(async () => { const { dataManager, styleManager } = window.__godsEyeView; - const siblingId = '__qa_voice_context_sibling__'; const rocketEntry = dataManager.layers.get('rocket-launches'); + if (!rocketEntry || dataManager.isEffectivelyEnabled('rocket-launches')) { + return { exercised: false, reason: 'Space Missions was not in a clean OFF state' }; + } + // Launch Library is not contacted: the layer's own work is stubbed so the + // check covers only how Space Missions sits beside Context. + const stubMissions = (rocketEntry) => { + const original = { + initialized: rocketEntry.initialized, + lifecycleState: rocketEntry.lifecycleState, + init: rocketEntry.module.init, + enable: rocketEntry.module.enable, + update: rocketEntry.module.update, + disable: rocketEntry.module.disable, + }; + rocketEntry.initialized = true; + rocketEntry.module.init = async () => true; + rocketEntry.module.enable = async () => true; + rocketEntry.module.update = async () => true; + rocketEntry.module.disable = async () => true; + return () => { + rocketEntry.initialized = original.initialized; + rocketEntry.lifecycleState = original.lifecycleState; + rocketEntry.module.init = original.init; + rocketEntry.module.enable = original.enable; + rocketEntry.module.update = original.update; + rocketEntry.module.disable = original.disable; + }; + }; + const siblingId = '__qa_space_missions_sibling__'; window.__gevQaRegisterLayer(dataManager, { id: siblingId, - name: 'QA voice Context sibling', + name: 'QA Space Missions sibling', icon: 'science', source: 'QA', updateInterval: -1, @@ -559,94 +423,48 @@ try { async destroy() {}, getStats() { return { count: 1, status: 'live' }; }, }); - const original = { - initialized: rocketEntry.initialized, - lifecycleState: rocketEntry.lifecycleState, - init: rocketEntry.module.init, - enable: rocketEntry.module.enable, - update: rocketEntry.module.update, - disable: rocketEntry.module.disable, - }; - const siblingLayerEntry = dataManager.layers.get(siblingId); - siblingLayerEntry.initialized = true; await dataManager.setEnabled(siblingId, true, { origin: 'programmatic' }); - rocketEntry.initialized = true; - rocketEntry.module.init = async () => true; - rocketEntry.module.enable = async () => true; - rocketEntry.module.update = async () => true; - rocketEntry.module.disable = async () => true; + const restoreMissions = stubMissions(rocketEntry); try { - const voiceOn = await dataManager.setEnabled('rocket-launches', true, { origin: 'voice' }); - await new Promise((resolve) => setTimeout(resolve, 80)); - const voiceState = { - voiceOn, - mode: styleManager._contextControls._contextMode, - entering: styleManager._contextControls._contextModeEntering, - snapshotRetained: Boolean(styleManager._contextControls._contextSessionSnapshot), - siblingIsolated: !dataManager.isEffectivelyEnabled(siblingId), - }; - const snapshotBeforeOff = [...(styleManager._contextControls._contextSessionSnapshot?.enabledLayerIds || [])]; - const voiceOff = await dataManager.setEnabled('rocket-launches', false, { origin: 'voice' }); - const reactionCountAfterOff = styleManager._contextControls._contextLayerReactionPromises.size; - await styleManager._waitForContextLayerSettlement(); - const restoredSiblingEntry = dataManager.layers.get(siblingId); - const voiceExit = { - voiceOff, - snapshotBeforeOff, - reactionCountAfterOff, - mode: styleManager._contextControls._contextMode, - entering: styleManager._contextControls._contextModeEntering, - snapshotRetained: Boolean(styleManager._contextControls._contextSessionSnapshot), - siblingRestored: dataManager.isEffectivelyEnabled(siblingId), - siblingEnabled: restoredSiblingEntry?.enabled, - siblingLifecycle: restoredSiblingEntry?.lifecycleState, - restoreActive: Boolean(styleManager._contextControls._contextRestoreState), - }; - - await dataManager.setEnabled('rocket-launches', true, { origin: 'programmatic' }); - await new Promise((resolve) => setTimeout(resolve, 40)); - const internalState = { - mode: styleManager._contextControls._contextMode, - entering: styleManager._contextControls._contextModeEntering, - snapshotRetained: Boolean(styleManager._contextControls._contextSessionSnapshot), - missionEnabled: dataManager.isEffectivelyEnabled('rocket-launches'), - }; - await dataManager.setEnabled('rocket-launches', false, { origin: 'programmatic' }); - return { exercised: true, voiceState, voiceExit, internalState }; + const results = {}; + for (const origin of ['user', 'voice', 'programmatic']) { + const on = await dataManager.setEnabled('rocket-launches', true, { origin }); + await styleManager._waitForContextLayerSettlement(); + const during = { + on, + mode: styleManager._contextControls._contextMode, + snapshot: Boolean(styleManager._contextControls._contextSessionSnapshot), + siblingOn: dataManager.isEffectivelyEnabled(siblingId), + }; + const off = await dataManager.setEnabled('rocket-launches', false, { origin }); + await styleManager._waitForContextLayerSettlement(); + results[origin] = { + ...during, + off, + siblingOnAfter: dataManager.isEffectivelyEnabled(siblingId), + snapshotAfter: Boolean(styleManager._contextControls._contextSessionSnapshot), + }; + } + return { exercised: true, results }; } finally { - rocketEntry.module.init = original.init; - rocketEntry.module.enable = original.enable; - rocketEntry.module.update = original.update; - rocketEntry.module.disable = original.disable; - rocketEntry.initialized = original.initialized; - rocketEntry.lifecycleState = original.lifecycleState; + restoreMissions(); await dataManager.setEnabled(siblingId, false, { origin: 'programmatic' }); - siblingLayerEntry.initialized = original.siblingInitialized; await window.__gevQaUnregisterLayer(dataManager, siblingId); } }); check( - 'voice Space Missions uses the same Context snapshot and exact-restore transaction as UI entry', - voiceMissionEntry.exercised - && voiceMissionEntry.voiceState?.voiceOn - && voiceMissionEntry.voiceState.mode === 'space-missions' - && voiceMissionEntry.voiceState.entering === null - && voiceMissionEntry.voiceState.snapshotRetained - && voiceMissionEntry.voiceState.siblingIsolated - && voiceMissionEntry.voiceExit?.voiceOff - && voiceMissionEntry.voiceExit.mode === null - && voiceMissionEntry.voiceExit.entering === null - && !voiceMissionEntry.voiceExit.snapshotRetained - && voiceMissionEntry.voiceExit.siblingRestored, - JSON.stringify(voiceMissionEntry), - ); - check( - 'internal programmatic Space Missions activation does not create a user Context session', - voiceMissionEntry.internalState?.missionEnabled - && voiceMissionEntry.internalState.mode === null - && voiceMissionEntry.internalState.entering === null - && !voiceMissionEntry.internalState.snapshotRetained, - JSON.stringify(voiceMissionEntry), + 'Space Missions is an ordinary layer: no Context session, no isolation, from any origin', + ordinaryMissionLayer.exercised + && Object.values(ordinaryMissionLayer.results || {}).length === 3 + && Object.values(ordinaryMissionLayer.results).every((entry) => + entry.on === true + && entry.mode === null + && !entry.snapshot + && entry.siblingOn + && entry.off === true + && entry.siblingOnAfter + && !entry.snapshotAfter), + JSON.stringify(ordinaryMissionLayer), ); await page.evaluate(() => window.__godsEyeView.dataManager.setEnabled( 'flights', diff --git a/scripts/qa-firstrun-mutations.mjs b/scripts/qa-firstrun-mutations.mjs index b15befc87e..91e303885a 100644 --- a/scripts/qa-firstrun-mutations.mjs +++ b/scripts/qa-firstrun-mutations.mjs @@ -307,8 +307,8 @@ const MUTATIONS = [ { defect: 'a cancelled globe flight fails the whole mission', file: 'module', - from: ' .catch(() => null);', - to: ' .catch(() => { throw new Error("flight failed"); });', + from: ' .catch(() => null)\n : null;', + to: ' .catch(() => { throw new Error("flight failed"); })\n : null;', }, { defect: 'Explore manually quietly runs a mission instead of nothing', diff --git a/scripts/qa-firstrun.mjs b/scripts/qa-firstrun.mjs index 021d1b58dc..fe461f6ba8 100644 --- a/scripts/qa-firstrun.mjs +++ b/scripts/qa-firstrun.mjs @@ -662,8 +662,18 @@ async function main() { await open(page, { query: "?welcome=1", errorSink: consoleErrors }); await pick(page, 'space-missions'); state = await appState(page); - record('SPACE MISSIONS activates its context mode', state.contextMode === 'space-missions', - `contextMode=${state.contextMode}`); + const missions = await page.evaluate(() => { + const panel = document.getElementById('space-missions-panel'); + return { + layerOn: window.__godsEyeView.dataManager.isEffectivelyEnabled('rocket-launches'), + panelOpen: !!panel && !panel.hidden && !panel.classList.contains('collapsed'), + }; + }); + record('SPACE MISSIONS switches its layer on without a Context mode', + missions.layerOn && state.contextMode == null, + `layerOn=${missions.layerOn} contextMode=${state.contextMode}`); + record('SPACE MISSIONS opens its own panel', missions.panelOpen, + `panelOpen=${missions.panelOpen}`); shots.push(await shoot(page, 'mission-space-missions')); }); diff --git a/scripts/qa-radio.mjs b/scripts/qa-radio.mjs index bec07d25c5..5093b81ff1 100644 --- a/scripts/qa-radio.mjs +++ b/scripts/qa-radio.mjs @@ -845,7 +845,7 @@ async function main() { params: {}, }; let failureUsed = false; - const entryLayerId = mode === 'flights' ? 'military-awareness' : 'rocket-launches'; + const entryLayerId = 'military-awareness'; dataManager.setEnabled = async (layerId, shouldEnable) => { const failsIsolation = phase === 'isolation' && layerId === 'local-datacenters' && !shouldEnable; const failsActivation = phase === 'activation' && layerId === entryLayerId && shouldEnable; @@ -872,7 +872,6 @@ async function main() { priorLayerRestored: enabled.has('local-datacenters'), entryEnabled: enabled.has(entryLayerId), flightsButtonDisabled: document.getElementById('global-context-flights-btn').disabled, - missionsButtonDisabled: document.getElementById('global-context-missions-btn').disabled, message: document.getElementById('toast').textContent, }; }; @@ -893,7 +892,7 @@ async function main() { } }; const contextFailures = []; - for (const mode of ['flights', 'space-missions']) { + for (const mode of ['flights']) { for (const phase of ['isolation', 'activation']) { for (const outcome of ['false', 'reject']) { contextFailures.push(await runContextFailure(mode, phase, outcome)); @@ -902,7 +901,7 @@ async function main() { } const directEntryFailures = []; - for (const layerId of ['military-awareness', 'rocket-launches']) { + for (const layerId of ['military-awareness']) { for (const outcome of ['false', 'reject']) { enabled.clear(); enabled.add('local-datacenters'); @@ -971,7 +970,7 @@ async function main() { styleManager._showToast = originalShowToast; const directActivationFailures = []; - for (const layerId of ['military-awareness', 'rocket-launches']) { + for (const layerId of ['military-awareness']) { enabled.clear(); styleManager._contextControls._contextMode = null; styleManager._contextControls._contextSessionSnapshot = { @@ -1001,7 +1000,7 @@ async function main() { } const directActivationRollbackFailures = []; - for (const layerId of ['military-awareness', 'rocket-launches']) { + for (const layerId of ['military-awareness']) { enabled.clear(); styleManager._contextControls._contextMode = null; styleManager._contextControls._contextSessionSnapshot = { @@ -1211,7 +1210,7 @@ async function main() { check( 'user-facing chip, real Context entry rollback, and installation Search failures settle safely', userFacingFailures.semanticFalseMessage === 'Radio could not stop cleanly' - && userFacingFailures.contextFailures.length === 8 + && userFacingFailures.contextFailures.length === 4 && userFacingFailures.contextFailures.every((failure) => ( failure.result === false && failure.visibleMode === null @@ -1219,10 +1218,9 @@ async function main() { && failure.priorLayerRestored && !failure.entryEnabled && !failure.flightsButtonDisabled - && !failure.missionsButtonDisabled && failure.message.includes('QA transition failed') )) - && userFacingFailures.directEntryFailures.length === 4 + && userFacingFailures.directEntryFailures.length === 2 && userFacingFailures.directEntryFailures.every((failure) => ( failure.reason.includes('could not start') && failure.retryReason === null @@ -1233,14 +1231,14 @@ async function main() { && failure.priorLayerRestored && !failure.modeChanging )) - && userFacingFailures.directActivationFailures.length === 2 + && userFacingFailures.directActivationFailures.length === 1 && userFacingFailures.directActivationFailures.every((failure) => ( failure.mode === null && failure.snapshotCleared && failure.priorLayerRestored && failure.failedLayerDisabled )) - && userFacingFailures.directActivationRollbackFailures.length === 2 + && userFacingFailures.directActivationRollbackFailures.length === 1 && userFacingFailures.directActivationRollbackFailures.every((failure) => ( failure.toastMessages.length === 1 && failure.toastMessages[0] === `${failure.layerId} could not start cleanly` diff --git a/scripts/qa-transit.mjs b/scripts/qa-transit.mjs index c73a0cafc6..f9bef563e2 100644 --- a/scripts/qa-transit.mjs +++ b/scripts/qa-transit.mjs @@ -1980,16 +1980,19 @@ try { await wait(12_000); check('leaving Contacts restores Transit', await isOn()); - // SPACE MISSIONS - await page.evaluate(() => - window.__godsEyeView.dataManager.setEnabled('transit', false, { - origin: 'user', - }), - ); - await wait(2_000); - await page.click('#global-context-missions-btn'); + // SPACE MISSIONS: an ordinary layer. It neither refuses nor puts away + // Transit, so a Transit switched on while it runs stays on after it ends. + const setMissions = (enabled) => + page.evaluate( + (on) => + window.__godsEyeView.dataManager.setEnabled('rocket-launches', on, { + origin: 'user', + }), + enabled, + ); + await setMissions(true); await wait(20_000); - const blocked = await page.evaluate(async () => { + const beside = await page.evaluate(async () => { const settled = await window.__godsEyeView.dataManager.setEnabled( 'transit', true, @@ -2001,16 +2004,13 @@ try { }; }); check( - 'Space Missions refuses to enable Transit while it isolates replay data', - blocked.enabled === false, - JSON.stringify(blocked), + 'Transit can be switched on while Space Missions runs', + beside.settled !== false && beside.enabled === true, + JSON.stringify(beside), ); - await page.click('#global-context-missions-btn'); + await setMissions(false); await wait(12_000); - check( - 'leaving Space Missions leaves Transit off, as it was on entry', - (await isOn()) === false, - ); + check('switching Space Missions off leaves Transit on', await isOn()); check( 'no uncaught page errors', diff --git a/src/cockpitMarkup.test.mjs b/src/cockpitMarkup.test.mjs index c240f28e80..3a084af32f 100644 --- a/src/cockpitMarkup.test.mjs +++ b/src/cockpitMarkup.test.mjs @@ -680,6 +680,7 @@ test('fresh Cockpit entry temporarily collapses map panels and exit restores the 'scene-panel', 'pp-toggles', 'global-context-panel', + 'space-missions-panel', 'radio-panel', ]) { assert.match( @@ -1261,14 +1262,15 @@ test('Global Context uses its dedicated right rail without a duplicate Data Laye ); assert.match(html, /id="global-context-panel"/); assert.match(html, /id="global-context-flights-btn"/); - assert.match(html, /id="global-context-missions-btn"/); + assert.doesNotMatch(html, /id="global-context-missions-btn"/); + assert.match(html, /id="space-missions-panel"/); }); -test('Global Context standby describes both chooser modes', () => { +test('Global Context standby describes Contacts', () => { const match = html.match(/
/); assert.ok(match, 'Global Context standby is missing'); assert.match(match[0], /CONTACTS — nearest planes · vessels · sites/); - assert.match(match[0], /SPACE MISSIONS — launches & orbital assets/); + assert.doesNotMatch(match[0], /SPACE MISSIONS/); }); test('cockpit briefing cycle control keeps its state as the accessible name', () => { diff --git a/src/contextModePolicy.js b/src/contextModePolicy.js index ec6b1f32c7..d4c7e4c497 100644 --- a/src/contextModePolicy.js +++ b/src/contextModePolicy.js @@ -1,5 +1,3 @@ -import { msg } from './i18n/marker.js'; - const CONTEXT_DEPENDENCIES = Object.freeze({ flights: new Set([ 'military-awareness', @@ -8,15 +6,18 @@ const CONTEXT_DEPENDENCIES = Object.freeze({ 'ais-live-vessels', 'military-installations', ]), - 'space-missions': new Set(['rocket-launches', 'satellites']), }); const CONTEXT_COMPANIONS = new Set(['radio']); -/** The Space Missions refusal, with the blocked layer's name as {layer}. */ -export const SPACE_MISSIONS_LAYER_BLOCK_REASON = msg( - 'Space Missions isolates replay data. Exit the mode to enable {layer}.', -); -const [BLOCK_REASON_PREFIX, BLOCK_REASON_SUFFIX] = - SPACE_MISSIONS_LAYER_BLOCK_REASON.split('{layer}'); +/** + * Layers Context never touches: Space Missions and the Satellites layer it + * depends on. Contacts neither switches them off on entry nor restores them + * on exit, so they run beside it in either order and keep their own state + * (the mission controller owns the Satellites dependency). + */ +export const CONTEXT_INDEPENDENT_LAYER_IDS = Object.freeze([ + 'rocket-launches', + 'satellites', +]); /** Return whether an origin represents a direct user choice on this route. */ export function isExplicitUserIntentOrigin(origin, layerId = null) { return origin === 'user' || origin === 'voice'; @@ -27,7 +28,8 @@ export function recordContextRestoreExplicitChange({ restoreState, change }) { if ( !restoreState?.enabledLayerIds || change?.type !== 'visibility' || - !isExplicitUserIntentOrigin(change.origin, change.layerId) + !isExplicitUserIntentOrigin(change.origin, change.layerId) || + CONTEXT_INDEPENDENT_LAYER_IDS.includes(change.layerId) ) return false; if (!restoreState.explicitLayerStates) @@ -121,10 +123,7 @@ export async function settleUserFacingContextAction({ * one into `userAdded` makes exit restoration re-enable the mode layer the * user just turned off. */ -export const CONTEXT_ENTRY_LAYER_IDS = Object.freeze([ - 'military-awareness', - 'rocket-launches', -]); +export const CONTEXT_ENTRY_LAYER_IDS = Object.freeze(['military-awareness']); /** * Leave a Context transaction: publish the settled coordination flag, then @@ -193,7 +192,8 @@ export function shouldExitContextForLayerChange({ change?.type !== 'visibility' || !isExplicitUserIntentOrigin(change.origin, change.layerId) || change.layerId === 'military-awareness' || - CONTEXT_COMPANIONS.has(change.layerId) + CONTEXT_COMPANIONS.has(change.layerId) || + CONTEXT_INDEPENDENT_LAYER_IDS.includes(change.layerId) ) { return false; } @@ -215,6 +215,7 @@ export function contextAllowedLayerIds(contextMode) { return new Set([ ...(CONTEXT_DEPENDENCIES[contextMode] || ['military-awareness']), ...CONTEXT_COMPANIONS, + ...CONTEXT_INDEPENDENT_LAYER_IDS, ]); } @@ -235,21 +236,6 @@ export function shouldCaptureContextSession(change) { ); } -/** - * Return whether one explicit mission intent superseded an in-flight Clear All - * reservation and therefore needs deferred Context adoption. - */ -export function shouldDeferContextEntryDuringClear({ change, clearInFlight }) { - return Boolean( - clearInFlight && - change?.type === 'visibility-requested' && - change.layerId === 'rocket-launches' && - change.enabled === true && - isExplicitUserIntentOrigin(change.origin, change.layerId) && - Number.isInteger(change.intentEpoch), - ); -} - /** * Bookkeep a user-owned layer change against the active Context session so * exit restoration can honor layers the user added mid-session. Two rules @@ -273,7 +259,8 @@ export function recordContextSessionUserChange({ if ( !snapshot?.userAdded || change?.type !== 'visibility' || - !isExplicitUserIntentOrigin(change.origin, change.layerId) + !isExplicitUserIntentOrigin(change.origin, change.layerId) || + CONTEXT_INDEPENDENT_LAYER_IDS.includes(change.layerId) ) { return false; } @@ -319,83 +306,10 @@ export function contextSnapshotLayerIds( ) { const snapshot = new Set(restoringLayerIds || currentEnabledLayerIds || []); for (const layerId of excludeLayerIds || []) snapshot.delete(layerId); + for (const layerId of CONTEXT_INDEPENDENT_LAYER_IDS) snapshot.delete(layerId); return snapshot; } -/** - * Block layers that would mix unrelated live/current data into Space Missions. - * The manager calls this before lifecycle work so a refused layer never starts. - * @param {object} input Current mode and requested visibility transition. - * @param {string|null} input.contextMode Active Context mode. - * @param {object|null} input.change Requested visibility transition. - * @param {string|null} [input.layerName] User-facing layer name. - * @returns {string|null} Honest user-facing refusal reason, or null when allowed. - */ -export function contextLayerEnableBlockReason({ - contextMode, - change, - layerName = null, -}) { - if ( - contextMode !== 'space-missions' || - change?.enabled !== true || - contextAllowedLayerIds('space-missions').has(change.layerId) - ) { - return null; - } - const label = String(layerName || change.layerId || 'that layer'); - return SPACE_MISSIONS_LAYER_BLOCK_REASON.replace('{layer}', label); -} - -/** - * The layer name from a Space Missions refusal, so the UI can rebuild the - * sentence in its language. - * @param {string} reason - * @returns {{layer: string}|null} The blocked layer's name, or null when the - * reason is not a Space Missions refusal. - */ -export function parseContextLayerBlockReason(reason) { - if ( - typeof reason !== 'string' || - !reason.startsWith(BLOCK_REASON_PREFIX) || - !reason.endsWith(BLOCK_REASON_SUFFIX) || - reason.length <= BLOCK_REASON_PREFIX.length + BLOCK_REASON_SUFFIX.length - ) - return null; - return { - layer: reason.slice( - BLOCK_REASON_PREFIX.length, - reason.length - BLOCK_REASON_SUFFIX.length, - ), - }; -} - -/** - * Resolve who owns a cancelled direct Space Missions entry. A newer ON keeps - * the entry shell reserved for its replacement transaction; every other - * cancellation must roll back the isolated pre-entry session. - * - * @param {object} input Cancellation and current manager intent state. - * @param {object|null} input.change Manager visibility notification. - * @returns {'ignore'|'replacement'|'restore'} Cancellation disposition. - */ -export function spaceMissionEntryCancellationDisposition({ change }) { - if ( - change?.type !== 'visibility-cancelled' || - change.layerId !== 'rocket-launches' || - change.enabled !== true - ) - return 'ignore'; - if ( - change.cancellationReason === 'superseded' && - Number.isInteger(change.successorIntentEpoch) && - change.successorIntentEpoch > change.intentEpoch && - change.successorEnabled === true - ) - return 'replacement'; - return 'restore'; -} - /** * Merge the pre-entry layer snapshot with layers the user enabled during the * Context session so both survive restoration. @@ -510,7 +424,6 @@ export function subjectEntryAllowed({ */ export const CONTEXT_MODE_VOICE_NAMES = Object.freeze({ flights: 'contacts', - 'space-missions': 'space-missions', }); /** diff --git a/src/contextModePolicy.test.mjs b/src/contextModePolicy.test.mjs index baea77fe55..8e99c33583 100644 --- a/src/contextModePolicy.test.mjs +++ b/src/contextModePolicy.test.mjs @@ -5,7 +5,6 @@ import { orbitEntryAllowed, cockpitEntryAllowed, contextAllowedLayerIds, - contextLayerEnableBlockReason, contextRestoreLayerIds, isExplicitUserIntentOrigin, mergeContextTransitionErrors, @@ -17,9 +16,7 @@ import { settleContextIntentReplay, settleUserFacingContextAction, shouldCaptureContextSession, - shouldDeferContextEntryDuringClear, shouldExitContextForLayerChange, - spaceMissionEntryCancellationDisposition, } from './contextModePolicy.js'; test('Context transition errors preserve primary identity and aggregate failed layers', () => { @@ -119,11 +116,6 @@ test('user-enabled layers are additive and do not exit Context', () => { globalContextEnabled: true, change: userEnable('earthquakes'), }), false); - assert.equal(shouldExitContextForLayerChange({ - contextMode: 'space-missions', - globalContextEnabled: false, - change: userEnable('traffic'), - }), false); assert.equal(shouldExitContextForLayerChange({ contextMode: null, globalContextEnabled: true, @@ -133,48 +125,16 @@ test('user-enabled layers are additive and do not exit Context', () => { test('programmatic Context dependencies and direct mode setup remain allowed', () => { assert.equal(shouldExitContextForLayerChange({ - contextMode: 'space-missions', + contextMode: 'flights', globalContextEnabled: true, - change: { ...userEnable('satellites'), origin: 'programmatic' }, + change: { ...userEnable('military'), enabled: false, origin: 'programmatic' }, }), false); }); -test('Space Missions cancellation retains only a newer authoritative ON entry', () => { - const cancelledEntry = { - type: 'visibility-cancelled', - layerId: 'rocket-launches', - enabled: true, - intentEpoch: 8, - cancellationReason: 'superseded', - successorIntentEpoch: 9, - successorEnabled: true, - successorOrigin: 'programmatic', - }; - assert.equal(spaceMissionEntryCancellationDisposition({ - change: cancelledEntry, - }), 'replacement'); - assert.equal(spaceMissionEntryCancellationDisposition({ - change: { ...cancelledEntry, successorEnabled: false }, - }), 'restore', 'a newer OFF releases the entry shell'); - assert.equal(spaceMissionEntryCancellationDisposition({ - change: { - ...cancelledEntry, - cancellationReason: 'caller-abort', - successorIntentEpoch: undefined, - successorEnabled: undefined, - }, - }), 'restore', 'caller abort at the same epoch restores the isolated session'); - assert.equal(spaceMissionEntryCancellationDisposition({ - change: { ...cancelledEntry, enabled: false }, - currentIntentEpoch: 9, - effectivelyEnabled: true, - }), 'ignore'); -}); - test('only explicit user-owned shell enables capture a Context restoration snapshot', () => { const userMissionEnable = { type: 'visibility-requested', - layerId: 'rocket-launches', + layerId: 'military-awareness', enabled: true, origin: 'user', }; @@ -186,40 +146,25 @@ test('only explicit user-owned shell enables capture a Context restoration snaps assert.equal(shouldCaptureContextSession({ ...userMissionEnable, origin: 'context-restore' }), false); assert.equal(shouldCaptureContextSession({ ...userMissionEnable, enabled: false }), false); assert.equal(shouldCaptureContextSession({ ...userMissionEnable, layerId: 'satellites' }), false); + assert.equal( + shouldCaptureContextSession({ ...userMissionEnable, layerId: 'rocket-launches' }), + false, + 'Space Missions is an ordinary layer, not a Context entry', + ); }); -test('voice dependency OFF exits Space Missions like the equivalent UI action', () => { +test('voice dependency OFF exits Contacts like the equivalent UI action', () => { assert.equal(shouldExitContextForLayerChange({ - contextMode: 'space-missions', + contextMode: 'flights', globalContextEnabled: false, - change: { type: 'visibility', layerId: 'satellites', enabled: false, origin: 'voice' }, + change: { type: 'visibility', layerId: 'flights', enabled: false, origin: 'voice' }, }), true); }); -test('only a newer explicit mission request is deferred during Clear All', () => { - const change = { - type: 'visibility-requested', - layerId: 'rocket-launches', - enabled: true, - origin: 'voice', - intentEpoch: 12, - }; - assert.equal(shouldDeferContextEntryDuringClear({ change, clearInFlight: true }), true); - assert.equal(shouldDeferContextEntryDuringClear({ change, clearInFlight: false }), false); - assert.equal(shouldDeferContextEntryDuringClear({ - change: { ...change, origin: 'programmatic' }, - clearInFlight: true, - }), false); - assert.equal(shouldDeferContextEntryDuringClear({ - change: { ...change, enabled: false }, - clearInFlight: true, - }), false); -}); - test('a rapid re-entry snapshots the settled restore target, not partial manager state', () => { assert.deepEqual( [...contextSnapshotLayerIds( - new Set(['rocket-launches', 'earthquakes']), + new Set(['cctv', 'earthquakes']), new Set(['flights', 'traffic']), )], ['flights', 'traffic'], @@ -230,31 +175,15 @@ test('a rapid re-entry snapshots the settled restore target, not partial manager ); assert.deepEqual( [...contextSnapshotLayerIds( - new Set(['rocket-launches', 'satellites']), + new Set(['military-awareness', 'cctv']), null, - ['rocket-launches'], + ['military-awareness'], )], - ['satellites'], + ['cctv'], 'the synchronous entry intent is not part of the pre-entry snapshot', ); }); -test('Space Missions blocks unrelated layer enables before replay data can mix', () => { - const change = { layerId: 'flights', enabled: true, origin: 'user' }; - assert.match( - contextLayerEnableBlockReason({ contextMode: 'space-missions', change, layerName: 'Live Flights' }), - /Exit the mode to enable Live Flights/, - ); - assert.equal(contextLayerEnableBlockReason({ - contextMode: 'space-missions', - change: { ...change, layerId: 'satellites' }, - }), null); - assert.equal(contextLayerEnableBlockReason({ - contextMode: 'flights', - change, - }), null, 'live cockpit keeps additive user layers'); -}); - test('the Global Context shell and layers selected while Context is off remain allowed', () => { assert.equal(shouldExitContextForLayerChange({ contextMode: null, @@ -275,14 +204,38 @@ test('manually disabling a mode dependency exits that Context bundle', () => { change: { ...userEnable('military'), enabled: false }, }), true); assert.equal(shouldExitContextForLayerChange({ - contextMode: 'space-missions', + contextMode: 'flights', globalContextEnabled: false, change: { ...userEnable('satellites'), enabled: false }, - }), true); + }), false, 'Satellites is not a Contacts dependency'); +}); + +test('Context never isolates, snapshots, restores or bookkeeps Space Missions and Satellites', () => { + for (const layerId of ['rocket-launches', 'satellites']) { + assert.equal(contextAllowedLayerIds('flights').has(layerId), true); + const snapshot = { userAdded: new Set(), userRemoved: new Set() }; + for (const enabled of [true, false]) { + assert.equal(recordContextSessionUserChange({ + snapshot, + change: { type: 'visibility', origin: 'user', layerId, enabled }, + effectiveContextMode: 'flights', + }), false); + const restoreState = { enabledLayerIds: new Set() }; + assert.equal(recordContextRestoreExplicitChange({ + restoreState, + change: { type: 'visibility', origin: 'user', layerId, enabled }, + }), false); + } + assert.equal(snapshot.userAdded.size + snapshot.userRemoved.size, 0); + } + assert.deepEqual( + [...contextSnapshotLayerIds(new Set(['rocket-launches', 'satellites', 'cctv']))], + ['cctv'], + ); }); test('Radio remains an independent companion across Context transitions', () => { - for (const contextMode of ['flights', 'space-missions']) { + for (const contextMode of ['flights', null]) { for (const enabled of [true, false]) { assert.equal(shouldExitContextForLayerChange({ contextMode, @@ -292,21 +245,17 @@ test('Radio remains an independent companion across Context transitions', () => } assert.equal(contextAllowedLayerIds(contextMode).has('radio'), true); } - assert.equal(contextLayerEnableBlockReason({ - contextMode: 'space-missions', - change: { type: 'visibility', origin: 'user', layerId: 'radio', enabled: true }, - layerName: 'Radio', - }), null); }); test('each Context mode exposes only its shell and dependencies', () => { assert.deepEqual( [...contextAllowedLayerIds(null)], - ['military-awareness', 'radio'], + ['military-awareness', 'radio', 'rocket-launches', 'satellites'], ); assert.deepEqual( [...contextAllowedLayerIds('space-missions')], - ['rocket-launches', 'satellites', 'radio'], + ['military-awareness', 'radio', 'rocket-launches', 'satellites'], + 'Space Missions is not a Context mode', ); }); @@ -332,7 +281,7 @@ test('Context restoration honors an explicit companion disable', () => { }); test('the latest explicit Radio state wins across a Context session', () => { - for (const effectiveContextMode of [null, 'flights', 'space-missions']) { + for (const effectiveContextMode of [null, 'flights']) { for (const origin of ['user', 'voice']) { const snapshot = { userAdded: new Set(), userRemoved: new Set() }; const record = (enabled) => recordContextSessionUserChange({ @@ -368,7 +317,7 @@ test('only direct UI and voice origins count as explicit Context intent', () => assert.equal(recordContextSessionUserChange({ snapshot, change: { type: 'visibility', origin, layerId: 'radio', enabled: true }, - effectiveContextMode: 'space-missions', + effectiveContextMode: 'flights', }), false); assert.equal(snapshot.userAdded.size, 0); } @@ -526,16 +475,8 @@ test('the teardown guard re-publishes on the way out, so a mid-flight exit is no test('the session-starting entry layer is never bookkept as user-added (chip ON→OFF restores exactly)', () => { const snapshot = { enabledLayerIds: new Set(['flights', 'ais-live-vessels']), userAdded: new Set() }; - // The exact left-panel regression: the rockets enable event lands while the - // mode is still being entered (or even null); it must not survive its own exit. - for (const effectiveContextMode of ['space-missions', null]) { - recordContextSessionUserChange({ - snapshot, - change: { type: 'visibility', layerId: 'rocket-launches', enabled: true, origin: 'user' }, - effectiveContextMode, - }); - assert.equal(snapshot.userAdded.has('rocket-launches'), false); - } + // The entry layer's enable event lands while the mode is still being + // entered; it must not survive its own exit. recordContextSessionUserChange({ snapshot, change: { type: 'visibility', layerId: 'military-awareness', enabled: true, origin: 'user' }, @@ -559,10 +500,21 @@ test('mid-session user additions are recorded, removed on disable, and judged ag // A dependency of the mode being ENTERED is not a user addition. recordContextSessionUserChange({ snapshot, - change: { type: 'visibility', layerId: 'satellites', enabled: true, origin: 'user' }, - effectiveContextMode: 'space-missions', + change: { type: 'visibility', layerId: 'military', enabled: true, origin: 'user' }, + effectiveContextMode: 'flights', }); - assert.equal(snapshot.userAdded.has('satellites'), false); + assert.equal(snapshot.userAdded.has('military'), false); + // Space Missions is not Context's: it is never bookkept. + recordContextSessionUserChange({ + snapshot, + change: { type: 'visibility', layerId: 'rocket-launches', enabled: true, origin: 'user' }, + effectiveContextMode: 'flights', + }); + assert.equal( + snapshot.userAdded.has('rocket-launches'), + false, + 'Space Missions is not Context state', + ); // Disabling a recorded addition removes it before any exit restore reads it. recordContextSessionUserChange({ snapshot, diff --git a/src/contextSessionOrdering.test.mjs b/src/contextSessionOrdering.test.mjs index cb0854ff44..7df32b154c 100644 --- a/src/contextSessionOrdering.test.mjs +++ b/src/contextSessionOrdering.test.mjs @@ -13,10 +13,7 @@ const radioControlsSource = readRadioSource(new URL('./ui/radioControls.js', imp // - session bookkeeping ran AFTER the exit early-return, so the compensating // userAdded.delete never ran on the left-panel chip exit and restoration // resurrected the mission layer the user just disabled; -// - the effective mode was read AFTER the entering flag was cleared, so the -// entry layer's own enable event was judged against a null mode; -// - a failed Space Missions START from the chip route cleared siblings with -// no rollback; +// - a failed direct Contacts START cleared siblings with no rollback; // - the right-rail entry ignored the activation result entirely. import { test } from 'node:test'; import assert from 'node:assert/strict'; @@ -33,25 +30,20 @@ test('context handler: session bookkeeping runs before the exit early-return', ( assert.ok(record < exit, 'bookkeeping must precede the exit check'); }); -test('context handler: effective mode is read before the entering flag is cleared', () => { - const effective = handler.indexOf('this._contextModeEntering || this._contextMode'); - const clear = handler.indexOf('this._contextModeEntering = null'); - assert.ok(effective > 0, 'effective-mode read present'); - assert.ok(clear > 0, 'entering-flag clear present'); - assert.ok(effective < clear, 'effective mode must be captured first'); +test('Space Missions is an ordinary layer the Context handler never enters', () => { + assert.doesNotMatch(handler, /'space-missions'/); + assert.doesNotMatch(handler, /_contextModeEntering = /); + const attach = connectContextManager.toString(); + assert.doesNotMatch(attach, /rocket-launches|space-missions/); }); -test('cancelled Space Missions entry resolves ownership before settled bookkeeping', () => { +test('a cancelled visibility request returns before settled bookkeeping', () => { const cancelled = handler.indexOf("change?.type === 'visibility-cancelled'"); const bookkeeping = handler.indexOf('recordContextSessionUserChange('); assert.ok(cancelled > 0, 'cancellation branch present'); assert.ok(cancelled < bookkeeping, 'cancellation returns before settled session bookkeeping'); const branch = handler.slice(cancelled, handler.indexOf("change?.type === 'visibility-blocked'")); - assert.match(branch, /spaceMissionEntryCancellationDisposition\(\{/); - assert.match(branch, /cancellationDisposition === 'replacement'[\s\S]*?_contextModeEntering = 'space-missions'[\s\S]*?entryIntent\.intentEpoch === change\.intentEpoch[\s\S]*?_contextModeReplacementIntent = \{[\s\S]*?intentEpoch: change\.successorIntentEpoch/); - assert.match(branch, /cancellationDisposition === 'restore'[\s\S]*?_contextModeEntering = null/); - assert.match(branch, /_restoreContextSessionAfterLayerSettles\(/); - assert.match(branch, /return;/); + assert.match(branch, /this\._syncContextModeButtons\(\);\s*return;/); }); test('direct Context entry captures on the synchronous request boundary', () => { @@ -60,18 +52,29 @@ test('direct Context entry captures on the synchronous request boundary', () => attach, /subscribeVisibilityRequests\(\(change\) => \{[\s\S]*?shouldCaptureContextSession\(change\)/, ); - assert.match( - attach, - /_captureContextSessionSnapshot\(\{\s*excludeLayerIds:\s*\[change\.layerId\],?\s*\}\)/, - ); }); -test('Clear All defers a newer explicit mission guard until its batch settles', () => { - const attach = connectContextManager.toString(); - assert.match(attach, /shouldDeferContextEntryDuringClear\(\{/); - assert.match(attach, /_contextModeDeferredEntryIntent = \{/); - assert.match(attach, /await this\._clearSelectedLayersManagerPromise/); - assert.match(attach, /await this\._clearLayersOutsideContextMode\(entryMode/); +test('only a direct Contacts entry request snapshots the layers', () => { + let request; + const controls = new ContextControls({ + elements: {}, + installations: {}, + actions: { getCockpit: () => null }, + }); + const captures = []; + controls._captureContextSessionSnapshot = (options) => captures.push(options); + controls._syncContextModeButtons = () => {}; + controls.connect({ + subscribe: () => () => {}, + subscribeVisibilityRequests(listener) { + request = listener; + return () => {}; + }, + }); + for (const layerId of ['rocket-launches', 'military-awareness']) + request({ type: 'visibility-requested', layerId, enabled: true, origin: 'user', intentEpoch: 1 }); + controls.stop(); + assert.deepEqual(captures, [{ excludeLayerIds: ['military-awareness'] }]); }); test('context restore replays explicit companion intent after the stale restore queue drains', () => { @@ -91,7 +94,7 @@ test('context restore settles the Contacts coordinator before dependency fanout' assert.ok(settle > 0, 'Contacts coordinator settlement is present'); assert.ok(coordinatorOff > settle, 'Contacts OFF is awaited'); assert.ok(fanout > coordinatorOff, 'snapshot fanout starts after Contacts settles'); - assert.match(restore, /excludeLayerIds: settleContactsCoordinator[\s\S]*?contactsCoordinatorId/); + assert.match(restore, /excludeLayerIds: \[[\s\S]*?CONTEXT_INDEPENDENT_LAYER_IDS[\s\S]*?settleContactsCoordinator \? \[contactsCoordinatorId\]/); }); test('Clear All during the Contacts settle stops the snapshot coming back', () => { @@ -116,7 +119,7 @@ test('context handler: either failed direct Context-shell start rolls the sessio handler.indexOf("change?.type === 'visibility-failed'"), handler.indexOf("change?.type === 'visibility-will-change'"), ); - assert.match(failedBranch, /\['military-awareness', 'rocket-launches'\]\.includes\(change\.layerId\)/); + assert.match(failedBranch, /change\.layerId === 'military-awareness' &&/); assert.match( failedBranch, /_restoreContextSessionAfterLayerSettles\(\s*change\.layerId,\s*\{\s*notificationToken,?\s*\},?\s*\)/, @@ -154,14 +157,14 @@ test('wrapped visibility blocks leave the accessible toast to the wrapper token test('every user-facing Context exit route settles through the failure surface', () => { const initPanel = _initGlobalContextPanel.toString(); - assert.equal((initPanel.match(/void this\._runUserFacingContextAction/g) || []).length, 3); + assert.equal((initPanel.match(/void this\._runUserFacingContextAction/g) || []).length, 2); assert.doesNotMatch(initPanel, /falseIsFailure:\s*false/); assert.doesNotMatch(initPanel, /void this\._selectContextMode/); const deactivationCalls = [...handler.matchAll( /void this\._trackContextLayerReaction\(\s*this\._runUserFacingContextAction\(\(notificationToken\) =>\s*this\._deactivateContextForLayerChange\(\{ notificationToken \}\),?\s*\),?\s*\)/g, )]; - assert.equal(deactivationCalls.length, 4, 'dependency and primary layer exits share the caught restore path'); + assert.equal(deactivationCalls.length, 3, 'dependency and primary layer exits share the caught restore path'); assert.doesNotMatch(handler, /void this\._deactivateContextForLayerChange\(\)/); }); @@ -193,10 +196,7 @@ test('right-rail context entry is transactional: activation result gates the mod const failureBlock = select.slice(activation); assert.match(failureBlock, /activated = await activationIntent\.promise/); assert.match(failureBlock, /catch \(error\) \{\s*activationError = error;/); - assert.match(failureBlock, /_contextModeReplacementIntent\?\.generation === generation/); assert.match(failureBlock, /await this\._dataManager\._waitForVisibilityIntent\?\.\(/); - assert.match(failureBlock, /outcome\?\.intentEpoch === replacementIntent\.intentEpoch[\s\S]*?outcome\.succeeded === true/); - assert.match(failureBlock, /outcome\?\.cancellationReason === 'superseded'[\s\S]*?outcome\.successorEnabled === true[\s\S]*?outcome\.successorIntentEpoch > replacementIntent\.intentEpoch/); assert.match(failureBlock, /activationError\s*\|\|\s*activated === false\s*\|\|\s*!this\._dataManager\.isEnabled\(entryLayerId\)/); assert.match(failureBlock, /cancelledAndSettled\s*=\s*terminalIntentOutcome\?\.succeeded === false/); assert.match(failureBlock, /\['caller-abort', 'resource-abort', 'superseded'\]/); @@ -216,9 +216,11 @@ test('Context entry awaits isolation and direct shell routes isolate in the visi // rests on Context OFF; the honesty lives in the REPORT, not in a racy // attempt to put the prior mode back (see the note above // _restoreContextSessionAfterLayerSettles). + const capture = select.indexOf('this._captureContextSessionSnapshot('); + assert.ok(capture > 0, 'Context snapshot capture is missing'); const crossMode = select.slice( select.indexOf('const crossModeSwitch = Boolean('), - select.indexOf('this._captureContextSessionSnapshot();'), + capture, ); assert.ok(crossMode, 'cross-mode teardown block is missing'); assert.doesNotMatch(crossMode, /if \(signal\?\.aborted\)[\s\S]*?await this\._restoreContextSession/); @@ -242,10 +244,10 @@ test('Context entry awaits isolation and direct shell routes isolate in the visi assert.match(ContextControls.prototype.stop.toString(), /this\._contextModeGeneration\+\+/); const guard = connectContextManager.toString(); - assert.match(guard, /\['military-awareness', 'rocket-launches'\]\.includes\(change\.layerId\)/); + assert.match(guard, /change\.layerId !== 'military-awareness'/); assert.match(guard, /const notificationToken\s*=\s*change\.notificationToken\s*\|\|\s*Symbol\('direct-context-shell-entry'\)/); assert.match(guard, /this\._userFacingContextNotificationTokens\.add\(notificationToken\)/); - assert.match(guard, /await this\._clearLayersOutsideContextMode\(entryMode,\s*\{\s*notificationToken,?\s*\}\)/); + assert.match(guard, /await this\._clearLayersOutsideContextMode\(null,\s*\{\s*notificationToken,?\s*\}\)/); assert.match( guard, /await this\._restoreContextSession\(\{\s*excludeLayerIds: \[change\.layerId\],\s*notificationToken,\s*\}\)/, diff --git a/src/contextTabKeyboard.test.mjs b/src/contextTabKeyboard.test.mjs index 2291d201b5..aa1b5321f7 100644 --- a/src/contextTabKeyboard.test.mjs +++ b/src/contextTabKeyboard.test.mjs @@ -2,7 +2,9 @@ import { renderApplicationHtml } from './testSupport/applicationHtml.mjs'; import { readStylesheet } from './testSupport/readStylesheet.mjs'; import { _selectContextMode } from './ui/contextTransactions.js'; import { _initGlobalContextPanel } from './ui/contextBindings.js'; +import { ContextControls } from './ui/contextControls.js'; import { clearSelectedLayers } from './ui/contextActions.js'; +import { PANEL_RAIL_ITEMS } from './ui/panelRailCatalog.js'; import { readFileSync as readRadioSource } from 'node:fs'; const radioBindings = readRadioSource( new URL('./ui/radioBindings.js', import.meta.url), @@ -21,43 +23,24 @@ const html = await renderApplicationHtml( ); const css = readStylesheet(new URL('../style.css', import.meta.url)); -test('Contacts and Space Missions both participate in the ordinary Tab sequence', () => { - for (const id of [ - 'global-context-flights-btn', - 'global-context-missions-btn', - ]) { - const button = html.match( - new RegExp(` -
{{ t('SELECT CONTEXT') }} - {{ t('CONTACTS — nearest planes · vessels · sites') }}
{{ t('SPACE MISSIONS — launches & orbital assets') }}
+ {{ t('CONTACTS — nearest planes · vessels · sites') }}
@@ -241,12 +236,6 @@ watch(
-
-
- - -
-
@@ -255,6 +244,7 @@ watch(
+ diff --git a/src/ui/views/panels/MissionDetail.vue b/src/ui/views/panels/MissionDetail.vue index 67aee31224..d88bc2e5ae 100644 --- a/src/ui/views/panels/MissionDetail.vue +++ b/src/ui/views/panels/MissionDetail.vue @@ -3,17 +3,17 @@ import { storeToRefs } from 'pinia'; import { nextTick, ref, watch } from 'vue'; import { t } from '../../../i18n/index.js'; import UiSlider from '../../kit/UiSlider.js'; -import { useContextStore } from '../../stores/context.js'; +import { useSpaceMissionsStore } from '../../stores/spaceMissions.js'; import UiButton from '../../kit/UiButton.vue'; -// The selected space mission inside Context. The launches layer presents it +// The selected space mission. The launches layer presents it // and hides the panel while none is selected; the roster beside it hides // while it shows. Buttons call the layer's panel commands. -const { mission: m, missionsLayer: layer } = storeToRefs(useContextStore()); +const { mission: m, layer } = storeToRefs(useSpaceMissionsStore()); const root = ref(null); -// Each newly presented selection returns the Context panel to the top. -const SCROLLER = '.global-context-panel-inner'; +// Each newly presented selection returns the mission panel to the top. +const SCROLLER = '.space-missions-panel-inner'; watch( () => m.value?.scrollRequest, async (request) => { diff --git a/src/ui/views/panels/MissionRoster.vue b/src/ui/views/panels/MissionRoster.vue index f0845b89aa..8c6a6aa130 100644 --- a/src/ui/views/panels/MissionRoster.vue +++ b/src/ui/views/panels/MissionRoster.vue @@ -2,13 +2,13 @@ import { storeToRefs } from 'pinia'; import { onBeforeUpdate, onUpdated, ref } from 'vue'; import { t } from '../../../i18n/index.js'; -import { useContextStore } from '../../stores/context.js'; +import { useSpaceMissionsStore } from '../../stores/spaceMissions.js'; import UiEmpty from '../../kit/UiEmpty.vue'; // The Space Missions roster. The launches layer presents it; until it does, // the list shows its loading line. Hover and keyboard focus drive the // layer's preview, and a click selects the mission. -const { missionRoster: roster, missionsLayer: layer } = storeToRefs(useContextStore()); +const { roster, layer } = storeToRefs(useSpaceMissionsStore()); const root = ref(null); const CONTINUATION = '[data-mission-roster-focus-continuation]'; diff --git a/src/ui/views/panels/PhoneTabBar.vue b/src/ui/views/panels/PhoneTabBar.vue index c8da5668d0..ed6ac0f3c1 100644 --- a/src/ui/views/panels/PhoneTabBar.vue +++ b/src/ui/views/panels/PhoneTabBar.vue @@ -1,19 +1,25 @@ diff --git a/src/ui/views/panels/SpaceMissionsPanel.vue b/src/ui/views/panels/SpaceMissionsPanel.vue new file mode 100644 index 0000000000..ae6c6ef60c --- /dev/null +++ b/src/ui/views/panels/SpaceMissionsPanel.vue @@ -0,0 +1,43 @@ + + + diff --git a/src/voice/actionSchemas.js b/src/voice/actionSchemas.js index 2b57090a12..ca94a6626a 100644 --- a/src/voice/actionSchemas.js +++ b/src/voice/actionSchemas.js @@ -211,6 +211,7 @@ const schemas = [ 'utilities-panel', 'pp-toggles', 'global-context-panel', + 'space-missions-panel', 'weather-panel', 'recent-imagery-panel', 'voice-settings', diff --git a/src/voice/actionSchemas.test.mjs b/src/voice/actionSchemas.test.mjs index d78acc0c79..cfd4ec0a3a 100644 --- a/src/voice/actionSchemas.test.mjs +++ b/src/voice/actionSchemas.test.mjs @@ -62,7 +62,8 @@ test('the complete Realtime tool payload pins the manifest-generated layer relea // open_stories adds the Stories Explore entry action. // The Cyber HUD layout leaves set_hud's layout enum (its sonar is a // visual style; set_cyber_sonar is excluded above). - '97f78bc5e66d757da87333c515ebdbf5c2a6908156b3e676e9c2ca45e9b5e4f3', + // The Space Missions panel adds one panel target. + '09abe70ef3a1fc4320e25cff997dd3b04db7e78ff31b8530e17bbbbb8156b4c6', ); }); @@ -195,6 +196,7 @@ test('all legacy action arguments are byte-identical after removing the delibera 'voice-preview', 'provider-settings', 'utilities-panel', + 'space-missions-panel', ].includes(id), ); for (const tool of legacy) { @@ -342,3 +344,17 @@ test('tilt accepts an angle with no direction', () => { validateArgs(schema, { motion: 'tilt', pitchDeg: 'steep' }).length > 0, ); }); + +test('set_panel_open accepts the Space Missions panel', () => { + const schema = GEV_ACTION_SCHEMAS.find( + (tool) => tool.name === 'set_panel_open', + ).parameters; + assert.deepEqual( + validateArgs(schema, { panelId: 'space-missions-panel', open: true }), + [], + ); + assert.ok( + validateArgs(schema, { panelId: 'space-missions', open: true }).length > 0, + 'the Context mode name is not a panel id', + ); +}); diff --git a/src/voice/gevActions.js b/src/voice/gevActions.js index a7d6d2690a..8f27790b0e 100644 --- a/src/voice/gevActions.js +++ b/src/voice/gevActions.js @@ -138,6 +138,9 @@ const PANEL_ALIASES = new Map([ ['global context', 'global-context-panel'], ['right context', 'global-context-panel'], ['context right panel', 'global-context-panel'], + ['space missions panel', 'space-missions-panel'], + ['missions panel', 'space-missions-panel'], + ['mission panel', 'space-missions-panel'], ['utilities', 'utilities-panel'], ['utilities panel', 'utilities-panel'], ['draw', 'utilities-panel'], @@ -167,6 +170,7 @@ const PANEL_IDS = new Set([ 'cctv-panel', 'radio-panel', 'global-context-panel', + 'space-missions-panel', 'utilities-panel', 'scene-panel', 'pp-toggles', @@ -607,6 +611,12 @@ export function createGevActionRunner({ changeOptions, ); } + if (layerId === 'satellites') { + // A Satellites OFF can end Space Missions, which needs it. + await dataManager.layers + .get('rocket-launches') + ?.module?.waitForSatelliteIntents?.(); + } if (layerId === 'rocket-launches' || layerId === 'satellites') { await styleManager?._waitForContextLayerSettlement?.(); } @@ -981,6 +991,47 @@ export function createGevActionRunner({ ...(!applied ? { error: say } : {}), }; } + // The Space Missions panel exists only while its layer is on; opening it + // otherwise would fold the other right-rail panels for nothing. + if ( + open && + panelId === 'space-missions-panel' && + !dataManager?.isEnabled?.('rocket-launches') + ) { + const say = dataManager?.isEffectivelyEnabled?.('rocket-launches') + ? 'Space Missions is still starting; its panel opens when it is on.' + : 'The Space Missions panel shows while Space Missions is on. Turn on Space Missions first.'; + return { + ok: false, + action: 'set_panel_open', + panelId, + open, + applied: false, + unavailable: true, + say, + error: say, + }; + } + // The Cockpit owns the screen and hides the right rail: the panel is + // not opened (or its preference written) under it. + if ( + open && + panelId === 'space-missions-panel' && + styleManager?.getCockpitState?.()?.active + ) { + const say = + 'The Space Missions panel opens once you leave the cockpit.'; + return { + ok: false, + action: 'set_panel_open', + panelId, + open, + applied: false, + unavailable: true, + say, + error: say, + }; + } if (!setPanelOpen(styleManager, panelId, open)) { const say = 'There is no panel to open here.'; return { @@ -992,6 +1043,9 @@ export function createGevActionRunner({ error: say, }; } + // A phone shows the right rail only as tab sheets: show this one's. + if (open && panelId === 'space-missions-panel') + styleManager?.revealPanel?.(panelId); return { ok: true, action: 'set_panel_open', panelId, open }; } @@ -1030,6 +1084,54 @@ export function createGevActionRunner({ ...cancellationState(), }; } + if (mode === 'space-missions') { + // Space Missions is an ordinary layer with its own panel, not a + // Context mode; older phrasings still reach it through this alias. + const result = await runGevAction( + 'set_layer_visibility', + { layerId: 'rocket-launches', enabled: true }, + runOptions, + ); + // Open the panel even when the layer was already on, but never under + // the Cockpit, which owns the screen (as the layer's own reveal). + if ( + result?.ok === true && + current() && + !styleManager?.getCockpitState?.()?.active + ) { + setPanelOpen(styleManager, 'space-missions-panel', true); + styleManager?.revealPanel?.('space-missions-panel'); + } + return { + ...result, + action: 'set_context_mode', + mode: 'space-missions', + }; + } + const contextState = styleManager.getContextModeState?.() || {}; + if ( + mode === 'off' && + !contextState.mode && + !contextState.changing && + !contextState.entering && + !dataManager.isEffectivelyEnabled?.('military-awareness') && + (dataManager.isEffectivelyEnabled?.('rocket-launches') ?? + dataManager.isEnabled?.('rocket-launches')) + ) { + // "Exit Space Missions" still arrives as context off. With no Context + // mode on, entering or starting (Contacts), Space Missions, on or + // still starting, is what is being left: switch its layer off. + const result = await runGevAction( + 'set_layer_visibility', + { layerId: 'rocket-launches', enabled: false }, + runOptions, + ); + return { + ...result, + action: 'set_context_mode', + mode: 'off', + }; + } if (mode && mode !== 'off') { setPanelOpen(styleManager, 'global-context-panel', true); } diff --git a/src/voice/gevActions.test.mjs b/src/voice/gevActions.test.mjs index 3aa74548c9..d2ccb6deec 100644 --- a/src/voice/gevActions.test.mjs +++ b/src/voice/gevActions.test.mjs @@ -340,7 +340,9 @@ test('opening Stories only admits current requests and can stop its own session' assert.equal(admitted, 1); let finishLoading; - loaded = new Promise((resolve) => { finishLoading = resolve; }); + loaded = new Promise((resolve) => { + finishLoading = resolve; + }); const second = new AbortController(); const pending = runner('open_stories', {}, { signal: second.signal }); assert.equal(admitted, 2); @@ -395,7 +397,11 @@ test('dependent voice navigation waits for the destination viewport to arrive', // Run at once, the tilt's navigation cancelled the flight; with a geocoded // place, the late flight replaced the tilt. function tiltAfterFlightHarness() { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; const harness = createVoiceNavigationHarness(); const { viewer, styleManager } = harness; const flights = []; @@ -403,15 +409,16 @@ function tiltAfterFlightHarness() { harness.order.push('fly'); flights.push(options); }; - styleManager.runImmediateLocationNavigation = (navigate) => ( - styleManager.runImmediateNavigation('location', navigate) - ); + styleManager.runImmediateLocationNavigation = (navigate) => + styleManager.runImmediateNavigation('location', navigate); return { ...harness, flights }; } const settledYet = (promise) => { let settled = false; - promise.then(() => { settled = true; }); + promise.then(() => { + settled = true; + }); return () => settled; }; @@ -447,12 +454,13 @@ test('a tilt waits through a geocoded fly-to search, then for its flight', async viewer, styleManager, dataManager: { layers: new Map(), getAll: () => [] }, - searchNavigation: (_viewer, query, options) => new Promise((resolve) => { - finishSearch = () => { - landFlight = options.onComplete; - resolve({ label: query, navigationMode: 'city-overview' }); - }; - }), + searchNavigation: (_viewer, query, options) => + new Promise((resolve) => { + finishSearch = () => { + landFlight = options.onComplete; + resolve({ label: query, navigationMode: 'city-overview' }); + }; + }), }); const fly = runner('fly_to_location', { query: 'Somewhere Far' }); const tilt = runner('move_camera', { motion: 'tilt', pitchDeg: -45 }); @@ -498,7 +506,10 @@ test('a tilt beside a fly-to that found nothing is not run', async () => { assert.equal(result.ok, false); assert.match(result.error, /did not arrive/); // A later, separate tilt is not held by the failed lookup. - assert.equal((await runner('move_camera', { motion: 'tilt', pitchDeg: -45 })).ok, true); + assert.equal( + (await runner('move_camera', { motion: 'tilt', pitchDeg: -45 })).ok, + true, + ); }); test('a tilt with no voice flight pending runs at once', async () => { @@ -529,11 +540,18 @@ for (const motion of [ styleManager, dataManager: { layers: new Map(), getAll: () => [] }, }); - assert.equal((await runner('fly_to_location', { locationId: 'austin' })).ok, true); + assert.equal( + (await runner('fly_to_location', { locationId: 'austin' })).ok, + true, + ); const moved = runner('move_camera', motion); const movedDone = settledYet(moved); await new Promise((resolve) => setTimeout(resolve, 0)); - assert.equal(movedDone(), false, `the ${motion.motion} must wait while the camera flies`); + assert.equal( + movedDone(), + false, + `the ${motion.motion} must wait while the camera flies`, + ); assert.equal( order.slice(order.indexOf('fly')).includes('cancel'), false, @@ -554,23 +572,36 @@ for (const motion of [ viewer, styleManager, dataManager: { layers: new Map(), getAll: () => [] }, - searchNavigation: (_viewer, query, options) => new Promise((resolve) => { - finishSearch = () => { - landFlight = options.onComplete; - resolve({ label: query, navigationMode: 'city-overview' }); - }; - }), + searchNavigation: (_viewer, query, options) => + new Promise((resolve) => { + finishSearch = () => { + landFlight = options.onComplete; + resolve({ label: query, navigationMode: 'city-overview' }); + }; + }), }); const fly = runner('fly_to_location', { query: 'Somewhere Far' }); const moved = runner('move_camera', motion); const movedDone = settledYet(moved); await new Promise((resolve) => setTimeout(resolve, 0)); - assert.equal(movedDone(), false, `the ${motion.motion} must wait for the place lookup`); - assert.equal(getActiveCameraMotion(), null, 'nothing moves before the flight'); + assert.equal( + movedDone(), + false, + `the ${motion.motion} must wait for the place lookup`, + ); + assert.equal( + getActiveCameraMotion(), + null, + 'nothing moves before the flight', + ); finishSearch(); assert.equal((await fly).ok, true); await new Promise((resolve) => setTimeout(resolve, 0)); - assert.equal(movedDone(), false, `the ${motion.motion} must wait for the flight too`); + assert.equal( + movedDone(), + false, + `the ${motion.motion} must wait for the flight too`, + ); landFlight(); assert.equal((await moved).ok, true); assert.equal(getActiveCameraMotion()?.kind, motion.motion); @@ -589,17 +620,17 @@ for (const motion of [ const result = await moved; assert.equal(result.ok, false); assert.equal(result.motion, motion.motion); - assert.match(result.error, new RegExp(`this ${motion.motion} was waiting for did not arrive`)); + assert.match( + result.error, + new RegExp(`this ${motion.motion} was waiting for did not arrive`), + ); assert.equal(getActiveCameraMotion(), null); }); } // Cesium lands a flight even when the user grabs the globe mid-flight, so the // motion queued behind it must not then take the camera back. -for (const motion of [ - { motion: 'orbit' }, - { motion: 'tilt', pitchDeg: -45 }, -]) { +for (const motion of [{ motion: 'orbit' }, { motion: 'tilt', pitchDeg: -45 }]) { test(`${motion.motion} queued behind a fly-to is dropped when the user drags mid-flight`, async () => { const { viewer, styleManager, flights } = tiltAfterFlightHarness(); const canvasListeners = new Map(); @@ -611,7 +642,10 @@ for (const motion of [ styleManager, dataManager: { layers: new Map(), getAll: () => [] }, }); - assert.equal((await runner('fly_to_location', { locationId: 'austin' })).ok, true); + assert.equal( + (await runner('fly_to_location', { locationId: 'austin' })).ok, + true, + ); const moved = runner('move_camera', motion); canvasListeners.get('pointerdown')(); flights[0].complete(); @@ -634,9 +668,15 @@ test('a drag during the first of two chained fly-tos still drops the queued moti styleManager, dataManager: { layers: new Map(), getAll: () => [] }, }); - assert.equal((await runner('fly_to_location', { locationId: 'austin' })).ok, true); + assert.equal( + (await runner('fly_to_location', { locationId: 'austin' })).ok, + true, + ); canvasListeners.get('touchstart')(); - assert.equal((await runner('fly_to_location', { locationId: 'austin' })).ok, true); + assert.equal( + (await runner('fly_to_location', { locationId: 'austin' })).ok, + true, + ); const moved = runner('move_camera', { motion: 'orbit' }); flights.at(-1).complete(); const result = await moved; @@ -657,7 +697,10 @@ test('input before a fly-to does not drop the motion queued behind it', async (t dataManager: { layers: new Map(), getAll: () => [] }, }); canvasListeners.get('wheel')(); - assert.equal((await runner('fly_to_location', { locationId: 'austin' })).ok, true); + assert.equal( + (await runner('fly_to_location', { locationId: 'austin' })).ok, + true, + ); const moved = runner('move_camera', { motion: 'orbit' }); flights[0].complete(); assert.equal((await moved).ok, true); @@ -671,10 +714,16 @@ test('a motion follows a later fly-to in the same reply that cancels its flight' styleManager, dataManager: { layers: new Map(), getAll: () => [] }, }); - assert.equal((await runner('fly_to_location', { locationId: 'austin' })).ok, true); + assert.equal( + (await runner('fly_to_location', { locationId: 'austin' })).ok, + true, + ); const moved = runner('move_camera', { motion: 'orbit' }); const movedDone = settledYet(moved); - assert.equal((await runner('fly_to_location', { locationId: 'austin' })).ok, true); + assert.equal( + (await runner('fly_to_location', { locationId: 'austin' })).ok, + true, + ); // The second flight supersedes the first, as Cesium's flyTo does. flights[0].cancel(); await new Promise((resolve) => setTimeout(resolve, 0)); @@ -693,9 +742,10 @@ test('a motion follows a later fly-to whose start cancels its geocode', async (t viewer, styleManager, dataManager: { layers: new Map(), getAll: () => [] }, - searchNavigation: (_viewer, query, options) => new Promise((resolve) => { - searches.push({ query, options, resolve }); - }), + searchNavigation: (_viewer, query, options) => + new Promise((resolve) => { + searches.push({ query, options, resolve }); + }), }); const flyA = runner('fly_to_location', { query: 'Place A' }); const moved = runner('move_camera', { motion: 'orbit' }); @@ -723,11 +773,15 @@ test('a motion does not run at a flight that lands while the next place is looke viewer, styleManager, dataManager: { layers: new Map(), getAll: () => [] }, - searchNavigation: (_viewer, query, options) => new Promise((resolve) => { - searches.push({ query, options, resolve }); - }), + searchNavigation: (_viewer, query, options) => + new Promise((resolve) => { + searches.push({ query, options, resolve }); + }), }); - assert.equal((await runner('fly_to_location', { locationId: 'austin' })).ok, true); + assert.equal( + (await runner('fly_to_location', { locationId: 'austin' })).ok, + true, + ); const moved = runner('move_camera', { motion: 'tilt', pitchDeg: -45 }); const movedDone = settledYet(moved); const flyB = runner('fly_to_location', { query: 'Place B' }); @@ -762,11 +816,15 @@ for (const order of ['lands first', 'not found first']) { viewer, styleManager, dataManager: { layers: new Map(), getAll: () => [] }, - searchNavigation: (_viewer, query, options) => new Promise((resolve) => { - searches.push({ query, options, resolve }); - }), + searchNavigation: (_viewer, query, options) => + new Promise((resolve) => { + searches.push({ query, options, resolve }); + }), }); - assert.equal((await runner('fly_to_location', { locationId: 'austin' })).ok, true); + assert.equal( + (await runner('fly_to_location', { locationId: 'austin' })).ok, + true, + ); const moved = runner('move_camera', { motion: 'tilt', pitchDeg: -45 }); const flyB = runner('fly_to_location', { query: 'Nowhere' }); await new Promise((resolve) => setTimeout(resolve, 0)); @@ -780,19 +838,23 @@ for (const order of ['lands first', 'not found first']) { }); } -test('a motion beside a fly-to that finds nothing never acts at an earlier reply\'s flight', async () => { +test("a motion beside a fly-to that finds nothing never acts at an earlier reply's flight", async () => { const { viewer, styleManager, flights } = tiltAfterFlightHarness(); const searches = []; const runner = createGevActionRunner({ viewer, styleManager, dataManager: { layers: new Map(), getAll: () => [] }, - searchNavigation: (_viewer, query, options) => new Promise((resolve) => { - searches.push({ query, options, resolve }); - }), + searchNavigation: (_viewer, query, options) => + new Promise((resolve) => { + searches.push({ query, options, resolve }); + }), }); // Reply 1: "fly to Austin", still flying. - assert.equal((await runner('fly_to_location', { locationId: 'austin' })).ok, true); + assert.equal( + (await runner('fly_to_location', { locationId: 'austin' })).ok, + true, + ); // Reply 2: "fly to Nowhere and tilt". const flyB = runner('fly_to_location', { query: 'Nowhere' }); const moved = runner('move_camera', { motion: 'tilt', pitchDeg: -45 }); @@ -816,11 +878,15 @@ for (const first of [0, 1]) { viewer, styleManager, dataManager: { layers: new Map(), getAll: () => [] }, - searchNavigation: (_viewer, query, options) => new Promise((resolve) => { - searches.push({ query, options, resolve }); - }), + searchNavigation: (_viewer, query, options) => + new Promise((resolve) => { + searches.push({ query, options, resolve }); + }), }); - assert.equal((await runner('fly_to_location', { locationId: 'austin' })).ok, true); + assert.equal( + (await runner('fly_to_location', { locationId: 'austin' })).ok, + true, + ); const moved = runner('move_camera', { motion: 'orbit' }); const flyB = runner('fly_to_location', { query: 'Nowhere B' }); const flyC = runner('fly_to_location', { query: 'Nowhere C' }); @@ -843,11 +909,15 @@ test('a lookup cancelled by a newer one that finds nothing does not hide the fli viewer, styleManager, dataManager: { layers: new Map(), getAll: () => [] }, - searchNavigation: (_viewer, query, options) => new Promise((resolve) => { - searches.push({ query, options, resolve }); - }), + searchNavigation: (_viewer, query, options) => + new Promise((resolve) => { + searches.push({ query, options, resolve }); + }), }); - assert.equal((await runner('fly_to_location', { locationId: 'austin' })).ok, true); + assert.equal( + (await runner('fly_to_location', { locationId: 'austin' })).ok, + true, + ); const moved = runner('move_camera', { motion: 'tilt', pitchDeg: -45 }); const flyB = runner('fly_to_location', { query: 'Place B' }); const flyC = runner('fly_to_location', { query: 'Nowhere C' }); @@ -872,8 +942,14 @@ test('a motion sent after a fly-to that found nothing still waits for the flight dataManager: { layers: new Map(), getAll: () => [] }, searchNavigation: async () => null, }); - assert.equal((await runner('fly_to_location', { locationId: 'austin' })).ok, true); - assert.equal((await runner('fly_to_location', { query: 'Nowhere' })).ok, false); + assert.equal( + (await runner('fly_to_location', { locationId: 'austin' })).ok, + true, + ); + assert.equal( + (await runner('fly_to_location', { query: 'Nowhere' })).ok, + false, + ); const before = order.length; const moved = runner('move_camera', { motion: 'tilt', pitchDeg: -45 }); const movedDone = settledYet(moved); @@ -893,9 +969,18 @@ test('two lookups that found nothing in a row still leave the motion waiting for dataManager: { layers: new Map(), getAll: () => [] }, searchNavigation: async () => null, }); - assert.equal((await runner('fly_to_location', { locationId: 'austin' })).ok, true); - assert.equal((await runner('fly_to_location', { query: 'Nowhere' })).ok, false); - assert.equal((await runner('fly_to_location', { query: 'Nowhere 2' })).ok, false); + assert.equal( + (await runner('fly_to_location', { locationId: 'austin' })).ok, + true, + ); + assert.equal( + (await runner('fly_to_location', { query: 'Nowhere' })).ok, + false, + ); + assert.equal( + (await runner('fly_to_location', { query: 'Nowhere 2' })).ok, + false, + ); const before = order.length; const moved = runner('move_camera', { motion: 'orbit' }); const movedDone = settledYet(moved); @@ -915,13 +1000,17 @@ test('a motion acts at a landed flight that a later failed lookup replaced', asy viewer, styleManager, dataManager: { layers: new Map(), getAll: () => [] }, - searchNavigation: (_viewer, query, options) => new Promise((resolve) => { - searches.push({ query, options, resolve }); - }), + searchNavigation: (_viewer, query, options) => + new Promise((resolve) => { + searches.push({ query, options, resolve }); + }), }); const flyA = runner('fly_to_location', { query: 'Slow A' }); const moved = runner('move_camera', { motion: 'orbit' }); - assert.equal((await runner('fly_to_location', { locationId: 'austin' })).ok, true); + assert.equal( + (await runner('fly_to_location', { locationId: 'austin' })).ok, + true, + ); flights[0].complete(); const flyC = runner('fly_to_location', { query: 'Nowhere C' }); await new Promise((resolve) => setTimeout(resolve, 0)); @@ -941,18 +1030,25 @@ test('a motion refuses when the flight a later failed lookup replaced was cancel viewer, styleManager, dataManager: { layers: new Map(), getAll: () => [] }, - searchNavigation: (_viewer, query, options) => new Promise((resolve) => { - searches.push({ query, options, resolve }); - }), + searchNavigation: (_viewer, query, options) => + new Promise((resolve) => { + searches.push({ query, options, resolve }); + }), }); - assert.equal((await runner('fly_to_location', { locationId: 'austin' })).ok, true); + assert.equal( + (await runner('fly_to_location', { locationId: 'austin' })).ok, + true, + ); const moved = runner('move_camera', { motion: 'orbit' }); const flyA = runner('fly_to_location', { query: 'Slow A' }); await new Promise((resolve) => setTimeout(resolve, 0)); // The motion sees Austin land, then follows A's lookup. flights[0].complete(); await new Promise((resolve) => setTimeout(resolve, 0)); - assert.equal((await runner('fly_to_location', { locationId: 'austin' })).ok, true); + assert.equal( + (await runner('fly_to_location', { locationId: 'austin' })).ok, + true, + ); flights[1].cancel(); const flyC = runner('fly_to_location', { query: 'Nowhere C' }); await new Promise((resolve) => setTimeout(resolve, 0)); @@ -965,7 +1061,7 @@ test('a motion refuses when the flight a later failed lookup replaced was cancel assert.match(result.error, /did not arrive/); }); -test('a stale motion does not follow a newer reply\'s fly-to', async () => { +test("a stale motion does not follow a newer reply's fly-to", async () => { const { viewer, styleManager, flights } = tiltAfterFlightHarness(); const runner = createGevActionRunner({ viewer, @@ -973,11 +1069,21 @@ test('a stale motion does not follow a newer reply\'s fly-to', async () => { dataManager: { layers: new Map(), getAll: () => [] }, }); let live = true; - assert.equal((await runner('fly_to_location', { locationId: 'austin' })).ok, true); - const moved = runner('move_camera', { motion: 'orbit' }, { isCurrent: () => live }); + assert.equal( + (await runner('fly_to_location', { locationId: 'austin' })).ok, + true, + ); + const moved = runner( + 'move_camera', + { motion: 'orbit' }, + { isCurrent: () => live }, + ); // A newer reply takes over and flies elsewhere; this reply is stale. live = false; - assert.equal((await runner('fly_to_location', { locationId: 'austin' })).ok, true); + assert.equal( + (await runner('fly_to_location', { locationId: 'austin' })).ok, + true, + ); flights[0].cancel(); // The newer flight never lands here: following it would hold this answer. const result = await Promise.race([ @@ -996,7 +1102,10 @@ test('a motion gives up on a flight that has not landed in 15 s', async (t) => { styleManager, dataManager: { layers: new Map(), getAll: () => [] }, }); - assert.equal((await runner('fly_to_location', { locationId: 'austin' })).ok, true); + assert.equal( + (await runner('fly_to_location', { locationId: 'austin' })).ok, + true, + ); t.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); const moved = runner('move_camera', { motion: 'orbit' }); const movedDone = settledYet(moved); @@ -1024,10 +1133,17 @@ test('a motion follows a newer fly-to that lands while its own lookup stalls', a runner('fly_to_location', { query: 'Place A' }); const moved = runner('move_camera', { motion: 'orbit' }); const movedDone = settledYet(moved); - assert.equal((await runner('fly_to_location', { locationId: 'austin' })).ok, true); + assert.equal( + (await runner('fly_to_location', { locationId: 'austin' })).ok, + true, + ); t.mock.timers.tick(2_000); await Promise.resolve(); - assert.equal(movedDone(), false, 'the orbit must wait for the newer flight to land'); + assert.equal( + movedDone(), + false, + 'the orbit must wait for the newer flight to land', + ); flights[0].complete(); for (let i = 0; i < 5 && !movedDone(); i += 1) await Promise.resolve(); assert.equal(movedDone(), true, 'the orbit must not wait out A'); @@ -1043,7 +1159,7 @@ test('a motion follows a newer fly-to that lands while its own lookup stalls', a // Gemini runs one reply's calls one after another: by the time "pan left" // runs, "fly to Xyzzyville" has already found nothing, so there is no flight // to wait on, and the pan moved the old view with ok: true. -test('a motion run after its reply\'s fly-to found nothing is not run', async (t) => { +test("a motion run after its reply's fly-to found nothing is not run", async (t) => { t.after(() => interruptCameraMotion('test-cleanup')); const { viewer, styleManager } = tiltAfterFlightHarness(); const runner = createGevActionRunner({ @@ -1053,7 +1169,11 @@ test('a motion run after its reply\'s fly-to found nothing is not run', async (t searchNavigation: async () => null, }); const reply = { turn: 1 }; - const fly = await runner('fly_to_location', { query: 'Xyzzyville' }, { reply }); + const fly = await runner( + 'fly_to_location', + { query: 'Xyzzyville' }, + { reply }, + ); assert.equal(fly.ok, false); const pan = await runner( 'move_camera', @@ -1065,7 +1185,11 @@ test('a motion run after its reply\'s fly-to found nothing is not run', async (t assert.equal(getActiveCameraMotion(), null); // The same holds for OpenAI's reply identity. const group = 'response-1'; - await runner('fly_to_location', { query: 'Xyzzyville' }, { authorityGroup: group }); + await runner( + 'fly_to_location', + { query: 'Xyzzyville' }, + { authorityGroup: group }, + ); const tilt = await runner( 'move_camera', { motion: 'tilt', pitchDeg: -45 }, @@ -1084,7 +1208,11 @@ test('a motion in a later reply runs after a fly-to that found nothing', async ( dataManager: { layers: new Map(), getAll: () => [] }, searchNavigation: async () => null, }); - await runner('fly_to_location', { query: 'Xyzzyville' }, { reply: { turn: 1 } }); + await runner( + 'fly_to_location', + { query: 'Xyzzyville' }, + { reply: { turn: 1 } }, + ); const pan = await runner( 'move_camera', { motion: 'pan', direction: 'left' }, @@ -1104,7 +1232,10 @@ test('a motion runs at a flight of its reply that landed after another lookup fo }); const reply = { turn: 1 }; await runner('fly_to_location', { query: 'Xyzzyville' }, { reply }); - assert.equal((await runner('fly_to_location', { locationId: 'austin' }, { reply })).ok, true); + assert.equal( + (await runner('fly_to_location', { locationId: 'austin' }, { reply })).ok, + true, + ); flights[0].complete(); const pan = await runner( 'move_camera', @@ -1123,7 +1254,10 @@ test('a motion queued behind a fly-to yields to a search started during the flig styleManager, dataManager: { layers: new Map(), getAll: () => [] }, }); - assert.equal((await runner('fly_to_location', { locationId: 'austin' })).ok, true); + assert.equal( + (await runner('fly_to_location', { locationId: 'austin' })).ok, + true, + ); const moved = runner('move_camera', { motion: 'orbit' }); await new Promise((resolve) => setTimeout(resolve, 0)); const search = panelSearch(); @@ -1143,9 +1277,10 @@ test('a motion behind a geocoded fly-to yields to a search started while it flie viewer, styleManager, dataManager: { layers: new Map(), getAll: () => [] }, - searchNavigation: (_viewer, query, options) => new Promise((resolve) => { - searches.push({ query, options, resolve }); - }), + searchNavigation: (_viewer, query, options) => + new Promise((resolve) => { + searches.push({ query, options, resolve }); + }), }); const fly = runner('fly_to_location', { query: 'Place A' }); const moved = runner('move_camera', { motion: 'orbit' }); @@ -1162,14 +1297,18 @@ test('a motion behind a geocoded fly-to yields to a search started while it flie test('a search before the fly-to does not drop the motion queued behind it', async (t) => { t.after(() => interruptCameraMotion('test-cleanup')); - const { viewer, styleManager, flights, panelSearch } = tiltAfterFlightHarness(); + const { viewer, styleManager, flights, panelSearch } = + tiltAfterFlightHarness(); const runner = createGevActionRunner({ viewer, styleManager, dataManager: { layers: new Map(), getAll: () => [] }, }); panelSearch(); - assert.equal((await runner('fly_to_location', { locationId: 'austin' })).ok, true); + assert.equal( + (await runner('fly_to_location', { locationId: 'austin' })).ok, + true, + ); const moved = runner('move_camera', { motion: 'tilt', pitchDeg: -45 }); await new Promise((resolve) => setTimeout(resolve, 0)); flights[0].complete(); @@ -1187,7 +1326,10 @@ test('a fly-to that stops a running motion says so', async (t) => { dataManager: { layers: new Map(), getAll: () => [] }, }); // The model sent the orbit first, so it ran at once. - const orbit = await runner('move_camera', { motion: 'orbit', mode: 'continuous' }); + const orbit = await runner('move_camera', { + motion: 'orbit', + mode: 'continuous', + }); assert.equal(orbit.ok, true); const fly = await runner('fly_to_location', { locationId: 'austin' }); assert.equal(fly.ok, true); @@ -1203,7 +1345,10 @@ test('bad move_camera arguments are refused without waiting for a flight', async styleManager, dataManager: { layers: new Map(), getAll: () => [] }, }); - assert.equal((await runner('fly_to_location', { locationId: 'austin' })).ok, true); + assert.equal( + (await runner('fly_to_location', { locationId: 'austin' })).ok, + true, + ); const moved = runner('move_camera', { motion: 'pan' }); const movedDone = settledYet(moved); await new Promise((resolve) => setTimeout(resolve, 0)); @@ -4742,7 +4887,7 @@ test('a lost cross-mode switch reports every mode field in the shared vocabulary styleManager, dataManager: { layers: new Map(), getAll: () => [] }, }); - const result = await runner('set_context_mode', { mode: 'space-missions' }); + const result = await runner('set_context_mode', { mode: 'contacts' }); assert.equal(result.mode, 'off'); assert.equal(result.modeInternal, null); assert.equal( @@ -4760,6 +4905,141 @@ test('a lost cross-mode switch reports every mode field in the shared vocabulary ); }); +/** A runner over one Space Missions layer whose switch answers `enable`. */ +function spaceMissionsVoiceRig({ + enable = true, + cockpit = false, + missionsOn = false, + contextMode = null, +} = {}) { + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; + const calls = { setEnabled: [], panels: [], contextModes: [], waits: 0 }; + let satellitesOn = true; + const missions = { + id: 'rocket-launches', + name: 'Space Missions (30d)', + async waitForSatelliteIntents() { + calls.waits += 1; + missionsOn = false; + return true; + }, + }; + const dataManager = { + layers: new Map([ + ['rocket-launches', { module: missions }], + ['satellites', { module: { id: 'satellites', name: 'Satellites' } }], + ]), + getAll: () => [ + { id: 'rocket-launches', name: missions.name, enabled: missionsOn }, + { id: 'satellites', name: 'Satellites', enabled: satellitesOn }, + ], + isEnabled: (id) => (id === 'rocket-launches' ? missionsOn : satellitesOn), + async setEnabled(id, enabled, options) { + calls.setEnabled.push([id, enabled, options?.origin]); + if (id === 'rocket-launches') missionsOn = enable && enabled; + else satellitesOn = enabled; + return id === 'rocket-launches' ? enable || !enabled : true; + }, + }; + const styleManager = { + getContextModeState: () => ({ + mode: contextMode, + active: Boolean(contextMode), + }), + getCockpitState: () => ({ active: cockpit }), + setPanelCollapsed: (...args) => calls.panels.push(args), + async setContextMode(mode) { + calls.contextModes.push(mode); + return { ok: true, mode }; + }, + }; + const runner = createGevActionRunner({ + viewer: { + clock: { onTick: { addEventListener: () => () => {} } }, + scene: { canvas: { addEventListener() {}, removeEventListener() {} } }, + camera: { moveEnd: { addEventListener() {} } }, + }, + styleManager, + dataManager, + }); + return { calls, runner }; +} + +test('set_context_mode space-missions switches the layer on and opens its panel', async () => { + for (const mode of ['space-missions', 'missions', 'space mission']) { + const { calls, runner } = spaceMissionsVoiceRig(); + const result = await runner('set_context_mode', { mode }); + assert.equal(result.ok, true, mode); + assert.equal(result.action, 'set_context_mode'); + assert.equal(result.mode, 'space-missions'); + assert.equal(result.layerId, 'rocket-launches'); + assert.deepEqual( + calls.contextModes, + [], + 'Space Missions is not a Context mode', + ); + assert.deepEqual(calls.setEnabled, [['rocket-launches', true, 'voice']]); + assert.deepEqual(calls.panels, [ + ['space-missions-panel', false, { explicit: true }], + ]); + } +}); + +test('set_context_mode off leaves Space Missions when no Context mode is on', async () => { + const { calls, runner } = spaceMissionsVoiceRig({ missionsOn: true }); + const result = await runner('set_context_mode', { mode: 'off' }); + assert.equal(result.ok, true); + assert.equal(result.mode, 'off'); + assert.deepEqual(calls.setEnabled, [['rocket-launches', false, 'voice']]); + assert.deepEqual(calls.contextModes, [], 'Context is not asked to change'); +}); + +test('set_context_mode off still ends Contacts first and leaves Space Missions on', async () => { + const { calls, runner } = spaceMissionsVoiceRig({ + missionsOn: true, + contextMode: 'flights', + }); + await runner('set_context_mode', { mode: 'off' }); + assert.deepEqual(calls.contextModes, [null]); + assert.deepEqual(calls.setEnabled, []); +}); + +test('set_context_mode space-missions leaves the panel shut under the Cockpit', async () => { + const { calls, runner } = spaceMissionsVoiceRig({ cockpit: true }); + const result = await runner('set_context_mode', { mode: 'space-missions' }); + assert.equal(result.ok, true, 'the layer still switches on'); + assert.deepEqual(calls.setEnabled, [['rocket-launches', true, 'voice']]); + assert.deepEqual( + calls.panels, + [], + 'no panel write while the Cockpit owns the screen', + ); +}); + +test('a Space Missions start that fails opens no panel and says so', async () => { + const { calls, runner } = spaceMissionsVoiceRig({ enable: false }); + const result = await runner('set_context_mode', { mode: 'space-missions' }); + assert.equal(result.ok, false); + assert.equal(result.action, 'set_context_mode'); + assert.match(result.error, /Could not enable/); + assert.deepEqual(calls.panels, []); + assert.deepEqual(calls.contextModes, []); +}); + +test('a voice Satellites OFF waits for Space Missions to finish reacting', async () => { + const { calls, runner } = spaceMissionsVoiceRig(); + const result = await runner('set_layer_visibility', { + layerId: 'satellites', + enabled: false, + }); + assert.equal(result.ok, true); + assert.equal(calls.waits, 1); +}); + test('an absent secondary mode stays absent instead of claiming to be off', async () => { globalThis.window = globalThis.window || { clearTimeout, @@ -6834,12 +7114,16 @@ function createStreetLevelHarness({ const lookups = []; const origins = []; const revealed = []; - const { viewer, styleManager, currentGeneration, panelSearch } = createVoiceNavigationHarness(); + const { viewer, styleManager, currentGeneration, panelSearch } = + createVoiceNavigationHarness(); // Who owns the camera: the shell's navigation stamps and globe gestures. Object.defineProperty(styleManager, '_navigationGeneration', { get: () => currentGeneration(), }); - viewer.scene.canvas = Object.assign(new EventTarget(), { clientWidth: 1200, clientHeight: 800 }); + viewer.scene.canvas = Object.assign(new EventTarget(), { + clientWidth: 1200, + clientHeight: 800, + }); let completeFlight = null; viewer.camera.lookAt = () => {}; viewer.camera.flyToBoundingSphere = (_sphere, options) => { @@ -6874,7 +7158,11 @@ function createStreetLevelHarness({ configured, keyRequired: keyRequired || keyRejected, keyRejected, - error: keyRejected ? KEY_REJECTED_MESSAGE : keyRequired ? `${names[id]} needs its key` : null, + error: keyRejected + ? KEY_REJECTED_MESSAGE + : keyRequired + ? `${names[id]} needs its key` + : null, groundClick: id === 'google', billed: id === 'google', available: id !== 'google' || stack === 'photoreal', @@ -6882,7 +7170,9 @@ function createStreetLevelHarness({ : null, getUIState: () => ({ providers: ['mapillary', 'google'] - .filter((id) => id !== 'google' || (stack === 'photoreal' && listGoogle)) + .filter( + (id) => id !== 'google' || (stack === 'photoreal' && listGoogle), + ) .map((id) => ({ id, name: id === 'google' ? 'Google Street View' : 'Mapillary', @@ -6899,14 +7189,23 @@ function createStreetLevelHarness({ }), closeViewer() { order.push('close'); - Object.assign(street, { open: false, imageId: null, error: null, nearestOutcome: null }); + Object.assign(street, { + open: false, + imageId: null, + error: null, + nearestOutcome: null, + }); }, armNearest(point, options) { - order.push(`arm:${options.providerIds.join('+')}:${options.radiusM ?? 'default'}:${point ? `${point.lat},${point.lon}` : 'view-centre'}`); + order.push( + `arm:${options.providerIds.join('+')}:${options.radiusM ?? 'default'}:${point ? `${point.lat},${point.lon}` : 'view-centre'}`, + ); }, async openNearest(point, options) { lookups.push({ point, ...options }); - order.push(`open:${options.providerIds.join('+')}:${options.radiusM ?? 'default'}:${options.frame}${point ? '' : ':view-centre'}`); + order.push( + `open:${options.providerIds.join('+')}:${options.radiusM ?? 'default'}:${options.frame}${point ? '' : ':view-centre'}`, + ); if (options.signal?.aborted) return false; if (duringLookup) { const effect = duringLookup(); @@ -6934,7 +7233,8 @@ function createStreetLevelHarness({ } if (!nearest) { closeReplaced(); - street.nearestOutcome = options.aim === 'screen-centre' && sky ? 'sky' : 'empty'; + street.nearestOutcome = + options.aim === 'screen-centre' && sky ? 'sky' : 'empty'; street.error = `No street-level imagery within ${options.radiusM ?? 50} m of ${point ? 'that point' : 'the view centre'}`; return false; } @@ -6951,7 +7251,12 @@ function createStreetLevelHarness({ getLayerParams: () => ({ ...params }), setLayerParams(id, next, { origin }) { origins.push(origin); - order.push(`params:${Object.entries(next).filter(([, on]) => on).map(([k]) => k).join('+')}:${origin}`); + order.push( + `params:${Object.entries(next) + .filter(([, on]) => on) + .map(([k]) => k) + .join('+')}:${origin}`, + ); if (paramsAccepted === false) return false; if (!lightFails) params = { ...params, ...next }; return true; @@ -6966,7 +7271,8 @@ function createStreetLevelHarness({ }, getAll: () => [{ id: 'street-level', name: 'Street Level', enabled }], }; - styleManager.setPanelCollapsed = (id, collapsed) => revealed.push(`collapse:${id}:${collapsed}`); + styleManager.setPanelCollapsed = (id, collapsed) => + revealed.push(`collapse:${id}:${collapsed}`); styleManager.revealPanel = (id) => revealed.push(`reveal:${id}`); const runner = createGevActionRunner({ viewer, styleManager, dataManager }); return { @@ -6990,7 +7296,8 @@ function createStreetLevelHarness({ function withCamera(harness) { harness.dataManager.layers.set('cctv', { module: { - findByQuery: (id) => (id === 'cam-9' ? { latitude: 38.58, longitude: -121.5 } : null), + findByQuery: (id) => + id === 'cam-9' ? { latitude: 38.58, longitude: -121.5 } : null, }, }); const wasEnabled = harness.dataManager.isEnabled; @@ -6999,11 +7306,23 @@ function withCamera(harness) { } test('show_street_level flies first, then switches the map, lights the source, turns the layer on and opens the nearest photo', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; const { runner, order, finishFlight } = createStreetLevelHarness(); - const pending = runner('show_street_level', { latitude: 38.5799, longitude: -121.4937, provider: 'google' }); + const pending = runner('show_street_level', { + latitude: 38.5799, + longitude: -121.4937, + provider: 'google', + }); await new Promise((resolve) => setImmediate(resolve)); - assert.deepEqual(order, ['fly'], 'nothing changes until the place is reached'); + assert.deepEqual( + order, + ['fly'], + 'nothing changes until the place is reached', + ); finishFlight(); const result = await pending; assert.equal(result.ok, true, result.error); @@ -7022,7 +7341,10 @@ test('show_street_level flies first, then switches the map, lights the source, t // A name given with its coordinates is what the answer says. const named = createStreetLevelHarness(); const naming = named.runner('show_street_level', { - query: 'Capitol Mall', latitude: 38.5799, longitude: -121.4937, provider: 'google', + query: 'Capitol Mall', + latitude: 38.5799, + longitude: -121.4937, + provider: 'google', }); await new Promise((resolve) => setImmediate(resolve)); named.finishFlight(); @@ -7030,8 +7352,15 @@ test('show_street_level flies first, then switches the map, lights the source, t }); test('show_street_level on Mapillary keeps the map, searches at the default radius and skips what is already on', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; - const { runner, order } = createStreetLevelHarness({ enabled: true, activeStack: 'osm' }); + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; + const { runner, order } = createStreetLevelHarness({ + enabled: true, + activeStack: 'osm', + }); const result = await runner('show_street_level', { latitude: 38.58, longitude: -121.49, @@ -7039,68 +7368,126 @@ test('show_street_level on Mapillary keeps the map, searches at the default radi fly: false, }); assert.equal(result.ok, true, result.error); - assert.deepEqual(order, ['params:mapillary:voice', 'open:mapillary:default:false']); + assert.deepEqual(order, [ + 'params:mapillary:voice', + 'open:mapillary:default:false', + ]); assert.equal(result.flew, false); }); test('show_street_level without a source uses the one lit in the panel', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; const { runner, order } = createStreetLevelHarness({ activeStack: 'photoreal', lit: { mapillary: false, google: true }, enabled: true, }); - const result = await runner('show_street_level', { latitude: 1, longitude: 2, fly: false }); + const result = await runner('show_street_level', { + latitude: 1, + longitude: 2, + fly: false, + }); assert.equal(result.ok, true, result.error); assert.equal(result.provider, 'google'); assert.deepEqual(order, ['params:google:voice', 'open:google:250:false']); }); test('show_street_level reports each stage it could not pass', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; - const centre = createStreetLevelHarness({ enabled: true, activeStack: 'photoreal' }); + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; + const centre = createStreetLevelHarness({ + enabled: true, + activeStack: 'photoreal', + }); const none = await centre.runner('show_street_level', { provider: 'google' }); assert.equal(none.ok, true, 'no place at all means the view centre'); assert.equal(none.label, 'the view centre'); - assert.deepEqual(centre.order, ['params:google:voice', 'open:google:250:false:view-centre']); + assert.deepEqual(centre.order, [ + 'params:google:voice', + 'open:google:250:false:view-centre', + ]); - const offGlobe = createStreetLevelHarness({ enabled: true, activeStack: 'photoreal' }); - const outOfRange = await offGlobe.runner('show_street_level', { latitude: 95, longitude: 2, provider: 'google' }); + const offGlobe = createStreetLevelHarness({ + enabled: true, + activeStack: 'photoreal', + }); + const outOfRange = await offGlobe.runner('show_street_level', { + latitude: 95, + longitude: 2, + provider: 'google', + }); assert.deepEqual([outOfRange.ok, outOfRange.stage], [false, 'location']); assert.deepEqual(offGlobe.order, [], 'nothing flies, switches or looks up'); const unknown = await createStreetLevelHarness().runner('show_street_level', { - latitude: 1, longitude: 2, provider: 'openstreetcam', fly: false, + latitude: 1, + longitude: 2, + provider: 'openstreetcam', + fly: false, }); assert.deepEqual([unknown.ok, unknown.stage], [false, 'provider']); assert.match(unknown.error, /openstreetcam/); - const keylessHarness = createStreetLevelHarness({ enabled: true, keyRequired: true }); + const keylessHarness = createStreetLevelHarness({ + enabled: true, + keyRequired: true, + }); const keyless = await keylessHarness.runner('show_street_level', { - latitude: 1, longitude: 2, provider: 'google', fly: false, + latitude: 1, + longitude: 2, + provider: 'google', + fly: false, }); assert.deepEqual([keyless.ok, keyless.stage], [false, 'key']); assert.match(keyless.error, /needs its key/); assert.equal(keyless.providerName, 'Google Street View'); - assert.deepEqual(keylessHarness.order, [], 'a keyless source changes nothing: no flight, no map, no switch'); + assert.deepEqual( + keylessHarness.order, + [], + 'a keyless source changes nothing: no flight, no map, no switch', + ); - const refusedSwitch = await createStreetLevelHarness({ enabled: true, paramsAccepted: false }).runner( - 'show_street_level', - { latitude: 1, longitude: 2, provider: 'google', fly: false }, + const refusedSwitch = await createStreetLevelHarness({ + enabled: true, + paramsAccepted: false, + }).runner('show_street_level', { + latitude: 1, + longitude: 2, + provider: 'google', + fly: false, + }); + assert.deepEqual( + [refusedSwitch.ok, refusedSwitch.stage], + [false, 'provider'], ); - assert.deepEqual([refusedSwitch.ok, refusedSwitch.stage], [false, 'provider']); assert.match(refusedSwitch.error, /could not be switched on/); - const empty = await createStreetLevelHarness({ enabled: true, nearest: null }).runner( - 'show_street_level', - { latitude: 1, longitude: 2, provider: 'google', fly: false }, - ); + const empty = await createStreetLevelHarness({ + enabled: true, + nearest: null, + }).runner('show_street_level', { + latitude: 1, + longitude: 2, + provider: 'google', + fly: false, + }); assert.deepEqual([empty.ok, empty.stage], [false, 'imagery']); assert.match(empty.error, /within 250 m/); }); test('show_street_level stops at the map when the source’s map is refused, before touching the panel', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; const { layer, order } = createStreetLevelHarness({ enabled: true }); const reason = 'Google 3D needs GOOGLE_MAPS_API_KEY'; const dataManager = { @@ -7112,21 +7499,47 @@ test('show_street_level stops at the map when the source’s map is refused, bef }; const { viewer, styleManager } = createVoiceNavigationHarness(); styleManager.mapStackController = { getActiveId: () => 'osm' }; - styleManager.setMapStack = async () => ({ ok: false, activeStack: 'osm', error: reason }); + styleManager.setMapStack = async () => ({ + ok: false, + activeStack: 'osm', + error: reason, + }); const runner = createGevActionRunner({ viewer, styleManager, dataManager }); - const result = await runner('show_street_level', { latitude: 1, longitude: 2, provider: 'google', fly: false }); - assert.deepEqual([result.ok, result.stage, result.error], [false, 'map', reason]); - assert.deepEqual(order, [], 'the source is not switched when its map is refused'); + const result = await runner('show_street_level', { + latitude: 1, + longitude: 2, + provider: 'google', + fly: false, + }); + assert.deepEqual( + [result.ok, result.stage, result.error], + [false, 'map', reason], + ); + assert.deepEqual( + order, + [], + 'the source is not switched when its map is refused', + ); }); test('show_street_level opens photos of a numbered item or a pointed spot through its entity', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; const { runner, order, finishFlight } = withCamera( createStreetLevelHarness({ enabled: true, activeStack: 'photoreal' }), ); const pending = runner('show_street_level', { provider: 'google', - entity: { layerId: 'cctv', id: 'cam-9', label: 'Camera 9', lat: 38.58, lon: -121.5 }, + entity: { + layerId: 'cctv', + id: 'cam-9', + label: 'Camera 9', + lat: 38.58, + lon: -121.5, + }, }); await new Promise((resolve) => setImmediate(resolve)); assert.deepEqual(order, ['fly'], 'the entity position is flown to'); @@ -7134,14 +7547,25 @@ test('show_street_level opens photos of a numbered item or a pointed spot throug const result = await pending; assert.equal(result.ok, true, result.error); assert.equal(result.label, 'Camera 9'); - assert.deepEqual(order, ['fly', 'params:google:voice', 'open:google:250:false']); + assert.deepEqual(order, [ + 'fly', + 'params:google:voice', + 'open:google:250:false', + ]); }); test('show_street_level hands the point from a named place, a preset and a curated POI to the lookup', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; const points = []; const make = () => { - const harness = createStreetLevelHarness({ enabled: true, activeStack: 'osm' }); + const harness = createStreetLevelHarness({ + enabled: true, + activeStack: 'osm', + }); const open = harness.layer.openNearest; harness.layer.openNearest = async (point, options) => { points.push(point); @@ -7154,7 +7578,10 @@ test('show_street_level hands the point from a named place, a preset and a curat const viewerFor = () => ({ ...createVoiceNavigationHarness().viewer }); const runnerWithSearch = createGevActionRunner({ viewer: viewerFor(), - styleManager: { mapStackController: { getActiveId: () => 'osm' }, setMapStack: async () => ({ ok: true }) }, + styleManager: { + mapStackController: { getActiveId: () => 'osm' }, + setMapStack: async () => ({ ok: true }), + }, dataManager: { layers: new Map([['street-level', { module: named.layer }]]), isEnabled: () => true, @@ -7164,16 +7591,28 @@ test('show_street_level hands the point from a named place, a preset and a curat }, searchNavigation: async (_viewer, query, options) => { options.onComplete?.(); - return { label: `${query}, CA`, latitude: 38.5799, longitude: -121.4937, navigationMode: 'precise-place', rangeM: 250 }; + return { + label: `${query}, CA`, + latitude: 38.5799, + longitude: -121.4937, + navigationMode: 'precise-place', + rangeM: 250, + }; }, }); - const geocoded = await runnerWithSearch('show_street_level', { query: '10th Street, Sacramento', provider: 'mapillary' }); + const geocoded = await runnerWithSearch('show_street_level', { + query: '10th Street, Sacramento', + provider: 'mapillary', + }); assert.equal(geocoded.ok, true, geocoded.error); assert.equal(geocoded.label, '10th Street, Sacramento, CA'); assert.deepEqual(points.at(-1), { lat: 38.5799, lon: -121.4937 }); // A curated POI and a city preset fly to their hand-tuned poses and report them. for (const [args, expected] of [ - [{ query: 'Golden Gate Bridge', provider: 'mapillary' }, { lat: 37.8199, lon: -122.4783 }], + [ + { query: 'Golden Gate Bridge', provider: 'mapillary' }, + { lat: 37.8199, lon: -122.4783 }, + ], [{ query: 'austin', provider: 'mapillary' }, null], ]) { const harness = make(); @@ -7184,13 +7623,24 @@ test('show_street_level hands the point from a named place, a preset and a curat assert.equal(result.ok, true, `${args.query}: ${result.error}`); const point = points.at(-1); if (expected) assert.deepEqual(point, expected); - else assert.ok(Number.isFinite(point.lat) && Number.isFinite(point.lon), 'a preset flight reports its point'); + else + assert.ok( + Number.isFinite(point.lat) && Number.isFinite(point.lon), + 'a preset flight reports its point', + ); } }); test('show_street_level retires its lookup when the turn is superseded, and says so', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; - const { runner, order, layer } = createStreetLevelHarness({ enabled: true, activeStack: 'photoreal' }); + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; + const { runner, order, layer } = createStreetLevelHarness({ + enabled: true, + activeStack: 'photoreal', + }); const controller = new AbortController(); let currentTurn = true; layer.openNearest = async (_point, options) => { @@ -7204,33 +7654,68 @@ test('show_street_level retires its lookup when the turn is superseded, and says { latitude: 1, longitude: 2, provider: 'google', fly: false }, { signal: controller.signal, isCurrent: () => currentTurn }, ); - assert.deepEqual([result.ok, result.cancelled, result.stage], [false, true, 'imagery']); + assert.deepEqual( + [result.ok, result.cancelled, result.stage], + [false, true, 'imagery'], + ); assert.doesNotMatch(result.error, /No .* imagery/); - assert.ok(order.includes('open:signal:true'), 'the lookup gets the turn signal'); + assert.ok( + order.includes('open:signal:true'), + 'the lookup gets the turn signal', + ); }); test('show_street_level with autoOpen:false arms a billed source and leaves the load to a click; a free source still opens', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; - const armedHarness = createStreetLevelHarness({ enabled: true, activeStack: 'osm' }); + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; + const armedHarness = createStreetLevelHarness({ + enabled: true, + activeStack: 'osm', + }); const armed = await armedHarness.runner('show_street_level', { - latitude: 38.5799, longitude: -121.4937, provider: 'google', fly: false, autoOpen: false, + latitude: 38.5799, + longitude: -121.4937, + provider: 'google', + fly: false, + autoOpen: false, }); assert.equal(armed.ok, true, armed.error); assert.equal(armed.armed, true); assert.equal(armed.imageId, undefined); assert.deepEqual( armedHarness.order, - ['map:photoreal', 'params:google:voice', 'arm:google:250:38.5799,-121.4937'], + [ + 'map:photoreal', + 'params:google:voice', + 'arm:google:250:38.5799,-121.4937', + ], 'map and source are ready, the lookup is armed at the point, nothing is loaded', ); assert.match(armed.say, /^Google Street View is ready at .*press OPEN/); assert.deepEqual( { ...armed, say: undefined, display: undefined }, - { ok: true, action: 'show_street_level', provider: 'google', providerName: 'Google Street View', label: '38.5799, -121.4937', armed: true, flew: false, say: undefined, display: undefined }, + { + ok: true, + action: 'show_street_level', + provider: 'google', + providerName: 'Google Street View', + label: '38.5799, -121.4937', + armed: true, + flew: false, + say: undefined, + display: undefined, + }, ); const free = createStreetLevelHarness({ enabled: true, activeStack: 'osm' }); const opened = await free.runner('show_street_level', { - latitude: 38.5799, longitude: -121.4937, provider: 'mapillary', fly: false, autoOpen: false, + latitude: 38.5799, + longitude: -121.4937, + provider: 'mapillary', + fly: false, + autoOpen: false, }); assert.equal(opened.ok, true, opened.error); assert.equal(opened.armed, undefined); @@ -7238,38 +7723,81 @@ test('show_street_level with autoOpen:false arms a billed source and leaves the }); test('show_street_level tells a failed enable, a delisted source, a key refused mid-lookup and a layer switched off apart', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; const at = { latitude: 1, longitude: 2, provider: 'google', fly: false }; - const notEnabled = await createStreetLevelHarness({ activeStack: 'photoreal', enableResult: false }).runner('show_street_level', at); - assert.deepEqual([notEnabled.ok, notEnabled.stage, notEnabled.cancelled], [false, 'layer', false]); + const notEnabled = await createStreetLevelHarness({ + activeStack: 'photoreal', + enableResult: false, + }).runner('show_street_level', at); + assert.deepEqual( + [notEnabled.ok, notEnabled.stage, notEnabled.cancelled], + [false, 'layer', false], + ); assert.match(notEnabled.say, /Couldn't turn on Street Level/); - const delisted = await createStreetLevelHarness({ enabled: true, activeStack: 'photoreal', listGoogle: false }).runner('show_street_level', at); + const delisted = await createStreetLevelHarness({ + enabled: true, + activeStack: 'photoreal', + listGoogle: false, + }).runner('show_street_level', at); assert.deepEqual([delisted.ok, delisted.stage], [false, 'provider']); assert.equal(delisted.error, 'not on this map'); - const refused = await createStreetLevelHarness({ enabled: true, activeStack: 'photoreal', duringLookup: () => 'key-rejected' }).runner('show_street_level', at); - assert.deepEqual([refused.ok, refused.stage, refused.keyRejected], [false, 'key', true]); + const refused = await createStreetLevelHarness({ + enabled: true, + activeStack: 'photoreal', + duringLookup: () => 'key-rejected', + }).runner('show_street_level', at); + assert.deepEqual( + [refused.ok, refused.stage, refused.keyRejected], + [false, 'key', true], + ); assert.equal(refused.say, 'Google Street View refused its key.'); - const switchedOff = await createStreetLevelHarness({ enabled: true, activeStack: 'photoreal', duringLookup: () => 'layer-off' }).runner('show_street_level', at); - assert.deepEqual([switchedOff.ok, switchedOff.stage, switchedOff.cancelled], [false, 'imagery', true]); - assert.equal(switchedOff.say, undefined, 'a request the user withdrew is not spoken'); + const switchedOff = await createStreetLevelHarness({ + enabled: true, + activeStack: 'photoreal', + duringLookup: () => 'layer-off', + }).runner('show_street_level', at); + assert.deepEqual( + [switchedOff.ok, switchedOff.stage, switchedOff.cancelled], + [false, 'imagery', true], + ); + assert.equal( + switchedOff.say, + undefined, + 'a request the user withdrew is not spoken', + ); // A source whose status call says it is not configured is key-gated even // before its coverage reports a missing key. - const unconfigured = createStreetLevelHarness({ enabled: true, activeStack: 'photoreal', configured: false }); + const unconfigured = createStreetLevelHarness({ + enabled: true, + activeStack: 'photoreal', + configured: false, + }); const gated = await unconfigured.runner('show_street_level', at); assert.deepEqual([gated.ok, gated.stage], [false, 'key']); assert.deepEqual(unconfigured.order, [], 'nothing changed'); }); test('show_street_level reports a geocoder that throws as its location stage', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; const h = createStreetLevelHarness({ enabled: true, activeStack: 'osm' }); const runner = createGevActionRunner({ viewer: createVoiceNavigationHarness().viewer, - styleManager: { mapStackController: { getActiveId: () => 'osm' }, setMapStack: async () => ({ ok: true }) }, + styleManager: { + mapStackController: { getActiveId: () => 'osm' }, + setMapStack: async () => ({ ok: true }), + }, dataManager: h.dataManager, placeSearch: { geocode: async () => { @@ -7277,76 +7805,157 @@ test('show_street_level reports a geocoder that throws as its location stage', a }, }, }); - const result = await runner('show_street_level', { query: 'Capitol Mall', provider: 'mapillary' }); + const result = await runner('show_street_level', { + query: 'Capitol Mall', + provider: 'mapillary', + }); assert.deepEqual([result.ok, result.stage], [false, 'location']); assert.equal(result.error, 'Could not arrive at Capitol Mall'); - assert.deepEqual(h.order.filter((step) => /^(params|open|arm)/.test(step)), [], 'nothing switched or looked up'); + assert.deepEqual( + h.order.filter((step) => /^(params|open|arm)/.test(step)), + [], + 'nothing switched or looked up', + ); }); test('show_street_level reports a flight that lands without a position', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; const hit = createStreetLevelHarness({ enabled: true, activeStack: 'osm' }); // A flight that reports no coordinates cannot be followed by a lookup. const noPoint = createGevActionRunner({ viewer: createVoiceNavigationHarness().viewer, - styleManager: { mapStackController: { getActiveId: () => 'osm' }, setMapStack: async () => ({ ok: true }) }, + styleManager: { + mapStackController: { getActiveId: () => 'osm' }, + setMapStack: async () => ({ ok: true }), + }, dataManager: hit.dataManager, searchNavigation: async (_viewer, query, options) => { options.onComplete?.(); return { label: query, navigationMode: 'city-overview', rangeM: null }; }, }); - const unplaced = await noPoint('show_street_level', { query: 'Somewhere', provider: 'mapillary' }); + const unplaced = await noPoint('show_street_level', { + query: 'Somewhere', + provider: 'mapillary', + }); assert.deepEqual([unplaced.ok, unplaced.stage], [false, 'location']); assert.match(unplaced.error, /no position/); }); test('fly_to_location reports the overview centre for a city framed as a whole, and the first POI for a close view', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; const { viewer, styleManager } = createVoiceNavigationHarness(); viewer.camera.lookAt = () => {}; viewer.camera.flyTo = (options) => options.complete?.(); viewer.camera.flyToBoundingSphere = (_s, options) => options.complete?.(); - styleManager.runImmediateLocationNavigation = (navigate) => styleManager.runImmediateNavigation('location', navigate); - const runner = createGevActionRunner({ viewer, styleManager, dataManager: { layers: new Map(), getAll: () => [] } }); + styleManager.runImmediateLocationNavigation = (navigate) => + styleManager.runImmediateNavigation('location', navigate); + const runner = createGevActionRunner({ + viewer, + styleManager, + dataManager: { layers: new Map(), getAll: () => [] }, + }); const overview = await runner('fly_to_location', { locationId: 'austin' }); assert.equal(overview.ok, true); - assert.ok(Math.abs(overview.latitude - 30.31) < 0.001, String(overview.latitude)); - assert.ok(Math.abs(overview.longitude - -97.75) < 0.001, String(overview.longitude)); - const close = await runner('fly_to_location', { locationId: 'austin', viewMode: 'close' }); + assert.ok( + Math.abs(overview.latitude - 30.31) < 0.001, + String(overview.latitude), + ); + assert.ok( + Math.abs(overview.longitude - -97.75) < 0.001, + String(overview.longitude), + ); + const close = await runner('fly_to_location', { + locationId: 'austin', + viewMode: 'close', + }); assert.deepEqual([close.latitude, close.longitude], [30.2747, -97.7403]); }); test('show_street_level arms the view centre when a billed link names no place, and keeps the flight label when it flew', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; - const centre = createStreetLevelHarness({ enabled: true, activeStack: 'photoreal' }); - const armed = await centre.runner('show_street_level', { provider: 'google', autoOpen: false }); + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; + const centre = createStreetLevelHarness({ + enabled: true, + activeStack: 'photoreal', + }); + const armed = await centre.runner('show_street_level', { + provider: 'google', + autoOpen: false, + }); assert.equal(armed.ok, true, armed.error); assert.equal(armed.armed, true); - assert.deepEqual(centre.order, ['params:google:voice', 'arm:google:250:view-centre'], 'armed at the view centre, nothing opened'); - const flown = createStreetLevelHarness({ enabled: true, activeStack: 'photoreal' }); - const pending = flown.runner('show_street_level', { latitude: 38.5799, longitude: -121.4937, provider: 'google', autoOpen: false }); + assert.deepEqual( + centre.order, + ['params:google:voice', 'arm:google:250:view-centre'], + 'armed at the view centre, nothing opened', + ); + const flown = createStreetLevelHarness({ + enabled: true, + activeStack: 'photoreal', + }); + const pending = flown.runner('show_street_level', { + latitude: 38.5799, + longitude: -121.4937, + provider: 'google', + autoOpen: false, + }); await new Promise((resolve) => setImmediate(resolve)); flown.finishFlight(); const result = await pending; assert.equal(result.armed, true); assert.equal(result.flew, true); assert.equal(result.location, '38.5799, -121.4937'); - assert.ok(!flown.order.some((entry) => entry.startsWith('open:')), 'no load after the flight'); + assert.ok( + !flown.order.some((entry) => entry.startsWith('open:')), + 'no load after the flight', + ); }); test('show_street_level says "refused its key" when Google already refused it, and fails when the source will not light', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; - const refusedHarness = createStreetLevelHarness({ enabled: true, keyRejectedAtStart: true }); - const refused = await refusedHarness.runner('show_street_level', { latitude: 1, longitude: 2, provider: 'google', fly: false }); - assert.deepEqual([refused.ok, refused.stage, refused.keyRejected], [false, 'key', true]); + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; + const refusedHarness = createStreetLevelHarness({ + enabled: true, + keyRejectedAtStart: true, + }); + const refused = await refusedHarness.runner('show_street_level', { + latitude: 1, + longitude: 2, + provider: 'google', + fly: false, + }); + assert.deepEqual( + [refused.ok, refused.stage, refused.keyRejected], + [false, 'key', true], + ); assert.equal(refused.error, KEY_REJECTED_MESSAGE); assert.equal(refused.say, 'Google Street View refused its key.'); assert.deepEqual(refusedHarness.order, [], 'nothing changed'); - const dark = await createStreetLevelHarness({ enabled: true, activeStack: 'photoreal', lightFails: true }).runner( - 'show_street_level', - { latitude: 1, longitude: 2, provider: 'google', fly: false }, - ); + const dark = await createStreetLevelHarness({ + enabled: true, + activeStack: 'photoreal', + lightFails: true, + }).runner('show_street_level', { + latitude: 1, + longitude: 2, + provider: 'google', + fly: false, + }); assert.deepEqual([dark.ok, dark.stage], [false, 'provider']); assert.match(dark.error, /could not be switched on/); }); @@ -7354,18 +7963,39 @@ test('show_street_level says "refused its key" when Google already refused it, a test('activeImageryFilter reports only the narrowing filters the lit source honours', async () => { const { activeImageryFilter } = await import('./gevActions.js'); const both = { pano: true, since: true }; - assert.equal(activeImageryFilter({ filter: { pano: 'all', sinceDays: 0 }, filterControls: both }), null); - assert.deepEqual(activeImageryFilter({ filter: { pano: 'pano', sinceDays: 0 }, filterControls: both }), { - pano: 'pano', - label: '360° filter', - }); - assert.deepEqual(activeImageryFilter({ filter: { pano: 'flat', sinceDays: 365 }, filterControls: both }), { - pano: 'flat', - sinceDays: 365, - label: 'flat-photo and SINCE filters', - }); assert.equal( - activeImageryFilter({ filter: { pano: 'pano', sinceDays: 365 }, filterControls: { pano: false, since: false } }), + activeImageryFilter({ + filter: { pano: 'all', sinceDays: 0 }, + filterControls: both, + }), + null, + ); + assert.deepEqual( + activeImageryFilter({ + filter: { pano: 'pano', sinceDays: 0 }, + filterControls: both, + }), + { + pano: 'pano', + label: '360° filter', + }, + ); + assert.deepEqual( + activeImageryFilter({ + filter: { pano: 'flat', sinceDays: 365 }, + filterControls: both, + }), + { + pano: 'flat', + sinceDays: 365, + label: 'flat-photo and SINCE filters', + }, + ); + assert.equal( + activeImageryFilter({ + filter: { pano: 'pano', sinceDays: 365 }, + filterControls: { pano: false, since: false }, + }), null, 'Street View honours neither', ); @@ -7373,19 +8003,46 @@ test('activeImageryFilter reports only the narrowing filters the lit source hono }); test('analyst item display strings are single-line and bounded for voice', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; - const rows = [{ id: 'stable-id', name: 'Şehir\n' + 'x'.repeat(3000), label: 'Town\tStation', operator: 'City\nPD', lat: 30, lon: -97 }]; - const { runner } = manifestRunner({ bikeshare: { getStats: () => ({ count: 1, lastUpdate: Date.now() }), getAnalystRecords: () => rows } }); - const result = await runner('analyst_query', { layers: ['bikeshare'], scope: { kind: 'anywhere' }, limit: 1 }); + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; + const rows = [ + { + id: 'stable-id', + name: 'Şehir\n' + 'x'.repeat(3000), + label: 'Town\tStation', + operator: 'City\nPD', + lat: 30, + lon: -97, + }, + ]; + const { runner } = manifestRunner({ + bikeshare: { + getStats: () => ({ count: 1, lastUpdate: Date.now() }), + getAnalystRecords: () => rows, + }, + }); + const result = await runner('analyst_query', { + layers: ['bikeshare'], + scope: { kind: 'anywhere' }, + limit: 1, + }); assert.equal(result.ok, true); assert.equal(result.items[0].name.length, 180); assert.equal(result.items[0].label, 'Town Station'); assert.equal(result.items[0].id, 'stable-id'); - for (const value of Object.values(result.items[0])) if (typeof value === 'string') assert.doesNotMatch(value, /[\r\n\t]/); + for (const value of Object.values(result.items[0])) + if (typeof value === 'string') assert.doesNotMatch(value, /[\r\n\t]/); }); test('analyst_query keeps canonical IDs raw so numbered references still fly to the station', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; const { viewer, styleManager } = createVoiceNavigationHarness(); const referents = createReferentRegistry(); const longName = 'Station ' + 'é'.repeat(200); @@ -7394,51 +8051,97 @@ test('analyst_query keeps canonical IDs raw so numbered references still fly to { id: spaced, name: spaced, lat: 30.2672, lon: -97.7431 }, { id: longName, name: longName, lat: 30.2711, lon: -97.7437 }, ]; - const bikeshare = { getStats: () => ({ count: stations.length, lastUpdate: Date.now() }), getAnalystRecords: () => stations }; + const bikeshare = { + getStats: () => ({ count: stations.length, lastUpdate: Date.now() }), + getAnalystRecords: () => stations, + }; const runner = createActionRunner({ - viewer, styleManager, + viewer, + styleManager, dataManager: { layers: new Map([['bikeshare', { module: bikeshare }]]), isEnabled: () => true, - getAll: () => [{ id: 'bikeshare', name: 'bikeshare', enabled: true, stats: bikeshare.getStats() }], + getAll: () => [ + { + id: 'bikeshare', + name: 'bikeshare', + enabled: true, + stats: bikeshare.getStats(), + }, + ], }, deixis: { referents }, }); - const listed = await runner('analyst_query', { layers: ['bikeshare'], scope: { kind: 'anywhere' }, limit: 2 }); + const listed = await runner('analyst_query', { + layers: ['bikeshare'], + scope: { kind: 'anywhere' }, + limit: 2, + }); assert.equal(listed.ok, true); const bySpaced = listed.items.find((item) => item.id === spaced); const byLong = listed.items.find((item) => item.id === longName); assert.ok(bySpaced && byLong, 'compact items keep the raw station-name IDs'); - assert.equal(bySpaced.name, 'Congress Ave & 2nd', 'display name is still normalized'); + assert.equal( + bySpaced.name, + 'Congress Ave & 2nd', + 'display name is still normalized', + ); assert.equal(byLong.name.length, 180, 'display name is still bounded'); assert.equal(byLong.id.length, longName.length); const registered = referents.list(); - assert.equal(registered.length, 2, 'the analyst result became the numbered list'); + assert.equal( + registered.length, + 2, + 'the analyst result became the numbered list', + ); for (const ref of registered) { const station = stations.find((row) => row.id === ref.id); assert.ok(station, `referent ${ref.n} keeps the canonical ID`); const flown = await runner('fly_to_location', { referent: ref.n }); - assert.equal(flown.ok, true, `referent ${ref.n} resolves instead of "no longer loaded"`); + assert.equal( + flown.ok, + true, + `referent ${ref.n} resolves instead of "no longer loaded"`, + ); assert.equal(flown.latitude, station.lat); assert.equal(flown.longitude, station.lon); } }); test('analyst_query keeps transit route IDs raw so a follow-up filter still matches', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; for (const routeId of ['Route 17', 'R'.repeat(181)]) { const { viewer, styleManager } = createVoiceNavigationHarness(); const vehicles = [{ id: 'bus-1', routeId, lat: 30, lon: -97 }]; - const transit = { getStats: () => ({ count: 1, lastUpdate: Date.now() }), getAnalystRecords: () => vehicles }; + const transit = { + getStats: () => ({ count: 1, lastUpdate: Date.now() }), + getAnalystRecords: () => vehicles, + }; const runner = createActionRunner({ - viewer, styleManager, + viewer, + styleManager, dataManager: { layers: new Map([['transit', { module: transit }]]), isEnabled: () => true, - getAll: () => [{ id: 'transit', name: 'transit', enabled: true, stats: transit.getStats() }], + getAll: () => [ + { + id: 'transit', + name: 'transit', + enabled: true, + stats: transit.getStats(), + }, + ], }, }); - const listed = await runner('analyst_query', { layers: ['transit'], scope: { kind: 'anywhere' }, limit: 1 }); + const listed = await runner('analyst_query', { + layers: ['transit'], + scope: { kind: 'anywhere' }, + limit: 1, + }); assert.equal(listed.ok, true); assert.equal(listed.items[0].routeId, routeId); const followUp = await runner('analyst_query', { @@ -7446,7 +8149,11 @@ test('analyst_query keeps transit route IDs raw so a follow-up filter still matc filters: [{ field: 'routeId', op: 'eq', value: listed.items[0].routeId }], }); assert.equal(followUp.ok, true); - assert.equal(followUp.count, 1, 'the returned route ID matches the same vehicle'); + assert.equal( + followUp.count, + 1, + 'the returned route ID matches the same vehicle', + ); } }); @@ -7480,6 +8187,106 @@ test('set_panel_open accepts the Authoring name for the scene panel', async () = assert.deepEqual(calls.at(-1), ['scene-panel', false, { explicit: true }]); }); +test('set_panel_open reaches the Space Missions panel by its id or name', async () => { + const calls = []; + const runner = createGevActionRunner({ + viewer: { + clock: { onTick: { addEventListener: () => () => {} } }, + scene: { canvas: { addEventListener() {}, removeEventListener() {} } }, + camera: { + moveEnd: { addEventListener() {} }, + positionWC: Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 1000), + }, + }, + styleManager: { + setPanelCollapsed: (...args) => calls.push(args), + }, + dataManager: { + layers: new Map(), + isEnabled: () => false, + getAll: () => [], + }, + }); + for (const panel of ['space-missions-panel', 'space missions panel']) { + const result = await runner('set_panel_open', { + panelId: panel, + open: false, + }); + assert.equal(result.panelId, 'space-missions-panel', panel); + } + assert.deepEqual(calls.at(-1), [ + 'space-missions-panel', + true, + { explicit: true }, + ]); +}); + +test('set_panel_open opens the Space Missions panel only while its layer is on', async () => { + const calls = []; + let missionsOn = false; + let starting = false; + let cockpit = false; + const runner = createGevActionRunner({ + viewer: { + clock: { onTick: { addEventListener: () => () => {} } }, + scene: { canvas: { addEventListener() {}, removeEventListener() {} } }, + camera: { + moveEnd: { addEventListener() {} }, + positionWC: Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 1000), + }, + }, + styleManager: { + setPanelCollapsed: (...args) => calls.push(args), + revealPanel: (id) => calls.push(['reveal', id]), + getCockpitState: () => ({ active: cockpit }), + }, + dataManager: { + layers: new Map(), + isEnabled: (id) => id === 'rocket-launches' && missionsOn, + isEffectivelyEnabled: (id) => + id === 'rocket-launches' && (missionsOn || starting), + getAll: () => [], + }, + }); + const refused = await runner('set_panel_open', { + panelId: 'space-missions-panel', + open: true, + }); + assert.equal(refused.ok, false); + assert.equal(refused.applied, false); + assert.match(refused.say, /Turn on Space Missions first/); + assert.deepEqual(calls, [], 'no right-rail panel is folded for nothing'); + starting = true; + const early = await runner('set_panel_open', { + panelId: 'space-missions-panel', + open: true, + }); + assert.equal(early.ok, false); + assert.match(early.say, /still starting/); + assert.deepEqual(calls, []); + missionsOn = true; + const opened = await runner('set_panel_open', { + panelId: 'space-missions-panel', + open: true, + }); + assert.equal(opened.ok, true); + // On a phone the Missions sheet shows too. + assert.deepEqual(calls, [ + ['space-missions-panel', false, { explicit: true }], + ['reveal', 'space-missions-panel'], + ]); + // The Cockpit owns the screen: nothing opens and no preference is written. + calls.length = 0; + cockpit = true; + const underCockpit = await runner('set_panel_open', { + panelId: 'space-missions-panel', + open: true, + }); + assert.equal(underCockpit.ok, false); + assert.match(underCockpit.say, /leave the cockpit/); + assert.deepEqual(calls, []); +}); + test('set_panel_open reaches the Utilities panel by its name, Draw or Import', async () => { const calls = []; const runner = createGevActionRunner({ @@ -7532,20 +8339,36 @@ test('a partial analyst card shows one partial chip', () => { }); test('show_street_level superseded during its flight switches nothing', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; const h = createStreetLevelHarness(); let current = true; - const pending = h.runner('show_street_level', { latitude: 38.5799, longitude: -121.4937, provider: 'google' }, { isCurrent: () => current }); + const pending = h.runner( + 'show_street_level', + { latitude: 38.5799, longitude: -121.4937, provider: 'google' }, + { isCurrent: () => current }, + ); await new Promise((resolve) => setImmediate(resolve)); current = false; h.finishFlight(); const result = await pending; - assert.deepEqual(h.order.filter((step) => /^(map|params|open|arm|enable)/.test(step)), [], 'the stale turn switched nothing'); + assert.deepEqual( + h.order.filter((step) => /^(map|params|open|arm|enable)/.test(step)), + [], + 'the stale turn switched nothing', + ); assert.equal(result.cancelled, true); }); test('show_street_level superseded during its map switch lights no source', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; const h = createStreetLevelHarness({ enabled: true }); let current = true; const runner = createGevActionRunner({ @@ -7560,31 +8383,71 @@ test('show_street_level superseded during its map switch lights no source', asyn }, dataManager: h.dataManager, }); - const result = await runner('show_street_level', { latitude: 1, longitude: 2, provider: 'google', fly: false }, { isCurrent: () => current }); - assert.deepEqual(h.order.filter((step) => /^(params|open|arm)/.test(step)), [], 'the stale turn lit nothing'); + const result = await runner( + 'show_street_level', + { latitude: 1, longitude: 2, provider: 'google', fly: false }, + { isCurrent: () => current }, + ); + assert.deepEqual( + h.order.filter((step) => /^(params|open|arm)/.test(step)), + [], + 'the stale turn lit nothing', + ); assert.deepEqual([result.stage, result.cancelled], ['map', true]); }); test('show_street_level goes ahead while a source’s key status is still unknown', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; // A freshly loaded sl= link meets the source before its status call answers. - const { runner, order } = createStreetLevelHarness({ enabled: true, configured: null }); - const result = await runner('show_street_level', { latitude: 38.58, longitude: -121.49, provider: 'mapillary', fly: false }); + const { runner, order } = createStreetLevelHarness({ + enabled: true, + configured: null, + }); + const result = await runner('show_street_level', { + latitude: 38.58, + longitude: -121.49, + provider: 'mapillary', + fly: false, + }); assert.equal(result.ok, true); assert.ok(order.some((step) => step.startsWith('open:mapillary'))); }); test('show_street_level in a view that hides its panel stops before anything loads unseen', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; const saved = globalThis.document; - for (const mode of ['cockpit-mode', 'ui-clean-view', 'recording-mode', 'scene-playback-mode']) { - globalThis.document = { body: { classList: { contains: (name) => name === mode } } }; + for (const mode of [ + 'cockpit-mode', + 'ui-clean-view', + 'recording-mode', + 'scene-playback-mode', + ]) { + globalThis.document = { + body: { classList: { contains: (name) => name === mode } }, + }; try { const { runner, order } = createStreetLevelHarness({ enabled: true }); - const result = await runner('show_street_level', { latitude: 38.58, longitude: -121.49, provider: 'google', fly: false }); + const result = await runner('show_street_level', { + latitude: 38.58, + longitude: -121.49, + provider: 'google', + fly: false, + }); assert.deepEqual([result.ok, result.stage], [false, 'view'], mode); assert.match(result.error, /hidden in the current view/); - assert.deepEqual(order.filter((step) => /^(map|params|open|arm|enable)/.test(step)), [], `${mode}: nothing switched`); + assert.deepEqual( + order.filter((step) => /^(map|params|open|arm|enable)/.test(step)), + [], + `${mode}: nothing switched`, + ); } finally { globalThis.document = saved; } @@ -7592,10 +8455,16 @@ test('show_street_level in a view that hides its panel stops before anything loa }); test('show_street_level checks the panel again after every wait: a mode entered meanwhile loads nothing unseen', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; const saved = globalThis.document; const classes = new Set(); - globalThis.document = { body: { classList: { contains: (name) => classes.has(name) } } }; + globalThis.document = { + body: { classList: { contains: (name) => classes.has(name) } }, + }; try { for (const [mode, when] of [ ['ui-clean-view', 'duringEnable'], @@ -7603,9 +8472,18 @@ test('show_street_level checks the panel again after every wait: a mode entered ]) { classes.clear(); const h = createStreetLevelHarness({ [when]: () => classes.add(mode) }); - const result = await h.runner('show_street_level', { latitude: 38.58, longitude: -121.49, provider: 'google', fly: false }); + const result = await h.runner('show_street_level', { + latitude: 38.58, + longitude: -121.49, + provider: 'google', + fly: false, + }); assert.deepEqual([result.ok, result.stage], [false, 'view'], mode); - assert.deepEqual(h.order.filter((step) => /^(open|arm)/.test(step)), [], `${mode}: no billed load`); + assert.deepEqual( + h.order.filter((step) => /^(open|arm)/.test(step)), + [], + `${mode}: no billed load`, + ); assert.deepEqual(h.revealed, [], `${mode}: nothing revealed`); } // Entered while the photo loaded: it is closed again, not reported as shown. @@ -7617,7 +8495,12 @@ test('show_street_level checks the panel again after every wait: a mode entered classes.add('recording-mode'); return opened; }; - const result = await late.runner('show_street_level', { latitude: 38.58, longitude: -121.49, provider: 'mapillary', fly: false }); + const result = await late.runner('show_street_level', { + latitude: 38.58, + longitude: -121.49, + provider: 'mapillary', + fly: false, + }); assert.deepEqual([result.ok, result.stage], [false, 'view']); assert.equal(late.order.at(-1), 'close'); assert.deepEqual(late.revealed, []); @@ -7627,12 +8510,21 @@ test('show_street_level checks the panel again after every wait: a mode entered }); test('show_street_level refuses a hidden panel before the camera leaves a recording', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; const saved = globalThis.document; - globalThis.document = { body: { classList: { contains: (name) => name === 'recording-mode' } } }; + globalThis.document = { + body: { classList: { contains: (name) => name === 'recording-mode' } }, + }; try { const { runner, order } = createStreetLevelHarness(); - const result = await runner('show_street_level', { query: 'Eiffel Tower', provider: 'mapillary' }); + const result = await runner('show_street_level', { + query: 'Eiffel Tower', + provider: 'mapillary', + }); assert.deepEqual([result.ok, result.stage], [false, 'view']); assert.deepEqual(order, [], 'no flight'); } finally { @@ -7641,42 +8533,107 @@ test('show_street_level refuses a hidden panel before the camera leaves a record }); test('show_street_level stops once the camera is someone else’s: a navigation or a gesture during the map switch', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; for (const take of ['navigate', 'gesture']) { let h; h = createStreetLevelHarness({ duringMapSwitch: () => h[take]() }); - const result = await h.runner('show_street_level', { latitude: 38.58, longitude: -121.49, provider: 'mapillary', fly: false }); + const result = await h.runner('show_street_level', { + latitude: 38.58, + longitude: -121.49, + provider: 'mapillary', + fly: false, + }); assert.equal(result.ok, true, `${take}: Mapillary needs no map switch`); h = createStreetLevelHarness({ duringMapSwitch: () => h[take]() }); - const google = await h.runner('show_street_level', { latitude: 38.58, longitude: -121.49, provider: 'google', fly: false }); - assert.deepEqual([google.ok, google.stage, google.cancelled, google.superseded], [false, 'map', true, true], take); - assert.deepEqual(h.order.filter((step) => /^(params|enable|open|arm)/.test(step)), [], `${take}: nothing lit for the old place`); + const google = await h.runner('show_street_level', { + latitude: 38.58, + longitude: -121.49, + provider: 'google', + fly: false, + }); + assert.deepEqual( + [google.ok, google.stage, google.cancelled, google.superseded], + [false, 'map', true, true], + take, + ); + assert.deepEqual( + h.order.filter((step) => /^(params|enable|open|arm)/.test(step)), + [], + `${take}: nothing lit for the old place`, + ); } // During the layer switch-on: the photo lookup never runs. let h; h = createStreetLevelHarness({ duringEnable: () => h.navigate() }); - const result = await h.runner('show_street_level', { latitude: 38.58, longitude: -121.49, provider: 'mapillary', fly: false }); - assert.deepEqual([result.ok, result.stage, result.superseded], [false, 'layer', true]); + const result = await h.runner('show_street_level', { + latitude: 38.58, + longitude: -121.49, + provider: 'mapillary', + fly: false, + }); + assert.deepEqual( + [result.ok, result.stage, result.superseded], + [false, 'layer', true], + ); assert.ok(!h.order.some((step) => step.startsWith('open:'))); }); test('show_street_level loads no photo it found once the camera or the panel moved on during the lookup', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; for (const take of ['navigate', 'gesture']) { let h; - h = createStreetLevelHarness({ enabled: true, activeStack: 'photoreal', duringLookup: () => h[take]() }); - const result = await h.runner('show_street_level', { latitude: 38.58, longitude: -121.49, provider: 'google', fly: false }); - assert.deepEqual([result.ok, result.stage, result.superseded], [false, 'imagery', true], take); + h = createStreetLevelHarness({ + enabled: true, + activeStack: 'photoreal', + duringLookup: () => h[take](), + }); + const result = await h.runner('show_street_level', { + latitude: 38.58, + longitude: -121.49, + provider: 'google', + fly: false, + }); + assert.deepEqual( + [result.ok, result.stage, result.superseded], + [false, 'imagery', true], + take, + ); assert.equal(h.lookups.length, 1); - assert.equal(h.street.open, false, `${take}: the billed panorama never loads`); - assert.ok(!h.order.includes('close'), `${take}: nothing opened, nothing to close`); + assert.equal( + h.street.open, + false, + `${take}: the billed panorama never loads`, + ); + assert.ok( + !h.order.includes('close'), + `${take}: nothing opened, nothing to close`, + ); } const saved = globalThis.document; const classes = new Set(); - globalThis.document = { body: { classList: { contains: (name) => classes.has(name) } } }; + globalThis.document = { + body: { classList: { contains: (name) => classes.has(name) } }, + }; try { - const h = createStreetLevelHarness({ enabled: true, activeStack: 'photoreal', duringLookup: () => classes.add('ui-clean-view') }); - const result = await h.runner('show_street_level', { latitude: 38.58, longitude: -121.49, provider: 'google', fly: false }); + const h = createStreetLevelHarness({ + enabled: true, + activeStack: 'photoreal', + duringLookup: () => classes.add('ui-clean-view'), + }); + const result = await h.runner('show_street_level', { + latitude: 38.58, + longitude: -121.49, + provider: 'google', + fly: false, + }); assert.deepEqual([result.ok, result.stage], [false, 'view']); assert.equal(h.street.open, false, 'nothing loads into the hidden panel'); } finally { @@ -7685,19 +8642,44 @@ test('show_street_level loads no photo it found once the camera or the panel mov }); test('show_street_level replaces an open photo in place: the viewer (and EXPAND) stays up while it looks', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; - const h = createStreetLevelHarness({ enabled: true, photoOpen: true, nearest: 'pano-b' }); - const result = await h.runner('show_street_level', { latitude: 38.58, longitude: -121.49, provider: 'mapillary', fly: false }); + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; + const h = createStreetLevelHarness({ + enabled: true, + photoOpen: true, + nearest: 'pano-b', + }); + const result = await h.runner('show_street_level', { + latitude: 38.58, + longitude: -121.49, + provider: 'mapillary', + fly: false, + }); assert.equal(result.ok, true); - assert.equal(h.lookups[0].replace, true, 'the lookup takes over the open photo'); + assert.equal( + h.lookups[0].replace, + true, + 'the lookup takes over the open photo', + ); assert.ok(!h.order.includes('close'), 'never closed on the way'); assert.deepEqual([h.street.open, h.street.imageId], [true, 'pano-b']); }); test('show_street_level owns the camera from where its own flight lands', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; const h = createStreetLevelHarness(); - const pending = h.runner('show_street_level', { latitude: 38.58, longitude: -121.49, provider: 'mapillary' }); + const pending = h.runner('show_street_level', { + latitude: 38.58, + longitude: -121.49, + provider: 'mapillary', + }); await new Promise((resolve) => setTimeout(resolve, 0)); h.finishFlight(); const result = await pending; @@ -7710,15 +8692,27 @@ test('show_street_level owns the camera from where its own flight lands', async // press on the globe, which does not cancel a Cesium flight either. for (const take of ['navigate', 'gesture']) { test(`show_street_level stands down when the camera is taken during its own flight (${take})`, async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; const h = createStreetLevelHarness(); - const pending = h.runner('show_street_level', { latitude: 38.58, longitude: -121.49, provider: 'google' }); + const pending = h.runner('show_street_level', { + latitude: 38.58, + longitude: -121.49, + provider: 'google', + }); await new Promise((resolve) => setTimeout(resolve, 0)); assert.deepEqual(h.order, ['fly'], 'the flight is under way'); h[take](); h.finishFlight(); const result = await pending; - assert.deepEqual([result.ok, result.superseded], [false, true], result.error); + assert.deepEqual( + [result.ok, result.superseded], + [false, true], + result.error, + ); assert.deepEqual( h.order.filter((step) => /^(map|params|open|arm|enable)/.test(step)), [], @@ -7728,32 +8722,88 @@ for (const take of ['navigate', 'gesture']) { } test('show_street_level closes the previous photo, so one that finds nothing leaves no other place on screen', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; - const empty = createStreetLevelHarness({ enabled: true, photoOpen: true, nearest: null }); - const result = await empty.runner('show_street_level', { latitude: 23.4, longitude: 12.5, provider: 'mapillary', fly: false }); + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; + const empty = createStreetLevelHarness({ + enabled: true, + photoOpen: true, + nearest: null, + }); + const result = await empty.runner('show_street_level', { + latitude: 23.4, + longitude: 12.5, + provider: 'mapillary', + fly: false, + }); assert.deepEqual([result.ok, result.noImagery], [false, true]); assert.equal(empty.street.open, false, 'the Paris photo is gone'); - assert.match(empty.street.error, /No street-level imagery/, 'the panel shows why'); + assert.match( + empty.street.error, + /No street-level imagery/, + 'the panel shows why', + ); // A link that only arms a billed source closes it too. - const armed = createStreetLevelHarness({ enabled: true, photoOpen: true, activeStack: 'photoreal' }); - await armed.runner('show_street_level', { latitude: 23.4, longitude: 12.5, provider: 'google', fly: false, autoOpen: false }); - assert.deepEqual(armed.order.filter((step) => /^(close|arm)/.test(step)).map((step) => step.split(':')[0]), ['close', 'arm']); + const armed = createStreetLevelHarness({ + enabled: true, + photoOpen: true, + activeStack: 'photoreal', + }); + await armed.runner('show_street_level', { + latitude: 23.4, + longitude: 12.5, + provider: 'google', + fly: false, + autoOpen: false, + }); + assert.deepEqual( + armed.order + .filter((step) => /^(close|arm)/.test(step)) + .map((step) => step.split(':')[0]), + ['close', 'arm'], + ); }); test('show_street_level opens over the clean embedded globe but respects its other exclusive modes', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; const saved = globalThis.document; try { - for (const mode of [null, 'cockpit-mode', 'recording-mode', 'scene-playback-mode']) { + for (const mode of [ + null, + 'cockpit-mode', + 'recording-mode', + 'scene-playback-mode', + ]) { const classes = new Set(['ui-embed', 'ui-clean-view', mode]); - globalThis.document = { body: { classList: { contains: (name) => classes.has(name) } } }; + globalThis.document = { + body: { classList: { contains: (name) => classes.has(name) } }, + }; const { runner, order } = createStreetLevelHarness({ enabled: true }); - const result = await runner('show_street_level', { latitude: 38.58, longitude: -121.49, provider: 'mapillary', fly: false }); + const result = await runner('show_street_level', { + latitude: 38.58, + longitude: -121.49, + provider: 'mapillary', + fly: false, + }); if (mode) { assert.deepEqual([result.ok, result.stage], [false, 'view'], mode); - assert.deepEqual(order.filter((step) => /^(map|params|open|arm|enable)/.test(step)), [], `${mode}: nothing switched`); + assert.deepEqual( + order.filter((step) => /^(map|params|open|arm|enable)/.test(step)), + [], + `${mode}: nothing switched`, + ); } else { - assert.equal(result.ok, true, 'embed clean view lifts the photo over the globe'); + assert.equal( + result.ok, + true, + 'embed clean view lifts the photo over the globe', + ); assert.ok(order.some((step) => step.startsWith('open:mapillary'))); } } @@ -7763,7 +8813,11 @@ test('show_street_level opens over the clean embedded globe but respects its oth }); test('show_street_level from a link keeps the recipient’s preferences: its switches are not the user’s', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; const link = createStreetLevelHarness(); const linked = await link.runner( 'show_street_level', @@ -7771,48 +8825,120 @@ test('show_street_level from a link keeps the recipient’s preferences: its swi { origin: 'programmatic' }, ); assert.equal(linked.ok, true, linked.error); - assert.deepEqual(link.origins, ['programmatic', 'programmatic'], 'source switch and layer on'); + assert.deepEqual( + link.origins, + ['programmatic', 'programmatic'], + 'source switch and layer on', + ); const asked = createStreetLevelHarness(); - await asked.runner('show_street_level', { latitude: 1, longitude: 2, provider: 'mapillary', fly: false }); - assert.deepEqual(asked.origins, ['voice', 'voice'], 'the assistant’s request is the user’s choice'); + await asked.runner('show_street_level', { + latitude: 1, + longitude: 2, + provider: 'mapillary', + fly: false, + }); + assert.deepEqual( + asked.origins, + ['voice', 'voice'], + 'the assistant’s request is the user’s choice', + ); }); test('show_street_level with no place looks under the screen centre, not a link’s armed point', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; const here = createStreetLevelHarness({ enabled: true }); - const result = await here.runner('show_street_level', { provider: 'mapillary' }); + const result = await here.runner('show_street_level', { + provider: 'mapillary', + }); assert.equal(result.ok, true, result.error); assert.equal(result.atViewCentre, true); assert.equal(here.lookups[0].point, null); assert.equal(here.lookups[0].aim, 'screen-centre'); assert.equal(here.lookups[0].armed, false); const placed = createStreetLevelHarness({ enabled: true }); - await placed.runner('show_street_level', { latitude: 1, longitude: 2, provider: 'mapillary', fly: false }); - assert.equal(placed.lookups[0].aim, undefined, 'a place is looked up where it is'); - const sky = createStreetLevelHarness({ enabled: true, nearest: null, sky: true }); - const refused = await sky.runner('show_street_level', { provider: 'mapillary' }); - assert.deepEqual([refused.ok, refused.stage, refused.aim], [false, 'imagery', 'sky']); + await placed.runner('show_street_level', { + latitude: 1, + longitude: 2, + provider: 'mapillary', + fly: false, + }); + assert.equal( + placed.lookups[0].aim, + undefined, + 'a place is looked up where it is', + ); + const sky = createStreetLevelHarness({ + enabled: true, + nearest: null, + sky: true, + }); + const refused = await sky.runner('show_street_level', { + provider: 'mapillary', + }); + assert.deepEqual( + [refused.ok, refused.stage, refused.aim], + [false, 'imagery', 'sky'], + ); }); test('show_street_level tells missing imagery from a failing source', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; - const empty = await createStreetLevelHarness({ enabled: true, nearest: null }).runner('show_street_level', { - latitude: 1, longitude: 2, provider: 'mapillary', fly: false, + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; + const empty = await createStreetLevelHarness({ + enabled: true, + nearest: null, + }).runner('show_street_level', { + latitude: 1, + longitude: 2, + provider: 'mapillary', + fly: false, }); - assert.deepEqual([empty.stage, empty.noImagery, empty.imageryError], ['imagery', true, undefined]); - const broken = await createStreetLevelHarness({ enabled: true, imageryError: 'Mapillary graph HTTP 500' }).runner( - 'show_street_level', - { latitude: 1, longitude: 2, provider: 'mapillary', fly: false }, + assert.deepEqual( + [empty.stage, empty.noImagery, empty.imageryError], + ['imagery', true, undefined], + ); + const broken = await createStreetLevelHarness({ + enabled: true, + imageryError: 'Mapillary graph HTTP 500', + }).runner('show_street_level', { + latitude: 1, + longitude: 2, + provider: 'mapillary', + fly: false, + }); + assert.deepEqual( + [broken.stage, broken.noImagery, broken.imageryError], + ['imagery', undefined, true], ); - assert.deepEqual([broken.stage, broken.noImagery, broken.imageryError], ['imagery', undefined, true]); assert.equal(broken.error, 'Mapillary graph HTTP 500'); }); test('show_street_level shows every photo it opens, also over a panel the user had closed', async () => { - globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; const harness = createStreetLevelHarness({ enabled: true }); - await harness.runner('show_street_level', { latitude: 1, longitude: 2, provider: 'mapillary', fly: false }); - await harness.runner('show_street_level', { latitude: 3, longitude: 4, provider: 'mapillary', fly: false }); + await harness.runner('show_street_level', { + latitude: 1, + longitude: 2, + provider: 'mapillary', + fly: false, + }); + await harness.runner('show_street_level', { + latitude: 3, + longitude: 4, + provider: 'mapillary', + fly: false, + }); assert.deepEqual(harness.revealed, [ 'collapse:street-level-panel:false', 'reveal:street-level-panel', @@ -7820,6 +8946,11 @@ test('show_street_level shows every photo it opens, also over a panel the user h 'reveal:street-level-panel', ]); const missing = createStreetLevelHarness({ enabled: true, nearest: null }); - await missing.runner('show_street_level', { latitude: 1, longitude: 2, provider: 'mapillary', fly: false }); + await missing.runner('show_street_level', { + latitude: 1, + longitude: 2, + provider: 'mapillary', + fly: false, + }); assert.deepEqual(missing.revealed, [], 'nothing opened, nothing revealed'); });