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 @@
- Dispatch console / 01 Vehicle type or click the map Address search needs the backend Pick an incident location to choose the fastest station. Simulation parameters Green Wave enabled Simulated ITS feedback How the simulated signal controller answers each priority request. Times count from each priority request in simulated seconds. Acceptance starts signal clearing. After a rejection or an 8 s acknowledgement timeout, only those junctions use ordinary signals; the run continues. Cascade corridor mode Group nearby signals within 250 m Times are model estimates. Controller responses may delay passage or cause individual junctions to use ordinary signals; the run continues. Select an incident and wait for a station selection to see the simulated run times. Route estimates come from the simulation backend. All signal states are simulated. Dispatch console / 01 Vehicle type or click the map Address search needs the backend Pick an incident location to choose the fastest station. Simulation parameters Green Wave enabled Simulated ITS feedback How the simulated signal controller answers each priority request. Times count from each priority request in simulated seconds. Acceptance starts signal clearing. After a rejection or an 8 s acknowledgement timeout, only those junctions use ordinary signals; the run continues. Cascade corridor mode Group nearby signals within 250 m Times are model estimates. Controller responses may delay passage or cause individual junctions to use ordinary signals; the run continues. Select an incident and wait for a station selection to see approximate mock estimates. Demo uses synthetic route estimates and sample signal telemetry. Dispatch console / 01 Vehicle type or click the map Address search needs the backend Pick an incident location to choose the fastest station. Simulation parameters Green Wave enabled Simulated ITS feedback How the simulated signal controller answers each priority request. Times count from each priority request in simulated seconds. Acceptance starts signal clearing. After a rejection or an 8 s acknowledgement timeout, only those junctions use ordinary signals; the run continues. Cascade corridor mode Group nearby signals within 250 m Times are model estimates. Controller responses may delay passage or cause individual junctions to use ordinary signals; the run continues. Select an incident and wait for a station selection to see approximate mock estimates. Demo uses synthetic route estimates and sample signal telemetry.Incident dispatch
Traffic model
Incident dispatch
Traffic model
Incident dispatch
Traffic model
{t("Corridor monitoring")}
@@ -77,7 +77,12 @@ export function IntersectionList() {{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 ( -+ {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
ITS feedback unavailable
Corridor monitoring
ITS feedback unavailable