diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index be2d062..3f9f804 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -100,7 +100,7 @@ A task is done only when **all** of these hold. Anything missing must be stated - Tests exist for the behaviour and encode *why* it matters; `pnpm check` green, no skipped tests. - Relevant e2e spec green. -- No `alert` / `confirm` / `prompt`; no API keys; nothing from the banned list (Shopify, Google Maps, geocoders, QR, GPS). No external API calls, with ONE user-approved exception (2026-08-31): `plan_route` calls the keyless FOSSGIS OSRM service (`routing.openstreetmap.de`) at runtime — throttled to their published 1 request/second policy, attributed on the page, failing honestly when unreachable, and mocked or network-blocked in every test (the suite stays network-isolated). No other runtime external data call is permitted (the keyless OpenFreeMap basemap tiles predate this rule and stay display-only). +- No `alert` / `confirm` / `prompt`; no API keys; nothing from the banned list (Shopify, Google Maps, geocoders, QR, GPS). No external API calls, with ONE user-approved exception (2026-08-31, widened to the human gesture 2026-09-02): walking routes are planned by the keyless FOSSGIS OSRM service (`routing.openstreetmap.de`) at runtime — asked by the `plan_route` tool and by the human Route pill, through the one shared throttle in `src/lib/map-tools/route.ts` that keeps their published 1 request/second policy, attributed on the page, failing honestly when unreachable, and mocked or network-blocked in every test (the suite stays network-isolated). No other runtime external data call is permitted (the keyless OpenFreeMap basemap tiles predate this rule and stay display-only). - Docs updated if the change is visible to judges or users. - Everything in the repo is English. The only permitted CJK is a genuine place name or OSM tag value: in string literals that are data (queries, test inputs), and quoted inside English prose — a comment or commit message may name 大安森林公園 when that specific name is what the sentence is about, because renaming it would make the sentence false. Prose around the quoted name stays English; CJK sentences never appear. - A PR whose suite contains `test.fail()`-marked known-defect tests must say so explicitly in "How verified" — green CI must never hide a known defect. diff --git a/docs/TASKS.md b/docs/TASKS.md index 432c361..28ecbbe 100644 --- a/docs/TASKS.md +++ b/docs/TASKS.md @@ -72,7 +72,7 @@ Owner asked how a human uses routing; the answer was "only through an agent". Pa | ID | Task | Owner | Status | Notes | |---|---|---|---|---| -| T-110 | Fourth pill "Route": click a start, click an end, the same `planWalk` (shared 1 req/s throttle, not re-implemented) draws a `source: "user"` line labelled `walking route · 1.2 km · 16 min`; a refusal shows the service's sentence in the hint and leaves the person in route mode; `Escape` cancels. A human route latches the FOSSGIS credit exactly as an agent's does | map-ui-dev → qa → review | doing | Nothing under `src/lib/**` changes; `remove_from_map` keeps refusing human marks, so an agent cannot remove a human's route | +| T-110 | Fourth pill "Route": click a start, click an end, the same `planWalk` (shared 1 req/s throttle, not re-implemented — a unit test finds the shared queue still busy after a hand-planned walk) draws a `source: "user"` line labelled `walking route · 1.2 km · 16 min`; a refusal shows the service's sentence in the hint and leaves the person in route mode; `Escape` cancels. A human route latches the FOSSGIS credit exactly as an agent's does | map-ui-dev → qa → review | done | Nothing under `src/lib/**` changes; `remove_from_map` keeps refusing human marks, so an agent cannot remove a human's route. Review: no blockers; README and CONTRIBUTING wording widened to name both callers of the routing service (README half rides T-111). e2e `route-human-gesture.spec.ts` pins all seven contract points | ## Follow-ups (ticketed, unscheduled) @@ -91,6 +91,7 @@ Owner asked how a human uses routing; the answer was "only through an agent". Pa - **F-13 (tool-dev)** No tool echoes an annotation's coordinate: `AnnotationOutput` (`state.ts:55`) carries `id`, `note`, `source` only, so an agent that pinned a note by place name cannot confirm where it landed without re-resolving the name itself. Found writing the T-106 e2e, which had to read the store directly. Adding `at: [lng, lat]` (5 dp) costs ~30 B a note. - **F-14 (map-ui-dev)** At ≤640 px the loaded-categories strip overflows the bottom bar's left edge by 6–22 px (`.bottom-bar` is `justify-content: flex-end` and `.corner` is `flex-shrink: 0`, so overflow goes left). Text stays readable. Fix is letting `.corner` shrink at that tier — not `safe flex-end`, which would push the attribution off the right instead. Found during T-109. - **F-15 (map-ui-dev)** `.pin-card` has `max-width: 210px` and no `max-height`: `annotate` with `"a\n".repeat(250)` renders a ~4,400 px bubble that covers other pins. The fold (T-107) is the current escape hatch. A companion cap (`max-height` + fold-on-overflow, or collapsing interior newlines in the bubble only) is a design call. Found during T-108's review. +- **F-16 (qa)** `e2e/awakening-flight.spec.ts:249` reads bounds immediately after `setViewportSize` and races the republish (~4/24 on develop). Same family as F-1; the fix is a wait on the republished bounds, never a sleep. Handed to qa 2026-09-02. ## Handoff log @@ -115,5 +116,7 @@ Append-only. `date · from → to · what`. - 2026-08-31 · orchestrator → all · The 2026-08-28 line "delete is UI-only" is superseded by T-90: `remove_from_map` gives agents removal of agent-sourced drawings/annotations and any selection entry; user-sourced marks stay human-only (refused per-id with the reason). - 2026-09-01 · orchestrator → all · `CONTRIBUTING.md` English rule relaxed: a genuine place name may be quoted inside English prose (a comment or commit message), because `gazetteer.ts:32-33` cannot explain the 大安 / 大安森林公園 disambiguation without naming it. CJK sentences are still banned. The rule text was out of date, not the code. - 2026-09-01 · orchestrator → all · `scripts/ship-pr.sh --merge-back` runs `git switch` in the repo root, which fails when the head branch is checked out in a worktree. Merge `origin/develop` inside the worktree instead, then ship without the flag — and it is the better order anyway, because the integration check then runs against the base you are merging into. +- 2026-09-02 · qa → all (lesson) · Every tool call writes an activity row, read-only ones included — `get_map_state` too. "A human gesture writes no row" is only assertable before the next tool call, so an e2e that checks it must read the store, not call a tool, or assert before the first call. +- 2026-09-02 · orchestrator → qa · `e2e/awakening-flight.spec.ts:249` flakes ~4/24 on develop: it reads bounds right after `setViewportSize` with no wait for the republish. Wait for the republished bounds (no fixed sleep). Ticketed F-16. - 2026-09-01 · review → all (lesson) · Four of the T-41 README defects were the same shape: prose describing what a surface was *designed* to do rather than what the component does. Read the component before the sentence, not the sibling doc. - 2026-09-02 · qa → tool-dev · Beads are tier-2/browse-only: a selected *bundled* feature paints a selection ring, and its clickable render is its category's circle layer (`INTERACTIVE_LAYER_IDS`), not `BEAD_LAYER_IDS`. A spec that needs to tap a selected station must query the interactive layers. diff --git a/e2e/route-human-gesture.spec.ts b/e2e/route-human-gesture.spec.ts new file mode 100644 index 0000000..d6799a9 --- /dev/null +++ b/e2e/route-human-gesture.spec.ts @@ -0,0 +1,436 @@ +/** + * T-110 -- a person plans a walking route by hand: click where it starts, + * click where it ends, and the Route pill draws it the same way `plan_route` + * does, but as `source: "user"` and with no activity row (a hand gesture is + * not a tool call). + * + * `src/components/draw-store.ts` (`addRouteVertex`, the same-point guard, the + * planning ticket), `DrawToolbar.tsx` (`RoutePill`, `routeHint`, `DrawHint`), + * `route-label.ts` (`routeLabel`), `route-draft-marker.ts` and the route half + * of `MapCanvas.tsx`'s click handlers already have this file's premises spelt + * out; nothing here mirrors their logic back at them; every expected string + * below is either the contract's own wording or computed by hand from + * `route-label.ts`'s documented rounding, not by importing the formatter. + * + * `plan-route.spec.ts` proves the agent's `plan_route` end to end and this + * file leans on its conventions throughout (`mockExternalHost`, the OSRM + * fixture shape, the network-isolation posture: this suite aborts every + * non-localhost request by default, so `routing.openstreetmap.de` must be + * registered and mocked per test that expects a real request to complete). + * `note-human-gestures.spec.ts` is where the human-gesture conventions this + * file follows come from: fresh page per test, `clickMapOffset`/ + * `unprojectRounded` against the map's own `unproject`, and the + * basemap-style-mock escape hatch needed for `INTERACTIVE_LAYER_IDS` click + * handlers to exist at all (they are only added inside MapLibre's `load`). + */ +import type { Page } from "@playwright/test"; +import type { Position } from "geojson"; +import type { LngLat } from "@/lib/store/map-store"; +import { INTERACTIVE_LAYER_IDS } from "@/components/map-style"; +import { callTool } from "./mcp"; +import { expect, mockExternalHost, test } from "./fixtures"; +import { waitForFeatures, waitForLiveMap, waitForStoreHandle, waitForTools } from "./helpers"; + +const ROUTE_HOST = "routing.openstreetmap.de"; +const ROUTE_PATTERN = "**/routing.openstreetmap.de/**"; + +/** Any two valid points, unrelated to what a test actually clicked: nothing + * in `route.ts` cross-checks the service's returned geometry against the + * request's endpoints, so a fixed line is enough for every "success" fixture + * below. */ +const FIXTURE_LINE: Position[] = [ + [121.54355, 25.03333], + [121.51591, 25.04747], +]; + +/** + * The OSRM-shaped success body this file draws its walk from throughout. + * distance/duration are chosen, not arbitrary: `routeLabel(1234, 754)` is + * "walking route · 1.2 km · 13 min" by `route-label.ts`'s own documented + * rules (1234 m -> 1.234 km, one decimal since < 10 km; 754 s -> ceil(754/60) + * = 13 min, never rounded down) -- computed here by hand, not by calling the + * formatter, so a change to either rule breaks this file's own expectation + * rather than silently agreeing with whatever the code now does. + */ +const FIXTURE_DISTANCE_M = 1234; +const FIXTURE_DURATION_S = 754; +const EXPECTED_ROUTE_LABEL = "walking route · 1.2 km · 13 min"; +const ROUTE_ATTRIBUTION_TEXT = + "Walking route by the FOSSGIS OSRM service, data © OpenStreetMap contributors"; + +function routeSuccessBody(distance = FIXTURE_DISTANCE_M, duration = FIXTURE_DURATION_S) { + return { + code: "Ok", + routes: [ + { + distance, + duration, + geometry: { type: "LineString", coordinates: FIXTURE_LINE }, + }, + ], + }; +} + +async function goReady(page: Page): Promise { + await page.goto("/?shim=1"); + await waitForTools(page); + await waitForFeatures(page); + await waitForLiveMap(page); + await waitForStoreHandle(page); +} + +/** The map container's own box -- full-bleed (globals.css: `.map-wrap { inset: 0 }`). */ +async function mapBox(page: Page) { + const box = await page.getByTestId("map").boundingBox(); + if (!box) throw new Error("map container has no box"); + return box; +} + +/** Clicks `(dx, dy)` away from the map's own centre and returns the page-space pixel clicked. */ +async function clickMapOffset(page: Page, dx: number, dy: number): Promise<{ x: number; y: number }> { + const box = await mapBox(page); + const x = box.x + box.width / 2 + dx; + const y = box.y + box.height / 2 + dy; + await page.mouse.click(x, y); + return { x, y }; +} + +/** What the click at `(x, y)` really unprojects to, rounded the same way `draw-store.ts`'s + * `roundVertex` rounds a clicked point -- the independent half of the "the request carries + * what was actually clicked" proof. */ +async function unprojectRounded(page: Page, x: number, y: number): Promise { + return page.evaluate( + ({ x, y }) => { + const { lng, lat } = window.__glassmapMap!.unproject([x, y]); + const round5 = (n: number) => Math.round(n * 1e5) / 1e5; + return [round5(lng), round5(lat)] as LngLat; + }, + { x, y }, + ); +} + +async function startRouteMode(page: Page): Promise { + await page.getByTestId("route-toggle").click(); + await expect(page.getByTestId("route-toggle")).toHaveAttribute("aria-pressed", "true"); +} + +function rectsOverlap( + a: { x: number; y: number; width: number; height: number }, + b: { x: number; y: number; width: number; height: number }, +): boolean { + return a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y; +} + +test.describe("T-110 -- a person plans a walk by clicking two points", () => { + test("happy path: two clicks plan and draw the walk, with no activity row -- and the agent's own plan_route stays untouched", async ({ + page, + mockedExternalHosts, + }) => { + test.setTimeout(45_000); + await goReady(page); + + mockExternalHost(mockedExternalHosts, ROUTE_HOST); + const urls: string[] = []; + let releasePlanning: () => void = () => {}; + const planningGate = new Promise((resolve) => { + releasePlanning = resolve; + }); + await page.route(ROUTE_PATTERN, async (route) => { + urls.push(route.request().url()); + await planningGate; + return route.fulfill({ + status: 200, + contentType: "application/json", + body: JSON.stringify(routeSuccessBody()), + }); + }); + + await startRouteMode(page); + await expect(page.getByTestId("route-toggle").locator(".lbl")).toHaveText("Cancel"); + await expect(page.getByTestId("draw-mode")).toHaveText("route"); + const hint = page.getByTestId("draw-hint"); + await expect(hint).toHaveAttribute("data-mode", "route"); + await expect(hint).toHaveText("Click where the walk starts. Esc to cancel."); + + // Well clear of the tools row (top:14/right:14) and the search box + // (top:62/left:14/width:302) at this viewport, and far enough apart from + // each other that neither click could round to the other by accident. + const start = await clickMapOffset(page, 220, 90); + await expect(page.getByTestId("route-draft-pin")).toHaveCount(1); + await expect(hint).toHaveText("Click where it ends."); + + const end = await clickMapOffset(page, -220, -90); + // Caught mid-flight, before the delayed fixture answers. + await expect(hint).toHaveText("Planning the walk…"); + + expect(urls).toHaveLength(1); + const fromPoint = await unprojectRounded(page, start.x, start.y); + const toPoint = await unprojectRounded(page, end.x, end.y); + expect(urls[0]).toContain(`${fromPoint[0]},${fromPoint[1]}`); + expect(urls[0]).toContain(`${toPoint[0]},${toPoint[1]}`); + + releasePlanning(); + + await expect(page.getByTestId("draw-hint")).toHaveCount(0); + await expect(page.getByTestId("draw-mode")).toHaveText("off"); + await expect(page.getByTestId("route-draft-pin")).toHaveCount(0); + // A second click while planning would have spent the next second's + // request or been dropped by the store -- either way, still exactly one. + expect(urls).toHaveLength(1); + + await expect(page.getByTestId("route-attribution")).toHaveText(ROUTE_ATTRIBUTION_TEXT); + // A hand-planned walk is not a tool call: nothing in the feed yet -- checked + // before any tool below runs (get_map_state/measure/plan_route each log + // their own row; every one of those would land here too, since the + // selector below is untargeted). + await expect(page.locator('[data-testid="activity-call"]')).toHaveCount(0); + + const state = await callTool(page, "get_map_state"); + expect(state.error).toBeUndefined(); + expect(state.drawings?.count).toBe(1); + expect(state.drawings?.items[0]).toMatchObject({ + source: "user", + kind: "line", + label: EXPECTED_ROUTE_LABEL, + }); + + const measured = await callTool(page, "measure", { target: "drawing:1" }); + expect(measured.error).toBeUndefined(); + expect(measured.length_m).toBeGreaterThan(0); + + // --- Agent tool untouched (T-110's other half) ------------------------ + const planned = await callTool(page, "plan_route", { from: "Daan Station", to: "Daan Forest Park" }); + expect(planned.error).toBeUndefined(); + expect(planned.drawing_id).toBe("drawing:2"); + + const drawings = await page.evaluate(() => window.__glassmapStore!.getState().drawings); + expect(drawings).toHaveLength(2); + expect(drawings[0]).toMatchObject({ id: "drawing:1", source: "user" }); + expect(drawings[1]).toMatchObject({ id: "drawing:2", source: "agent" }); + await expect( + page.locator('[data-testid="activity-call"][data-tool="plan_route"]'), + ).toHaveCount(1); + + // remove_from_map refuses the human's own line, and it survives. + const removed = await callTool(page, "remove_from_map", { ids: ["drawing:1"] }); + expect(removed.error).toBeUndefined(); + expect(removed.removed).toEqual([]); + expect(removed.refused).toEqual([{ id: "drawing:1", kind: "drawing", source: "user" }]); + const survivingIds = await page.evaluate(() => + window.__glassmapStore!.getState().drawings.map((d) => d.id), + ); + expect(survivingIds).toContain("drawing:1"); + }); + + test("refusal: the service's own sentence is shown verbatim, nothing is drawn, and a retry is possible", async ({ + page, + mockedExternalHosts, + }) => { + await goReady(page); + + mockExternalHost(mockedExternalHosts, ROUTE_HOST); + const urls: string[] = []; + await page.route(ROUTE_PATTERN, (route) => { + urls.push(route.request().url()); + return route.fulfill({ + status: 200, + contentType: "application/json", + body: JSON.stringify({ code: "NoRoute" }), + }); + }); + + await startRouteMode(page); + await clickMapOffset(page, 220, 90); + await clickMapOffset(page, -220, -90); + + const hint = page.getByTestId("draw-hint"); + await expect(hint).toHaveText( + "the routing service could not plan this walk: there is no walking route between " + + "these two points. Nothing was drawn and the map is unchanged. Click a new start, or Esc.", + ); + expect(urls).toHaveLength(1); + + const state = await callTool(page, "get_map_state"); + expect(state.error).toBeUndefined(); + expect(state.drawings?.count).toBe(0); + await expect(page.getByTestId("draw-mode")).toHaveText("route"); + await expect(page.getByTestId("route-attribution")).toHaveCount(0); + + // The person can retry: a new pair of clicks makes a second request. + await clickMapOffset(page, 220, 90); + await clickMapOffset(page, -220, -90); + await expect.poll(() => urls.length).toBe(2); + }); + + test("same point twice: no request, the start survives, and the hint says what is still missing", async ({ + page, + blockedRequests, + }) => { + await goReady(page); + await startRouteMode(page); + + const start = await clickMapOffset(page, 220, 90); + await expect(page.getByTestId("route-draft-pin")).toHaveCount(1); + await page.mouse.click(start.x, start.y); + + await expect(page.getByTestId("draw-hint")).toHaveText( + "That is where the walk starts. Click where it ends.", + ); + await expect(page.getByTestId("route-draft-pin")).toHaveCount(1); + await expect(page.getByTestId("draw-mode")).toHaveText("route"); + expect(blockedRequests.filter((u) => u.includes(ROUTE_HOST))).toEqual([]); + }); + + test("Escape after one click cancels immediately, with no request ever made", async ({ + page, + blockedRequests, + }) => { + await goReady(page); + await startRouteMode(page); + await clickMapOffset(page, 220, 90); + await expect(page.getByTestId("route-draft-pin")).toHaveCount(1); + + await page.keyboard.press("Escape"); + + await expect(page.getByTestId("draw-mode")).toHaveText("off"); + await expect(page.getByTestId("route-draft-pin")).toHaveCount(0); + await expect(page.getByTestId("draw-hint")).toHaveCount(0); + expect(blockedRequests.filter((u) => u.includes(ROUTE_HOST))).toEqual([]); + }); + + test("Escape while planning discards the answer -- the line never appears, even once the fixture resolves", async ({ + page, + mockedExternalHosts, + }) => { + await goReady(page); + + mockExternalHost(mockedExternalHosts, ROUTE_HOST); + let releasePlanning: () => void = () => {}; + const planningGate = new Promise((resolve) => { + releasePlanning = resolve; + }); + await page.route(ROUTE_PATTERN, async (route) => { + await planningGate; + return route.fulfill({ + status: 200, + contentType: "application/json", + body: JSON.stringify(routeSuccessBody()), + }); + }); + + await startRouteMode(page); + await clickMapOffset(page, 220, 90); + await clickMapOffset(page, -220, -90); + await expect(page.getByTestId("draw-hint")).toHaveText("Planning the walk…"); + + await page.keyboard.press("Escape"); + await expect(page.getByTestId("draw-mode")).toHaveText("off"); + await expect(page.getByTestId("draw-hint")).toHaveCount(0); + + releasePlanning(); + // Give the now-answered (but invalidated) fetch a real chance to land. + await page.waitForTimeout(500); + + const state = await callTool(page, "get_map_state"); + expect(state.error).toBeUndefined(); + expect(state.drawings?.count).toBe(0); + await expect(page.getByTestId("route-attribution")).toHaveCount(0); + }); + + test("a click on a selected bundled feature is suppressed as a card and counted as the route's start", async ({ + page, + mockedExternalHosts, + }) => { + test.setTimeout(60_000); + // The bundled data layers' click handlers are only added inside MapLibre's + // `load`, which never fires under this suite's default network isolation + // (the real basemap CDN is blocked). A minimal-but-valid style response + // for that same blocked host is enough for `load` to fire without leaking + // a real network call -- the same escape hatch `note-human-gestures.spec.ts` + // and `place-details.spec.ts` already established for exactly this gap. + const BASEMAP_HOST = "tiles.openfreemap.org"; + mockExternalHost(mockedExternalHosts, BASEMAP_HOST); + await page.route(`**/${BASEMAP_HOST}/**`, (route) => + route.fulfill({ + status: 200, + contentType: "application/json", + body: JSON.stringify({ version: 8, sources: {}, layers: [] }), + }), + ); + await goReady(page); + await expect(page.getByTestId("map-status")).toHaveText("ready", { timeout: 20_000 }); + + // Da'an MRT station: bundled base data, loaded from the moment the page's + // datasets arrive, never through tier-2. + const STATION = { id: "osm:node:3494960748", lng: 121.54355, lat: 25.03333 }; + const selected = await callTool(page, "select_features", { ids: [STATION.id] }); + expect(selected.error).toBeUndefined(); + const view = await callTool(page, "set_map_view", { center: { lng: STATION.lng, lat: STATION.lat }, zoom: 15 }); + expect(view.error).toBeUndefined(); + + await page.evaluate( + () => + new Promise((resolve) => { + const map = window.__glassmapMap!; + const timer = setTimeout(resolve, 8000); + map.once("idle", () => { + clearTimeout(timer); + resolve(); + }); + }), + ); + + const stationPixel = await page.evaluate( + ({ id, layers }) => { + const map = window.__glassmapMap!; + const match = map + .queryRenderedFeatures({ layers }) + .find((f) => (f.properties as { id?: string })?.id === id && f.geometry.type === "Point"); + if (!match || match.geometry.type !== "Point") return null; + const projected = map.project(match.geometry.coordinates as [number, number]); + const hit = map.queryRenderedFeatures([projected.x, projected.y], { layers }); + return hit.some((f) => (f.properties as { id?: string })?.id === id) + ? { x: projected.x, y: projected.y } + : null; + }, + { id: STATION.id, layers: [...INTERACTIVE_LAYER_IDS] }, + ); + if (!stationPixel) { + throw new Error(`${STATION.id} was not hit-testable at INTERACTIVE_LAYER_IDS after set_map_view zoom 15`); + } + + // Closed route mode: the ordinary tap answers "what is this?" -- proof + // the station really is clickable at this pixel before route mode hides it. + await page.mouse.click(stationPixel.x, stationPixel.y); + const card = page.getByTestId("on-the-map-card"); + await expect(card).toHaveCount(1); + await page.getByTestId("otm-close").click(); + await expect(card).toHaveCount(0); + + await startRouteMode(page); + await page.mouse.click(stationPixel.x, stationPixel.y); + await expect(card).toHaveCount(0); + await expect(page.getByTestId("route-draft-pin")).toHaveCount(1); + await expect(page.getByTestId("draw-hint")).toHaveText("Click where it ends."); + }); + + test("phone tier (390x844): the route hint is exempted from the polygon hint's hiding, and clears the search box and tools row", async ({ + page, + }) => { + await page.setViewportSize({ width: 390, height: 844 }); + await goReady(page); + + await startRouteMode(page); + const hint = page.getByTestId("draw-hint"); + await expect(hint).toBeVisible(); + + const hintBox = await hint.boundingBox(); + const searchBox = await page.getByTestId("search-box").boundingBox(); + const toolsBox = await page.getByTestId("tools").boundingBox(); + if (!hintBox || !searchBox || !toolsBox) { + throw new Error("draw-hint, search-box or tools has no box at the phone tier"); + } + expect(rectsOverlap(hintBox, searchBox)).toBe(false); + expect(rectsOverlap(hintBox, toolsBox)).toBe(false); + }); +}); diff --git a/src/app/globals.css b/src/app/globals.css index 1b6bf81..3dd6951 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -1289,6 +1289,20 @@ html:is([data-chrome="awake"]:not(:where([data-panel="closed"])), :where([data-p transform: translateY(-2px); } +/* Where a hand-planned walk starts (T-110), between the two clicks that make + it. Solid, unlike the note's hollow dashed pin: this end is decided — what + is missing is the other one — and it is the same rose the drawn line will + be. Click-through, because the next click on the map is the walk's end. */ +.route-draft-pin { + width: 12px; + height: 12px; + border-radius: 50%; + background: var(--human); + border: 2px solid rgba(255, 255, 255, 0.92); + box-shadow: 0 1px 6px rgba(0, 0, 0, 0.45); + pointer-events: none; +} + /* ---------------------------------------------------- inspector */ .grab { display: none; @@ -2834,6 +2848,16 @@ html:is(:not([data-chrome="awake"]), [data-panel="closed"]):not(:where([data-pan .draw-hint { display: none; } + /* Except the walk's (T-110). The polygon's hint is a convenience down here — + the pressed pill already says what mode the map is in, and every corner is + visible as it is clicked. The walk's is not: it is the only place the + routing service's refusal is ever shown, and a two-click gesture that can + fail silently is worse than a crowded corner. One band lower than the + desktop position, clear of the search box that owns 58px at this width. */ + .draw-hint[data-mode="route"] { + display: flex; + top: 104px; + } } /* ============================================================ diff --git a/src/components/Attribution.tsx b/src/components/Attribution.tsx index aaf3632..a74e44e 100644 --- a/src/components/Attribution.tsx +++ b/src/components/Attribution.tsx @@ -3,6 +3,7 @@ import { Fragment, useSyncExternalStore } from "react"; import { ROUTE_ATTRIBUTION } from "@/lib/map-tools/route"; import { useMapStore } from "@/lib/store/map-store"; +import { useDrawStore } from "./draw-store"; import { STYLE_ATTRIBUTION } from "./map-style"; import { createRoutingCredit } from "./route-credit"; @@ -15,18 +16,36 @@ import { createRoutingCredit } from "./route-credit"; * effect the naive version needs, and the server has no store to read. The * snapshot is monotonic (`route-credit.ts`), so React sees exactly one change — * false to true, the first time a route is planned — and the server snapshot is - * always false, because a page that has served no tool call has used no routing - * service. A restored share link never writes `activity` either (see - * `badge-claim.ts`), so hydration cannot disagree with it. + * always false, because a page that has served no tool call and drawn no walk + * by hand has used no routing service. A restored share link never writes + * `activity` either (see `badge-claim.ts`), so hydration cannot disagree with + * it. */ const readCredit = createRoutingCredit(); -const subscribeToCalls = (onChange: () => void) => - useMapStore.subscribe((state, previous) => { +/** + * Two ways to owe the credit, because there are two ways to use the service. + * An agent's `plan_route` leaves an activity row; a person clicking two points + * on the map leaves none — a hand gesture is not agent activity and the feed + * must not claim it was (`fx/human-events.ts`) — so the human half carries its + * own latch in `draw-store.ts`. Both are monotonic, so the combined snapshot + * still changes at most once, which is what `useSyncExternalStore` needs. + */ +const subscribeToCalls = (onChange: () => void) => { + const unsubscribeCalls = useMapStore.subscribe((state, previous) => { if (state.activity !== previous.activity) onChange(); }); + const unsubscribeHand = useDrawStore.subscribe((state, previous) => { + if (state.routeCredited !== previous.routeCredited) onChange(); + }); + return () => { + unsubscribeCalls(); + unsubscribeHand(); + }; +}; -const creditSnapshot = () => readCredit(useMapStore.getState().activity); +const creditSnapshot = () => + readCredit(useMapStore.getState().activity) || useDrawStore.getState().routeCredited; /** * The basemap's licence attribution, with its links. Not decoration and not @@ -38,7 +57,8 @@ const creditSnapshot = () => readCredit(useMapStore.getState().activity); * desktop width; the text itself is `STYLE_ATTRIBUTION`, kept beside the style * URL it belongs to. * - * Above it, once and only once a walking route has really been planned here, + * Above it, once and only once a walking route has really been planned here — + * by an agent's tool call or by a person clicking its two ends (T-110) — * sits the second credit this page can owe: the routing service's. It is a * sibling line in the same corner rather than a banner — the same 10px glass, * the same right edge — because it is the same kind of statement about where diff --git a/src/components/DrawToolbar.tsx b/src/components/DrawToolbar.tsx index f7015d7..7a2ff92 100644 --- a/src/components/DrawToolbar.tsx +++ b/src/components/DrawToolbar.tsx @@ -1,7 +1,7 @@ "use client"; import { useEffect } from "react"; -import { useDrawStore } from "./draw-store"; +import { useDrawStore, type RouteStatus } from "./draw-store"; /** * The "human draws, agent reads" entry point: toggles polygon drawing on the @@ -9,8 +9,15 @@ import { useDrawStore } from "./draw-store"; * component owns the switch, the keyboard shortcuts and the off-screen mirror * of the mode. * + * The shortcuts cover *both* hand gestures that own the map's clicks — drawing + * a polygon and planning a walk (`RoutePill`) — because they are one keyboard: + * Esc is "stop whatever the next click was going to do", and it must not + * depend on which of the two pills is lit. Enter finishes a polygon and does + * nothing in route mode, where there is nothing half-made to keep: a walk is + * planned by its second click or not at all. + * * Rose, like every hand-drawn shape on the map, against the teal the agent's - * own tools use. It is the first of the three human pills (`Tools`), and it is + * own tools use. It is the first of the four human pills (`Tools`), and it is * there in both chromes: drawing is a thing a person does, agent or no agent. */ export function DrawPill() { @@ -21,7 +28,7 @@ export function DrawPill() { const drawing = mode === "polygon"; useEffect(() => { - if (!drawing) return; + if (mode === "none") return; const onKeyDown = (event: KeyboardEvent) => { // Typing a note must not finish or cancel a drawing. if (event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement) { @@ -30,7 +37,7 @@ export function DrawPill() { if (event.key === "Escape") { event.preventDefault(); cancel(); - } else if (event.key === "Enter") { + } else if (event.key === "Enter" && mode === "polygon") { // Also stops the focused toggle button from being activated by Enter. event.preventDefault(); finish(); @@ -38,7 +45,7 @@ export function DrawPill() { }; window.addEventListener("keydown", onKeyDown); return () => window.removeEventListener("keydown", onKeyDown); - }, [drawing, cancel, finish]); + }, [mode, cancel, finish]); return ( <> @@ -60,29 +67,96 @@ export function DrawPill() { {drawing ? "Cancel" : "Draw"} {/* Off screen: the chip's pressed state is the visible answer, but a - test should not have to read a CSS class to know the mode. */} + test should not have to read a CSS class to know the mode. "on" and + "off" are the polygon's, kept as they were; "route" is the third + value the same span grew when the second gesture arrived. */} - {drawing ? "on" : "off"} + {mode === "route" ? "route" : drawing ? "on" : "off"} ); } /** - * What to do with the map while drawing is on, under the pill that turned it - * on. Separate from the pill because it hangs below the row rather than in it, - * and it exists only while there is something to say. + * The human half of `plan_route` (T-110): click where the walk starts, click + * where it ends, and the same FOSSGIS OSRM service the agent's tool asks draws + * the walk as a rose line a person made. + * + * A pill beside Draw rather than a mode inside it, because the two gestures + * answer different questions and neither is a step of the other — and because + * "what can I do to this map by hand?" has to be readable off the row itself. + * The pill is the only control: the second click plans, so there is nothing to + * confirm, and Esc (handled in `DrawPill`, one keyboard) gets out. + */ +export function RoutePill() { + const mode = useDrawStore((s) => s.mode); + const startRoute = useDrawStore((s) => s.startRoute); + const cancel = useDrawStore((s) => s.cancel); + const routing = mode === "route"; + + return ( + + ); +} + +/** The error sentence plus what to do next, which depends on what is left. */ +function routeHint(points: number, status: RouteStatus): string { + if (status === "planning") return "Planning the walk…"; + // The service's sentences (and the same-point guard's) end without a full + // stop, so the instruction that follows supplies it — and it is a different + // instruction depending on whether the start survived the failure. + if (typeof status === "object") { + return `${status.error}. ${points === 1 ? "Click where it ends." : "Click a new start, or Esc."}`; + } + return points === 0 ? "Click where the walk starts. Esc to cancel." : "Click where it ends."; +} + +/** + * What to do with the map while a hand gesture owns its clicks, under the pill + * that turned it on. Separate from the pills because it hangs below the row + * rather than in it, and it exists only while there is something to say. + * + * It is also where a walk that could not be planned is reported — the routing + * service's own sentence, verbatim, in the place the person was already + * reading. Not a toast and never an `alert`: the failure leaves the map in + * route mode waiting for another click, so the message belongs where the + * instruction it replaces was. */ export function DrawHint() { const mode = useDrawStore((s) => s.mode); const vertexCount = useDrawStore((s) => s.draft.length); - if (mode !== "polygon") return null; + const routePoints = useDrawStore((s) => s.routeDraft.length); + const routeStatus = useDrawStore((s) => s.routeStatus); + if (mode === "none") return null; return ( -

+

- {vertexCount < 3 - ? `Click the map to add points (${vertexCount} of at least 3).` - : `${vertexCount} points. Double-click or Enter to finish, Esc to cancel.`} + {mode === "route" + ? routeHint(routePoints, routeStatus) + : vertexCount < 3 + ? `Click the map to add points (${vertexCount} of at least 3).` + : `${vertexCount} points. Double-click or Enter to finish, Esc to cancel.`}

); } diff --git a/src/components/MapCanvas.tsx b/src/components/MapCanvas.tsx index 59dac91..ab51cc0 100644 --- a/src/components/MapCanvas.tsx +++ b/src/components/MapCanvas.tsx @@ -44,6 +44,7 @@ import { useDrawStore, type DrawMode } from "./draw-store"; import { setFxMap } from "./fx/map-handle"; import { useNoteStore } from "./note-store"; import { readChromeVisible, subscribeChromeVisible } from "./panel-store"; +import { createRouteDraftElement } from "./route-draft-marker"; import { DRAFT_SOURCE, DRAWING_LABEL_SOURCE, @@ -251,13 +252,14 @@ export default function MapCanvas() { const card = useCardStore; /** - * A hand gesture owns the next click on the map: a polygon corner, or the - * place a note is about to be pinned to (T-106). While one is running a - * click is not a question about what is under it, so the feature, bead and - * drawing handlers defer and the cursor is a crosshair either way. + * A hand gesture owns the next click on the map: a polygon corner, an end + * of a walk being planned (T-110), or the place a note is about to be + * pinned to (T-106). While one is running a click is not a question about + * what is under it, so the feature, bead and drawing handlers defer and the + * cursor is a crosshair either way. * * Draw mode has precedence: with the note popover left open, clicking is - * still how a polygon is drawn. + * still how a polygon is drawn or a walk is planned. */ const handOwnsClick = () => draw.getState().mode !== "none" || note.getState().open; @@ -896,22 +898,33 @@ export default function MapCanvas() { // a no-op until the style is up. /** - * The cursor says what the next click will do, and two gestures can claim - * it: a polygon corner and a note waiting for its place. Only the polygon - * also takes the double-click away from the zoom, which is why the mode is + * The cursor says what the next click will do, and three gestures can claim + * it: a polygon corner, an end of a walk, and a note waiting for its place. + * Only the note leaves the double-click alone, which is why the mode is * still the argument — a person placing a note may double-click to zoom in * on the spot they are aiming at, and the second click simply re-places the - * pin where they zoomed. + * pin where they zoomed. The other two read every click as a point, so a + * double-click that also zoomed would move the map out from under the + * second one. */ const applyDrawCursor = (mode: DrawMode) => { - map.getCanvas().style.cursor = mode === "polygon" || handOwnsClick() ? "crosshair" : ""; + map.getCanvas().style.cursor = mode !== "none" || handOwnsClick() ? "crosshair" : ""; // Otherwise the second click of "double-click to finish" zooms the map. - if (mode === "polygon") map.doubleClickZoom.disable(); - else map.doubleClickZoom.enable(); + if (mode === "none") map.doubleClickZoom.enable(); + else map.doubleClickZoom.disable(); }; map.on("click", (event: MapMouseEvent) => { const state = draw.getState(); + if (state.mode === "route") { + // Planning is a request to somebody else's server, allowed one per + // second: a second click while it is out would either be dropped by the + // store anyway or spend the next second's request. Ignored here so the + // map does not even look like it took it. + if (state.routeStatus === "planning") return; + void state.addRouteVertex([event.lngLat.lng, event.lngLat.lat]); + return; + } if (state.mode !== "polygon") return; const last = state.draft[state.draft.length - 1]; if (last) { @@ -952,9 +965,30 @@ export default function MapCanvas() { } }; + /** + * Where a hand-planned walk starts, while it has one end and not two + * (T-110). The same imperative marker the note draft uses, and there for + * the same reason: between the two clicks the only thing on screen saying + * the first one landed is the hint, and a hint is not a place. + */ + let routeMarker: Marker | null = null; + + const applyRouteDraft = (at: LngLat | null) => { + if (!at) { + routeMarker?.remove(); + routeMarker = null; + return; + } + if (routeMarker) routeMarker.setLngLat(at); + else { + routeMarker = new Marker({ element: createRouteDraftElement() }).setLngLat(at).addTo(map); + } + }; + map.on("click", (event: MapMouseEvent) => { // Draw mode has precedence: with the note popover left open, a click is - // still a corner (the guard above has already taken it). + // still a corner or an end of a walk (the guard above has already taken + // it). if (draw.getState().mode !== "none") return; const state = note.getState(); if (!state.open) return; @@ -1000,6 +1034,11 @@ export default function MapCanvas() { const unsubscribeDraw = draw.subscribe((state, previous) => { if (state.draft !== previous.draft) applyDraft(map, state.draft); + // Only the start is ever a mark of its own — the end is the line, or the + // failure that clears both. It stays put while the walk is being planned: + // the answer comes from somebody else's server, and a pin that vanished + // on the second click would read as the first one having been lost. + if (state.routeDraft !== previous.routeDraft) applyRouteDraft(state.routeDraft[0] ?? null); if (state.mode !== previous.mode) { applyDrawCursor(state.mode); // Drawing takes the map's clicks over, so a note left half-placed under @@ -1060,8 +1099,10 @@ export default function MapCanvas() { syncAnnotationMarkers(map, markers, store.getState().annotations, tapAnnotation); applyDrawCursor(draw.getState().mode); // The UI stores outlive this effect (a remount, or React's development - // double-mount), so a note being placed keeps its pin across one. + // double-mount), so a note being placed and a walk half-clicked keep their + // pins across one. applyNoteDraft(note.getState().draft); + applyRouteDraft(draw.getState().routeDraft[0] ?? null); return () => { window.removeEventListener("resize", onResize); @@ -1075,6 +1116,8 @@ export default function MapCanvas() { markers.clear(); draftMarker?.remove(); draftMarker = null; + routeMarker?.remove(); + routeMarker = null; try { map.remove(); } catch { diff --git a/src/components/Tools.tsx b/src/components/Tools.tsx index fc0717d..4f5f05a 100644 --- a/src/components/Tools.tsx +++ b/src/components/Tools.tsx @@ -2,18 +2,24 @@ import { useCallback, useEffect, useRef } from "react"; import { AddNoteForm } from "./AddNoteForm"; -import { DrawHint, DrawPill } from "./DrawToolbar"; +import { DrawHint, DrawPill, RoutePill } from "./DrawToolbar"; import { useNoteStore } from "./note-store"; import { ShareChip } from "./ShareChip"; /** - * The three things a person can do to this map, in one row: Draw, Note, Share. + * The four things a person can do to this map, in one row: Draw, Route, + * Note, Share. * * They are the human half of the repositioning (BRIEF item 3) and they are on * screen in both chromes — an agent arriving does not take the map away from * the person watching it. The row sits opposite the brand and steps aside for * the inspector lane when the agent chrome is up (globals.css). * + * Route is the youngest of them (T-110) and it is there for the same reason + * the others are: `plan_route` was an agent-only verb, so a walk was something + * this map could only be *told* to plan. Clicking two points is the human way + * to ask the same question of the same service. + * * The draw switch, the note form and the copy chip are the ones that shipped, * re-skinned into pills and given a home that survives the agent panels being * hidden. The note form especially — it is the declarative `add_note` WebMCP @@ -78,6 +84,7 @@ export function Tools() { <>
+