Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions backend/src/greenwave/api/dispatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
11 changes: 10 additions & 1 deletion backend/src/greenwave/routing/station_ranking.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)."""
Expand Down Expand Up @@ -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(
Expand Down
3 changes: 3 additions & 0 deletions backend/src/greenwave/schemas/dispatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
GreenWaveMode,
OnFootLeg,
Position,
RouteGeometry,
SchemaVersion,
SnappedEndpoint,
VehicleType,
Expand Down Expand Up @@ -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.
Expand Down
42 changes: 42 additions & 0 deletions backend/tests/api/test_dispatch_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
10 changes: 10 additions & 0 deletions contracts/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -1189,6 +1189,16 @@
"title": "On Site",
"type": "boolean"
},
"route_geometry": {
"anyOf": [
{
"$ref": "#/components/schemas/RouteGeometry"
},
{
"type": "null"
}
]
},
"selection_reason": {
"anyOf": [
{
Expand Down
16 changes: 16 additions & 0 deletions docs/engineering/frontend-dashboard.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
42 changes: 42 additions & 0 deletions docs/superpowers/plans/2026-10-30-route-preview.md
Original file line number Diff line number Diff line change
@@ -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.
15 changes: 15 additions & 0 deletions docs/superpowers/specs/2026-10-30-route-preview-design.md
Original file line number Diff line number Diff line change
@@ -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.
69 changes: 69 additions & 0 deletions frontend/scripts/smoke/route-preview-and-scroll.js
Original file line number Diff line number Diff line change
@@ -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);
}
32 changes: 32 additions & 0 deletions frontend/scripts/smoke/route-preview-modes.js
Original file line number Diff line number Diff line change
@@ -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;
}
51 changes: 51 additions & 0 deletions frontend/src/app/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Loading
Loading