diff --git a/changelog.d/2-space-missions-panel.md b/changelog.d/2-space-missions-panel.md new file mode 100644 index 0000000000..e7cc6bc355 --- /dev/null +++ b/changelog.d/2-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, #2). 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/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..1e90c34c73 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,27 @@ 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, + }; + } if (!setPanelOpen(styleManager, panelId, open)) { const say = 'There is no panel to open here.'; return { @@ -1030,6 +1061,47 @@ 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); + } + return { + ...result, + action: 'set_context_mode', + mode: 'space-missions', + }; + } + if ( + mode === 'off' && + !styleManager.getContextModeState?.()?.mode && + dataManager.isEnabled?.('rocket-launches') + ) { + // "Exit Space Missions" still arrives as context off. With no Context + // mode on, Space Missions 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..65224d15ec 100644 --- a/src/voice/gevActions.test.mjs +++ b/src/voice/gevActions.test.mjs @@ -4742,7 +4742,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 +4760,137 @@ 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, @@ -7480,6 +7611,91 @@ 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; + 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: (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); + assert.deepEqual(calls, [ + ['space-missions-panel', false, { explicit: true }], + ]); +}); + test('set_panel_open reaches the Utilities panel by its name, Draw or Import', async () => { const calls = []; const runner = createGevActionRunner({