diff --git a/README.md b/README.md index 9e49c64..25bd382 100644 --- a/README.md +++ b/README.md @@ -1,251 +1,124 @@ # GlassMap +**A web map is a WebGL canvas — a black box to AI agents. WebMCP makes it glass.** -**An agent-native web map.** GlassMap uses [WebMCP](https://webmachinelearning.github.io/webmcp/) to turn the map canvas from a black box into a semantic surface: an AI agent can read the current view, find features, move the camera, draw shapes and annotate the map **without taking a single screenshot** — and the human watches it happen on the same map. +Live: **https://glassmap.clyeh.xyz** · **15 WebMCP tools, no backend, no API keys** · Built for [The WebMCP Challenge](https://webmcp.devpost.com/) (Aug 25 – Sep 3, 2026). -> Live: **https://glassmap.clyeh.xyz** · Built for [The WebMCP Challenge](https://webmcp.devpost.com/) (Aug 25 – Sep 3, 2026). -> **Status:** all fourteen planned tools are implemented and unit-tested — `get_map_state`, `set_map_view`, `list_features_in_view`, `find_features`, `select_features`, `draw_shape`, `plan_route`, `annotate`, `remove_from_map`, `describe_surroundings`, `compare_areas`, `measure`, `get_place_details`, `get_share_link` — plus one declarative form, `add_note`: fifteen in total, the number the on-page WebMCP badge counts. (`set_layers` was cut on 2026-08-29 — the demo script never needed layer toggling, so it was never built.) They act on 24 categories of data — six bundled Taipei datasets (2,063 features, always in memory; five are real OpenStreetMap data, the sixth is 25 fabricated sample listings, not OSM) plus 18 more real OpenStreetMap point-of-interest categories (31,069 features, loaded lazily per category on first use). The redesigned "Smoked Glass" interface and the agent-presence FX layer (every tool call renders a brief, self-clearing effect on the map) are both live. The page itself opens as a plain map with no agent chrome; the first live tool call wakes the inspector panel and the "Agent activity" feed into view, and a human can also open or close that view by hand at any time. Remaining: the demo video and the submission freeze. +![The map after an agent session: a 6-call activity feed, a dashed teal 800 m "10-minute walk" circle around 7 teal-ringed parks, an inspector reading SELECTED 7 · SHAPES 1 · NOTES 1, and a footer reading "Agent connected · 15 tools · WebMCP".](docs/media/hero.jpg) ## Why "Glass" +To an agent, every station, park and pin on a web map is just pixels. A screenshot can't read an unlabeled green polygon, a click stops working the moment the zoom changes, and drawing a shape, measuring a distance or selecting every park in view is essentially impossible from a picture. WebMCP exposes the map's state, features and actions as tools instead, so an agent never has to guess from pixels — the black box becomes **glass**. Every web map has this problem — property search, delivery planning, travel — and the fix is a tool contract, not a bigger screenshot model. For someone who cannot see the map at all, the same read-only tools double as agent-mediated map access — not a WCAG or accessibility-compliance claim. -A web map is a WebGL canvas. To a browser agent every station, park and pin is just pixels: +## The same task, two ways +Both arms were asked: *"Show every park within a 10-minute walk of Daan Station."* — the first "Try asking" card on the page. Open the live site and say it verbatim. -- To *see*, it must screenshot and let a multimodal model guess what the markers are. -- To *act*, it must click at coordinates that stop being valid the moment the zoom changes. -- To *draw a polygon*, *measure a distance* or *select every park in view*, it has essentially no way at all. +**Screenshot agent** +![The screenshot agent driving GlassMap by clicks, keys and full-page screenshots, with no tool access.](docs/media/screenshot-agent.gif) +19 UI actions · 8 screenshots → finds 2 of 7 parks. The 800 m "circle" is an 8-vertex polygon whose radius is a guess (the page shows a screenshot agent no scale bar and no zoom readout). The other 5 were never found: each one is another click-and-read-the-card round trip, and nothing on screen says how many are left. The search box needs two tries — "Daan Station" has no match, "Daan" does. -Maps are the largest "DOM without semantics" surface on the web. WebMCP fills exactly that gap: the page exposes map state, features and actions as structured tools, so the agent never has to look at pixels. The black box becomes **glass** — the agent sees straight through the canvas to the data underneath. +**WebMCP agent** +![The WebMCP agent calling map tools directly, with the map updating and no screenshots taken.](docs/media/webmcp-agent.gif) +5 tool calls · 2.9 KB returned · 82 ms of tool time · 0 screenshots → all 7 parks inside an exact 800 m circle, each with an id, a distance and a compass direction — two of them parks OpenStreetMap never named: +`set_map_view({ place: "Daan Station" })` → `draw_shape({ type: "circle", center: "Daan Station", radius_m: 800, label: "10-minute walk" })` → `set_map_view({ fit: "drawing:1" })` → `find_features({ near: "Daan Station", radius_m: 800, categories: ["park"] })` → `select_features({ ids: [...] })`. -The same opacity that blocks agents also blocks screen readers, so the read-only tools double as a semantic layer for people who cannot see the map. We call this *agent-mediated map access*; it is not a WCAG or accessibility-compliance claim. +Both clips are scripted replays recorded on 2026-09-02 with Playwright's headless Chromium against a local production build of this repository — not a live model. The screenshot arm was allowed only what a generic computer-use agent has: a search box, clicks, keys, mouse wheel, screenshots. The WebMCP arm calls `document.modelContext.executeTool` through the page's own dev shim (`?shim=1`), because headless Chromium has no native WebMCP; the tool code and its output are identical to what Chrome's native surface exposes. The measured, live-model comparison is the table below. -`describe_surroundings` is the clearest example. It names the district a point is in — falling back to the nearest district boundary within 300 m when the point sits in a seam between two independently simplified polygons, and naming none rather than guessing beyond that — then lists nearby features grouped into up to eight compass directions, nearest first, each with a distance in metres and a feature id an agent can act on next (`select_features`, `set_map_view`). When more features match than the tool describes, it says so instead of staying quiet: `total` is how many are within `radius_m`, `returned` is how many were actually listed (at most 30) — so a wider radius is never implied to reveal features that were simply cut off. - -## What an agent can do - -| You say | Without WebMCP | With GlassMap | -|---|---|---| -| "Move the map to Daan Park Station" | screenshot → find search box → type → screenshot → maybe click the wrong result | `set_map_view({ place: "Daan Park Station" })` | -| "Which parks are in view?" | screenshot → guess that green blobs are parks → can't read names | `list_features_in_view({ categories: ["park"] })` | -| "Circle an 800 m walk from the station" | nearly impossible: compute a pixel radius at the right zoom, then drag | `draw_shape({ type: "circle", center: …, radius_m: 800 })` | -| "What's inside the area I just drew?" | impossible — the agent cannot see vector geometry | `find_features({ within: "drawing:1" })` | -| "How big is the circle I just drew?" | impossible — a screenshot has no scale, so area has to be guessed from pixels | `measure({ target: "drawing:1" })` → `{ area_m2, perimeter_m }` | -| "Is Daan or Zhongshan better connected?" | screenshot both, eyeball the pins on each, guess which side has more | `compare_areas({ a: "Daan Park Station", b: "Zhongshan Station" })` → per-category counts and nearest match on each side | -| "I can't see the map. Where's the nearest park?" | impossible | `describe_surroundings()` → nearest features grouped by direction, each with a name, distance in metres and id | - -## Screenshots vs. tools, measured - -One run per arm, per task, measured on 2026-08-28 against the production build of that date — no statistical claims. The tool output has changed since (`docs/comparison.md`'s dated footnote quantifies one such change), so read the byte counts below as of that date, not today's; full method and every other honesty caveat are in [`docs/comparison.md`](./docs/comparison.md). +One run per arm per task, measured 2026-08-28 against that date's production build, before the page had a human search box (one response below has since grown a field); full method and every caveat: [`docs/comparison.md`](./docs/comparison.md). | Task | Screenshot agent | WebMCP | |---|---|---| -| Move to a station and mark an 800 m walking radius | 16 UI actions + 7 screenshots (~6 min); circle approximated as an 8-vertex polygon; centring 33 m off | **2 tool calls, 576 B (~1 s)**; exact centre (gazetteer); a true circle | -| List the parks in the current view, by name | 3 screenshots (full + 2 crops); only **1 of 11** parks nameable — the rest are unlabeled green polygons at this zoom | **1 tool call, ~1.2 KB**; all **11** parks, each with a name, distance and compass direction | -| How far and which direction to a named park | 1 screenshot + pixel/overlay arithmetic; ≈426 m guessed from pixels, +20% error (correct direction) | **1 tool call**, 2,771 B; **355 m**, computed from feature geometry (ground truth) | - -Four tool calls, ~4.5 KB of structured output, zero screenshots, across all three tasks — against 11 screenshots/crops on the control side, which still failed the second task outright and approximated the other two. - -## Tools - -Three layers, fourteen tools implemented. `set_layers` was cut before build — never built, not counted here (see below). Every write tool returns the new map state so the agent never needs a follow-up read. - -``` -Perceive (read-only, replaces screenshots) Navigate (camera only) Act (page state, no server) -├─ get_map_state ✅ ├─ set_map_view ✅ ├─ draw_shape ✅ -│ └─ set_layers (cut) ├─ plan_route ✅ -├─ list_features_in_view ✅ ├─ select_features ✅ -├─ find_features ✅ ├─ annotate ✅ -├─ describe_surroundings ✅ ├─ remove_from_map ✅ -│ └─ get_share_link ✅ -├─ measure ✅ -├─ compare_areas ✅ -└─ get_place_details ✅ -``` - -✅ = implemented and covered by unit tests. `set_layers` was cut on 2026-08-29 — not planned, not pending, simply not built once the demo script turned out not to need layer toggling. - -| Tool | What it does | Key inputs | -|---|---|---| -| `get_map_state` | Reads the camera, visible bounds, feature count, selection, drawings and annotations in one call — the read that used to require a screenshot. | *(none)* | -| `set_map_view` | Moves the camera: by exact `center`/`zoom`/`bearing`/`pitch`, by `feature_id` or `place` name (defaulting to a zoom *floor* — flying to a place never zooms you out; pass `zoom` to override, in either direction), or by `fit` — a drawing or feature id framed whole, with the same math the inspector's row clicks use. An ambiguous `place` does not move the map — it returns candidates with distances instead. | `place`, `feature_id`, `fit`, `center`, `zoom`, `bearing`, `pitch` | -| `list_features_in_view` | Lists loaded features whose bounds overlap the current view, nearest-first, each with distance in metres and an 8-point compass direction from the view centre; `query` searches within the view over the same five fields `find_features` matches (name, English name, brand, cuisine, address). | `query`, `categories`, `limit` | -| `find_features` | Searches every loaded feature, not just what's visible, by a substring of its name, English name, brand, cuisine or address, by category, by distance from a place/feature/coordinate, and by whether it's inside a shape on the map — including one a human drew by hand; a query that matches places in categories not yet loaded says so under `unloaded_matches`. | `query`, `categories`, `near`, `radius_m`, `within`, `limit` | -| `select_features` | Highlights features on the map and in the inspector's Selected list, by explicit ids or the same `query`/`near`/`radius_m`/`categories`/`within` filter `find_features` accepts — but selects every match, not just the first `limit`. | `ids` or filter, `within`, `replace` | -| `draw_shape` | Draws a circle, polygon or line on the map so the human can see the area being discussed; returns its area (circle/polygon) or length (line) and a `drawing:` id. | `type`, `center`+`radius_m` (circle) or `coordinates` (polygon/line), `label` | -| `plan_route` | Plans a walking route between two places via the keyless FOSSGIS OSRM service (OpenStreetMap data) and draws it as a line the human can see; returns the drawing id, `distance_m` and `duration_s`, says `simplified: true` when the geometry was thinned to fit, and fails honestly — never a fake route — when the service cannot answer. The one tool that talks to an external service; attribution renders on the page. | `from`, `to`, `label` | -| `annotate` | Pins a short note to a place on the map, so the human sees what was found where it was found. | `at`, `note`, `icon` | -| `remove_from_map` | Takes things off the map by id: the agent's own drawings and notes are removed, named features leave the selection, and a shape or note the *human* made is refused per-id — the person who drew it can tap it and press Remove. Every id in the batch is accounted for in exactly one bucket; removal is permanent, with no undo. | `ids` (drawing/annotation/feature ids) | -| `describe_surroundings` | Describes what's around a point the way a person would say it out loud: the district, then nearby features grouped by compass direction, nearest first, each with a distance and an id. | `from`, `radius_m` | -| `compare_areas` | Compares two places in one call: per-category counts of what's within `radius_m` of each, plus the nearest match of each category on each side; if a place name doesn't resolve, the error names which side (`a` or `b`) failed. | `a`, `b`, `radius_m`, `categories` | -| `measure` | Measures one drawing or loaded feature: area and perimeter for a circle or polygon, length for a line. A point has no extent and is refused, with a pointer to `find_features` for distances instead. | `target` | -| `get_place_details` | Everything the page knows about one place — address, phone, website, opening hours, wheelchair (as OpenStreetMap reports it, not a verified accessibility claim) and category-specific facts — for the questions a list answer is too lean for. Fields exist only where OSM has them; absent means absent. | `id` | -| `get_share_link` | Builds a link that reproduces this map for whoever opens it — camera, selection, every drawing and every note, encoded in the URL itself, nothing uploaded. Returns `{ url, bytes }`; a map too large to fit in a URL (over 8 KB) is refused with an error naming what to remove. | *(none)* | - -`within: "drawing:"` on `find_features` and `select_features` is the read half of the collaborative loop: any circle or polygon on the map — agent-drawn or hand-drawn by a human — becomes something an agent can query by id, not just something rendered on screen. (A line has no inside, so `within` does not apply to it.) - -Design rules the tool layer follows: - -- Every write tool (`set_map_view`, `select_features`, `draw_shape`, `annotate`, `plan_route`, `remove_from_map`) returns the full new map state, so the agent never needs a follow-up read. -- Read-only tools carry `readOnlyHint: true` so clients can skip confirmation prompts. -- Output that contains OpenStreetMap or user-entered text carries `untrustedContentHint: true`. -- Responses are small on purpose: `limit` defaults to 20, coordinates are rounded to 5 decimals, geometry is returned by id rather than inline. -- Bad input returns a structured `{ error }` instead of throwing, so the agent can recover. -- No `alert` / `confirm` / `prompt` anywhere — modal dialogs freeze agents. - -## City-wide breadth - -The six bundled datasets above (2,063 features) are always in memory. Beyond them, GlassMap knows about 18 more OpenStreetMap point-of-interest categories — `restaurant`, `cafe`, `pharmacy`, `hotel`, `bank` and 13 others — covering 31,069 more features across Taipei, held as static files under `public/data/tier2/` and described by a manifest the tools read without loading a byte of feature data. - -**Naming a category is what fetches it.** Pass `categories: ["restaurant"]` to `find_features`, `list_features_in_view`, `describe_surroundings` or `compare_areas` and it fetches every restaurant in the city once — 13,789 of them — and keeps them in memory for the rest of the session. There is no "list every category" call: loading all 18 at once would put 31,069 features into a browser tab for a question nobody asked. A query that omits `categories` is answered only from what is already loaded (the six bundled datasets plus whatever a category call already fetched this session) — and it says so: the answer's `unsearched_categories` names every category it did not search, each with its true city-wide count from the manifest, so "no cafes nearby" can never be confused with "no cafe file was ever fetched." - -A few real counts from the manifest (`public/data/tier2/index.json`): `restaurant` 13,789, `convenience` 3,231, `bicycle_rental` 2,602 (YouBike stations), `cafe` 2,298, down to `museum` 119 and `hospital` 74. Full table, tag mapping and Overpass queries for all 18 are in [`public/data/README.md`](./public/data/README.md). - -`select_features` still highlights every match a filter finds, its contract since the tool shipped — but once a point-of-interest category is involved, a filter matching more than 500 of them is refused rather than lighting up half the city: the answer gives the true count and asks for `near`+`radius_m`, `within` or `query` to narrow it. The six bundled categories are exempt from that cap. - -A `get_share_link` link carries the *names* of every point-of-interest category the sender had loaded, not their features — the recipient's page fetches the same files itself — so opening the link rebuilds the sender's map, selection included, instead of resolving to features the recipient's session never heard of. A link that names a category is written as `v2`; a link with none still encodes to the exact `v1` bytes it always did, so no existing link breaks. The one exception is a map whose drawings would not fit in a URL at all: their coordinates then travel delta-encoded and the link is written as `v3` — smaller maps keep their old bytes, and every older link still decodes. - -Fetching a category file can fail two honestly different ways: a **permanent** failure (this deployment ships no such file — a 404) drops the category and is not retried; a **transient** one (a slow connection, a rate-limited mirror — a 5xx, or a 408/425/429 that means "ask again") keeps the category on the books, including in any share link handed out meanwhile, so the next call simply tries again. - -## Working together on the same map - -The map is shared state, not a private channel for the agent: - -- **Human draws, agent reads.** Click "Draw a polygon", add vertices, close it — the shape appears in `get_map_state().drawings` with `source: "user"` and is immediately queryable with `find_features({ within: "drawing:" })`, the same call an agent uses on its own shapes. -- **Agent draws or annotates, human sees and edits.** A `draw_shape` or `annotate` call renders on the map at once and lists in the inspector's Shapes / Notes section with an "agent" or "user" provenance tag and a ✕ button to remove it — no confirmation dialog blocks either side. -- **A search box for humans, calling no tool.** Top-left, under the brand: type a place name and get results instantly from what the page already has loaded, plus a citywide name index for what it does not, and a list of categories the words might mean. Picking any of them moves the camera onto it (never zooming out) and writes a `source: "user"` selection; picking a citywide place first fetches its category, and picking a category outright loads and paints it exactly as the Places tray does, evictions included. None of this calls a tool, records an activity or wakes the agent chrome — it is the human half of the same question `find_features` answers for an agent. -- **A Places tray for browsing by kind.** The six bundled datasets are always painted; below them, a tap adds one of the 18 point-of-interest categories the tools fetch — "cafes" or "pharmacies" — up to three kinds painted at once; a fourth tap retires the oldest and says so out loud in the tray's foot line ("Cafés came off the map — 3 kinds of place at a time"), so nobody is left guessing what left. -- **`get_place_details`, echoed on the tap card.** The address, phone, website, opening hours and category-specific facts described under [Data and licensing](#data-and-licensing) are not agent-only: tapping the same pin opens a card that renders the same fields from the same table, so an agent saying "vegetarian, open till nine" and a person tapping the pin see the same two facts. The inspector's Selected list stays deliberately lean (name, English name when the data has one, and category) and does not repeat them — a ratified narrowing, not an oversight. -- **Inspector rows act, not just list.** Click a Selected, Shape or Note row and the camera flies to it — a point centres, an area or line is framed whole — except a Selected row whose id nothing has loaded, which is inert by design (nowhere to fly). Each Selected row carries its own ✕ to deselect just that one, and every row is keyboard reachable. -- **The human decides what chrome is on screen.** The page opens as a plain map and wakes into the agent view on the first live tool call — but the person can also open that view by hand (the corner spark's card offers a preview) and close it again at any time. A closed view stays closed while the agent keeps working; the spark carries a pulse and an exact count of the calls made since, and `get_map_state().bounds` always describes the rectangle actually on screen. -- **Two WebMCP APIs, one state.** Besides the imperative tools above, the inspector's pin-note field is a plain `
` — the declarative half of WebMCP, filled in by a human or submitted by an agent with no JavaScript registration. `SubmitEvent.agentInvoked` tells the store which one happened, so the note is stored as `source: "agent"` or `source: "user"` honestly either way. Together the 14 registered tools and this one declarative form are the 15 the on-page WebMCP badge counts. - -The address bar is part of that shared state, too: it always holds a link back to the map exactly as it stands, kept current whether the human or the agent made the last change, and opening that link — or one handed off from `get_share_link` — restores the same camera, selection, drawings and notes rather than a description of them. That is what lets a judge (or anyone else) reproduce what this README can only show as a screenshot. - -## Seeing the agent work - -Every tool call also plays out on the map itself, not just as a row in the activity feed: a read (`get_map_state`, `find_features`, `describe_surroundings`, …) washes translucent teal across whatever it looked at — a compass sweep, a glinting hit, a soft glow over the viewport — then fades to nothing; a write (`set_map_view`, `draw_shape`, `select_features`, `annotate`, …) materializes in the same teal as the change lands — a reticle drops onto the new camera centre, a shape draws itself on, a pin lands — and what's left behind is exactly the ordinary map state it always would have been. A shape or note a human adds by hand plays the identical two verbs in rose instead of teal, so who did what is legible without reading a word. Every effect is capped under two seconds and leaves zero residue on the canvas, and the matching row in the "Agent activity" feed glows on the same clock it animates on. Append `?fx=off` to the URL to turn the whole layer off, and it already honours `prefers-reduced-motion` (a short opacity crossfade plays instead of the full animation). +| Move to a station, mark an 800 m radius | 16 actions + 7 screenshots (~6 min); circle approximated, centring 33 m off | 2 calls, 576 B (~1 s); exact centre, true circle | +| List the parks in view, by name | 3 screenshots; **1 of 11** parks nameable | 1 call, ~1.2 KB; all **11** parks, named | +| Distance and direction to a named park | 1 screenshot + pixel math; ≈426 m, +20% error | 1 call, 2,771 B; **355 m**, ground truth | ## Try it - -### Chrome (149+) +**Chrome 149+:** 1. Enable `chrome://flags/#enable-webmcp-testing` and restart Chrome. -2. Open **https://glassmap.clyeh.xyz** or run it locally (below). -3. Open the [Model Context Tool Inspector](https://developer.chrome.com/docs/ai/webmcp) extension (or any WebMCP-capable agent) and ask it one of these, verbatim: - - *"Show every park within a 10-minute walk of Daan Station."* → `draw_shape` · `find_features` · `select_features` - - *"Compare Daan District and Xinyi District for parks and supermarkets."* → `compare_areas` - - *"Describe the area around Daan Station."* → `describe_surroundings` -4. Or skip the agent and call the tools directly from DevTools: +2. Open **https://glassmap.clyeh.xyz**. +3. Open the [Model Context Tool Inspector extension](https://developer.chrome.com/docs/ai/webmcp) or any WebMCP-capable agent and ask it one of these, verbatim: + - "Show every park within a 10-minute walk of Daan Station." → `draw_shape` · `find_features` · `select_features` + - "Compare Daan District and Xinyi District for parks and supermarkets." → `compare_areas` + - "Describe the area around Daan Station." → `describe_surroundings` + - "How big is Daan Forest Park?" → `find_features` · `measure` + - "What is the phone number and address of the post office nearest Daan Station?" → `find_features` · `get_place_details` + +Or call the tools directly from DevTools: ```js const tools = await document.modelContext.getTools(); -const byName = Object.fromEntries(tools.map(t => [t.name, t])); - -// Move the camera by name — no coordinates needed. +const byName = Object.fromEntries(tools.map((t) => [t.name, t])); await document.modelContext.executeTool(byName.set_map_view, { place: "Daan Park Station" }); - -// Everything within comfortable walking distance of the station. const found = await document.modelContext.executeTool(byName.find_features, { near: "Daan Park Station", radius_m: 800, - categories: ["park", "school"], -}); -JSON.parse(found); -// → { total: , returned: , -// features: [ { id, name, name_en?, category: "park" | "school", distance_m, direction }, … ], -// origin: { lng, lat }, // what these distances were measured from -// radius_m: 800 } // echoed back because near/radius_m bounded the search -// e.g. { total: 13, returned: 13, features: [ -// { id: "osm:way:1227733215", name: "大安森林公園", name_en: "Da-an Forest Park", -// category: "park", distance_m: 355, direction: "S" }, … ], -// origin: { lng: 121.53528, lat: 25.03356 }, radius_m: 800 } - -// Draw a circle so the human can see the area, then ask what's inside it — the -// same "within" an agent would use to read a shape a human drew by hand. -const drawn = await document.modelContext.executeTool(byName.draw_shape, { - type: "circle", - center: "Daan Park Station", - radius_m: 500, - label: "5-minute walk", -}); -const { drawing_id } = JSON.parse(drawn); -// → { drawing_id: "drawing:", area_m2: , state: { …, drawings: { count: 1, items: [...] } } } - -const inside = await document.modelContext.executeTool(byName.find_features, { - within: drawing_id, categories: ["park"], }); -JSON.parse(inside); -// → { total, returned, features: [ { id, name, category: "park", distance_m, direction }, … ] } +JSON.parse(found); ``` -### ChatGPT desktop app +Any browser works with `?shim=1` appended to the URL: the shim installs `document.modelContext` only when no native implementation exists, and it is already on in development builds. + +## Fifteen tools +Three layers, listed in that order: **Perceive** (read-only, replaces screenshots), **Navigate** (camera only) and **Act** (writes page state; only `plan_route` leaves the page). + +| Tool | What it does | +|---|---| +| `get_map_state` | Reads the camera, bounds, feature count, selection, drawings and notes in one call — no screenshot needed. | +| `list_features_in_view` | Lists what's on screen right now, nearest first, each with distance and compass direction. | +| `find_features` | Searches every loaded feature by name, category, distance from a point, or containment inside a shape. | +| `describe_surroundings` | Describes what's around a point out loud: the district, then nearby features by compass direction. | +| `measure` | Measures a drawing's or feature's area, perimeter or length. | +| `compare_areas` | Compares two places' per-category counts and nearest match, in one call. | +| `get_place_details` | Returns everything known about one place: address, phone, website, hours, `wheelchair` (an OSM tag, not a verified accessibility claim). | +| `get_share_link` | Builds a URL that restores this exact map — camera, selection, drawings, notes — for whoever opens it. | +| `set_map_view` | Moves the camera by place name, feature id, `fit` (frame a drawing or feature whole), or exact center/zoom/bearing/pitch. | +| `select_features` | Highlights features on the map and in the inspector, by id or the same filter `find_features` accepts. | +| `draw_shape` | Draws a circle, polygon or line so the human can see the area being discussed. | +| `plan_route` | Plans a walking route via the keyless FOSSGIS OSRM service and draws it as a line. | +| `annotate` | Pins a short note to a place on the map. | +| `remove_from_map` | Removes the agent's own drawings, notes or a selection entry; refuses to touch what a human drew. | +| `add_note` (``) | Pins a note from a plain HTML form; `SubmitEvent.agentInvoked` decides `source: "agent"` or `"user"`. | + +Design rules the tool layer follows: + +- Every write tool returns the new map state, so no follow-up read is needed. +- Read-only tools carry `readOnlyHint: true`. +- Output containing OpenStreetMap or user text carries `untrustedContentHint: true`. +- Responses stay small: `limit` defaults to 20, coordinates round to 5 decimals, geometry returns by id. +- Bad input returns a structured `{ error }`, never throws; no `alert` / `confirm` / `prompt` anywhere. + +More on how these behave: [`docs/details.md`](./docs/details.md). + +Verified once, 2026-08-28, against the ChatGPT desktop app: it listed the eleven tools the page declared at the time and called `get_map_state` live, no Chrome flag needed. The roster has grown to fourteen registered tools since (the `add_note` form is the fifteenth), and that growth is unverified against ChatGPT. -ChatGPT's built-in browser supports WebMCP tools on supported plans and models. Verified once, 2026-08-28, against this app's production build: ChatGPT desktop listed the 11 tools the page declared at the time and called `get_map_state` live — no Chrome flag needed. The roster has grown to fourteen tools since; that growth has not been re-verified against ChatGPT. Open the app URL in that browser and ask it to use the map. +## One map, two hands +The map is shared state, not a private channel for the agent. +![The page as it opens: a plain map with no agent chrome — search box, Draw/Note/Share buttons, Places tray and a small "also readable by AI agents" hint.](docs/media/landing.jpg) -### Any other browser +- The page opens as a plain map. The first live tool call wakes the inspector and activity feed into view, and a human can open or close that view by hand at any time (a share link that carries agent state opens with that view already up). +- Human draws, agent reads: a shape drawn by hand appears with `source: "user"` and is immediately queryable with `find_features({ within: "drawing:" })`. +- Agent draws or annotates, human sees and edits: the shape or note renders at once with an "agent" or "user" provenance tag and a ✕ to remove it — no confirmation dialog on either side. +- **Two WebMCP APIs, one state.** The pin-note field is a plain `` — no JavaScript registration — and `SubmitEvent.agentInvoked` decides whether the note is stored as `agent` or `user`. +- A search box lets a human find a place, calling no tool; a Places tray loads any of 18 OpenStreetMap categories, up to 3 painted at once — a fourth tap evicts the oldest and says so. +- Every tool call plays a brief effect on the map, capped at 2 seconds — teal for the agent, rose for a human action. `?fx=off` turns it off, and it honours `prefers-reduced-motion`. +- The address bar holds a link that restores this exact map — camera, selection, drawings and notes — for whoever opens it. -In development builds — or with `?shim=1` appended to the URL — GlassMap installs a small `document.modelContext` shim that implements the same `registerTool / getTools / executeTool / toolchange` surface, so the snippet above works even without the flag. The shim is never installed when a native implementation exists. +## Data +Six bundled Taipei datasets are always in memory — 109 MRT stations, 12 districts, 865 parks, 445 schools, 607 supermarkets and 25 sample listings (fabricated, not OSM) — 2,063 features total. 18 more OpenStreetMap point-of-interest categories (31,069 features) load lazily, one at a time, the moment a category is named; an answer that didn't search one lists it under `unsearched_categories`. Full provenance and tag mapping: [`public/data/README.md`](./public/data/README.md). -## Development +- Map data © [OpenStreetMap](https://www.openstreetmap.org/copyright) contributors, [ODbL](https://opendatacommons.org/licenses/odbl/). Tiles by [OpenFreeMap](https://openfreemap.org/). +- Listings shown are **sample data**, not real properties. +- Code: [MIT](./LICENSE). -Requires Node 22+ (matches CI) and [pnpm](https://pnpm.io/). +## How it is built +A single Next.js app on Vercel — **no backend, no database, no API keys, no login**. [MapLibre GL JS](https://maplibre.org/) renders [OpenFreeMap](https://openfreemap.org/) vector tiles; [Turf.js](https://turfjs.org/) runs every spatial query in the browser; [Zustand](https://zustand.docs.pmnd.rs/) holds map state. Tools in `src/lib/map-tools/` talk to the map only through a `MapToolStore` interface, so they are unit-tested against an in-memory store. `src/lib/webmcp/register.ts` registers on both `document.modelContext` and `navigator.modelContext`, cancellable via `AbortSignal`. The one external service is `plan_route`, which asks the keyless FOSSGIS OSRM instance for walking routes, throttled to its 1 request/second policy, and answers with an honest error (map unchanged) when it is unreachable. ```bash pnpm install pnpm dev # http://localhost:3000 pnpm check # typecheck + lint + unit tests -pnpm test:e2e # Playwright: drives the tools through document.modelContext +pnpm test:e2e # Playwright, via document.modelContext pnpm build ``` -### Layout - -``` -src/ - app/ Next.js App Router pages - components/ React components (WebMcpProvider registers tools on mount) - lib/ - webmcp/ WebMCP glue: ambient types, registration, dev shim - map-tools/ Tool definitions + execute, decoupled from React/MapLibre - store/ Zustand map state + the narrow MapToolStore adapter tools use - geo/ Camera/projection math shared by the tools and the UI - data/ Bundled dataset schema + GeoJSON loader - awaken/ When the page wakes from a plain map into the agent view - types/webmcp.d.ts Types for document.modelContext / navigator.modelContext -e2e/ Playwright specs -``` - -Tools talk to the map only through the `MapToolStore` interface, so they are unit-tested against an in-memory store and can be lifted out of this app. - -Branching, worktrees, commit and PR conventions are in [CONTRIBUTING.md](./CONTRIBUTING.md). CI (`.github/workflows/ci.yml`) runs `pnpm check`, `pnpm build` and the Playwright suite on every PR. - -### WebMCP registration - -`src/lib/webmcp/register.ts` feature-detects both `document.modelContext` (current spec and Chrome) and `navigator.modelContext` (older shape some clients still expose) and registers on whichever exists. Registration is cancelled with an `AbortSignal`, per the current spec. Every tool's `execute` returns a JSON string, the lowest common denominator across clients. - -## Architecture - -Single Next.js app on Vercel. **No backend, no database, no API keys, no login.** One keyless external data service: `plan_route` asks the [FOSSGIS OSRM instance](https://routing.openstreetmap.de/) for walking routes at call time — throttled to their 1 request/second policy, credited on the page for the rest of the session once a route has been planned, and answering with an honest error (map unchanged) when unreachable. Everything else runs on bundled data entirely in the browser; the only other network the app touches is the keyless OpenFreeMap basemap tiles below, which stay display-only. - -- [MapLibre GL JS](https://maplibre.org/) with [OpenFreeMap](https://openfreemap.org/) vector tiles (no key required) -- Bundled GeoJSON under `public/data/` (Taipei MRT stations, districts, parks, schools, supermarkets, sample listings) -- [Turf.js](https://turfjs.org/) for spatial queries in the browser -- [Zustand](https://zustand.docs.pmnd.rs/) for map state; share links encode the full state in the URL hash - -## Data and licensing - -Six GeoJSON files under `public/data/` are bundled and loaded on startup, prepared ahead of time by the scripts in `scripts/` — the running app never calls Overpass or any other external data API at runtime; the single exception is the `plan_route` routing request described under [Architecture](#architecture). A further 18 point-of-interest files under `public/data/tier2/` (31,069 features total) are prepared the same way but loaded lazily, one category at a time, on first use — by an agent naming the category, or by a human picking it from the search box or the Places tray (see [City-wide breadth](#city-wide-breadth) above). Full provenance, Overpass queries and export notes for all 24 categories are in [`public/data/README.md`](./public/data/README.md). - -| Dataset | Category | Features | -|---|---|---:| -| MRT stations | `mrt_station` | 109 | -| Districts | `district` | 12 | -| Parks | `park` | 865 | -| Schools | `school` | 445 | -| Supermarkets | `supermarket` | 607 | -| Sample listings | `listing` | 25 (fabricated, not OSM) | - -Tier-2 features can also carry up to eleven further OSM tags, added in this build's enrichment pass: address, phone, website and `wheelchair` (as OpenStreetMap tags it — never a verified accessibility claim) apply to any category; seven more are gated to one category each — hotel `stars`; parking `fee` and `capacity`; pharmacy `dispensing`; place-of-worship `religion` and `denomination`; hospital `emergency` (five categories, seven fields). Together with the `cuisine`/`brand`/`opening_hours` already used for search, that is fourteen OSM tags a tier-2 feature can carry in total — but only where a contributor entered them: coverage citywide across all 31,069 features is roughly 43% for `address`, 22% for `phone`, 14% for `wheelchair` and 9% for `website`, and a field's absence means the tag was never recorded, not that the place lacks the thing it names. These fields are answered by `get_place_details`, one place per call, and rendered on the human's tap card from the same table; the inspector's Selected list stays deliberately lean and does not repeat them (a ratified narrowing, not an oversight). The six bundled datasets above do not carry these fields at all. - -- Map data © [OpenStreetMap](https://www.openstreetmap.org/copyright) contributors, [ODbL](https://opendatacommons.org/licenses/odbl/). Tiles by [OpenFreeMap](https://openfreemap.org/). -- Listings shown in the demo are **sample data**, not real properties. -- Code: [MIT](./LICENSE). +CI runs the same commands plus Playwright on every PR: 1,436 unit tests across 60 files, all green. Requires Node 22+. Branching, worktrees, commit and PR conventions: [CONTRIBUTING.md](./CONTRIBUTING.md). diff --git a/docs/TASKS.md b/docs/TASKS.md index 9dd87ff..5357487 100644 --- a/docs/TASKS.md +++ b/docs/TASKS.md @@ -24,6 +24,10 @@ Deadline: 2026-09-03 13:00 PDT. Must-have tools: `get_map_state`, `list_features ## D6 — 2026-09-02 · buffer; submit by evening of 2026-09-03 Taiwan time +| ID | Task | Owner | Status | Notes | +|---|---|---|---|---| +| T-105 | README shows the map before it explains it: 251 → 124 lines, describes only shipped behaviour; hero and landing images; two GIFs of the same ask card run by a screenshot agent and by a WebMCP agent; `docs/details.md` keeps the cut prose | docs-writer → review → docs-writer → review | done | Owner asked 2026-09-02 for: no unshipped work in the README, a 2–3 scenario comparison recording, images, and a condensed pitch judged adversarially. Two scenarios recorded (Playwright headless Chromium, scripted replays, WebMCP arm on `?shim=1`; the README says all of this); a third, human–agent collaboration, was not recorded — the "One map, two hands" section carries it in text. Recording the first arm surfaced T-104. Two review rounds: nine false or unsupported claims corrected before merge | + ## UI redesign — "Smoked Glass" · approved 2026-08-29 · gate: production matches the shipped mockup Design handoff: `docs/design/ui-redesign-handoff.md` (tokens, component inventory, ship-gates, honesty caveats). Verdict: SHIP after a five-round adversarial design review; mockup + evidence live in the design session workspace outside the repo. @@ -124,6 +128,14 @@ Found by adversarial review of T-41's fifth ask card. `resolveQueryInput` loads |---|---|---|---|---| | T-103 | `baseDataLoaded` flag + guard on the place-name form of `resolveNear` and `set_map_view.place` (ids and coordinates deliberately ungated); retryable refusal naming an accurate remedy; the refusal documented in `POINT_STRING_FORM` so the model reads it before calling; gated `base_data_loading` on state and on the four read-only answers that return none; `planCategories` splits the claim from the filter so `searched_categories` stops vouching for files that are not in the store | tool-dev → review | done | PR #88 → develop `da6c27b`. Regression test proven to fail without the fix (12/26 red on reverted sources); the coverage test proven to bite (removing the `annotate` row goes red). Blast radius is the load window only — output is byte-identical on any settled page | +## T-104 — the awakening cancelled the flight it interrupted · found 2026-09-02 while recording the README comparison · gate: an agent's first `set_map_view` lands where the tool said + +Reproduced on production: `set_map_view({ place: "Daan Station" })` as the very first tool call returned a z15 camera, and the map settled back at z12. The first live call wakes the inspector lane, which calls `map.setPadding` — in maplibre-gl 6.6.0 that is `jumpTo({ padding })`, which opens with `stop()` and fires two synchronous `moveend`s carrying the pre-flight camera; the store adopted them and the flight was gone. Every later call (page already awake) was fine, which is why no e2e spec ever saw it: the default network-isolated page never loads a style, so `flyTo` degraded to a synchronous jump there. + +| ID | Task | Owner | Status | Notes | +|---|---|---|---|---| +| T-104 | `flying` flag in `MapCanvas`: a corridor change (chrome wake, chrome flip, window resize) during a flight of ours re-issues the flight to the same target inside the `toMap` guard; a human gesture clears the flag so a drag mid-flight is never overridden; a resize mid-flight calls `map.resize()` first so the re-fly aims at the new canvas and republishes `bounds` | map-ui-dev → review → qa → review | done | Two review rounds. Review 1 found the resize path landing ~300 m off and `bounds` stale for the flight's duration; both fixed and probed before/after on a live basemap (landing error 302.7 m → 0.0 m). `e2e/awakening-flight.spec.ts`: 4 tests on the mock basemap, three proven red on the pre-fix `MapCanvas`, the fourth guards human authority | + ## Follow-ups (ticketed, unscheduled) - **F-1 (qa)** `awakening.spec.ts:672` — the flake family's last site: `stateAfterWaking` returns ~600ms into the story, then two Node-side locator assertions race the remaining ~1200ms of the `disabled` window; fold the reads into the same in-page tick. Pre-existing; deterministic-failure mode once the story lands. @@ -137,6 +149,7 @@ Found by adversarial review of T-41's fifth ask card. `resolveQueryInput` loads - **F-9 (tool-dev)** In the same load window, `set_map_view({feature_id})`, `measure({target})` and `get_place_details({id})` answer `unknown feature_id` / `unknown target` for a bundled id. Loud, never a confident wrong answer, and `base_data_loading` on map state now lets an agent see why — but the remedy `get_place_details` prescribes ("use find_features") is the path that was silent until T-103. - **F-10 (docs-writer)** `docs/design/ui-redesign-handoff.md` still describes a standalone bottom-left "legend" component in at least four places (the component-inventory row naming `StateOverlay.tsx`, two breakpoint rows, two design-token rows); it is now `MapKey.tsx` / `PlacesTray.tsx`. Assessed during T-41 and deliberately not fixed there: correcting it honestly means re-verifying the current responsive behaviour, not renaming a word. Supersedes the 2026-08-31 T-91 handoff. - **F-11 (tool-dev)** `src/lib/map-tools/share.test.ts:545` says "The sender has 2297 cafes in memory"; the manifest says 2,298. Harmless fixture prose, but it is the last site of a stale count corrected everywhere else in PR #89. +- **F-12 (map-ui-dev)** Two camera moves still sit outside T-104's `flying` invariant (`MapCanvas.tsx`): the cluster-expansion `map.easeTo` is cancelled by a corridor change during its 500 ms and not re-issued (no agent was promised that landing, so loud-but-harmless), and `load`'s second `pushViewFromMap()` would clear `flying` if a flight were in the air when the style loads. Both pre-existing; review 1 charged neither. Review 2 added a third, same class: a resize while NOT flying still runs `applyPadding()` before MapLibre's own resize, so `bounds` is published against the old width for one rendering update — `map.resize()` first on both paths would close it (`onResize = () => { map.resize(); applyPadding(); if (flying) pushBoundsFromMap(); }`), deferred to keep T-104 to the flight case. ## Handoff log diff --git a/docs/details.md b/docs/details.md new file mode 100644 index 0000000..e2f57aa --- /dev/null +++ b/docs/details.md @@ -0,0 +1,19 @@ +# GlassMap — tool behaviour in detail + +Behaviour the README summarises, spelled out. + +## `describe_surroundings` district fallback + +`describe_surroundings` names the district a point is in — falling back to the nearest district boundary within 300 m when the point sits in a seam between two independently simplified polygons, and naming none rather than guessing beyond that — then lists nearby features grouped into up to eight compass directions, nearest first, each with a distance in metres and a feature id an agent can act on next (`select_features`, `set_map_view`). When more features match than the tool describes, it says so instead of staying quiet: `total` is how many are within `radius_m`, `returned` is how many were actually listed (at most 30) — so a wider radius is never implied to reveal features that were simply cut off. + +## `select_features` 500-match cap + +`select_features` still highlights every match a filter finds, its contract since the tool shipped — but once a point-of-interest category is involved, a filter matching more than 500 of them is refused rather than lighting up half the city: the answer gives the true count and asks for `near`+`radius_m`, `within` or `query` to narrow it. The six bundled categories are exempt from that cap. + +## `get_share_link` versioning (v1/v2/v3) + +A `get_share_link` link carries the *names* of every point-of-interest category the sender had loaded, not their features — the recipient's page fetches the same files itself — so opening the link rebuilds the sender's map, selection included, instead of resolving to features the recipient's session never heard of. A link that names a category is written as `v2`; a link with none still encodes to the exact `v1` bytes it always did, so no existing link breaks. The one exception is a map whose drawings would not fit in a URL at all: their coordinates then travel delta-encoded and the link is written as `v3` — smaller maps keep their old bytes, and every older link still decodes. + +## Tier-2 fetch failure: permanent vs. transient + +Fetching a category file can fail two honestly different ways: a **permanent** failure (this deployment ships no such file — a 404) drops the category and is not retried; a **transient** one (a slow connection, a rate-limited mirror — a 5xx, or a 408/425/429 that means "ask again") keeps the category on the books, including in any share link handed out meanwhile, so the next call simply tries again. diff --git a/docs/media/hero.jpg b/docs/media/hero.jpg new file mode 100644 index 0000000..977e7d2 Binary files /dev/null and b/docs/media/hero.jpg differ diff --git a/docs/media/landing.jpg b/docs/media/landing.jpg new file mode 100644 index 0000000..1f32f94 Binary files /dev/null and b/docs/media/landing.jpg differ diff --git a/docs/media/screenshot-agent.gif b/docs/media/screenshot-agent.gif new file mode 100644 index 0000000..28812c2 Binary files /dev/null and b/docs/media/screenshot-agent.gif differ diff --git a/docs/media/webmcp-agent.gif b/docs/media/webmcp-agent.gif new file mode 100644 index 0000000..1c52bd2 Binary files /dev/null and b/docs/media/webmcp-agent.gif differ diff --git a/e2e/awakening-flight.spec.ts b/e2e/awakening-flight.spec.ts new file mode 100644 index 0000000..85ac387 --- /dev/null +++ b/e2e/awakening-flight.spec.ts @@ -0,0 +1,388 @@ +/** + * T-104 -- a corridor change must not cancel the flight it interrupts. + * + * The defect: `set_map_view` as the FIRST tool call on a fresh page returned + * the new camera, but the map itself snapped back to the landing view within + * ~550ms. That first call is also the one that wakes the chrome (the + * inspector lane opens -- `src/lib/awaken/`'s mode flips idle -> waking on the + * very first `recordActivity`), and `MapCanvas.tsx`'s own padding effect + * (`subscribeChromeVisible`) reacts to that flip by calling `map.setPadding`, + * which in maplibre-gl 6 is `jumpTo({padding})` -- and `jumpTo` opens with + * `this.stop()`. An ease already in flight is cancelled at whatever frame it + * had reached, firing `moveend` SYNCHRONOUSLY with the pre-flight camera, and + * (before the fix) `pushViewFromMap` believed it: the store's `view` was + * overwritten back to the landing camera, and nothing re-flew. The fix (the + * comment block above `applyPadding` in `MapCanvas.tsx`) re-issues the flight + * toward the same target when a corridor change interrupts one still in the + * air. + * + * This suite's own default network isolation (`fixtures.ts`) is exactly why + * T-104 was invisible to the existing e2e suite: with no basemap style + * `applyView` calls `map.jumpTo` (no animation, nothing to cancel; see + * `redesign-corridor-bounds.spec.ts`'s own note on this). Every test below + * mocks a minimal-but-valid style document, the same escape hatch + * `place-details.spec.ts` uses, so MapLibre actually runs a render loop and + * `flyTo` actually eases -- the only way this defect can exist at all. + * + * A trap this file's own history fell into once, worth naming: `set_map_view` + * writes `store.view` (`center`/`zoom`/...) SYNCHRONOUSLY, the instant the + * tool runs -- that is what lets its own JSON answer report the new camera + * before a single animation frame has run. Polling `get_map_state().zoom` + * alone therefore resolves immediately on BOTH the broken and the fixed + * build, and proves nothing: only the LIVE map (`window.__glassmapMap`, + * dev-only handle) and `bounds` (written solely from a real `moveend`) can + * tell a landed flight from one that never left. Every "settled" wait below + * polls the live map directly. + */ +import type { Page } from "@playwright/test"; +import { callTool } from "./mcp"; +import { waitForFeatures, waitForLiveMap, waitForTools } from "./helpers"; +import { blockExternalNetwork, expect, mockExternalHost, test } from "./fixtures"; + +/** "Daan" MRT station (osm:node:3494960748, public/data/mrt-stations.geojson) -- + * the same alias the rest of this codebase's own tests resolve "Daan Station" + * to (activity.test.ts, place-race.test.ts). Real, shipped data, not a + * fixture: the whole point is a real `flyTo` over a real distance. + */ +const DAAN_STATION = { lng: 121.54355, lat: 25.03333 }; +const PLACE_ZOOM = 15; + +/** Same mock as `place-details.spec.ts:57` -- a minimal-but-valid style + * document is enough for MapLibre to fire `load` and run a real render loop, + * without this suite ever depending on a third-party CDN's uptime. + */ +const BASEMAP_HOST = "tiles.openfreemap.org"; + +/** + * Registers the tiles mock. On the default `page`/`context` this only needs + * to declare the host to `blockedRequests` (fixtures.ts's own auto fixture + * already blocks every other non-localhost request there). A page opened + * through a manually-created `browser.newContext()` has none of that + * protection, so `blockExternalNetwork` must be applied to it FIRST -- routes + * on the same page match in REVERSE registration order (Playwright's own + * rule: the last-registered handler runs first), so registering the blanket + * abort before this specific mock is what lets the mock's `fulfill` win for + * `tiles.openfreemap.org` while every other host on that page still gets + * aborted rather than silently reaching the real network. + */ +async function mockMinimalBasemap(page: Page, mockedExternalHosts: Set): Promise { + mockExternalHost(mockedExternalHosts, BASEMAP_HOST); + await page.route(`**/${BASEMAP_HOST}/**`, (route) => + route.fulfill({ + status: 200, + contentType: "application/json", + body: JSON.stringify({ version: 8, sources: {}, layers: [] }), + }), + ); +} + +/** + * A page with a real, loaded map and NO tool call yet -- `map-status` only + * reaches "ready" on MapLibre's `load` event, which fires strictly after + * `style.load` (MapCanvas.tsx), so this also guarantees `styleLoaded` is + * already true and `flyTo` will actually ease rather than jump. Asserts idle + * chrome on the way out: this suite's whole premise is the FIRST tool call, + * and every caller below depends on nothing having touched the map before it + * makes that call itself. + */ +async function goReadyCold(page: Page): Promise { + await page.goto("/"); + await waitForTools(page); + await waitForFeatures(page); + await waitForLiveMap(page); + await expect(page.getByTestId("map-status")).toHaveText("ready", { timeout: 20_000 }); + expect(await page.evaluate(() => document.body.dataset.awaken)).toBe("idle"); +} + +/** The live map's own camera -- not the store's, which `set_map_view` writes + * synchronously regardless of whether the camera has actually arrived there. + */ +async function liveCamera(page: Page): Promise<{ lng: number; lat: number; zoom: number }> { + return page.evaluate(() => { + const map = window.__glassmapMap!; + const center = map.getCenter(); + return { lng: center.lng, lat: center.lat, zoom: map.getZoom() }; + }); +} + +/** + * Waits until the LIVE map itself has stopped moving at (approximately) the + * target zoom -- `map.isMoving()` false and `map.getZoom()` within 0.01 of + * `targetZoom`. Reading `window.__glassmapMap` directly rather than polling + * `get_map_state` is deliberate (see this file's top-of-file note): the store + * already reports the target the instant the tool runs, so only the live map + * can distinguish "commanded" from "arrived". + */ +async function waitForLiveArrival(page: Page, targetZoom: number, timeoutMs = 6000): Promise { + await page.waitForFunction( + (zoom) => { + const map = window.__glassmapMap; + return !!map && !map.isMoving() && Math.abs(map.getZoom() - zoom) < 0.01; + }, + targetZoom, + { timeout: timeoutMs }, + ); +} + +test.describe("the Awakening does not cancel the first flight (T-104)", () => { + // Desktop tier throughout (globals.css: the 336px lane only applies above + // 1240px), and the exact canvas width the corridor-pixel checks below + // reason about. + test.use({ viewport: { width: 1280, height: 800 } }); + + test("set_map_view as the very first tool call still lands at its own target, on screen and in the tool's own answer", async ({ + page, + mockedExternalHosts, + }) => { + await mockMinimalBasemap(page, mockedExternalHosts); + await goReadyCold(page); + + // The cold path the defect lived in: this is the first tool call this + // page has ever made, so it is also the call that wakes the chrome. + const flown = await callTool(page, "set_map_view", { place: "Daan Station" }); + expect(flown.error).toBeUndefined(); + expect(flown.zoom).toBe(PLACE_ZOOM); + expect(flown.center!.lng).toBeCloseTo(DAAN_STATION.lng, 4); + expect(flown.center!.lat).toBeCloseTo(DAAN_STATION.lat, 4); + + // The failure shape, checked fast rather than only after the full poll + // budget: on the broken build the live camera is back at the LANDING + // zoom (12) within ~550ms and never leaves it again, so even this loose, + // early check already tells the two builds apart. + await page.waitForTimeout(1000); + const midFlight = await liveCamera(page); + expect(midFlight.zoom).not.toBeCloseTo(12); + + // The regression itself: on the broken build the live map never reaches + // zoom 15 at all -- this times out loud rather than being waited past. + await waitForLiveArrival(page, PLACE_ZOOM); + const landed = await liveCamera(page); + expect(landed.lng).toBeCloseTo(DAAN_STATION.lng, 4); + expect(landed.lat).toBeCloseTo(DAAN_STATION.lat, 4); + + // The store agrees with the live map it is supposed to be describing -- + // not merely with the value the tool wrote before the flight even began. + const settled = await callTool(page, "get_map_state"); + expect(settled.error).toBeUndefined(); + expect(settled.center).toEqual(flown.center); + expect(settled.zoom).toBe(PLACE_ZOOM); + + // The visible half: the human-readable camera chip (BrandBar.tsx) agrees + // with the JSON a tool just returned -- the project's own law that + // whatever an agent can read, a person can see on the page. + await expect(page.getByTestId("camera-readout")).toContainText("z15"); + }); + + test("the settled camera sits in the padded corridor, not the full canvas -- a cold first call agrees with an already-awake control to 5 decimals", async ({ + page, + browser, + mockedExternalHosts, + }) => { + await mockMinimalBasemap(page, mockedExternalHosts); + await goReadyCold(page); + + // Cold: `set_map_view` is the first tool call, so the flight and the + // corridor's arrival race in the same tick -- exactly the defect. + const coldFlown = await callTool(page, "set_map_view", { place: "Daan Station" }); + expect(coldFlown.error).toBeUndefined(); + await waitForLiveArrival(page, PLACE_ZOOM); + const cold = await callTool(page, "get_map_state"); + expect(cold.error).toBeUndefined(); + expect(cold.bounds).not.toBeNull(); + + // Warm control, in a second page: a read call wakes the chrome and lands + // (`get_map_state` alone never starts a flight, so there is nothing for + // that corridor change to interrupt), THEN the identical `set_map_view` + // runs on an already-awake page -- the case T-104's own report says was + // always fine. Same viewport, same style mock, same target; the only + // variable this isolates is whether the flight and the wake collided. + const context2 = await browser.newContext({ viewport: { width: 1280, height: 800 } }); + const page2 = await context2.newPage(); + const errors2: string[] = []; + page2.on("pageerror", (err) => errors2.push(err.message)); + // Order matters (see mockMinimalBasemap's own doc comment): the blanket + // abort first, the specific tiles mock second, so the mock wins for + // tiles.openfreemap.org while every other host on this manually-created + // page/context still gets aborted rather than reaching the real network. + await blockExternalNetwork(page2); + await mockMinimalBasemap(page2, mockedExternalHosts); + await goReadyCold(page2); + + const warmUp = await callTool(page2, "get_map_state"); + expect(warmUp.error).toBeUndefined(); + await expect + .poll(() => page2.evaluate(() => document.body.dataset.awaken)) + .not.toBe("idle"); + + const warmFlown = await callTool(page2, "set_map_view", { place: "Daan Station" }); + expect(warmFlown.error).toBeUndefined(); + await waitForLiveArrival(page2, PLACE_ZOOM); + const warm = await callTool(page2, "get_map_state"); + expect(warm.error).toBeUndefined(); + await context2.close(); + expect(errors2).toEqual([]); + + // The equality itself is the regression test: on the broken build `cold` + // never reaches this target at all (previous test), but a build that + // "fixed" T-104 by, say, always re-flying regardless of corridor could + // still land the CENTRE right while getting the CORRIDOR wrong (padding + // applied to the wrong moment, or not republished after the re-fly). + // Comparing full state -- center, zoom AND bounds -- against a control + // that never raced the wake at all closes that gap. + expect(cold.center).toEqual(warm.center); + expect(cold.zoom).toBe(warm.zoom); + expect(cold.bounds).toEqual(warm.bounds); + + // Not the full 1280px canvas: asking the live map itself (not a + // recomputation of `visibleBounds`'s own formula) where `bounds.east` + // projects to must land ~336px inside the 1280px canvas -- the inspector + // lane's own width (globals.css `--lane: 336px` at desktop) -- not at the + // canvas's true edge, which is what a padding-less corridor would report. + const eastPixelX = await page.evaluate( + (lng) => window.__glassmapMap!.project([lng, window.__glassmapMap!.getCenter().lat]).x, + cold.bounds!.east, + ); + expect(eastPixelX).toBeGreaterThan(900); + expect(eastPixelX).toBeLessThan(960); + }); + + test("a mid-flight window resize keeps the flight's own target and republishes bounds at the new canvas width", async ({ + page, + mockedExternalHosts, + }) => { + await mockMinimalBasemap(page, mockedExternalHosts); + await goReadyCold(page); + + // Same cold first call: starts the flight AND wakes the chrome, so the + // corridor pads once already before the resize below pads it again. + const flown = await callTool(page, "set_map_view", { place: "Daan Station" }); + expect(flown.error).toBeUndefined(); + + // The corridor before the resize below, still at the 1280px canvas this + // page opened with -- the value the resize is supposed to move `bounds` + // AWAY from, not merely agree with once the flight eventually lands. + const beforeResize = await callTool(page, "get_map_state"); + expect(beforeResize.error).toBeUndefined(); + expect(beforeResize.bounds).not.toBeNull(); + + // Mid-flight, a second corridor change from an entirely different cause: + // `applyPadding` also runs on `resize` (MapCanvas.tsx), and the fix's + // `flying` guard has to re-fly regardless of which of the two callers + // interrupted the ease. 1440px stays inside the same >1240px lane tier + // (globals.css) -- the lane itself stays 336px, so only the CANVAS width + // changes (944px corridor -> 1104px), isolating this from a lane-width + // change. + await page.waitForTimeout(300); + await page.setViewportSize({ width: 1440, height: 900 }); + + // Read back WHILE the flight is still in the air -- the ~2s ease is + // nowhere near done at 300ms in, and this read is one fast `page.evaluate` + // round trip, so this samples well before `waitForLiveArrival` below ever + // resolves. `onResize`'s own `pushBoundsFromMap()` call is the only thing + // that can have moved `bounds` already: the flight's own `moveend` -- the + // other path that republishes bounds -- has not fired yet, and won't for + // another second or more. Without that line `bounds` would still equal + // `beforeResize.bounds` here, describing a canvas 160px narrower than the + // one actually on screen, until the flight happens to land on its own. + const midResize = await callTool(page, "get_map_state"); + expect(midResize.error).toBeUndefined(); + expect(midResize.bounds).not.toEqual(beforeResize.bounds); + + await waitForLiveArrival(page, PLACE_ZOOM); + const settled = await callTool(page, "get_map_state"); + expect(settled.error).toBeUndefined(); + expect(settled.center!.lng).toBeCloseTo(flown.center!.lng, 4); + expect(settled.center!.lat).toBeCloseTo(flown.center!.lat, 4); + expect(settled.bounds).not.toBeNull(); + + // Bounds describe the NEW 1440px canvas, not the 1280px one the flight + // started under: corridor right edge = 1440 - 336 = 1104px. + const eastPixelX = await page.evaluate( + (lng) => window.__glassmapMap!.project([lng, window.__glassmapMap!.getCenter().lat]).x, + settled.bounds!.east, + ); + expect(eastPixelX).toBeGreaterThan(1060); + expect(eastPixelX).toBeLessThan(1130); + }); + + test("a hand drag mid-flight is not overwritten by the chrome arriving: the human's own gesture wins", async ({ + page, + mockedExternalHosts, + }) => { + await mockMinimalBasemap(page, mockedExternalHosts); + await goReadyCold(page); + + // Same cold first call as above: starts the flight AND wakes the chrome. + const flown = await callTool(page, "set_map_view", { place: "Daan Station" }); + expect(flown.error).toBeUndefined(); + + // Mid-flight (the ~2s ease is nowhere near done): take the wheel. A real + // pointer drag over the live canvas -- MapLibre's own `dragPan` handler + // calls `this.stop()` on `mousedown`, cancelling the ease exactly the way + // `applyPadding`'s `jumpTo`-induced `stop()` does, but this one MUST be + // allowed to win: `flying` (MapCanvas.tsx) is cleared by this gesture's + // own `moveend`, and no later corridor change may treat the agent's old + // target as still owed. + // + // The LIVE camera, not the store's: `get_map_state().center` right now + // would still read the agent's TARGET (Daan Station) -- `set_map_view` + // writes it synchronously before a single animation frame runs (this + // file's own top-of-file note), and this flight is nowhere near landing. + // Measuring the drag's delta off that target, rather than off where the + // hand actually started, would pass even if the drag below were a no-op: + // the flight alone would already account for the whole "distance". + // + // And sampled AFTER `mouse.down()`, not before it. The pan handler is + // `activateOnStart`, so the mousedown alone makes the handler manager call + // `stop(true)`: from that instant the camera is frozen until the first + // pan delta. Sampled a few round trips earlier, the still-moving flight + // would pollute the delta -- on a slow CI runner it once cancelled most + // of a 160x120px pan and read 0.00055 against the 0.001 floor below. + const box = await page.getByTestId("map").boundingBox(); + if (!box) throw new Error("map container has no box to drag over"); + const startX = box.x + box.width * 0.3; + const startY = box.y + box.height * 0.5; + await page.mouse.move(startX, startY); + await page.mouse.down(); + const beforeDrag = await liveCamera(page); + await page.mouse.move(startX + 160, startY + 120, { steps: 12 }); + await page.mouse.up(); + // Let the drag's inertia run out before reading the position back -- the + // store publishes at `moveend`, and a fixed wait is a bet on the runner. + await page.waitForFunction(() => !window.__glassmapMap!.isMoving()); + + const afterDrag = await callTool(page, "get_map_state"); + expect(afterDrag.error).toBeUndefined(); + // The drag itself really moved the camera off its OWN pre-drag position -- + // a real geographic delta, not merely "the flight got interrupted + // somewhere else on its own ease" (mousedown alone would do that with no + // pixel of pan at all). At any zoom this flight passes through, a + // 160x120px pan is orders of magnitude larger than this threshold. + const dragDelta = + Math.abs(afterDrag.center!.lng - beforeDrag.lng) + Math.abs(afterDrag.center!.lat - beforeDrag.lat); + expect(dragDelta).toBeGreaterThan(1e-3); + + // A real corridor change after the drag, not another read call: `flying` + // is false now (the drag's own `moveend` cleared it), so `onResize` must + // take the NOT-flying branch and never re-fly toward the agent's old + // target. This is exactly the shape of event the `flying` guard exists to + // withstand -- a resize arriving after a human already took the wheel -- + // and unlike a bare read call, a resize genuinely runs `onResize`. + await page.setViewportSize({ width: 1440, height: 900 }); + await page.waitForTimeout(400); + + const settled = await callTool(page, "get_map_state"); + expect(settled.error).toBeUndefined(); + + // The human's hand wins: nothing moved the camera again after the drag, + // not even the resize above. + expect(settled.center).toEqual(afterDrag.center); + expect(settled.zoom).toBe(afterDrag.zoom); + + // And specifically: the camera did NOT snap back to the agent's original + // target -- the exact regression this guard exists to prevent. + const distanceFromTarget = + Math.abs(settled.center!.lng - DAAN_STATION.lng) + Math.abs(settled.center!.lat - DAAN_STATION.lat); + expect(distanceFromTarget).toBeGreaterThan(1e-3); + }); +}); diff --git a/src/components/MapCanvas.tsx b/src/components/MapCanvas.tsx index c9205f6..75c2105 100644 --- a/src/components/MapCanvas.tsx +++ b/src/components/MapCanvas.tsx @@ -205,6 +205,14 @@ const sameView = (a: MapView, b: MapView) => Math.abs(a.bearing - b.bearing) < 1e-4 && Math.abs(a.pitch - b.pitch) < 1e-4; +/** The camera options a `MapView` is: the same four fields, MapLibre's names. */ +const cameraOf = (view: MapView) => ({ + center: view.center, + zoom: view.zoom, + bearing: view.bearing, + pitch: view.pitch, +}); + /** * The map is a mirror of the store: tools write `view`/`selection` and the map * follows; user gestures write back through `moveend`. @@ -216,6 +224,11 @@ const sameView = (a: MapView, b: MapView) => * which fires `moveend` SYNCHRONOUSLY when an animation is already running; * without this guard that re-entrant `moveend` writes the mid-flight camera * back over the request a tool is about to read. + * + * And one fact, `flying`, that says a flight of ours is still owed. Not whose + * camera the map is obeying, which is a different question with a different + * answer: a human who drags mid-flight is obeyed at once, and that clears the + * flag. See `applyPadding`, which has to interrupt a flight without ending it. */ export default function MapCanvas() { const containerRef = useRef(null); @@ -352,6 +365,26 @@ export default function MapCanvas() { // request is not dropped just because it momentarily matches an unrelated // interpolated position. let lastView: MapView = initial; + /** + * True exactly while `lastView` is a camera WE commanded and the map has + * not reported reaching yet - i.e. one of our flights is still in the air. + * + * Set where the flight is issued, cleared in `pushViewFromMap`, which is + * every path by which the map itself gets to write `lastView`: the flight's + * own `moveend` (it arrived), and a human gesture's (they took the wheel - + * dragging cancels the ease, and the position they dragged from is now the + * truth). That is the whole invariant, and re-flying a camera the person + * just overrode would be the map arguing with them. + * + * Not a live read of `map.isMoving()`, which is `_camera.isMoving() || + * _handlers.isMoving()` and so answers true for a hand-dragged map as + * readily as for one of ours. This is sampled ONCE, at the instant our + * `flyTo` is issued - the moment `_prepareEase` has just set + * `_camera._moving` - and from then on any `moveend` that is not ours + * clears it. A hand-dragged map fires exactly such a `moveend`, so the flag + * never outlives the person's decision. + */ + let flying = false; /** * Publish the extent of the corridor the camera is currently over. Not @@ -374,6 +407,9 @@ export default function MapCanvas() { const pushViewFromMap = () => { // A `moveend` our own flyTo caused, not a user gesture - ignore it. if (toMap) return; + // Whatever this event is, the map is about to become the author of + // `lastView`, so no flight of ours is owed against it any more. + flying = false; const center = map.getCenter(); const view: MapView = { center: [center.lng, center.lat], @@ -394,12 +430,7 @@ export default function MapCanvas() { const applyView = (view: MapView) => { if (sameView(view, lastView)) return; lastView = view; - const camera = { - center: view.center, - zoom: view.zoom, - bearing: view.bearing, - pitch: view.pitch, - }; + const camera = cameraOf(view); toMap = true; try { // Animate only when there is a render loop to animate in. Without a @@ -409,8 +440,27 @@ export default function MapCanvas() { // store reports the new one, and `bounds` - only ever written from // `moveend` - would freeze there with it. A jump has no animation to // stall: the map really is where the store says it is. - if (styleLoaded) map.flyTo({ ...camera, essential: true }); - else map.jumpTo(camera); + if (styleLoaded) { + map.flyTo({ ...camera, essential: true }); + // Asked, not asserted. A flight that finishes inside this call - + // what `duration: 0` does, running its last frame and `finish` + // synchronously - has already fired the `moveend` that clears this, + // and fired it inside the `toMap` guard, which drops it. `flying = + // true` would then latch with nothing left to clear it, and every + // later corridor change would re-fly a camera nobody is owed. No + // caller does that today (both pass `essential: true` and no + // duration), so this costs nothing and cannot be got wrong later. + // + // `isMoving()` and not `Camera.isEasing()`, which is the narrower + // question but is not on `Map` in maplibre-gl 6 (`Map` composes a + // `Camera`, it no longer extends one). The wider answer is the one + // that keeps the invariant anyway: while the map is moving at all + // there is a `moveend` still to come, and every `moveend` that is + // not ours clears this flag. + flying = map.isMoving(); + } else { + map.jumpTo(camera); + } } finally { toMap = false; } @@ -429,11 +479,107 @@ export default function MapCanvas() { // corridor the human can actually see. Applied before the first // `pushViewFromMap` so the very first `center`/`bounds` pair a tool can // read already describes that corridor and not the full canvas. + // + // A corridor change must not cancel the flight it interrupts (T-104). In + // maplibre-gl 6 `Camera.setPadding(p)` is literally `this.jumpTo({padding: + // p})`, and `jumpTo` opens with `this.stop()`: an ease in progress is + // dropped at whatever frame it had reached and its `finish` fires `moveend` + // SYNCHRONOUSLY, carrying that frame's camera: the pre-flight one when the + // interruption lands in the same tick as the flight (frame 0 - the T-104 + // case), a genuine mid-flight one when it comes later, as a window resize + // does. `jumpTo` then fires a SECOND synchronous `moveend` of its own, once + // the new padding is on. Unguarded, `pushViewFromMap` believed both: it + // wrote a camera the flight had already left behind into the store and into + // `lastView`, so nothing was owed any more and nothing re-flew. Both are + // guarded now, and neither needs to be told apart from the other - every + // camera event this re-padding causes is one we caused. + // + // Which made the FIRST tool call on a page cancel its own flight, every + // time: that call is also the one that wakes the chrome, so the flight and + // the lane arrived in the same tick. `set_map_view` returned the new + // camera, the store held it for one tick, and the map never left the + // landing view. The same call on an already-awake page was fine, which is + // why this hid for so long - and why the suite hid it too. Network + // isolation is the reason: with the basemap host blocked no style ever + // arrives, so `applyView` jumps instead of flying and there is no ease to + // cancel. A spec that opts into the mock basemap (`mockMinimalBasemap` - a + // valid empty style document, all MapLibre needs to fire `load` and run a + // render loop) does fly, and reproduces this in seconds. + // + // So when a flight of ours is in the air, pad inside the `toMap` guard - + // that guard is for re-entrant camera events and this is one, an event that + // says where the map is while lying about where it is going - and then put + // the flight back in the air towards the target `lastView` still holds. The + // corridor really did move and the flight really is still owed; both + // statements survive. Publishing the new corridor is then the caller's job, + // because the `moveend` that would have done it is inside the guard: both + // callers - `subscribeChromeVisible` and `onResize` - follow this with + // `pushBoundsFromMap`, which reports the corridor around the camera as it + // is mid-flight, exactly as it does during any other flight, and the + // flight's own `moveend` corrects it on arrival. const applyPadding = () => { - map.setPadding({ top: 0, bottom: 0, left: 0, right: inspectorLane() }); + const padding = { top: 0, bottom: 0, left: 0, right: inspectorLane() }; + if (!flying) { + map.setPadding(padding); + return; + } + toMap = true; + try { + map.setPadding(padding); + map.flyTo({ ...cameraOf(lastView), essential: true }); + // Same reason as in `applyView`: never latch on a flight that is over. + flying = map.isMoving(); + } finally { + toMap = false; + } }; applyPadding(); - window.addEventListener("resize", applyPadding); + + /** + * The window changed size, so the corridor did too - and when a flight of + * ours is in the air, `applyPadding` re-issuing it is not enough on its own. + * + * `map.resize()` first. MapLibre learns its canvas size from a + * ResizeObserver, and we are ahead of it in the queue: the window `resize` + * event we are handling fires during the resize steps, while + * ResizeObserver callbacks are delivered later in the same rendering + * update, after rAF. So at this instant MapLibre's transform still has the + * old width - not because of the 50 ms throttle on that callback, which is + * leading-edge (its first call runs synchronously) and only bites on the + * 2nd..Nth event of a drag-resize burst, but because MapLibre's turn has + * not come yet - and `flyTo` captures the screen point it flies + * `center` to ONCE, at issue time (it re-derives it per frame only while the + * flight itself interpolates padding, which this one never does: the padding + * is applied before it starts). A flight aimed through a canvas that no + * longer exists lands a few hundred metres from the centre the tool already + * returned, and `moveend` then writes that wrong place into the store as + * fact. Resizing mid-ease is safe: `Map.resize` calls `stop()` and fires + * move events only when `!this._camera._moving`, which a running ease makes + * false - so it cannot cancel the flight it is here to protect. + * + * `pushBoundsFromMap()` after, because the flying branch of `applyPadding` + * re-pads inside the `toMap` guard, and that guard swallows the `moveend` + * which used to publish the new corridor. Without this line + * `get_map_state().bounds` keeps describing the old canvas width for the + * whole flight - byte-identical to the answer before the resize, on a page + * that visibly changed shape. + * + * The not-flying branch needs neither: nothing is aimed anywhere, and its + * `setPadding` is a `jumpTo` whose synchronous `moveend` publishes through + * `pushViewFromMap` as it always has (against the pre-resize transform, in + * that same gap - MapLibre's own resize corrects it with a + * `moveend` of its own, because with no ease running that one does fire). + */ + const onResize = () => { + if (!flying) { + applyPadding(); + return; + } + map.resize(); + applyPadding(); + pushBoundsFromMap(); + }; + window.addEventListener("resize", onResize); // The transform is valid as soon as the constructor returns, so bounds is // available immediately - a tool must not see `bounds: null` for the ~1.4 s @@ -843,7 +989,7 @@ export default function MapCanvas() { applyDrawCursor(draw.getState().mode); return () => { - window.removeEventListener("resize", applyPadding); + window.removeEventListener("resize", onResize); setFxMap(null); unsubscribe(); unsubscribeDraw(); diff --git a/src/components/TryAsking.tsx b/src/components/TryAsking.tsx index b8ff22c..22c5db7 100644 --- a/src/components/TryAsking.tsx +++ b/src/components/TryAsking.tsx @@ -12,11 +12,10 @@ * two-step `find_features · measure` chain. Re-verify resolution before * changing a single word. * - * And these strings are not only here: README.md's "Try it" section quotes the - * first three cards verbatim, question and tool tag both. Editing one of those - * three without editing the README leaves the repo saying two different things - * a judge can hand the same agent. (It quotes three of five and claims no - * completeness, so adding a card is safe; changing one of the three is not.) + * And these strings are not only here: README.md's "Try it" section quotes all + * five cards verbatim, question and tool tag both. Editing any of them without + * editing the README leaves the repo saying two different things a judge can + * hand the same agent. (Adding a card is safe; changing one is not.) * * The `get_place_details` card (F-4) is held to the same bar twice over, and * both halves are easy to break by rewording it: