diff --git a/backend/src/greenwave/api/dispatch.py b/backend/src/greenwave/api/dispatch.py index 594a6cb..9a9e1c4 100644 --- a/backend/src/greenwave/api/dispatch.py +++ b/backend/src/greenwave/api/dispatch.py @@ -237,6 +237,7 @@ def _candidate(index: RoutingIndex, c: RankedStation) -> RankedCandidate: greenwave_seconds=c.greenwave_seconds, standard_seconds=c.standard_seconds, distance_m=c.distance_m, + route_geometry=c.route_geometry, on_foot=OnFootLeg( access_point=node_position(index, c.on_foot.node_key), distance_m=c.on_foot.on_foot_m, diff --git a/backend/src/greenwave/routing/station_ranking.py b/backend/src/greenwave/routing/station_ranking.py index 600d61b..745917b 100644 --- a/backend/src/greenwave/routing/station_ranking.py +++ b/backend/src/greenwave/routing/station_ranking.py @@ -43,7 +43,14 @@ plan_route, snap_endpoint, ) -from greenwave.schemas import GreenWaveMode, Position, Station, StationSourceKind, VehicleType +from greenwave.schemas import ( + GreenWaveMode, + Position, + RouteGeometry, + Station, + StationSourceKind, + VehicleType, +) from greenwave.simulation.route_model import build_route_model from greenwave.simulation.standard_estimate import standard_run_seconds from greenwave.simulation_settings import SimulationSettings @@ -70,6 +77,7 @@ class RankedStation: on_site: bool = False walk_m: float | None = None walk_seconds: float | None = None + route_geometry: RouteGeometry | None = None def total_seconds_for(self, mode: GreenWaveMode) -> float: """The drive estimate of ``mode`` plus the walk from the access node (on-site: the walk).""" @@ -189,6 +197,7 @@ def rank_stations( standard_run_seconds(route, model, traffic_density_multiplier, settings), route.total_distance_m, route.on_foot, + route_geometry=RouteGeometry(type="LineString", coordinates=route.polyline_wgs84), ) walk = on_site.get(node.station.station_id) if walk is not None and walk.total_seconds_for(time_mode) < candidate.total_seconds_for( diff --git a/backend/src/greenwave/schemas/dispatch.py b/backend/src/greenwave/schemas/dispatch.py index f5858de..548867c 100644 --- a/backend/src/greenwave/schemas/dispatch.py +++ b/backend/src/greenwave/schemas/dispatch.py @@ -18,6 +18,7 @@ GreenWaveMode, OnFootLeg, Position, + RouteGeometry, SchemaVersion, SnappedEndpoint, VehicleType, @@ -195,6 +196,8 @@ def _local_scenario_time(cls, value: datetime | None) -> datetime | None: class RankedCandidate(BaseModel): + # Existing planner output for read-only setup preview; absent for an on-site walk. + route_geometry: RouteGeometry | None = None station: Station greenwave_seconds: Annotated[float, Field(ge=0.0)] # the preflight green-wave estimate # The exact pre-run standard estimate (ER Green Wave disabled) at the request's density. diff --git a/backend/tests/api/test_dispatch_api.py b/backend/tests/api/test_dispatch_api.py index 764439a..13e804c 100644 --- a/backend/tests/api/test_dispatch_api.py +++ b/backend/tests/api/test_dispatch_api.py @@ -474,3 +474,45 @@ def spy(*args: Any, **kwargs: Any) -> Any: assert response.status_code == 200, response.text assert seen == [GreenWaveMode.DISABLED] + + +@pytest.mark.parametrize("mode", ["ENABLED", "DISABLED"]) +@pytest.mark.parametrize("off_road", [False, True]) +def test_rank_previews_exact_start_geometry_without_starting( + layout: Layout, monkeypatch: pytest.MonkeyPatch, mode: str, off_road: bool +) -> None: + with client(layout) as c: + manager = c.app.state.session_manager # type: ignore[union-attr] + original_start = manager.start + starts: list[object] = [] + + async def observed_start(*args: Any, **kwargs: Any) -> Any: + starts.append(args) + return await original_start(*args, **kwargs) + + monkeypatch.setattr(manager, "start", observed_start) + incident = OFF_ROAD if off_road else _poprzeczna(c) + response = c.post( + "/api/v1/dispatch/rank", + json={"incident": incident, "vehicle_type": "FIRE_TRUCK", "time_mode": mode}, + ) + assert response.status_code == 200 + candidate = response.json()["candidates"][0] + assert starts == [] + assert len(candidate["route_geometry"]["coordinates"]) >= 2 + started = c.post( + "/api/v1/simulation/start", + json={ + "simulation_id": "SIM-preview", + "origin": candidate["station"]["position"], + "destination": incident, + "vehicle_type": "FIRE_TRUCK", + "green_wave_mode": mode, + "traffic_density_multiplier": 1, + "enable_cascade_mode": True, + "playback_speed": 1, + }, + ) + assert started.status_code == 200 + assert started.json()["route_geometry"] == candidate["route_geometry"] + c.post("/api/v1/simulation/SIM-preview/stop") diff --git a/contracts/openapi.json b/contracts/openapi.json index ef4ce0d..d27128e 100644 --- a/contracts/openapi.json +++ b/contracts/openapi.json @@ -1189,6 +1189,16 @@ "title": "On Site", "type": "boolean" }, + "route_geometry": { + "anyOf": [ + { + "$ref": "#/components/schemas/RouteGeometry" + }, + { + "type": "null" + } + ] + }, "selection_reason": { "anyOf": [ { diff --git a/docs/engineering/frontend-dashboard.md b/docs/engineering/frontend-dashboard.md index 34bef7f..0b987fe 100644 --- a/docs/engineering/frontend-dashboard.md +++ b/docs/engineering/frontend-dashboard.md @@ -85,3 +85,19 @@ the few core formulas. Formula blocks use compact notation (`x_i`, `t_{a,e}`, `x the audited parameter reference values, not runtime configuration. Keep it aligned with the audited backend settings and ETL constants when updating that reference. A footer on every tab credits the authors with their GitHub profiles. + +## Planning preview and monitoring scroll + +Setup displays the selected candidate's `route_geometry` from the existing dispatch ranking, +using the same `pageCandidate` selection as Start. Ranking owns loading, errors and request +freshness; a non-ready ranking never draws its previous geometry. The preview is a neutral +dashed line in either mode and becomes the normal live route on successful start. On-site +crews have no driven route. Mock preview and playback share their synthetic line constructor. +Ranking retains its already planned geometry; preview needs no additional request or session. +Start still validates and plans authoritatively on the server using the same deterministic planner. + +Live desktop details fill the inspector's available height. Controls have their own bounded +area, while Route Signals and the ITS audit log share the remainder with separate scrollable +bodies and fixed headings. Their focusable regions support keyboard scrolling. Phone sheets +keep their existing scroll and gesture model, with each monitoring panel capped by viewport +height; the sheet can still scroll between panels. diff --git a/docs/superpowers/plans/2026-10-30-route-preview.md b/docs/superpowers/plans/2026-10-30-route-preview.md new file mode 100644 index 0000000..14d0044 --- /dev/null +++ b/docs/superpowers/plans/2026-10-30-route-preview.md @@ -0,0 +1,42 @@ +# Route Preview and Sidebar Implementation Plan + +> Execute inline with executing-plans, TDD and verification-before-completion. User explicitly requested direct implementation; no implementation approval checkpoint. Later instructions authorize a separate branch, focused commits and a PR. + +**Goal:** Show the actual planned route during setup and independently scroll live monitoring panels. +**Architecture:** Extend ranking with already calculated geometry; render via RouteLayer. Existing dispatch state owns freshness; simulation state continues to own playback. Bound live inspector panels with grid/flex. +**Tech Stack:** Existing FastAPI/Pydantic, React, MapLibre and CSS. +**Spec:** docs/superpowers/specs/2026-10-30-route-preview-design.md + +## Constraints +No routing algorithm, timing, signal or dependency changes. Generate contracts. +Preserve bilingual copy, setup controls, phone sheets and endpoint markers. + +## Review Focus +Stale ranking during density debounce; empty and on-site candidates; manually selected station; +preview during STARTING; small viewport controls and independent scrolling. + +## Tasks +- [x] Add failing API tests proving rank geometry equals simulation geometry, with no sessions. + Retain geometry in RankedStation, expose optional canonical route_geometry, regenerate contracts, + validate it at frontend boundary, and provide mock geometry using shared mock route construction. +- [x] Add failing preview-selection tests for loading, errors, on-site, modes and manual selection. + Render ready ranking geometry as a dashed neutral RouteLayer in setup, with localized status; + fit preview geometry without enabling vehicle following or simulation effects. Reuse in comparison setup. + Exercise existing stale-response dispatch regressions with geometry-bearing results. +- [x] Bound the desktop live inspector, controls and both panel bodies; preserve phone sheet behavior. + Verify overflow, independent scrolling and visible headers in browser at desktop/laptop/mobile sizes. +- [x] Run frontend lint/typecheck/format/tests/build, backend checks and relevant browser smoke; + review diff and report changed files, evidence and limits. Proposed commit: feat: preview dispatch routes and bound monitoring panels. + +## Verification +Frontend lint, typecheck, format check, all 1,306 tests and production build passed. +Backend Ruff, formatting, mypy and all 1,557 tests passed. +Playwright preview updates passed in both modes. Independent scrolling passed at +1440×900, 1280×720, 1024×600 and 390×844. Existing mobile layout smoke passed, +including landscape. Existing localization smoke failed on its unchanged homepage +heading selector before reaching preview; targeted PL/EN preview checks passed. +Review found no blocking issues. Work is split into backend geometry, frontend preview and sidebar scrolling commits on `codex/route-preview-sidebar-scrolling`. + +Production-build smoke rerun passed for route updates in both modes, preview-to-playback +transition, independent panel scrolling, mobile landscape and targeted PL/EN preview copy. +Browser console recorded no errors or warnings. Full quality checks passed again before committing. diff --git a/docs/superpowers/specs/2026-10-30-route-preview-design.md b/docs/superpowers/specs/2026-10-30-route-preview-design.md new file mode 100644 index 0000000..1410a62 --- /dev/null +++ b/docs/superpowers/specs/2026-10-30-route-preview-design.md @@ -0,0 +1,15 @@ +# Route preview and bounded monitoring panels + +Implement the user's route-preview and independent-sidebar-scrolling requirements. +Ranking returns each candidate's existing planned geometry; setup renders the page's chosen +candidate only while ranking is ready. The existing abort/sequence handling owns preview +freshness. No preview operation starts sessions or dispatches ITS events. On-site candidates +have no driven route. Mock preview uses the same synthetic straight line as mock playback. +Playback replaces the dashed neutral preview with the existing live route. Simulation start +retains its deterministic server-side planning and validation; no client geometry is trusted. +Both modes retain their existing station selection semantics and share the same path planner. + +Desktop live details use a height-bounded flex layout: controls at natural size and two equal +monitoring rows with fixed headers and independently scrolling bodies. Very short screens +may scroll controls separately. Phone sheets retain their existing gesture/scroll model, +with bounded monitoring sections. Preserve PL/EN, markers, timing, signals and dependencies. diff --git a/frontend/scripts/smoke/route-preview-and-scroll.js b/frontend/scripts/smoke/route-preview-and-scroll.js new file mode 100644 index 0000000..6b42a43 --- /dev/null +++ b/frontend/scripts/smoke/route-preview-and-scroll.js @@ -0,0 +1,69 @@ +/* eslint-disable @typescript-eslint/no-unused-expressions -- playwright-cli consumes a function expression */ +async (page) => { + const base = new URL(page.url()).origin; + await page.context().addCookies([{ name: "greenwave-language", value: "en", url: base }]); + await page.goto(base + "/simulation/green-wave"); + const assert = (condition, message) => { if (!condition) throw new Error(message); }; + await page.setViewportSize({ width: 1440, height: 900 }); + await page.getByRole("button", { name: /Initialize green corridor/ }).waitFor(); + await page.locator(".maplibregl-canvas").click({ position: { x: 500, y: 400 } }); + await page.getByRole("status").filter({ hasText: "Planned route" }).waitFor(); + assert(await page.locator('[aria-label^="Simulated signal INT-"]').count() === 0, "Preview started signal telemetry"); + await page.getByRole("button", { name: /Initialize green corridor/ }).click(); + await page.getByRole("status").filter({ hasText: "Simulation stream: Live" }).waitFor(); + assert(await page.getByText("Planned route", { exact: true }).count() === 0, "Preview remains during playback"); + const results = []; + for (const viewport of [{ width: 1440, height: 900 }, { width: 1280, height: 720 }, { width: 1024, height: 600 }]) { + await page.setViewportSize(viewport); + const measurement = await page.evaluate(() => { + const inspector = document.querySelector("aside.workspace-inspector"); + const panels = [...inspector.querySelectorAll("section.hud-panel")].filter(p => /Route signals|ITS gateway audit log/.test(p.textContent)); + if (panels.length !== 2) throw new Error("Missing monitoring panels"); + const bodies = panels.map(p => p.querySelector(".monitor-panel-body") ?? p.lastElementChild); + for (const body of bodies) { + if (!body.querySelector("[data-stress]")) for (let i = 0; i < 40; i++) { + const row = document.createElement("p"); row.dataset.stress = "true"; row.textContent = `Long monitoring entry ${i}`; row.style.padding = "12px"; body.append(row); + } + } + const before = bodies.map(b => b.scrollTop); + const headerPositions = panels.map(p => p.firstElementChild.getBoundingClientRect().top); + bodies[0].scrollTop = 120; + const firstIndependent = bodies[0].scrollTop > 0 && bodies[1].scrollTop === before[1]; + const firstScroll = bodies[0].scrollTop; + bodies[1].scrollTop = 120; + const secondIndependent = bodies[1].scrollTop > 0 && bodies[0].scrollTop === firstScroll; + const headersFixed = panels.every((p, i) => p.firstElementChild.getBoundingClientRect().top === headerPositions[i]); + return { + firstIndependent, secondIndependent, headersFixed, + bounded: panels.every(p => p.getBoundingClientRect().bottom <= inspector.getBoundingClientRect().bottom + 1), + inspectorOverflow: inspector.scrollHeight - inspector.clientHeight, + horizontalOverflow: document.documentElement.scrollWidth - innerWidth, + heights: bodies.map(b => b.clientHeight), + }; + }); + assert(measurement.firstIndependent && measurement.secondIndependent, `Scrolling not independent: ${JSON.stringify(measurement)}`); + assert(measurement.headersFixed && measurement.bounded, `Panels unbounded: ${JSON.stringify(measurement)}`); + assert(measurement.inspectorOverflow <= 1 && measurement.horizontalOverflow <= 0, `Outer overflow: ${JSON.stringify(measurement)}`); + assert(await page.getByTestId("stop-simulation").first().isVisible(), "Stop inaccessible"); + results.push({ viewport, ...measurement }); + } + await page.setViewportSize({ width: 390, height: 844 }); + await page.getByRole("button", { name: "Show more", exact: true }).click(); + await page.locator('.bottom-sheet[data-snap="expanded"]').waitFor(); + const phonePanels = page.locator(".bottom-sheet .monitor-panel"); + assert(await phonePanels.count() === 2, "Phone monitoring panels missing"); + const phoneMeasurements = await phonePanels.evaluateAll(panels => panels.map(panel => { + const body = panel.querySelector(".monitor-panel-body"); + for (let i = 0; i < 30; i++) { + const row = document.createElement("p"); row.textContent = `Phone entry ${i}`; row.style.padding = "12px"; body.append(row); + } + const headingTop = panel.firstElementChild.getBoundingClientRect().top; + body.scrollTop = 100; + return { bounded: panel.clientHeight <= innerHeight * 0.45 + 1, scrolled: body.scrollTop > 0, headingFixed: panel.firstElementChild.getBoundingClientRect().top === headingTop }; + })); + assert(phoneMeasurements.every(p => p.bounded && p.scrolled && p.headingFixed), `Phone panels unusable: ${JSON.stringify(phoneMeasurements)}`); + assert(await page.getByTestId("stop-simulation").first().isVisible(), "Phone Stop inaccessible"); + results.push({ viewport: { width: 390, height: 844 }, phoneMeasurements }); + assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), "Phone horizontal overflow"); + return JSON.stringify(results); +} diff --git a/frontend/scripts/smoke/route-preview-modes.js b/frontend/scripts/smoke/route-preview-modes.js new file mode 100644 index 0000000..70a3225 --- /dev/null +++ b/frontend/scripts/smoke/route-preview-modes.js @@ -0,0 +1,32 @@ +/* eslint-disable @typescript-eslint/no-unused-expressions -- playwright-cli consumes a function expression */ +async page => { + const base = new URL(page.url()).origin; + await page.context().addCookies([{ name: "greenwave-language", value: "en", url: base }]); + await page.emulateMedia({ reducedMotion: "reduce" }); + const results = []; + for (const route of ["green-wave", "standard"]) { + await page.goto(`${base}/simulation/${route}`); + await page.setViewportSize({ width: 1440, height: 900 }); + await page.locator(".maplibregl-canvas").waitFor(); + await page.locator(".maplibregl-canvas").click({ position: { x: 500, y: 400 } }); + await page.getByRole("status").filter({ hasText: "Planned route" }).waitFor(); + const oldIncident = await page.locator("#incident").inputValue(); + await page.locator(".maplibregl-canvas").click({ position: { x: 600, y: 500 } }); + await page.getByRole("status").filter({ hasText: "Planned route" }).waitFor(); + const newIncident = await page.locator("#incident").inputValue(); + if (oldIncident === newIncident) throw new Error("Incident did not change"); + await page.getByRole("button", { name: "Fire", exact: true }).click(); + await page.getByRole("status").filter({ hasText: "Planned route" }).waitFor(); + const passesInput = await page.getByRole("status").filter({ hasText: "Planned route" }).evaluate(label => { + const r = label.getBoundingClientRect(); + return document.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2) !== label; + }); + if (!passesInput) throw new Error("Preview feedback intercepts map gestures"); + if (await page.locator('[aria-label^="Simulated signal INT-"]').count()) throw new Error("Preview started telemetry"); + if (!(await page.getByTestId("start-corridor").isEnabled())) throw new Error("Start unavailable after preview"); + await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))); + await page.screenshot({ path: `preview-${route}.png` }); + results.push({ route, oldIncident, newIncident, fireSelected: await page.getByRole("button", { name: "Fire", exact: true }).getAttribute("aria-pressed") }); + } + return results; +} diff --git a/frontend/src/app/globals.css b/frontend/src/app/globals.css index 7e04a4b..a6b7484 100644 --- a/frontend/src/app/globals.css +++ b/frontend/src/app/globals.css @@ -3643,3 +3643,54 @@ a.docs-chip:focus-visible, margin-inline: auto; } } + +/* Monitor headings stay outside their bounded, independently scrolling bodies. */ +.monitor-panel { + display: flex; + min-height: 0; + max-height: 45dvh; + flex-direction: column; + overflow: hidden; +} +.monitor-panel > :first-child { + flex-shrink: 0; +} +.monitor-panel-body { + min-height: 0; + overflow-y: auto; + overflow-x: hidden; + overscroll-behavior-y: contain; + overflow-wrap: anywhere; +} +.workspace-inspector[data-bounded] { + display: flex; + flex-direction: column; + overflow: hidden; +} +.workspace-inspector[data-bounded][hidden] { + display: none; +} +.live-inspector { + display: flex; + flex: 1; + min-height: 0; + flex-direction: column; + gap: 1rem; +} +.live-inspector-controls { + flex: 0 1 auto; + min-height: 0; + max-height: 40%; + overflow-y: auto; + overscroll-behavior-y: contain; +} +.live-inspector > .monitor-panel { + flex: 1 1 0; + max-height: none; +} + +/* Informational preview feedback must never intercept map or phone-sheet gestures. */ +.workspace-status > .route-preview-status { + width: fit-content; + pointer-events: none; +} diff --git a/frontend/src/components/__snapshots__/Dashboard.setup.backend.html b/frontend/src/components/__snapshots__/Dashboard.setup.backend.html index a87da5e..f282cb6 100644 --- a/frontend/src/components/__snapshots__/Dashboard.setup.backend.html +++ b/frontend/src/components/__snapshots__/Dashboard.setup.backend.html @@ -1 +1 @@ -
Simulated · all signal states
+
Simulated · all signal states
diff --git a/frontend/src/components/__snapshots__/Dashboard.setup.mock.html b/frontend/src/components/__snapshots__/Dashboard.setup.mock.html index 55f2ac4..923abcc 100644 --- a/frontend/src/components/__snapshots__/Dashboard.setup.mock.html +++ b/frontend/src/components/__snapshots__/Dashboard.setup.mock.html @@ -1 +1 @@ -
Simulated · all signal states
+
Simulated · all signal states
diff --git a/frontend/src/components/comparison/ComparisonWorkspace.tsx b/frontend/src/components/comparison/ComparisonWorkspace.tsx index 5fd5e56..4dfb180 100644 --- a/frontend/src/components/comparison/ComparisonWorkspace.tsx +++ b/frontend/src/components/comparison/ComparisonWorkspace.tsx @@ -13,6 +13,7 @@ import type { SheetSnap } from "@/lib/sheet-physics"; import { DispatchSettingsChip } from "@/components/driver/DispatchSettingsChip"; import { WorkspaceShell } from "@/components/workspace/WorkspaceShell"; import { DispatchStartButton } from "@/components/hud/dispatch/DispatchStartButton"; +import { RoutePreviewStatus } from "@/components/hud/RoutePreviewStatus"; import { DispatchForm } from "@/components/hud/DispatchForm"; import { OnSiteResult } from "@/components/hud/OnSiteResult"; import { MapContainer } from "@/components/map/MapContainer"; @@ -24,6 +25,7 @@ import { normalizeOutcomeSeed, type DispatchSettings } from "@/lib/start-request import { onSiteResult, pageCandidate, + plannedRoute, runnerUpIds, shownOnSite, type OnSite, @@ -130,6 +132,7 @@ export function ComparisonWorkspace() { /> ) : undefined } + status={!live ? : undefined} defaultDetails={!live} provenance={`${config.transport === "mock" ? "Synthetic mock" : "Backend simulation"} · ${live ? "Both runs live on one simulated clock" : "Comparison scenario"}`} controls={running && runRequest ? : undefined} @@ -147,6 +150,7 @@ export function ComparisonWorkspace() {
@@ -333,6 +336,8 @@ export function Dashboard({
+ ) : mode === "setup" ? ( + ) : undefined } header={ @@ -350,6 +355,7 @@ export function Dashboard({ map={ setMapFocusRequest((request) => request + 1)} /> ) : ( -
- - - +
+
+ + + +
diff --git a/frontend/src/components/hud/IntersectionList.tsx b/frontend/src/components/hud/IntersectionList.tsx index 3cf4ff8..5970d6e 100644 --- a/frontend/src/components/hud/IntersectionList.tsx +++ b/frontend/src/components/hud/IntersectionList.tsx @@ -63,7 +63,7 @@ export function IntersectionList() {
); return ( -
+

{t("Corridor monitoring")}

@@ -77,7 +77,12 @@ export function IntersectionList() {
-
+
{!intersections.length && (

{t("Waiting for simulation telemetry.")}

)} diff --git a/frontend/src/components/hud/ItsConsole.tsx b/frontend/src/components/hud/ItsConsole.tsx index 3a25a5b..27a0719 100644 --- a/frontend/src/components/hud/ItsConsole.tsx +++ b/frontend/src/components/hud/ItsConsole.tsx @@ -20,7 +20,7 @@ export function ItsConsole() { const { itsLog, simulationState, itsRequests, liveTelemetry } = useSimulationState(); const logEntries = itsLog.slice(-5); return ( -
+
@@ -34,7 +34,12 @@ export function ItsConsole() { {t(PHASE_CHIPS[simulationState] ?? "IDLE")}
-
+
{itsRequests.map((request) => ( { + it("announces planning, failure and missing geometry without a simulation", () => { + expect( + renderToStaticMarkup( + , + ), + ).toContain("Planning route…"); + expect( + renderToStaticMarkup( + , + ), + ).toContain("No station of this type can reach this location"); + expect(renderToStaticMarkup()).toContain( + "Route preview unavailable", + ); + expect( + renderToStaticMarkup( + , + ), + ).toContain("No eligible unit for this incident"); + }); + it("shows a planning label for geometry and no driven preview for an on-site crew", () => { + const ranking = { + ...TEAM_RANK, + candidates: [ + { + ...TEAM_RANK.candidates[0], + route_geometry: { + type: "LineString" as const, + coordinates: [ + [19.9, 50], + [19.94, 50.06], + ] as [number, number][], + }, + }, + ], + }; + expect( + renderToStaticMarkup(), + ).toContain("Planned route"); + expect( + renderToStaticMarkup( + , + ), + ).toContain("On site · no vehicle route"); + expect( + renderToStaticMarkup( + , + ), + ).toBe(""); + }); +}); diff --git a/frontend/src/components/hud/RoutePreviewStatus.tsx b/frontend/src/components/hud/RoutePreviewStatus.tsx new file mode 100644 index 0000000..a7d7429 --- /dev/null +++ b/frontend/src/components/hud/RoutePreviewStatus.tsx @@ -0,0 +1,40 @@ +"use client"; + +import { useTranslation } from "@/components/language-provider"; +import { pageCandidate, plannedRoute, type TimeMode } from "@/lib/station-choice"; +import type { IncidentDispatchState } from "@/lib/useIncidentDispatch"; + +export function RoutePreviewStatus({ + dispatch, + mode, +}: { + dispatch: Pick< + IncidentDispatchState, + "rankStatus" | "rankError" | "ranking" | "selectedStationId" + >; + mode: TimeMode; +}) { + const { t } = useTranslation(); + if (dispatch.rankStatus === "idle") return null; + const candidate = pageCandidate(dispatch, mode); + const message = + dispatch.rankStatus === "loading" + ? "Planning route…" + : dispatch.rankStatus === "error" + ? (dispatch.rankError ?? "Route preview unavailable") + : !candidate + ? "No eligible unit for this incident" + : candidate.on_site + ? "On site · no vehicle route" + : plannedRoute(dispatch, mode) + ? "Planned route" + : "Route preview unavailable"; + return ( +

+ {t(message)} +

+ ); +} diff --git a/frontend/src/components/hud/__snapshots__/IntersectionList.review.html b/frontend/src/components/hud/__snapshots__/IntersectionList.review.html index 39bc354..039c58a 100644 --- a/frontend/src/components/hud/__snapshots__/IntersectionList.review.html +++ b/frontend/src/components/hud/__snapshots__/IntersectionList.review.html @@ -1 +1 @@ -

Corridor monitoring

Route signals (TTI)

ITS feedback unavailable

INT-REVIEWUnnamed intersectionMid-block signal · 2 signalsSource data flagged for review
CLEARING
TTI 12sSIMULATED CORRIDOR ACTIVE
+

Corridor monitoring

Route signals (TTI)

ITS feedback unavailable

INT-REVIEWUnnamed intersectionMid-block signal · 2 signalsSource data flagged for review
CLEARING
TTI 12sSIMULATED CORRIDOR ACTIVE
diff --git a/frontend/src/components/map/MapContainer.tsx b/frontend/src/components/map/MapContainer.tsx index 31fd6e0..2937259 100644 --- a/frontend/src/components/map/MapContainer.tsx +++ b/frontend/src/components/map/MapContainer.tsx @@ -14,6 +14,7 @@ import { StationLayer } from "@/components/map/StationLayer"; import { useMaplibreMap } from "@/components/map/useMaplibreMap"; import { useMapCamera } from "@/components/map/useMapCamera"; import { useFollowTarget } from "@/components/map/follow-context"; +import { applyRouteFit } from "@/components/map/useRouteFit"; import { useVehicleWake } from "@/components/map/useVehicleWake"; import { VehicleMarker } from "@/components/map/VehicleMarker"; import { tickIntervalMilliseconds } from "@/lib/playback-speed"; @@ -25,6 +26,7 @@ import type { IntersectionTelemetry, Position, RouteIntersection, + RouteGeometry, SignalPhaseIndicator, Station, VehicleType, @@ -38,6 +40,7 @@ const NO_SIGNAL_PHASES: SignalPhaseIndicator[] = []; type MapContainerProps = { live: boolean; + previewGeometry?: RouteGeometry | null; snapshot?: SimulationState; origin: MapEndpoint | null; destination: MapEndpoint | null; @@ -65,6 +68,7 @@ export function MapContainer(props: MapContainerProps) { function MapCanvas({ live, + previewGeometry = null, snapshot, origin, destination, @@ -148,6 +152,18 @@ function MapCanvas({ }; }, [live, map, onMapClick]); + const incidentLat = destination?.position.lat; + const incidentLng = destination?.position.lng; + useEffect(() => { + if (!map || live || !previewGeometry) return; + const coordinates = + incidentLat !== undefined && incidentLng !== undefined + ? [...previewGeometry.coordinates, [incidentLng, incidentLat] as [number, number]] + : previewGeometry.coordinates; + map.stop(); + applyRouteFit(map, coordinates, window.matchMedia("(prefers-reduced-motion: reduce)").matches); + }, [map, live, previewGeometry, incidentLat, incidentLng, focusRequest]); + return ( <>
{ if (!map || !routeGeometry || routeGeometry.coordinates.length < 2) return; const palette = mapPalette(theme); @@ -51,8 +59,10 @@ export function RouteLayer({ map, routeGeometry, styleRevision, theme, mode }: R type: "line", source: sourceId, paint: { - "line-color": mode === "DISABLED" ? palette.routeStandard : palette.routeLive, + "line-color": + preview || mode === "DISABLED" ? palette.routeStandard : palette.routeLive, "line-width": 7, + ...(preview ? { "line-dasharray": [2, 1.5] } : {}), }, layout: { "line-cap": "round", "line-join": "round" }, }, @@ -64,7 +74,7 @@ export function RouteLayer({ map, routeGeometry, styleRevision, theme, mode }: R if (map.getLayer(casingId)) map.removeLayer(casingId); if (map.getSource(sourceId)) map.removeSource(sourceId); }; - }, [map, routeGeometry, styleRevision, theme, mode]); + }, [map, routeGeometry, styleRevision, theme, mode, preview]); return null; } diff --git a/frontend/src/components/workspace/WorkspaceShell.tsx b/frontend/src/components/workspace/WorkspaceShell.tsx index ca77942..c58a212 100644 --- a/frontend/src/components/workspace/WorkspaceShell.tsx +++ b/frontend/src/components/workspace/WorkspaceShell.tsx @@ -31,6 +31,7 @@ export function WorkspaceShell({ sheet, header, defaultDetails = true, + boundedInspector = false, provenance = "Simulated · all signal states", statusAlign = "start", }: { @@ -48,6 +49,8 @@ export function WorkspaceShell({ sheet?: WorkspaceSheet; header: ReactNode; defaultDetails?: boolean; + /** Live monitoring owns its inner scroll regions instead of scrolling the inspector. */ + boundedInspector?: boolean; provenance?: string; }) { const { t } = useTranslation(); @@ -149,6 +152,7 @@ export function WorkspaceShell({ id="workspace-inspector" aria-label={t("Simulation details")} className="workspace-inspector surface-glass" + data-bounded={boundedInspector || undefined} data-map-occluder hidden={panelHidden} inert={panelHidden} diff --git a/frontend/src/lib/mock-dispatch.test.ts b/frontend/src/lib/mock-dispatch.test.ts index 8ac3199..40114bb 100644 --- a/frontend/src/lib/mock-dispatch.test.ts +++ b/frontend/src/lib/mock-dispatch.test.ts @@ -172,3 +172,30 @@ describe("coincident station dispatch", () => { expect(result.candidates[0].station.station_id).toBe("STN-A-0001"); }); }); + +it("returns the same preview line that mock playback drives", async () => { + const { createMockSession } = await import("./mock-session"); + const destination = { lat: 50.065, lng: 19.945 }; + const ranked = await createMockDispatchAdapter(STATIONS).rank({ + incident: destination, + vehicle_type: "AMBULANCE", + availability: {}, + resource_aware: false, + time_mode: "ENABLED", + traffic_density_multiplier: 1, + }); + const chosen = ranked.candidates[0]; + const session = createMockSession({ + simulation_id: "SIM-preview", + origin: chosen.station.position, + destination, + vehicle_type: "AMBULANCE", + traffic_density_multiplier: 1, + enable_cascade_mode: true, + playback_speed: 1, + green_wave_mode: "ENABLED", + its_scenario: "NOMINAL", + its_outcome_seed: 0, + }); + expect(chosen.route_geometry).toEqual(session.route.route_geometry); +}); diff --git a/frontend/src/lib/mock-dispatch.ts b/frontend/src/lib/mock-dispatch.ts index 1ed7fc9..8c1bef9 100644 --- a/frontend/src/lib/mock-dispatch.ts +++ b/frontend/src/lib/mock-dispatch.ts @@ -8,7 +8,7 @@ import type { DispatchAdapter } from "@/lib/dispatch-adapter"; import { SimulationAdapterError } from "@/lib/transport/errors"; import { validateStations } from "@/lib/transport/validate"; import { warsawMinute } from "@/lib/local-time"; -import { haversineMeters } from "@/lib/mock-route-metrics"; +import { haversineMeters, mockRouteGeometry } from "@/lib/mock-route-metrics"; import type { Station } from "@/types/telemetry"; export function createMockDispatchAdapter( @@ -68,6 +68,7 @@ export function createMockDispatchAdapter( standard_seconds: 0, distance_m: nearest.distance, on_site: false, + route_geometry: mockRouteGeometry(nearest.station.position, incident), }, ] : []), diff --git a/frontend/src/lib/mock-route-metrics.ts b/frontend/src/lib/mock-route-metrics.ts index 444637c..8ac9929 100644 --- a/frontend/src/lib/mock-route-metrics.ts +++ b/frontend/src/lib/mock-route-metrics.ts @@ -4,7 +4,7 @@ import { MOCK_REFERENCE_GREENWAVE_SECONDS, MOCK_REFERENCE_NORMAL_SECONDS, } from "@/lib/mock-simulation-config"; -import type { Position } from "@/types/telemetry"; +import type { Position, RouteGeometry } from "@/types/telemetry"; const EARTH_RADIUS_M = 6_371_000; @@ -40,3 +40,14 @@ export function estimateMockRoute( greenwaveSeconds: scale * MOCK_REFERENCE_GREENWAVE_SECONDS, }; } + +/** The synthetic straight line used by both setup and mock playback. */ +export function mockRouteGeometry(origin: Position, destination: Position): RouteGeometry { + return { + type: "LineString", + coordinates: [ + [origin.lng, origin.lat], + [destination.lng, destination.lat], + ], + }; +} diff --git a/frontend/src/lib/mock-session.ts b/frontend/src/lib/mock-session.ts index c370514..9494e61 100644 --- a/frontend/src/lib/mock-session.ts +++ b/frontend/src/lib/mock-session.ts @@ -18,7 +18,11 @@ import { MOCK_STANDARD_MAX_RED_LOSS_SECONDS, MOCK_STANDARD_MIN_ROLLING_SPEED_MPS, } from "@/lib/mock-simulation-config"; -import { estimateMockRoute, type MockRouteMetrics } from "@/lib/mock-route-metrics"; +import { + estimateMockRoute, + mockRouteGeometry, + type MockRouteMetrics, +} from "@/lib/mock-route-metrics"; import { SimulationAdapterError } from "@/lib/transport/errors"; import { positionOnRoute } from "@/lib/route-position"; import { simulatedVehicleId } from "@/lib/vehicle-ids"; @@ -156,13 +160,7 @@ function createMockRoute( distance_along_route_m: routeFraction * metrics.distanceMeters, }), ); - const routeGeometry: SimulationStartResponse["route_geometry"] = { - type: "LineString", - coordinates: [ - [request.origin.lng, request.origin.lat], - [request.destination.lng, request.destination.lat], - ], - }; + const routeGeometry = mockRouteGeometry(request.origin, request.destination); const routeIntersections = scaledIntersections.map((intersection, sourceIndex) => { // Synthetic position: the sample distance projected onto the straight mock line. const coordinates = positionOnRoute( diff --git a/frontend/src/lib/polish.ts b/frontend/src/lib/polish.ts index f03d043..3411606 100644 --- a/frontend/src/lib/polish.ts +++ b/frontend/src/lib/polish.ts @@ -1,5 +1,12 @@ /** Polish presentation copy. English keys also provide the English catalog. */ export const polish: Record = { + "Route signal entries": "Lista sygnalizacji na trasie", + "ITS gateway entries": "Wpisy bramki ITS", + "Planning route…": "Wyznaczanie trasy…", + "Planned route": "Planowana trasa", + "Route preview unavailable": "Podgląd trasy niedostępny", + "No eligible unit for this incident": "Brak dostępnego zespołu dla tego zdarzenia", + "On site · no vehicle route": "Na miejscu · dojazd nie jest potrzebny", "Zoom in": "Powiększ", "Zoom out": "Pomniejsz", "Toggle attribution": "Pokaż źródła mapy", diff --git a/frontend/src/lib/station-choice.test.ts b/frontend/src/lib/station-choice.test.ts index a258613..d3ed071 100644 --- a/frontend/src/lib/station-choice.test.ts +++ b/frontend/src/lib/station-choice.test.ts @@ -214,3 +214,51 @@ describe("rankTimeModeFor", () => { expect(rankTimeModeFor("DISABLED", "comparison")).toBe("ENABLED"); }); }); + +it("previews only the ready, selected candidate using the page's start criteria", async () => { + const { plannedRoute } = await import("./station-choice"); + const { TEAM_RANK } = await import("./transport/__fixtures__/team-dispatch"); + const geometry = { + type: "LineString" as const, + coordinates: [ + [19.9, 50], + [19.94, 50.06], + ] as [number, number][], + }; + const ranking = { + ...TEAM_RANK, + candidates: TEAM_RANK.candidates.map((c, i) => ({ + ...c, + route_geometry: { + ...geometry, + coordinates: [ + [19.9 + i / 100, 50], + [19.94, 50.06], + ] as [number, number][], + }, + })), + }; + const ready = { rankStatus: "ready" as const, ranking, selectedStationId: null }; + expect(plannedRoute(ready, "GREENWAVE")).toEqual(ranking.candidates[0].route_geometry); + expect(plannedRoute(ready, "STANDARD")).toEqual(ranking.candidates[0].route_geometry); + expect( + plannedRoute( + { ...ready, selectedStationId: ranking.candidates[1].station.station_id }, + "STANDARD", + ), + ).toEqual(ranking.candidates[1].route_geometry); + for (const rankStatus of ["idle", "loading", "error"] as const) + expect(plannedRoute({ ...ready, rankStatus }, "GREENWAVE")).toBeNull(); + expect( + plannedRoute({ ...ready, ranking: { ...ranking, candidates: [] } }, "GREENWAVE"), + ).toBeNull(); + expect( + plannedRoute( + { + ...ready, + ranking: { ...ranking, candidates: [{ ...ranking.candidates[0], on_site: true }] }, + }, + "GREENWAVE", + ), + ).toBeNull(); +}); diff --git a/frontend/src/lib/station-choice.ts b/frontend/src/lib/station-choice.ts index ac0d07d..473e019 100644 --- a/frontend/src/lib/station-choice.ts +++ b/frontend/src/lib/station-choice.ts @@ -4,6 +4,7 @@ import type { GreenWaveMode, OnFootLeg, RankedCandidate, + RouteGeometry, Station, VehicleType, } from "@/types/telemetry"; @@ -143,3 +144,13 @@ export function shownOnSite( export function canStart(dispatch: Pick): boolean { return dispatch.rankStatus === "ready" && (dispatch.ranking?.candidates.length ?? 0) > 0; } + +/** The same candidate Start uses; never reveal stale geometry during a re-rank. */ +export function plannedRoute( + state: Pick, + mode: TimeMode, +): RouteGeometry | null { + if (state.rankStatus !== "ready") return null; + const candidate = pageCandidate(state, mode); + return candidate?.on_site ? null : (candidate?.route_geometry ?? null); +} diff --git a/frontend/src/lib/transport/validate.test.ts b/frontend/src/lib/transport/validate.test.ts index 2be1edc..f836324 100644 --- a/frontend/src/lib/transport/validate.test.ts +++ b/frontend/src/lib/transport/validate.test.ts @@ -626,3 +626,20 @@ describe("resource-aware ambulance ranking (ADR 0014)", () => { expect(() => validateResources(wire(RESOURCES, (c) => (c.roster = null)))).toThrow("roster"); }); }); + +it("rejects invalid preview geometry instead of drawing an untrusted route", () => { + expect(() => + validateRank( + wire(TEAM_RANK, (body) => { + const candidates = body.candidates as Record[]; + candidates[0].route_geometry = { + type: "LineString", + coordinates: [ + [19.9, 50], + ["bad", 50], + ], + }; + }), + ), + ).toThrow(); +}); diff --git a/frontend/src/lib/transport/validate.ts b/frontend/src/lib/transport/validate.ts index 3a9abce..9cc1949 100644 --- a/frontend/src/lib/transport/validate.ts +++ b/frontend/src/lib/transport/validate.ts @@ -240,17 +240,7 @@ export function parseStartResponse(value: unknown): SimulationStartResponse { envelope(body); if (body.status !== "INITIALIZED") fail("status", '"INITIALIZED"'); - const geometry = record(body.route_geometry, "route_geometry"); - if (geometry.type !== "LineString") fail("route_geometry.type", '"LineString"'); - const coordinates = list(geometry.coordinates, "route_geometry.coordinates"); - if (coordinates.length < 2) fail("route_geometry.coordinates", "at least 2 coordinates"); - coordinates.forEach((pair, index) => { - const path = `route_geometry.coordinates[${index}]`; - const lngLat = list(pair, path); - if (lngLat.length !== 2) fail(path, "a [lng, lat] pair"); - finite(lngLat[0], `${path}[0]`); - finite(lngLat[1], `${path}[1]`); - }); + routeGeometry(body.route_geometry, "route_geometry"); finite(body.total_distance_m, "total_distance_m"); finite(body.estimated_normal_time_sec, "estimated_normal_time_sec"); @@ -672,6 +662,20 @@ export function validateResources(body: unknown): ResourcesResponse { return response as ResourcesResponse; } +function routeGeometry(value: unknown, path: string): void { + const geometry = record(value, path); + if (geometry.type !== "LineString") fail(`${path}.type`, '"LineString"'); + const coordinates = list(geometry.coordinates, `${path}.coordinates`); + if (coordinates.length < 2) fail(`${path}.coordinates`, "at least 2 coordinates"); + coordinates.forEach((pair, index) => { + const pairPath = `${path}.coordinates[${index}]`; + const lngLat = list(pair, pairPath); + if (lngLat.length !== 2) fail(pairPath, "a [lng, lat] pair"); + finite(lngLat[0], `${pairPath}[0]`); + finite(lngLat[1], `${pairPath}[1]`); + }); +} + export function validateRank(body: unknown): DispatchRankResponse { const response = record(body, "response"); if (response.schema_version !== "1.0") fail("schema_version", '"1.0"'); @@ -689,6 +693,8 @@ export function validateRank(body: unknown): DispatchRankResponse { nonNegative(candidate.greenwave_seconds, `${path}.greenwave_seconds`); nonNegative(candidate.standard_seconds, `${path}.standard_seconds`); nonNegative(candidate.distance_m, `${path}.distance_m`); + if (candidate.route_geometry != null) + routeGeometry(candidate.route_geometry, `${path}.route_geometry`); optionalOnFootLeg(candidate.on_foot, `${path}.on_foot`); bool(candidate.on_site, `${path}.on_site`); teamAssignment(candidate.team, `${path}.team`); diff --git a/frontend/src/lib/useIncidentDispatch.test.ts b/frontend/src/lib/useIncidentDispatch.test.ts index 021591b..4807148 100644 --- a/frontend/src/lib/useIncidentDispatch.test.ts +++ b/frontend/src/lib/useIncidentDispatch.test.ts @@ -9,7 +9,7 @@ import { pinnedIncident, type Incident, } from "@/lib/useIncidentDispatch"; -import { pageCandidate } from "@/lib/station-choice"; +import { pageCandidate, plannedRoute } from "@/lib/station-choice"; import { RESOURCES } from "@/lib/transport/__fixtures__/team-dispatch"; import type { DispatchRankRequest, DispatchRankResponse } from "@/types/telemetry"; @@ -64,6 +64,13 @@ const ranking = (stationId: string): DispatchRankResponse => ({ greenwave_seconds: 120, standard_seconds: 150, distance_m: 900, + route_geometry: { + type: "LineString", + coordinates: [ + [19.9, 50], + [19.94, stationId.endsWith("2") ? 50.02 : 50.01], + ], + }, on_site: false, }, ], @@ -145,6 +152,7 @@ describe("createIncidentDispatch", () => { await flush(); expect(dispatch.getState().ranking?.candidates[0].station.station_id).toBe("STN-A-0002"); + expect(plannedRoute(dispatch.getState(), "GREENWAVE")?.coordinates[1]).toEqual([19.94, 50.02]); expect(dispatch.getState().incident?.position.lat).toBe(50.02); expect(dispatch.getState().rankStatus).toBe("ready"); }); @@ -169,7 +177,9 @@ describe("createIncidentDispatch", () => { calls[0].resolve(ranking("STN-A-0001")); await flush(); + expect(plannedRoute(dispatch.getState(), "GREENWAVE")).not.toBeNull(); dispatch.setVehicleType("FIRE_TRUCK"); + expect(plannedRoute(dispatch.getState(), "GREENWAVE")).toBeNull(); expect(calls).toHaveLength(2); expect(calls[1].request.vehicle_type).toBe("FIRE_TRUCK"); diff --git a/frontend/src/types/api.generated.ts b/frontend/src/types/api.generated.ts index c051a4d..9d6c73a 100644 --- a/frontend/src/types/api.generated.ts +++ b/frontend/src/types/api.generated.ts @@ -701,6 +701,7 @@ export interface components { * @default false */ on_site: boolean; + route_geometry?: components["schemas"]["RouteGeometry"] | null; /** Selection Reason */ selection_reason?: ("NEAREST" | "IN_AREA_WITHIN_MARGIN" | "NEAREST_OUTSIDE_MARGIN") | null; /** Standard Seconds */