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/README.md b/README.md index 7ad2fde..abc8122 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ JSON.parse(found); Any other browser works with `?shim=1` appended to the URL: the page installs `document.modelContext` itself when the browser has none. Development builds do this by default. ## Fifteen tools -Three layers, in that order: **Perceive** (read-only — replaces screenshots), **Navigate** (camera only) and **Act** (writes page state; only `plan_route` calls an external service). +Three layers, in that order: **Perceive** (read-only — replaces screenshots), **Navigate** (camera only) and **Act** (writes page state; only routing calls an external service). | Tool | What it does | |---|---| @@ -96,12 +96,14 @@ 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) - 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`. +- **Who did what.** Every shape and note carries `source: "agent"` or `"user"` — the tag a human sees on the mark, and the same field an agent reads back from `get_map_state`. A shape drawn by hand appears with `source: "user"` and is immediately queryable with `find_features({ within: "drawing:" })`; a shape or note an agent draws or annotates renders at once with its own tag and a ✕ to remove it — no confirmation dialog on either side. `remove_from_map` takes off only the marks tagged `agent`; a human's it refuses, by id, with the reason. +- **On the record — on screen.** Every tool call lands on the activity feed as a row — the tool, a one-line summary, success or error, when, and the ids it touched — the last 50 kept, its sequence number still counting past that. A human's own actions write no row: their trail is the tag on the mark, not a line in the feed. +- **Two WebMCP APIs, one state.** The pin-note field is a plain `` — no JavaScript registration — and `SubmitEvent.agentInvoked`, the browser's own signal rather than a guess the page makes, 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. +- With the Note popover open, a click on the map places the pin there — a second click moves it, `Escape` cancels — and with no click, the note pins at the map centre. +- A Route pill: click a start and an end, and the same walking-route service `plan_route` uses draws the walk as a `source: "user"` line, labelled with its distance and time (`walking route · 3.8 km · 47 min`) — a mark `remove_from_map` refuses like any other of the human's. - 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. +- The address bar holds a link that restores this exact map — camera, selection, drawings and notes, each still tagged `agent` or `user` — for whoever opens it. ## Data Six bundled Taipei datasets are always in memory — 109 MRT stations, 12 districts, 865 parks, 445 schools, 607 supermarkets and 25 sample listings (fictional, not from 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). @@ -111,7 +113,7 @@ Six bundled Taipei datasets are always in memory — 109 MRT stations, 12 distri - Code: [MIT](./LICENSE). ## 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; when the service is unreachable the tool returns an error and leaves the map unchanged. +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 the keyless FOSSGIS OSRM instance that plans walking routes, asked by `plan_route` and by the human Route pill through one shared throttle that keeps its 1 request/second policy; when the service is unreachable the tool returns an error, the pill says so, and the map is left unchanged. ```bash pnpm install @@ -121,4 +123,4 @@ pnpm test:e2e # Playwright, via document.modelContext pnpm build ``` -CI runs `pnpm check`, `pnpm build` and `pnpm test:e2e` on every code PR: 1,436 unit tests across 60 files. Node 22. Branching, worktrees, commit and PR conventions: [CONTRIBUTING.md](./CONTRIBUTING.md). +CI runs `pnpm check`, `pnpm build` and `pnpm test:e2e` on every code PR: 1,461 unit tests across 63 files. Node 22. Branching, worktrees, commit and PR conventions: [CONTRIBUTING.md](./CONTRIBUTING.md). diff --git a/docs/TASKS-archive.md b/docs/TASKS-archive.md index 47ada2b..f58eae8 100644 --- a/docs/TASKS-archive.md +++ b/docs/TASKS-archive.md @@ -43,3 +43,115 @@ Archived 2026-09-01 by the orchestrator, when D5 work pushed the board past ~150 | T-33 | `set_layers` | tool-dev / map-ui-dev | cut | the flagship demo script uses no layer toggling; cut confirmed 2026-08-29 | | T-34 | Screenshot-vs-WebMCP comparison (3 tasks, one run each) | orchestrator + qa | done | `docs/comparison.md`; headline: 4 calls/4.5 KB vs 16 actions+11 screenshots, control failed task B (1/11 names) | + +--- + +Archived 2026-09-02 by the orchestrator, when the T-106…T-110 rounds pushed the board past ~150 lines again. Every row below is `done`. + +## 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. + +| ID | Task | Owner | Status | Notes | +|---|---|---|---|---| +| T-50 | Activity feed data layer: record every tool call (tool, humanized summary, read/write, ok, ref ids, timestamp) into a store slice from the map-tools execute path; unit tests | tool-dev | done | PR #35 | +| T-51 | Smoked Glass chrome: brand bar, camera/Share chips, glass inspector, legend footer, Try-asking cards, breakpoint tiers incl. 769–920 sheet; WebMCP badge counts page-declared tools (11 imperative + declarative `add_note` = 12) per the handoff SHIP-GATE | map-ui-dev | done | PR #36; visual parity gate passed on independent production-build captures; bounds are the visible corridor | +| T-52 | `map-style.ts` calm ramp (z≤13 dot treatment) + selection halos per handoff | map-ui-dev | done | PR #36 | +| T-53 | Activity feed UI wired to the T-50 slice | map-ui-dev | done | PR #36; declarative add_note records agent-invoked submissions too | +| T-54 | e2e: suite green on the new chrome; share-link restore shows provenance labels on the receiving window (experience-case gate) | qa | done | PR #38 — provenance gate PASS; found the frozen-bounds defect, fixed as PR #39 (jump, don't fly, without a style) | + +## Tier-2 OSM breadth — approved 2026-08-30 · gate: category-addressed city-wide breadth, deterministic and shareable + +Outcome of the basemap-interop adversarial study (5 rounds; tile-reading refuted on licence/completeness/latency/actionability; the pipeline widened instead). Laws: **category filtering is the query model — no list-all tools**; category-lazy whole-city loading, NEVER bbox-lazy (store contents are a function of the requested-category set, not of camera history); tier-2 ships unpainted until a design pass; basemap stays pure display; interop = the shared `osm::` namespace; concurrent painted-category ceiling = 3 (the study's round-5 memory clause, applied to browse as `BROWSE_MAX` in T-92 — recorded here 2026-08-31 after T-92's implementer correctly flagged the citation as missing). + +| ID | Task | Owner | Status | Notes | +|---|---|---|---|---| +| T-60 | Tier-2 pipeline: 18 OSM categories via Overpass → `public/data/tier2/.geojson` (sorted, schema-compatible) + `tier2/index.json` manifest (category/count/bytes) | data-engineer | done | PR #44; 31,068 features, ~0.84MB gz | +| T-61 | Selection painting via feature-state (promoteId), retiring the `["in", …literal]` filter | map-ui-dev | done | PR #45; idle-to-idle flat in N, pixel-identical | +| T-62 | Category-lazy core: `loadCategory` in store; find/list/select category-required for tier-2 + disclosure of unsearched categories + counts-per-category from the manifest; select cap (refuse >500 with advice); gazetteer grows on load | tool-dev | done | PR #46; dual-tagged determinism mutation-proved | +| T-63 | Share manifest: hash wire v2 carries loaded-category list; recipient loads before resolving; prune-exemption for pending ids; loud failure | tool-dev | done | PR #48 wire v2 + #50 failure semantics (transient keeps categories declared; loaded clears failed); UI wiring PR #49 | +| T-64 | UI: disclosure strip + selected-POI materialization (membership-is-selection); tier-2 unpainted by default | map-ui-dev | done | PR #47 + share-hash wiring PR #49 | +| T-65 | e2e: determinism, lazy round-trip, share-manifest restore (money path PASS), select cap | qa | done | PR #51; 13 specs ×3 zero flake | +| T-66 | README: city-wide breadth + agent-FX sections; comparison footnotes | docs-writer | done | PR #54 | + +## Agent-presence FX — approved 2026-08-30 · shipped same day + +Three-round adversarial motion design (SHIP verdict; package in the design session workspace + repo `.claude` archive), then implementation. + +| ID | Task | Owner | Status | Notes | +|---|---|---|---|---| +| T-70 | FX tool contract: find/list origin echo (+radius_m), describe name echo, ActivityEntry.fx, RETRYABLE_4XX rider | tool-dev | done | PR #52; distances recompute from printed origins | +| T-71 | FX driver + 14 effects (reads=teal gaze, writes=materialize, human=rose; ≤2s, kill switch, reduced motion) | map-ui-dev | done | PR #53; zero residue 0/490k px reviewer-reproduced | +| T-72 | FX e2e: ON path, concurrency, kill, mount-replay guard, rm, human separation | qa | done | PR #55; MutationObserver over polling for sub-cadence windows | + +## The Awakening — approved 2026-08-30 · gate: human-first product that visibly wakes into agent mode + +Five-round adversarial design (SHIP verdict). Contract: `.claude/design-archive/redesign2/design2-v5.md` §8 (FINAL HANDOFF, file:line-verified) + `mockup2-v5.html` (reference, absolute path readable from worktrees). Owner signed off (2026-08-30): glow amendment; mixed-cluster=teal; caption-toast 3.2s dwell; su-less links keep teal beads with "from a shared link" hedged copy (su-on-every-link lever recorded, reversible); Chrome declarative-form exposure verified at implementation. Feed re-voicing supersedes the machine-voice rule; mono tool-name stays as the transparency spine. + +| ID | Task | Owner | Status | Notes | +|---|---|---|---|---| +| T-80 | Foundations: `selectionSources` store field; `su` share-wire key (ignorable, omitted-when-none) + `restoredAgentStateOf`; `src/lib/awaken/` module (mode machine, flag-first trigger, AWAKEN_MAX_MS=2000, T1–T11) | tool-dev | done | PR #60; su mirror trap closed (restore records su as user); replace:true re-attributes | +| T-81 | Bead marker system: sprites, provenance rims, cluster coalescing (~30px), browse ink budget (K=12, tier minimums), halo split | map-ui-dev | done | PR #61; found map.addLayer silently skips invalid layers — guard walks every spec | +| T-82 | Human-first IA: chrome flip, Places tray, OnTheMapCard (features+pins+drawings), liquid glass, boot-chrome no-flash probe, share su wiring | map-ui-dev | done | PR #62 (with qa's five-spec rider + the pin+card idle-note ruling) | +| T-83 | Awakening choreography (both tiers), restored surfaces, honest badge (Agent-readable until a live call) | map-ui-dev | done | PR #64; handover jumps 194/235/155px → 0.00 measured | +| T-84 | Feed re-voicing (11/11 templates tested; 'all' honestly gated) + riders | tool-dev | done | PR #63; the cafés-row decline recorded with corrected reasoning | +| T-85 | e2e: awakening contract end-to-end, bead/cluster live specs, suite hardening (browser-clock timing) | qa | done | PR #65 (+ the five-spec rider on #62, the flake fix #59); verdict: the contract holds | + +## UX feedback round — 2026-08-31 · owner feedback after the Awakening shipped + +Order reflects recommended sequence; all queued behind nothing — D5 assets (T-40..T-43) still own the deadline. T-90 is in flight (plan under adversarial review). + +| ID | Task | Owner | Status | Notes | +|---|---|---|---|---| +| T-90 | `remove_from_map` tool: agent-side removal of drawings, annotations and selection entries (prefix-dispatched ids; user-sourced marks refused per-id in `refused`; selection-first dispatch; closes the >20 partial-deselect gap and makes the share-link overflow advice actionable) | tool-dev → map-ui-dev (roster/FX/comments) → qa | done | PR #70 → develop 0f025c4 (fact-checked: liveMark dispatch, roster entry, README rows on tree). Mark-first resolution closed the reviewer's smuggled-selection lie; per-id refusals with hoisted reasons; dissolve FX with bounded ghost memory; v3-era advice fixtures pile 8 rings with 7+1 singular coverage | +| T-91 | Merge the bottom-left legend pill ("2,063 places") into the Places dock: one bottom surface, "On the map" (six painted, swatches, counts must still sum) + "More places" (18 loadable) | map-ui-dev | done | PR #68 → develop e87565b (fact-checked: MapKey in tree, Legend gone, CSS floor present); pill `Places · 2,063`, "Already here" key + "More places" grid, LoadedCategories bottom-left | +| T-92 | Multi-category browse: Places tray multi-select paints several POI categories at once (browse-store category → set; ink budget across categories; cap concurrent painted categories; tray active-chips UI) | map-ui-dev / qa | done | PR #71 → develop 7b8313b (fact-checked: BROWSE_MAX + rose cluster icon on tree). Ordered set ≤3, eviction reported by the store itself, teal blocker resolved to rose per the provenance grammar; §9 note: at city zoom nearly every counted bead is mixed — a popover split beats a third ink | +| T-93 | Manual agent-chrome toggle, design v2 (post-review): tri-state panel store overriding rendering (awaken machine and `played` untouched); open lives in the corner spark's card, close in the agent chrome; full close returns the lane to the map and MUST rework the corridor (`inspectorLane()` → driven by chrome visibility + recompute on toggle) so `get_map_state().bounds` never lies; pulse gated on calls>0; unseen count = activitySeq delta; no persistence across reload | map-ui-dev / qa | done | PR #72 → develop ba6baed (fact-checked: panel-store on tree, design doc in docs/design, corrected get_map_state description in). All four v1 failure modes closed with measured evidence; spark ring, FX lane and the doc's first-arrival exception fixed post-review; corridor ratios exact both directions | +| T-94 | `plan_route({from, to})`: walking route via FOSSGIS `routing.openstreetmap.de` foot profile (keyless, CORS `*`, verified 2026-08-31) → Turf-simplify to ≤500 points → drawing line with label; returns distance_m, duration_s, drawing id, state; 1 req/s throttle; honest error when the service is down; attribution + "fix the map" link per FOSSGIS policy; e2e stubs the service (suite stays network-isolated); README discloses the external dependency | tool-dev / qa / docs-writer | done | PR #73 → develop bd484ab (fact-checked: route module, ROUTE_MAX_WAIT_MS, CONTRIBUTING carve-out on tree). 13th tool; first and only runtime external dependency, engineered to the FOSSGIS policy | +| T-95 | Share wire v3: delta-encoded polyline coordinates (5-decimal, Google-polyline style) for drawings, so a 500-point route fits well under MAX_SHARE_URL_BYTES; v1/v2 links must keep decoding byte-for-byte (T-63 discipline); any simplification must obey the codec honesty contract (decoded map = sender's map, or say what was lost); raise-the-cap stays a last resort, not part of this task | tool-dev / qa | done | PR #69 → develop 73d2f7a (fact-checked: codec on tree, README v3 clause in). 500-pt route 12,453→3,341 bytes; v3 only when flat cannot fit; v1/v2 byte-frozen; reviewer verdict no blockers, S2 domain guard + S1 README clause shipped with it | + +## UI-parity round — 2026-08-31 · owner ruling: the UI is a first-class surface + +The point of this project is human-agent collaboration, not WebMCP alone. Law for this round: **whatever the agent can read through tools, the human can see on the page** — data parity between the two surfaces, in both directions. Recommended order: T-96 lays the card's details pattern; T-97's data work runs in parallel and lands on that pattern; T-98 is independent. + +| ID | Task | Owner | Status | Notes | +|---|---|---|---|---| +| T-96 | POI card/inspector details section: show the fields the data already carries — `cuisine`, `brand`, `opening_hours` — plus bilingual naming (local name primary, `nameEn` secondary when present) on the tap card and the inspector's selected rows. Establishes the details-section pattern T-97 extends | map-ui-dev → qa | done | PR #75 → develop (fact-checked: feature-details seam + measured card flip on tree). Card details + bilingual names; sidebar narrowing ratified; qa e2e rides the T-97 wave | +| T-97 | Data enrichment, reflected everywhere: (1) data-engineer extends the tier-1/tier-2 pipelines to keep addr (composed one-line), phone, website, wheelchair + category-specific fields (hotel stars, parking fee/capacity, pharmacy dispensing, worship religion, hospital emergency), re-runs them, measures the gz impact (Overpass sample 2026-08-31: addr 55-58%, phone 30%, wheelchair 26%); (2) tool-dev adds read-only `get_place_details(id)` — full fields for one feature, lists stay lean — plus roster/FX/e2e parity ripples; (3) map-ui-dev lands every new field in T-96's details section (opening_hours display treatment is the implementer's design call — raw OSM syntax needs taming); (4) qa e2e | data-engineer ∥ tool-dev → map-ui-dev → qa | done | PR #77 → develop 1636e64 (fact-checked: 14th tool, 31,069 enriched features, parity-law spec on tree). Address/phone/website/wheelchair + category facts on every surface; T-99's five poll sites rooted out; mockMinimalBasemap unlocks canvas-click e2e under isolation | +| T-98 | Search, both surfaces in one task: tool-dev gives `list_features_in_view` the same `query` parameter `find_features` has (view-scoped keyword search for agents — the two tools exist but cannot combine today); map-ui-dev adds the human search box (searches loaded features across name/nameEn/brand/cuisine, view-first ranking, result tap selects and flies; placement is the implementer's call within the human-first idle chrome); qa e2e for both | tool-dev ∥ map-ui-dev → qa | done | both halves shipped (PR #74 tool, PR #76 UI — fact-checked): agents search the view by name, humans search everything loaded with a box that never wakes the agent; search e2e rides the round's qa wrap-up | +| T-99 | qa hardening: the 2500ms `data-awaken` poll family | qa | done | all five poll sites fixed on the T-97 branch (waitForAwake in helpers, 280 repeat-runs green); ONE residual site ticketed below (awakening.spec.ts:672, a different shape — Node-side reads of the 1.8s disabled window) | + +## T-100 — search index · approved 2026-08-31 evening · gate: "starbucks" finds 152 stores on a fresh page + +Owner-reported defect: the search box only covers loaded features, so brand searches on a landing page find nothing and the empty-state hint expects the human to know which category to load. Fix: a citywide name index derived LOCALLY from the existing tier-2 files (no Overpass — F-5 avoided), fetched once on first search; index hits from unloaded categories render with a loads-on-pick affordance (the pick IS the deliberate load request — category-lazy law intact); find_features' disclosure names index hits in unloaded categories so the agent's next call is obvious (no auto-load). + +Index contract v2 (owner widened the goal 2026-08-31 evening: "almost ANY input finds something", not just brands): `public/data/tier2/search-index.json` = `{ "generated": "", "rows": [[id, name, nameEn|"", brand|"", cuisine|"", address|"", categories-comma-joined, lng5, lat5], ...] }`, tier-2 features only, sorted by id — address matching covers street/neighbourhood inputs (42.7%), cuisine covers "ramen"/"coffee"-style inputs. The UI additionally matches a curated bilingual CATEGORY vocabulary (18 categories × en/zh labels + common aliases: 咖啡→cafe, 藥局→pharmacy, 便利商店→convenience…) rendered as browse-this-kind rows, so category-word inputs always land. Fuzzy/typo matching is explicitly OUT of scope this round (substring over 33k names + addresses + the vocabulary is the "almost any input" bar; typo tolerance is its own project). Acceptance gate: a qa battery of arbitrary inputs (brands zh/en, cuisine words zh/en, street names, category words zh/en, bundled-data names) each produce ≥1 row on a FRESH page. Store contract: map-store + MapToolStore gain `getSearchIndex()`, `loadSearchIndex()` (one fetch via the tier2FetchJson injection path, cached, honest failure state). + +| ID | Task | Owner | Status | Notes | +|---|---|---|---|---| +| T-100 | Search index end to end: (1) pipeline emits the index (local derivation, size measured); (2) store loader + find_features disclosure extension; (3) search box consults index, loads-on-pick, then selects and flies; (4) qa: the starbucks path end to end | data-engineer → tool-dev → map-ui-dev → qa | done | PR #81 → develop c372da2 (fact-checked: index on tree, SearchBox on the plain loader). 12-input acceptance battery green; dual-track picks; unloaded_matches for agents; the restore-impersonation fix probed end to end | +| T-101 | Inspector rows become actionable (owner request): a Selected row zooms to its feature on click and carries a per-row deselect; Shapes/Notes rows zoom to their geometry on click (fitBounds for areas/lines, centre for pins), keeping their existing ✕; keyboard reachable; writers/provenance identical to the tap card's (human gestures, `"user"` attribution, human FX on removal) | map-ui-dev → qa | doing(qa) | implementation 433a2e1 (frame-model: corridor-derived zoomToFit, no DOM read; sibling-button hygiene; probes: district fit 80.0% of the binding axis, deselect preserves sources, activity untouched); RULING upheld: points never zoom out, area fits may widen — a district click that changes nothing is the failure the row exists to remove; done — PR #80 → develop 0cfee07 (fact-checked: frame-model + must-travel spec on tree). Widening ruling UPHELD as one rule branching on extent; review prescriptions landed (travel assertion, the third unsafe approximation named); handoffs: activity doc one-liner (tool-dev next baton), README collaboration bullet (F-4) | + +## T-102 — reverse-parity gaps · approved 2026-08-31 night · gate: the agent can do what the human can + +Owner: "A/B 都修". Gap A: the human box matches name/nameEn/brand/cuisine/address; the agent's query matches names only — widen the shared predicate on BOTH the loaded search and `unloaded_matches` together, which dissolves T-100's names-only asymmetry by making the promise and its fulfilment match again (the mutation tests that pinned names-only flip to pin all-five-on-both-sides). Gap B: `set_map_view` gains `fit` (a drawing or feature id) framed by the SAME math as T-101's rows — the pure frame/zoomToFit core relocates from src/components into src/lib (legal import direction) so agent and human literally share one function; point targets keep PLACE_ZOOM semantics, area targets may widen (the recorded one-rule-branching-on-extent). + +| ID | Task | Owner | Status | Notes | +|---|---|---|---|---| +| T-102 | Query parity (five-field matching, both sides of the disclosure) + camera fit-to-target for agents (frame math relocated to src/lib, components re-import) | tool-dev (waivered import flips) → map-ui-dev → qa → review | done | PR #84 → develop (fact-checked: src/lib/geo on tree, the zoom floor in). Five-field parity on every surface with one predicate; fit-vs-row byte-equal by e2e; the last silent zoom-out removed by ruling; ≥ floor proven un-overstatable | + +## T-103 — the load-window place-name race · approved 2026-09-01 · gate: a name is never answered out of a half-loaded gazetteer + +Found by adversarial review of T-41's fifth ask card. `resolveQueryInput` loads a named category **before** it resolves `near` (deliberate — it lets `{near:"Fika Fika Cafe", categories:["cafe"]}` find its own origin), while the six bundled datasets arrive asynchronously. In that window a place name matched the just-fetched category alone, and `post_office.geojson` holds exactly one substring match for "daan": `osm:way:206062024`, Taipei Da-an Post Office, 524 m from the real station. One match is not a tie, so `resolvePlaceOne` returned `found` — a confident wrong answer with no error and no candidates. Every spelling of the station collapsed onto it. Owner approved fixing the tool layer rather than rewording the card. + +| ID | Task | Owner | Status | Notes | +|---|---|---|---|---| +| 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 | diff --git a/docs/TASKS.md b/docs/TASKS.md index 88279f8..389bc79 100644 --- a/docs/TASKS.md +++ b/docs/TASKS.md @@ -27,138 +27,52 @@ Deadline: 2026-09-03 13:00 PDT. Must-have tools: `get_map_state`, `list_features | 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 | +| T-111 | README says who did what: a "Who did what" passage in "One map, two hands" — provenance on every mark, visible to both sides; every tool call on the activity feed with its outcome and the ids it touched (the last 50, errors included); an agent cannot remove a human's mark; a share link keeps provenance — plus one bullet each for the two new human gestures (T-106 note placement, T-110 route). Owner asked 2026-09-02 for the separation of agent and human trails to be stated; wording stays at "a legible record", never audit/verify/tamper-proof, because the feed is session-only and capped | docs-writer → review | done | Shipped after T-110 (#99) so the README never describes an unshipped gesture; also widened the two "only `plan_route` calls an external service" sentences to routing's two callers (T-110 review S1) and refreshed the test count | -## UI redesign — "Smoked Glass" · approved 2026-08-29 · gate: production matches the shipped mockup +## 2026-08-29 … 2026-09-02 · shipped rounds · all `done`; detail in [`docs/TASKS-archive.md`](./TASKS-archive.md) -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. +- **UI redesign — "Smoked Glass"** (T-50…T-54) · **Tier-2 OSM breadth** (T-60…T-66) · **Agent-presence FX** (T-70…T-72) · **The Awakening** (T-80…T-85) · **UX feedback round** (T-90…T-95) · **UI-parity round** (T-96…T-99). +- **T-100/T-101** search index + actionable inspector rows · **T-102** query and camera parity · **T-103** load-window place-name race · **T-104** the awakening no longer cancels an agent's flight. -| ID | Task | Owner | Status | Notes | -|---|---|---|---|---| -| T-50 | Activity feed data layer: record every tool call (tool, humanized summary, read/write, ok, ref ids, timestamp) into a store slice from the map-tools execute path; unit tests | tool-dev | done | PR #35 | -| T-51 | Smoked Glass chrome: brand bar, camera/Share chips, glass inspector, legend footer, Try-asking cards, breakpoint tiers incl. 769–920 sheet; WebMCP badge counts page-declared tools (11 imperative + declarative `add_note` = 12) per the handoff SHIP-GATE | map-ui-dev | done | PR #36; visual parity gate passed on independent production-build captures; bounds are the visible corridor | -| T-52 | `map-style.ts` calm ramp (z≤13 dot treatment) + selection halos per handoff | map-ui-dev | done | PR #36 | -| T-53 | Activity feed UI wired to the T-50 slice | map-ui-dev | done | PR #36; declarative add_note records agent-invoked submissions too | -| T-54 | e2e: suite green on the new chrome; share-link restore shows provenance labels on the receiving window (experience-case gate) | qa | done | PR #38 — provenance gate PASS; found the frozen-bounds defect, fixed as PR #39 (jump, don't fly, without a style) | - -## Tier-2 OSM breadth — approved 2026-08-30 · gate: category-addressed city-wide breadth, deterministic and shareable - -Outcome of the basemap-interop adversarial study (5 rounds; tile-reading refuted on licence/completeness/latency/actionability; the pipeline widened instead). Laws: **category filtering is the query model — no list-all tools**; category-lazy whole-city loading, NEVER bbox-lazy (store contents are a function of the requested-category set, not of camera history); tier-2 ships unpainted until a design pass; basemap stays pure display; interop = the shared `osm::` namespace; concurrent painted-category ceiling = 3 (the study's round-5 memory clause, applied to browse as `BROWSE_MAX` in T-92 — recorded here 2026-08-31 after T-92's implementer correctly flagged the citation as missing). - -| ID | Task | Owner | Status | Notes | -|---|---|---|---|---| -| T-60 | Tier-2 pipeline: 18 OSM categories via Overpass → `public/data/tier2/.geojson` (sorted, schema-compatible) + `tier2/index.json` manifest (category/count/bytes) | data-engineer | done | PR #44; 31,068 features, ~0.84MB gz | -| T-61 | Selection painting via feature-state (promoteId), retiring the `["in", …literal]` filter | map-ui-dev | done | PR #45; idle-to-idle flat in N, pixel-identical | -| T-62 | Category-lazy core: `loadCategory` in store; find/list/select category-required for tier-2 + disclosure of unsearched categories + counts-per-category from the manifest; select cap (refuse >500 with advice); gazetteer grows on load | tool-dev | done | PR #46; dual-tagged determinism mutation-proved | -| T-63 | Share manifest: hash wire v2 carries loaded-category list; recipient loads before resolving; prune-exemption for pending ids; loud failure | tool-dev | done | PR #48 wire v2 + #50 failure semantics (transient keeps categories declared; loaded clears failed); UI wiring PR #49 | -| T-64 | UI: disclosure strip + selected-POI materialization (membership-is-selection); tier-2 unpainted by default | map-ui-dev | done | PR #47 + share-hash wiring PR #49 | -| T-65 | e2e: determinism, lazy round-trip, share-manifest restore (money path PASS), select cap | qa | done | PR #51; 13 specs ×3 zero flake | -| T-66 | README: city-wide breadth + agent-FX sections; comparison footnotes | docs-writer | done | PR #54 | - -## Agent-presence FX — approved 2026-08-30 · shipped same day - -Three-round adversarial motion design (SHIP verdict; package in the design session workspace + repo `.claude` archive), then implementation. - -| ID | Task | Owner | Status | Notes | -|---|---|---|---|---| -| T-70 | FX tool contract: find/list origin echo (+radius_m), describe name echo, ActivityEntry.fx, RETRYABLE_4XX rider | tool-dev | done | PR #52; distances recompute from printed origins | -| T-71 | FX driver + 14 effects (reads=teal gaze, writes=materialize, human=rose; ≤2s, kill switch, reduced motion) | map-ui-dev | done | PR #53; zero residue 0/490k px reviewer-reproduced | -| T-72 | FX e2e: ON path, concurrency, kill, mount-replay guard, rm, human separation | qa | done | PR #55; MutationObserver over polling for sub-cadence windows | - -## The Awakening — approved 2026-08-30 · gate: human-first product that visibly wakes into agent mode - -Five-round adversarial design (SHIP verdict). Contract: `.claude/design-archive/redesign2/design2-v5.md` §8 (FINAL HANDOFF, file:line-verified) + `mockup2-v5.html` (reference, absolute path readable from worktrees). Owner signed off (2026-08-30): glow amendment; mixed-cluster=teal; caption-toast 3.2s dwell; su-less links keep teal beads with "from a shared link" hedged copy (su-on-every-link lever recorded, reversible); Chrome declarative-form exposure verified at implementation. Feed re-voicing supersedes the machine-voice rule; mono tool-name stays as the transparency spine. - -| ID | Task | Owner | Status | Notes | -|---|---|---|---|---| -| T-80 | Foundations: `selectionSources` store field; `su` share-wire key (ignorable, omitted-when-none) + `restoredAgentStateOf`; `src/lib/awaken/` module (mode machine, flag-first trigger, AWAKEN_MAX_MS=2000, T1–T11) | tool-dev | done | PR #60; su mirror trap closed (restore records su as user); replace:true re-attributes | -| T-81 | Bead marker system: sprites, provenance rims, cluster coalescing (~30px), browse ink budget (K=12, tier minimums), halo split | map-ui-dev | done | PR #61; found map.addLayer silently skips invalid layers — guard walks every spec | -| T-82 | Human-first IA: chrome flip, Places tray, OnTheMapCard (features+pins+drawings), liquid glass, boot-chrome no-flash probe, share su wiring | map-ui-dev | done | PR #62 (with qa's five-spec rider + the pin+card idle-note ruling) | -| T-83 | Awakening choreography (both tiers), restored surfaces, honest badge (Agent-readable until a live call) | map-ui-dev | done | PR #64; handover jumps 194/235/155px → 0.00 measured | -| T-84 | Feed re-voicing (11/11 templates tested; 'all' honestly gated) + riders | tool-dev | done | PR #63; the cafés-row decline recorded with corrected reasoning | -| T-85 | e2e: awakening contract end-to-end, bead/cluster live specs, suite hardening (browser-clock timing) | qa | done | PR #65 (+ the five-spec rider on #62, the flake fix #59); verdict: the contract holds | - -## UX feedback round — 2026-08-31 · owner feedback after the Awakening shipped - -Order reflects recommended sequence; all queued behind nothing — D5 assets (T-40..T-43) still own the deadline. T-90 is in flight (plan under adversarial review). - -| ID | Task | Owner | Status | Notes | -|---|---|---|---|---| -| T-90 | `remove_from_map` tool: agent-side removal of drawings, annotations and selection entries (prefix-dispatched ids; user-sourced marks refused per-id in `refused`; selection-first dispatch; closes the >20 partial-deselect gap and makes the share-link overflow advice actionable) | tool-dev → map-ui-dev (roster/FX/comments) → qa | done | PR #70 → develop 0f025c4 (fact-checked: liveMark dispatch, roster entry, README rows on tree). Mark-first resolution closed the reviewer's smuggled-selection lie; per-id refusals with hoisted reasons; dissolve FX with bounded ghost memory; v3-era advice fixtures pile 8 rings with 7+1 singular coverage | -| T-91 | Merge the bottom-left legend pill ("2,063 places") into the Places dock: one bottom surface, "On the map" (six painted, swatches, counts must still sum) + "More places" (18 loadable) | map-ui-dev | done | PR #68 → develop e87565b (fact-checked: MapKey in tree, Legend gone, CSS floor present); pill `Places · 2,063`, "Already here" key + "More places" grid, LoadedCategories bottom-left | -| T-92 | Multi-category browse: Places tray multi-select paints several POI categories at once (browse-store category → set; ink budget across categories; cap concurrent painted categories; tray active-chips UI) | map-ui-dev / qa | done | PR #71 → develop 7b8313b (fact-checked: BROWSE_MAX + rose cluster icon on tree). Ordered set ≤3, eviction reported by the store itself, teal blocker resolved to rose per the provenance grammar; §9 note: at city zoom nearly every counted bead is mixed — a popover split beats a third ink | -| T-93 | Manual agent-chrome toggle, design v2 (post-review): tri-state panel store overriding rendering (awaken machine and `played` untouched); open lives in the corner spark's card, close in the agent chrome; full close returns the lane to the map and MUST rework the corridor (`inspectorLane()` → driven by chrome visibility + recompute on toggle) so `get_map_state().bounds` never lies; pulse gated on calls>0; unseen count = activitySeq delta; no persistence across reload | map-ui-dev / qa | done | PR #72 → develop ba6baed (fact-checked: panel-store on tree, design doc in docs/design, corrected get_map_state description in). All four v1 failure modes closed with measured evidence; spark ring, FX lane and the doc's first-arrival exception fixed post-review; corridor ratios exact both directions | -| T-94 | `plan_route({from, to})`: walking route via FOSSGIS `routing.openstreetmap.de` foot profile (keyless, CORS `*`, verified 2026-08-31) → Turf-simplify to ≤500 points → drawing line with label; returns distance_m, duration_s, drawing id, state; 1 req/s throttle; honest error when the service is down; attribution + "fix the map" link per FOSSGIS policy; e2e stubs the service (suite stays network-isolated); README discloses the external dependency | tool-dev / qa / docs-writer | done | PR #73 → develop bd484ab (fact-checked: route module, ROUTE_MAX_WAIT_MS, CONTRIBUTING carve-out on tree). 13th tool; first and only runtime external dependency, engineered to the FOSSGIS policy | -| T-95 | Share wire v3: delta-encoded polyline coordinates (5-decimal, Google-polyline style) for drawings, so a 500-point route fits well under MAX_SHARE_URL_BYTES; v1/v2 links must keep decoding byte-for-byte (T-63 discipline); any simplification must obey the codec honesty contract (decoded map = sender's map, or say what was lost); raise-the-cap stays a last resort, not part of this task | tool-dev / qa | done | PR #69 → develop 73d2f7a (fact-checked: codec on tree, README v3 clause in). 500-pt route 12,453→3,341 bytes; v3 only when flat cannot fit; v1/v2 byte-frozen; reviewer verdict no blockers, S2 domain guard + S1 README clause shipped with it | - -## UI-parity round — 2026-08-31 · owner ruling: the UI is a first-class surface - -The point of this project is human-agent collaboration, not WebMCP alone. Law for this round: **whatever the agent can read through tools, the human can see on the page** — data parity between the two surfaces, in both directions. Recommended order: T-96 lays the card's details pattern; T-97's data work runs in parallel and lands on that pattern; T-98 is independent. - -| ID | Task | Owner | Status | Notes | -|---|---|---|---|---| -| T-96 | POI card/inspector details section: show the fields the data already carries — `cuisine`, `brand`, `opening_hours` — plus bilingual naming (local name primary, `nameEn` secondary when present) on the tap card and the inspector's selected rows. Establishes the details-section pattern T-97 extends | map-ui-dev → qa | done | PR #75 → develop (fact-checked: feature-details seam + measured card flip on tree). Card details + bilingual names; sidebar narrowing ratified; qa e2e rides the T-97 wave | -| T-97 | Data enrichment, reflected everywhere: (1) data-engineer extends the tier-1/tier-2 pipelines to keep addr (composed one-line), phone, website, wheelchair + category-specific fields (hotel stars, parking fee/capacity, pharmacy dispensing, worship religion, hospital emergency), re-runs them, measures the gz impact (Overpass sample 2026-08-31: addr 55-58%, phone 30%, wheelchair 26%); (2) tool-dev adds read-only `get_place_details(id)` — full fields for one feature, lists stay lean — plus roster/FX/e2e parity ripples; (3) map-ui-dev lands every new field in T-96's details section (opening_hours display treatment is the implementer's design call — raw OSM syntax needs taming); (4) qa e2e | data-engineer ∥ tool-dev → map-ui-dev → qa | done | PR #77 → develop 1636e64 (fact-checked: 14th tool, 31,069 enriched features, parity-law spec on tree). Address/phone/website/wheelchair + category facts on every surface; T-99's five poll sites rooted out; mockMinimalBasemap unlocks canvas-click e2e under isolation | -| T-98 | Search, both surfaces in one task: tool-dev gives `list_features_in_view` the same `query` parameter `find_features` has (view-scoped keyword search for agents — the two tools exist but cannot combine today); map-ui-dev adds the human search box (searches loaded features across name/nameEn/brand/cuisine, view-first ranking, result tap selects and flies; placement is the implementer's call within the human-first idle chrome); qa e2e for both | tool-dev ∥ map-ui-dev → qa | done | both halves shipped (PR #74 tool, PR #76 UI — fact-checked): agents search the view by name, humans search everything loaded with a box that never wakes the agent; search e2e rides the round's qa wrap-up | -| T-99 | qa hardening: the 2500ms `data-awaken` poll family | qa | done | all five poll sites fixed on the T-97 branch (waitForAwake in helpers, 280 repeat-runs green); ONE residual site ticketed below (awakening.spec.ts:672, a different shape — Node-side reads of the 1.8s disabled window) | - -## T-100 — search index · approved 2026-08-31 evening · gate: "starbucks" finds 152 stores on a fresh page - -Owner-reported defect: the search box only covers loaded features, so brand searches on a landing page find nothing and the empty-state hint expects the human to know which category to load. Fix: a citywide name index derived LOCALLY from the existing tier-2 files (no Overpass — F-5 avoided), fetched once on first search; index hits from unloaded categories render with a loads-on-pick affordance (the pick IS the deliberate load request — category-lazy law intact); find_features' disclosure names index hits in unloaded categories so the agent's next call is obvious (no auto-load). - -Index contract v2 (owner widened the goal 2026-08-31 evening: "almost ANY input finds something", not just brands): `public/data/tier2/search-index.json` = `{ "generated": "", "rows": [[id, name, nameEn|"", brand|"", cuisine|"", address|"", categories-comma-joined, lng5, lat5], ...] }`, tier-2 features only, sorted by id — address matching covers street/neighbourhood inputs (42.7%), cuisine covers "ramen"/"coffee"-style inputs. The UI additionally matches a curated bilingual CATEGORY vocabulary (18 categories × en/zh labels + common aliases: 咖啡→cafe, 藥局→pharmacy, 便利商店→convenience…) rendered as browse-this-kind rows, so category-word inputs always land. Fuzzy/typo matching is explicitly OUT of scope this round (substring over 33k names + addresses + the vocabulary is the "almost any input" bar; typo tolerance is its own project). Acceptance gate: a qa battery of arbitrary inputs (brands zh/en, cuisine words zh/en, street names, category words zh/en, bundled-data names) each produce ≥1 row on a FRESH page. Store contract: map-store + MapToolStore gain `getSearchIndex()`, `loadSearchIndex()` (one fetch via the tier2FetchJson injection path, cached, honest failure state). - -| ID | Task | Owner | Status | Notes | -|---|---|---|---|---| -| T-100 | Search index end to end: (1) pipeline emits the index (local derivation, size measured); (2) store loader + find_features disclosure extension; (3) search box consults index, loads-on-pick, then selects and flies; (4) qa: the starbucks path end to end | data-engineer → tool-dev → map-ui-dev → qa | done | PR #81 → develop c372da2 (fact-checked: index on tree, SearchBox on the plain loader). 12-input acceptance battery green; dual-track picks; unloaded_matches for agents; the restore-impersonation fix probed end to end | -| T-101 | Inspector rows become actionable (owner request): a Selected row zooms to its feature on click and carries a per-row deselect; Shapes/Notes rows zoom to their geometry on click (fitBounds for areas/lines, centre for pins), keeping their existing ✕; keyboard reachable; writers/provenance identical to the tap card's (human gestures, `"user"` attribution, human FX on removal) | map-ui-dev → qa | doing(qa) | implementation 433a2e1 (frame-model: corridor-derived zoomToFit, no DOM read; sibling-button hygiene; probes: district fit 80.0% of the binding axis, deselect preserves sources, activity untouched); RULING upheld: points never zoom out, area fits may widen — a district click that changes nothing is the failure the row exists to remove; done — PR #80 → develop 0cfee07 (fact-checked: frame-model + must-travel spec on tree). Widening ruling UPHELD as one rule branching on extent; review prescriptions landed (travel assertion, the third unsafe approximation named); handoffs: activity doc one-liner (tool-dev next baton), README collaboration bullet (F-4) | - -## T-102 — reverse-parity gaps · approved 2026-08-31 night · gate: the agent can do what the human can - -Owner: "A/B 都修". Gap A: the human box matches name/nameEn/brand/cuisine/address; the agent's query matches names only — widen the shared predicate on BOTH the loaded search and `unloaded_matches` together, which dissolves T-100's names-only asymmetry by making the promise and its fulfilment match again (the mutation tests that pinned names-only flip to pin all-five-on-both-sides). Gap B: `set_map_view` gains `fit` (a drawing or feature id) framed by the SAME math as T-101's rows — the pure frame/zoomToFit core relocates from src/components into src/lib (legal import direction) so agent and human literally share one function; point targets keep PLACE_ZOOM semantics, area targets may widen (the recorded one-rule-branching-on-extent). - -| ID | Task | Owner | Status | Notes | -|---|---|---|---|---| -| T-102 | Query parity (five-field matching, both sides of the disclosure) + camera fit-to-target for agents (frame math relocated to src/lib, components re-import) | tool-dev (waivered import flips) → map-ui-dev → qa → review | done | PR #84 → develop (fact-checked: src/lib/geo on tree, the zoom floor in). Five-field parity on every surface with one predicate; fit-vs-row byte-equal by e2e; the last silent zoom-out removed by ruling; ≥ floor proven un-overstatable | - -## T-103 — the load-window place-name race · approved 2026-09-01 · gate: a name is never answered out of a half-loaded gazetteer +## T-106 — a human pins a note where they click · owner request 2026-09-02 · gate: a person's note lands under their cursor, an agent's exactly where it landed before -Found by adversarial review of T-41's fifth ask card. `resolveQueryInput` loads a named category **before** it resolves `near` (deliberate — it lets `{near:"Fika Fika Cafe", categories:["cafe"]}` find its own origin), while the six bundled datasets arrive asynchronously. In that window a place name matched the just-fetched category alone, and `post_office.geojson` holds exactly one substring match for "daan": `osm:way:206062024`, Taipei Da-an Post Office, 524 m from the real station. One match is not a tie, so `resolvePlaceOne` returned `found` — a confident wrong answer with no error and no candidates. Every spelling of the station collapsed onto it. Owner approved fixing the tool layer rather than rewording the card. +Owner: the Note pill is unfriendly to a person — the form pins only at the map centre, so placing a note means panning the whole map until the spot is under the crosshair. Human side only: the declarative `add_note` tool (its `toolname`, `tooldescription`, `toolparamdescription`, and an agent-invoked submit landing at `view.center`) does not change, and neither does the imperative `annotate`. | ID | Task | Owner | Status | Notes | |---|---|---|---|---| -| 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-106 | While the Note popover is open and draw mode is off, a map click places a provisional rose pin at the cursor (a second click moves it); the human's submit pins there, falling back to the map centre when nothing was clicked; closing the popover or submitting clears the draft. Draft location lives in a UI store next to `draw-store.ts`, never in `map-store.ts`, so no tool can see it. An `agentInvoked` submit ignores the draft and pins at `view.center` exactly as today | map-ui-dev → review → qa | done | Feature taps are suppressed while the popover is open, as in draw mode; draw mode keeps precedence; `Escape` leaves note mode. Review caught an agent `add_note` wiping the human's half-placed draft — an agent submit now neither reads nor spends it. e2e `note-human-gestures.spec.ts` pins the whole contract incl. the agent-at-centre invariant | -## 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 +## T-107 — a folded note can be unfolded · owner report 2026-09-02 · gate: no gesture on a note leaves it unreadable with no way back -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. +Owner: "a note disappears when clicked, and there is no way to bring it back." Root cause in `annotation-marker.ts`: a click on the bubble toggles `.pin-card.hidden` (`display: none`), and a click on what remains — a 9 px anchor and a 1.5 px stem — opens the "On the map" card rather than unfolding the bubble. The fold is one-way in practice. | 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 | +| T-107 | A click on a folded pin unfolds it (and does nothing else); a click on the bubble folds it as before; a click on the stem/anchor of an unfolded pin opens the "On the map" card as before. A folded pin must stay visibly clickable — keep a compact chip (the source dot with the note's first word or an ellipsis) rather than a bare anchor, so the way back is on screen. Same PR as T-106 | map-ui-dev → review → qa | done | Agent-facing behaviour unchanged: annotations, ids, `annotate`/`add_note`/`remove_from_map` untouched. Fold state lives only in the pin's DOM (`data-folded`), never in `map-store` or the share hash | -## T-106 — a human pins a note where they click · owner request 2026-09-02 · gate: a person's note lands under their cursor, an agent's exactly where it landed before +## T-108 — the "On the map" card shows the whole note · owner report 2026-09-02 · gate: a person can read every character of a note somewhere on the map, whatever state the pin is in -Owner: the Note pill is unfriendly to a person — the form pins only at the map centre, so placing a note means panning the whole map until the spot is under the crosshair. Human side only: the declarative `add_note` tool (its `toolname`, `tooldescription`, `toolparamdescription`, and an agent-invoked submit landing at `view.center`) does not change, and neither does the imperative `annotate`. +Owner: after folding a pin and reopening it, a long note is cut to "…" and there is no way to read the rest. Root cause in `card-model.ts:220`: the card's headline is `truncate(annotation.note, CARD_NOTE_CHARS)` with `CARD_NOTE_CHARS = 72`, while a note may be `MAX_NOTE_CHARS` (500; the human form's own input caps at 200) long; the card has no other line that carries the note, and with the bubble folded (T-107) the text was on screen nowhere. | ID | Task | Owner | Status | Notes | |---|---|---|---|---| -| T-106 | While the Note popover is open and draw mode is off, a map click places a provisional rose pin at the cursor (a second click moves it); the human's submit pins there, falling back to the map centre when nothing was clicked; closing the popover or submitting clears the draft. Draft location lives in a UI store next to `draw-store.ts`, never in `map-store.ts`, so no tool can see it. An `agentInvoked` submit ignores the draft and pins at `view.center` exactly as today | map-ui-dev → qa → review | doing | Feature taps are suppressed while the popover is open, as in draw mode; draw mode keeps precedence over note placement | +| T-108 | The card for a note shows the full note text, wrapped (`pre-wrap`, `overflow-wrap: anywhere`), instead of a 72-character headline; `CARD_NOTE_CHARS` and the "clips a long note" unit test are replaced by a test that pins the whole-note intent. Card placement already re-measures through `ResizeObserver`, so a taller card still flips above/below correctly. Same PR as T-106/T-107 | map-ui-dev → review → qa | done | Feature and drawing headlines unchanged. Review found the un-capped card: `"a\n".repeat(250)` grew it off the top of a phone viewport, so the note block is capped at `25vh` and scrolls (40vh measured and rejected — `cardPlacement` can only guarantee a side that fits while the card is under half the viewport) | -## T-107 — a folded note can be unfolded · owner report 2026-09-02 · gate: no gesture on a note leaves it unreadable with no way back +## T-109 — the loaded-categories strip ran under the Places dock · owner report 2026-09-02 · gate: nothing in the bottom band covers anything else, at any width, with any number of categories loaded -Owner: "a note disappears when clicked, and there is no way to bring it back." Root cause in `annotation-marker.ts`: a click on the bubble toggles `.pin-card.hidden` (`display: none`), and a click on what remains — a 9 px anchor and a 1.5 px stem — opens the "On the map" card rather than unfolding the bubble. The fold is one-way in practice. +Owner: "with many categories loaded the strip grows from the bottom-left and overlaps the Places dock." Measured: 22 of 40 (width × chips × chrome) cases overlapped, up to 720 × 43 px. Root cause: `.poi-strip` wraps and grows right; `.dock` is absolutely centred and out of flow; nothing bounds the strip's right edge against the dock's left. Found while measuring: with three categories browsed the two-row dock **covered the OpenStreetMap attribution** at 641–1240 px (up to 87 px) — a licence condition. | ID | Task | Owner | Status | Notes | |---|---|---|---|---| -| T-107 | A click on a folded pin unfolds it (and does nothing else); a click on the bubble folds it as before; a click on the stem/anchor of an unfolded pin opens the "On the map" card as before. A folded pin must stay visibly clickable — keep a compact chip (the source dot with the note's first word or an ellipsis) rather than a bare anchor, so the way back is on screen. Same PR as T-106 | map-ui-dev → qa → review | doing | Agent-facing behaviour unchanged: annotations, ids, `annotate`/`add_note`/`remove_from_map` untouched | +| T-109 | The dock publishes its own box as `--dock-w` / `--dock-h` (one `ResizeObserver`, no React state); above 640 px `.poi-strip` and `.corner` cap at `(100% − var(--dock-w)) / 2 − 16px`, and while a category is browsed (`.dock-actives`) the whole bottom bar lifts above the dock (`bottom: calc(var(--dock-h) + 28px)`) so the attribution is never covered. Correct by construction because the dock is centred on the bar in both chromes | map-ui-dev → review → qa | done | Alternatives weighed and rejected in the PR: a summary chip past N, a static max-width (no constant works — the agent lane moves the gutter), one flex row (touches the tray anchor, landing hint and four media queries). Review: merge after fixes (stale comment, duplicate `.badge` rule, `usePublishedBox` contract) — applied. Layout is not measurable in the node vitest environment, so the gate is e2e: `bottom-band.spec.ts` sweeps 18 cells (921/1024/1440 × human/agent chrome × none/3 browsed/15 loaded) with `boundingBox()` intersections and `elementFromPoint` on every attribution link; 13/18 red on develop, 54/54 green on the fix (`--repeat-each=3`). ≤640 px stays F-14 | -## T-108 — the "On the map" card shows the whole note · owner report 2026-09-02 · gate: a person can read every character of a note somewhere on the map, whatever state the pin is in +## T-110 — a person plans a walking route by clicking two points · owner approved 2026-09-02 · gate: the human can do what `plan_route` does, and the agent's tool is untouched -Owner: after folding a pin and reopening it, a long note is cut to "…" and there is no way to read the rest. Root cause in `card-model.ts:220`: the card's headline is `truncate(annotation.note, CARD_NOTE_CHARS)` with `CARD_NOTE_CHARS = 72`, while a note may be `MAX_NOTE_CHARS` (200) long; the card has no other line that carries the note, and with the bubble folded (T-107) the text was on screen nowhere. +Owner asked how a human uses routing; the answer was "only through an agent". Parity gap of the T-102 kind, the other way round. | ID | Task | Owner | Status | Notes | |---|---|---|---|---| -| T-108 | The card for a note shows the full note text, wrapped (`pre-wrap`, `overflow-wrap: anywhere`), instead of a 72-character headline; `CARD_NOTE_CHARS` and the "clips a long note" unit test are replaced by a test that pins the whole-note intent. Card placement already re-measures through `ResizeObserver`, so a taller card still flips above/below correctly. Same PR as T-106/T-107 | map-ui-dev → qa → review | doing | Feature and drawing headlines unchanged | +| 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) @@ -174,6 +88,11 @@ Owner: after folding a pin and reopening it, a long note is cut to "…" and the - **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. +- **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).~~ Fixed 2026-09-02, rides the T-109 PR: the spec captures the raw bounds tuple before the resize and `waitForFunction`s until it changes (bounded 1,500 ms, no sleep); 48/48 with `--repeat-each=12`. +- **F-17 (map-ui-dev)** With the inspector open at 1350 px, the *open* Places tray's bottom-right corner overlaps the OpenFreeMap attribution pill by ~7 CSS px (tray bottom 835 vs attribution top 828). The tray is anchored above the dock and the attribution to the map's right edge; T-109's caps and lift only govern the closed bar, not the tray panel. Cosmetic; the links stay clickable. Found capturing Devpost media 2026-09-02. ## Handoff log @@ -198,4 +117,8 @@ 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-02 · qa → all (lesson) · Any real tool call wakes the page into agent chrome, so a human-chrome e2e cell must reach its content state by hand: `bottom-band.spec.ts` loads 15 categories by tapping chips in the Places tray (a 4th tap evicts the oldest *painted* chip but never unloads it) and un-paints with the chips' `×`. Also: `page.waitForFunction(fn, arg, options)` — the timeout goes in the third argument; in the second it is silently the page function's argument and the wait falls back to the test timeout. - 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/awakening-flight.spec.ts b/e2e/awakening-flight.spec.ts index 85ac387..2e0d1b7 100644 --- a/e2e/awakening-flight.spec.ts +++ b/e2e/awakening-flight.spec.ts @@ -273,17 +273,37 @@ test.describe("the Awakening does not cancel the first flight (T-104)", () => { // changes (944px corridor -> 1104px), isolating this from a lane-width // change. await page.waitForTimeout(300); + // Captured raw (unrounded) so the poll below can compare tuple to tuple -- + // `beforeResize.bounds` is the tool's own *rounded* echo, and comparing a + // raw live value against a rounded one would nearly always read as + // "changed" even when nothing has, defeating the wait. + const rawBoundsBeforeResize = await page.evaluate(() => window.__glassmapStore!.getState().bounds); 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. + // nowhere near done at 300ms in. `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. + // + // `page.setViewportSize` resolves once the emulated viewport itself has + // been resized, not once the window's own "resize" event -- and + // `onResize`'s listener with it -- has actually run; that dispatch is + // asynchronous relative to the CDP call, so reading `bounds` immediately + // after raced it and occasionally won, seeing the PRE-resize bounds + // (observed ~4/24 CI runs). Poll the live store directly instead of + // reading once: bounded well under the flight's own remaining ease, so a + // build whose flight simply lands before the resize handler ever runs + // cannot make this pass for the wrong reason. + await page.waitForFunction( + (previous) => { + const bounds = window.__glassmapStore?.getState().bounds; + return !!bounds && JSON.stringify(bounds) !== JSON.stringify(previous); + }, + rawBoundsBeforeResize, + { timeout: 1500 }, + ); + const midResize = await callTool(page, "get_map_state"); expect(midResize.error).toBeUndefined(); expect(midResize.bounds).not.toEqual(beforeResize.bounds); diff --git a/e2e/bottom-band.spec.ts b/e2e/bottom-band.spec.ts new file mode 100644 index 0000000..0ef7f48 --- /dev/null +++ b/e2e/bottom-band.spec.ts @@ -0,0 +1,271 @@ +/** + * T-109 -- the gate `docs/TASKS.md` states for the bottom band: "nothing in + * the bottom band covers anything else, at any width, with any number of + * categories loaded." + * + * Three fix commits earn this file (`fix/ui-poi-strip-dock-overlap`): + * - `stop the loaded-POI strip before the Places dock` -- the strip + * (`LoadedCategories.tsx`, `poi-loaded`) now stops in the gutter beside the + * dock instead of running under it. + * - `the attribution stays clear of the dock` -- three browsed chips make + * the dock wide enough to cover the licence attribution, the WebMCP badge + * and the corner whisper; the bottom bar now lifts a row above the dock + * the moment a browsed chip lands on it (`.dock-actives`). + * - `review follow-ups for the dock caps` -- tier-boundary and naming fixes + * to the same mechanism. + * + * The mechanism (`usePublishedBox.ts`, `PlacesTray.tsx`): the dock publishes + * its own border-box as `--dock-w`/`--dock-h` custom properties on + * `document.documentElement` via a `ResizeObserver`, and every other bottom- + * band surface's CSS reads them back (`.poi-strip`'s `max-width`, `.corner`'s + * `max-width`, `.bottom-bar`'s lifted `bottom`). This file never re-derives + * that arithmetic -- it only measures the DOM's own boxes and asserts they do + * not intersect, which is the one thing a CSS change could get wrong that a + * unit test of the arithmetic could not see. + * + * ## Reaching "many categories loaded, none painted" without an agent + * + * `find_features` is a real WebMCP tool call, and *every* real call wakes the + * page (`lib/awaken`; see `chrome-toggle.spec.ts`'s own note on this) -- + * calling it to load categories would contaminate every "human chrome" cell + * of the matrix below with an agent that was never supposed to be there. + * Loading is reached by hand instead, the way a person really would: tapping + * a category chip in the Places tray loads its file and paints it + * (`browse-store.ts`), and a fourth tap evicts the oldest *painted* one + * without ever unloading it (`multi-category browse: eviction`, + * `multi-browse.spec.ts`) -- so tapping fifteen chips in a row loads all + * fifteen while painting only the last three, and removing those three with + * their own `x` (`places-clear`, which only un-paints, never unloads) leaves + * exactly "fifteen loaded, zero painted, zero tool calls" -- the strip's own + * worst case, reached the same way a human reaches it. + * + * ## Settling + * + * `--dock-w`/`--dock-h` are written by a `ResizeObserver` callback, not + * synchronously with the DOM change that resizes the dock -- `waitForDock + * Published` polls both back against the dock's own measured box (rounded up + * the same way `usePublishedBox.ts` rounds) instead of sleeping. It is a + * *bounded* poll, deliberately: this file is also run once against the + * pre-fix build (which never publishes either property at all) to confirm the + * regression, and a wait for a signal that build will never send must not + * hang the whole matrix -- it degrades to "whatever the DOM actually settled + * to" instead, which is exactly what the overlap assertions need to fail + * honestly on that build. + * + * ## What is deliberately out of scope + * + * No phone-tier (390px) case: F-14 is a known, separate overflow there. No + * width below 921px: that is the sheet-inspector tier (`@media + * (max-width:920px)`), a different layout question from the lane-inspector + * one this file is about. The matrix is 3 widths x 2 chromes x 3 content + * states = 18 cases, chosen to span the fix's own documented worst points + * (921 is where the corner's licence line starts wrapping in agent chrome; + * 1024 and 1440 are representative mid/wide lane-tier widths) without + * re-running every width the manual verification in the fix commits covered. + */ +import type { Locator, Page } from "@playwright/test"; +import { TIER2_CATEGORIES } from "@/lib/store/tier2"; +import { callTool } from "./mcp"; +import { expect, test } from "./fixtures"; +import { waitForAwake, waitForFeatures, waitForTools } from "./helpers"; + +const WIDTHS = [921, 1024, 1440] as const; +const CHROMES = ["human", "agent"] as const; +const CONTENT_STATES = ["none", "browsed3", "loaded15"] as const; + +/** Three real tier-2 categories, the same ones `multi-browse.spec.ts` picks. */ +const BROWSE_PICKS = ["cafe", "bar", "bakery"] as const; + +/** 15 of the 18 tier-2 categories -- enough to stress the strip's width the + * same way the fix commits' own manual verification did ("fifteen loaded + * categories"), leaving 3 unloaded (irrelevant: nothing here asserts on the + * total roster). */ +const STRIP_CATEGORIES = TIER2_CATEGORIES.slice(0, 15); + +interface Box { + x: number; + y: number; + width: number; + height: number; +} + +function overlaps(a: Box, b: Box): boolean { + // 0px of overlap is allowed (touching edges): strict inequalities only. + return a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height; +} + +async function boxOf(locator: Locator): Promise { + const box = await locator.boundingBox(); + if (!box) throw new Error("expected element to have a box"); + return box; +} + +function chip(page: Page, category: string): Locator { + return page.locator(`[data-testid="place-chip"][data-category="${category}"]`); +} + +/** Taps a category chip and waits for its own fetch to land, the same + * `pick` idiom `multi-browse.spec.ts` uses. */ +async function pickCategory(page: Page, category: string): Promise { + await chip(page, category).click(); + await expect(chip(page, category)).not.toHaveAttribute("data-loading", "true"); +} + +/** Un-paints whatever is currently on the dock's `places-active` row, one `x` + * per chip -- `remove()` (browse-store.ts) only un-paints; it never unloads, + * so this is how "loaded, not painted" is reached for categories that were + * necessarily painted for a moment while they were the newest of three. */ +async function clearAllPainted(page: Page): Promise { + const active = page.getByTestId("places-active"); + if ((await active.count()) === 0) return; + const attr = (await active.getAttribute("data-categories")) ?? ""; + for (const category of attr.split(",").filter(Boolean)) { + await page.locator(`[data-testid="places-clear"][data-category="${category}"]`).click(); + } + await expect(page.getByTestId("places-active")).toHaveCount(0); +} + +/** + * Polls until `--dock-w`/`--dock-h` (published by `usePublishedBox.ts`'s + * `ResizeObserver`) agree with the dock's own measured, rounded-up box -- + * bounded, and swallowed on timeout (see the file header: a pre-fix build + * never publishes either property, and that is not itself the regression + * this file exists to catch). + */ +async function waitForDockPublished(page: Page): Promise { + try { + await page.waitForFunction( + () => { + const dock = document.querySelector('[data-testid="places-dock"]'); + if (!dock) return false; + const rect = dock.getBoundingClientRect(); + const width = `${Math.ceil(rect.width)}px`; + const height = `${Math.ceil(rect.height)}px`; + const styles = getComputedStyle(document.documentElement); + return ( + styles.getPropertyValue("--dock-w").trim() === width && + styles.getPropertyValue("--dock-h").trim() === height + ); + }, + // No argument to pass into the page function -- `undefined` here is + // load-bearing: `waitForFunction`'s second positional parameter is the + // page-function argument, not the options bag, and passing `{timeout}` + // there instead of as the third parameter silently falls back to the + // ambient TEST timeout (30s/60s) instead of the 3s meant to bound this + // wait -- exactly the gap that let a pre-fix build's never-resolving + // predicate eat the whole test budget instead of degrading quickly. + undefined, + { timeout: 3000 }, + ); + } catch { + // See the file header's "Settling" section. + } +} + +/** Every `.attribution a` link: on screen, and not covered by anything -- + * `document.elementFromPoint` at its own centre must land on the link + * itself or a descendant of it. */ +async function assertAttributionLinksClickable(page: Page): Promise { + const viewport = page.viewportSize(); + if (!viewport) throw new Error("page has no viewport size"); + const links = page.locator(".attribution a"); + const count = await links.count(); + expect(count).toBeGreaterThan(0); + for (let i = 0; i < count; i += 1) { + const result = await links.nth(i).evaluate((el) => { + const rect = el.getBoundingClientRect(); + const cx = rect.left + rect.width / 2; + const cy = rect.top + rect.height / 2; + const hit = document.elementFromPoint(cx, cy); + return { + rect: { x: rect.left, y: rect.top, width: rect.width, height: rect.height }, + clickable: hit === el || el.contains(hit), + text: el.textContent, + }; + }); + expect(result.clickable, `attribution link "${result.text}" covered: ${JSON.stringify(result.rect)}`).toBe( + true, + ); + expect(result.rect.x, `"${result.text}" left of viewport`).toBeGreaterThanOrEqual(0); + expect(result.rect.y, `"${result.text}" above viewport`).toBeGreaterThanOrEqual(0); + expect(result.rect.x + result.rect.width, `"${result.text}" right of viewport`).toBeLessThanOrEqual( + viewport.width, + ); + expect(result.rect.y + result.rect.height, `"${result.text}" below viewport`).toBeLessThanOrEqual( + viewport.height, + ); + } +} + +test.describe("T-109 -- nothing in the bottom band covers anything else", () => { + for (const width of WIDTHS) { + for (const chrome of CHROMES) { + for (const content of CONTENT_STATES) { + test(`${width}x900, ${chrome} chrome, ${content}`, async ({ page }) => { + if (content === "loaded15") test.setTimeout(60_000); + + await page.setViewportSize({ width, height: 900 }); + await page.goto("/"); + await waitForTools(page); + await waitForFeatures(page); + + if (chrome === "agent") { + const state = await callTool(page, "get_map_state"); + expect(state.error).toBeUndefined(); + expect(await waitForAwake(page, 2500)).toBe("awake"); + } + + let expectedActive = 0; + let expectedStrip = 0; + + if (content === "browsed3") { + await page.getByTestId("places-toggle").click(); + for (const category of BROWSE_PICKS) await pickCategory(page, category); + await page.getByTestId("places-toggle").click(); + expectedActive = 3; + expectedStrip = 0; + } else if (content === "loaded15") { + await page.getByTestId("places-toggle").click(); + for (const category of STRIP_CATEGORIES) await pickCategory(page, category); + await clearAllPainted(page); + await page.getByTestId("places-toggle").click(); + expectedActive = 0; + expectedStrip = 15; + } + + // The setup really reached the state this cell claims to test -- + // without this, a broken `pick`/`clearAllPainted` would leave every + // assertion below vacuously true against the "none" layout instead + // of failing where the setup actually broke. + await expect(page.getByTestId("places-active-item")).toHaveCount(expectedActive); + await expect(page.getByTestId("poi-loaded-item")).toHaveCount(expectedStrip); + + await waitForDockPublished(page); + + const dockBox = await boxOf(page.getByTestId("places-dock")); + const attributionBox = await boxOf(page.getByTestId("attribution")); + const badgeBox = await boxOf(page.getByTestId("webmcp-status")); + + expect( + overlaps(dockBox, attributionBox), + `dock ${JSON.stringify(dockBox)} overlaps attribution ${JSON.stringify(attributionBox)}`, + ).toBe(false); + expect( + overlaps(dockBox, badgeBox), + `dock ${JSON.stringify(dockBox)} overlaps webmcp-status ${JSON.stringify(badgeBox)}`, + ).toBe(false); + + if (expectedStrip > 0) { + const stripBox = await boxOf(page.getByTestId("poi-loaded")); + expect( + overlaps(dockBox, stripBox), + `dock ${JSON.stringify(dockBox)} overlaps poi-loaded ${JSON.stringify(stripBox)}`, + ).toBe(false); + } + + await assertAttributionLinksClickable(page); + }); + } + } + } +}); diff --git a/e2e/note-human-gestures.spec.ts b/e2e/note-human-gestures.spec.ts new file mode 100644 index 0000000..ec6f468 --- /dev/null +++ b/e2e/note-human-gestures.spec.ts @@ -0,0 +1,476 @@ +/** + * T-106 / T-107 / T-108 -- three human-side fixes to the note a person pins + * by hand (`note-store.ts`, `AddNoteForm.tsx`, `annotation-marker.ts`, + * `card-model.ts`). The unit suites already prove the pure halves -- + * `note-store.test.ts` (the draft's own rounding/replace/clear rules), + * `annotation-marker.test.ts` (`foldedLabel`) and `card-model.test.ts` + * (the headline is the whole note). What this file adds is the part those + * cannot see: a real click on a real MapLibre canvas, a real form submit, a + * real pin in the DOM -- and the one thing a unit test can never prove either + * way, the agent path staying untouched by a human's half-placed pin. + * + * T-106 -- a person's note used to always land at `view.center`; it now + * lands where they clicked while the note popover was open (`note-store.ts`'s + * `draft`), with the centre kept as the fallback for a submit with no click. + * `add_note`'s own `agentInvoked` branch is asserted to ignore the draft + * entirely -- the regression this suite exists to catch is an agent's note + * silently inheriting a human's half-placed pin. + * + * T-107 -- folding a pin's bubble used to leave a 9px anchor whose only + * answer was "open the card about me"; a folded pin now keeps a chip on + * screen and a click anywhere on a folded pin unfolds it and does nothing + * else. + * + * T-108 -- the "On the map" card used to clip a note at 72 characters; it now + * shows the whole thing, however long, wrapped rather than cut. + */ +import type { Page } from "@playwright/test"; +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"; + +/** Same precision `note-store.ts`'s own `round5` rounds a clicked place to. */ +const round5 = (n: number) => Math.round(n * 1e5) / 1e5; + +async function goReady(page: Page): Promise { + await page.goto("/"); + await waitForTools(page); + await waitForFeatures(page); + await waitForLiveMap(page); + await waitForStoreHandle(page); +} + +/** The map container's own box -- full-bleed and unaffected by chrome (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 the draft is -- the independent half of the "the pin is where I clicked" proof. */ +async function unprojectRounded(page: Page, x: number, y: number): Promise<[number, number]> { + 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 [number, number]; + }, + { x, y }, + ); +} + +/** `add-note-target`'s text, parsed: "centre", or the `[lng, lat]` it names. */ +function parseTarget(text: string): "centre" | [number, number] { + if (text === "centre") return "centre"; + const [lng, lat] = text.split(", ").map(Number); + return [lng!, lat!]; +} + +test.describe("T-106 -- a human pins a note where they click", () => { + test("a click while the popover is open places a draft off the map's centre; a second click moves it, not adds another", async ({ + page, + }) => { + await goReady(page); + + await page.getByTestId("note-toggle").click(); + await expect(page.getByTestId("note-popover")).toHaveAttribute("data-open", "true"); + + // 150px right of centre: away from the tools row and the popover, both + // pinned to the top-right corner (globals.css), and far enough from + // DEFAULT_VIEW's centre at zoom 12 (~35 m/px) that a click there cannot + // round back to the same coordinate by accident. + const firstClick = await clickMapOffset(page, 150, 0); + await expect(page.getByTestId("note-draft-pin")).toHaveCount(1); + + const firstTarget = parseTarget(await page.getByTestId("add-note-target").innerText()); + if (firstTarget === "centre") throw new Error("add-note-target still reads centre after a click"); + // The pin is drawn, the form reports and the click actually landed on the + // same coordinate -- not merely "some coordinate that isn't the centre". + expect(firstTarget).toEqual(await unprojectRounded(page, firstClick.x, firstClick.y)); + + const state = await callTool(page, "get_map_state"); + expect(state.error).toBeUndefined(); + expect([round5(state.center!.lng), round5(state.center!.lat)]).not.toEqual(firstTarget); + + // A second click, well clear of the first and of the chrome either side. + const secondClick = await clickMapOffset(page, -150, 90); + // Still exactly one: the second click corrects the place, it does not add + // a second draft (note-store.test.ts: "moves the pin ... rather than + // collecting places"). + await expect(page.getByTestId("note-draft-pin")).toHaveCount(1); + const secondTarget = parseTarget(await page.getByTestId("add-note-target").innerText()); + if (secondTarget === "centre") throw new Error("add-note-target reverted to centre after a second click"); + expect(secondTarget).not.toEqual(firstTarget); + expect(secondTarget).toEqual(await unprojectRounded(page, secondClick.x, secondClick.y)); + }); + + test("submitting after a click pins the note at the clicked place, with zero agent activity", async ({ page }) => { + await goReady(page); + + await page.getByTestId("note-toggle").click(); + await clickMapOffset(page, 150, 0); + const target = parseTarget(await page.getByTestId("add-note-target").innerText()); + if (target === "centre") throw new Error("add-note-target still reads centre after a click"); + + await page.getByTestId("add-note-input").fill("pinned where I tapped"); + await page.getByTestId("add-note-submit").click(); + + const annotations = await page.evaluate(() => window.__glassmapStore!.getState().annotations); + expect(annotations).toHaveLength(1); + expect(annotations[0]!.source).toBe("user"); + // Landed at the clicked place -- NOT at the map centre, which is what + // every submit pinned to before T-106. + expect(annotations[0]!.at).toEqual(target); + + await expect(page.locator('[data-testid="activity-call"][data-tool="add_note"]')).toHaveCount(0); + // The place is spent with the note: the draft goes with it. + await expect(page.getByTestId("note-draft-pin")).toHaveCount(0); + await expect(page.getByTestId("add-note-target")).toHaveText("centre"); + }); + + test("submitting with no click still pins at the map centre -- the fallback", async ({ page }) => { + await goReady(page); + const center = await page.evaluate(() => window.__glassmapStore!.getState().view.center); + + await page.getByTestId("note-toggle").click(); + await expect(page.getByTestId("add-note-target")).toHaveText("centre"); + await page.getByTestId("add-note-input").fill("no click, so the centre"); + await page.getByTestId("add-note-submit").click(); + + const annotations = await page.evaluate(() => window.__glassmapStore!.getState().annotations); + expect(annotations).toHaveLength(1); + expect(annotations[0]!.at).toEqual(center); + }); + + test("an agent-invoked submit pins at the map centre and leaves a human's half-placed draft alone; a later human submit still uses it", async ({ + page, + }) => { + await goReady(page); + const center = await page.evaluate(() => window.__glassmapStore!.getState().view.center); + + await page.getByTestId("note-toggle").click(); + await clickMapOffset(page, 150, 0); + await expect(page.getByTestId("note-draft-pin")).toHaveCount(1); + const target = parseTarget(await page.getByTestId("add-note-target").innerText()); + expect(target).not.toBe("centre"); + + await page.getByTestId("add-note-input").fill("an agent submitted this, not the human"); + + // The spec's own discriminator (docs/webmcp-reference.md), dispatched + // directly on the form rather than through a prototype patch + a real + // click: this marks exactly this one submit as the agent's, without + // touching how any other submit in this file is attributed. + await page.evaluate(() => { + const form = document.querySelector('form[toolname="add_note"]')!; + const submit = new SubmitEvent("submit", { cancelable: true, bubbles: true }); + Object.defineProperty(submit, "agentInvoked", { value: true }); + form.dispatchEvent(submit); + }); + + const afterAgent = await page.evaluate(() => window.__glassmapStore!.getState().annotations); + expect(afterAgent).toHaveLength(1); + expect(afterAgent[0]!.source).toBe("agent"); + // The regression this test exists to catch: an agent's note routed + // through the human's draft instead of the centre the tool promises. + expect(afterAgent[0]!.at).toEqual(center); + await expect(page.locator('[data-testid="activity-call"][data-tool="add_note"]')).toHaveCount(1); + + // S1 (review fix): an agent's submit never touches the draft -- it did + // not use it, and must not spend it either. The pin a person is still + // placing survives the agent's own call untouched, byte for byte. + await expect(page.getByTestId("note-draft-pin")).toHaveCount(1); + expect(parseTarget(await page.getByTestId("add-note-target").innerText())).toEqual(target); + + // The surviving draft is still good for the human's OWN next submit -- + // proof this is a real draft, not a target frozen in the DOM. + await page.getByTestId("add-note-input").fill("and now the human, using the same draft"); + await page.getByTestId("add-note-submit").click(); + + const afterHuman = await page.evaluate(() => window.__glassmapStore!.getState().annotations); + expect(afterHuman).toHaveLength(2); + expect(afterHuman[1]!.source).toBe("user"); + expect(afterHuman[1]!.at).toEqual(target); + + // NOW the draft is spent -- by the human's submit, not the agent's. + await expect(page.getByTestId("note-draft-pin")).toHaveCount(0); + await expect(page.getByTestId("add-note-target")).toHaveText("centre"); + }); + + test("the popover suppresses a feature tap and places a draft instead; closed, the same tap opens the card", async ({ + page, + mockedExternalHosts, + }) => { + test.setTimeout(60_000); + // The bundled data layers' click handlers are only added inside + // MapLibre's `load` (MapCanvas.tsx), 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 `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 (public/data/mrt-stations.geojson), + // loaded from the moment the page's datasets arrive, never through + // tier-2 -- see inspector-actions.spec.ts's own fixture comment. A + // selected BUNDLED feature paints a selection ring, not a bead (beads + // are tier-2/browse only -- bead-style.ts, `selectedPoiFeatures`); the + // clickable render is the category's own circle layer, so the hit-test + // below queries `INTERACTIVE_LAYER_IDS`. + 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 popover: the ordinary tap answers "what is this?". + await page.mouse.click(stationPixel.x, stationPixel.y); + const card = page.getByTestId("on-the-map-card"); + await expect(card).toHaveCount(1); + await expect(card).toHaveAttribute("data-kind", "feature"); + await expect(card).toHaveAttribute("data-card-id", STATION.id); + await page.getByTestId("otm-close").click(); + await expect(card).toHaveCount(0); + + // Open popover: the same tap is a place-picker's click. No card, and the + // tap that used to select/open now drops a draft instead. + await page.getByTestId("note-toggle").click(); + await expect(page.getByTestId("note-popover")).toHaveAttribute("data-open", "true"); + await page.mouse.click(stationPixel.x, stationPixel.y); + await expect(card).toHaveCount(0); + await expect(page.getByTestId("note-draft-pin")).toHaveCount(1); + }); + + test("closing the popover, or starting Draw, throws the half-placed draft away", async ({ page }) => { + await goReady(page); + + await page.getByTestId("note-toggle").click(); + await clickMapOffset(page, 150, 0); + await expect(page.getByTestId("note-draft-pin")).toHaveCount(1); + + // Closing the popover. + await page.getByTestId("note-toggle").click(); + await expect(page.getByTestId("note-popover")).toHaveAttribute("data-open", "false"); + await expect(page.getByTestId("note-draft-pin")).toHaveCount(0); + await expect(page.getByTestId("add-note-target")).toHaveText("centre"); + + // Reopen, place another draft, then start Draw instead of closing. + await page.getByTestId("note-toggle").click(); + await clickMapOffset(page, -150, 60); + await expect(page.getByTestId("note-draft-pin")).toHaveCount(1); + + await page.getByTestId("draw-toggle").click(); + await expect(page.getByTestId("draw-mode")).toHaveText("on"); + await expect(page.getByTestId("note-draft-pin")).toHaveCount(0); + await expect(page.getByTestId("add-note-target")).toHaveText("centre"); + }); + + // S4 (review fix): while the popover is open the map is a place-picker and + // every tap on a place, bead or shape is suppressed -- before this, a + // second press on the Note chip was the only way out. Esc is bound at the + // window, not the popover, because a click on the map (the placing + // gesture) usually moves focus out of the form onto the canvas. + test("Escape leaves note mode: it closes the popover, throws the draft away, and returns focus to the Note chip", async ({ + page, + }) => { + await goReady(page); + + await page.getByTestId("note-toggle").click(); + await expect(page.getByTestId("note-popover")).toHaveAttribute("data-open", "true"); + await clickMapOffset(page, 150, 0); + await expect(page.getByTestId("note-draft-pin")).toHaveCount(1); + + await page.keyboard.press("Escape"); + + await expect(page.getByTestId("note-popover")).toHaveAttribute("data-open", "false"); + await expect(page.getByTestId("note-draft-pin")).toHaveCount(0); + await expect(page.getByTestId("add-note-target")).toHaveText("centre"); + await expect(page.getByTestId("note-toggle")).toBeFocused(); + }); + + test("Escape closes the popover even with the caret inside add-note-input", async ({ page }) => { + await goReady(page); + + await page.getByTestId("note-toggle").click(); + await clickMapOffset(page, 150, 0); + await expect(page.getByTestId("note-draft-pin")).toHaveCount(1); + + // The caret itself, not just a click somewhere on the map: a person may + // still be mid-sentence in the field when they decide to bail out. + const input = page.getByTestId("add-note-input"); + await input.click(); + await input.pressSequentially("never mind"); + await input.press("Escape"); + + await expect(page.getByTestId("note-popover")).toHaveAttribute("data-open", "false"); + await expect(page.getByTestId("note-draft-pin")).toHaveCount(0); + await expect(page.getByTestId("add-note-target")).toHaveText("centre"); + await expect(page.getByTestId("note-toggle")).toBeFocused(); + }); +}); + +test.describe("T-107 -- a folded note can be unfolded", () => { + test("a folded pin's bubble and chip fold and unfold it without ever opening a card; the unfolded anchor still does", async ({ + page, + }) => { + await goReady(page); + + await page.getByTestId("note-toggle").click(); + await page.getByTestId("add-note-input").fill("fold me and see"); + await page.getByTestId("add-note-submit").click(); + + const id = (await page.evaluate(() => window.__glassmapStore!.getState().annotations))[0]!.id; + const pin = page.locator(`[data-testid="annotation-pin"][data-annotation-id="${id}"]`); + await expect(pin).toHaveAttribute("data-folded", "false"); + + await pin.locator('[data-testid="annotation-popup"]').click(); + await expect(pin).toHaveAttribute("data-folded", "true"); + await expect(pin.locator('[data-testid="annotation-chip"]')).toBeVisible(); + await expect(page.getByTestId("on-the-map-card")).toHaveCount(0); + + await pin.locator('[data-testid="annotation-chip"]').click(); + await expect(pin).toHaveAttribute("data-folded", "false"); + await expect(page.getByTestId("on-the-map-card")).toHaveCount(0); + + await pin.locator(".pin-anchor").click(); + const card = page.getByTestId("on-the-map-card"); + await expect(card).toHaveCount(1); + await expect(card).toHaveAttribute("data-kind", "annotation"); + }); +}); + +test.describe("T-108 -- the card shows the whole note", () => { + test("a 200-character note's card shows every character, wrapped rather than cut", async ({ page }) => { + await goReady(page); + + // Padded to exactly 200 rather than hand-counted, so the assertion below + // proves the card against exactly 200 characters regardless of how this + // sentence is phrased. + const note = "This note is meant to run to exactly two hundred characters, so the on-the-map card must show every one of them without truncation, wrapped rather than clipped, however tall that makes the card.".padEnd( + 200, + ".", + ); + expect(note).toHaveLength(200); + + await page.getByTestId("note-toggle").click(); + await page.getByTestId("add-note-input").fill(note); + await page.getByTestId("add-note-submit").click(); + + const id = (await page.evaluate(() => window.__glassmapStore!.getState().annotations))[0]!.id; + const pin = page.locator(`[data-testid="annotation-pin"][data-annotation-id="${id}"]`); + await pin.locator(".pin-anchor").click(); + + const card = page.getByTestId("on-the-map-card"); + await expect(card).toHaveAttribute("data-kind", "annotation"); + const name = await page.getByTestId("otm-name").innerText(); + expect(name).toBe(note); + expect(name).toHaveLength(200); + expect(name).not.toContain("…"); + }); + + // S2 (review fix): `annotate` accepts MAX_NOTE_CHARS (500), and every one of + // those characters may be a newline -- 250 lines of card, which used to run + // off the top of the map above 640px and could not be scrolled back into + // view at all below it (`.otm-card` is `position: fixed` against the bottom + // bar down there). `.otm-name` is now capped at 25vh with its own + // scrollbar, so the worst case stays reachable and the card itself stays + // placeable on both tiers. + for (const viewport of [ + { width: 1440, height: 900, label: "desktop" }, + { width: 390, height: 844, label: "mobile" }, + ]) { + test(`a pathological 500-character note (every other character a newline) stays scrollable, and the card's edges stay on screen at ${viewport.label} (${viewport.width}x${viewport.height})`, async ({ + page, + }) => { + await page.setViewportSize(viewport); + await goReady(page); + + // Exactly MAX_NOTE_CHARS (500) -- the worst case the tool will accept, + // not an arbitrary long string. + const pathological = "a\n".repeat(250); + expect(pathological).toHaveLength(500); + const center = await page.evaluate(() => window.__glassmapStore!.getState().view.center); + const result = await callTool(page, "annotate", { + at: { lng: center[0], lat: center[1] }, + note: pathological, + }); + expect(result.error).toBeUndefined(); + const id = result.annotation_id!; + + const pin = page.locator(`[data-testid="annotation-pin"][data-annotation-id="${id}"]`); + await pin.locator(".pin-anchor").click(); + + const card = page.getByTestId("on-the-map-card"); + await expect(card).toHaveAttribute("data-kind", "annotation"); + + const nameBox = page.getByTestId("otm-name"); + const { scrollHeight, clientHeight } = await nameBox.evaluate((el) => ({ + scrollHeight: el.scrollHeight, + clientHeight: el.clientHeight, + })); + // The 25vh cap is doing something: the note overflows its own box + // rather than stretching it to fit every line. + expect(scrollHeight).toBeGreaterThan(clientHeight); + + const box = await card.boundingBox(); + if (!box) throw new Error("on-the-map-card has no box"); + expect(box.y + box.height).toBeLessThanOrEqual(viewport.height); + // Not asked for, but cheap and the more telling half of the same fix at + // the fixed-bottom-sheet tier (<=640px): an uncapped note grows the + // card upward from its fixed bottom offset and pushes the top off + // screen even though the bottom edge alone would still read as fine. + expect(box.y).toBeGreaterThanOrEqual(0); + }); + } +}); 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 95cb70b..35e5bb5 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -988,6 +988,88 @@ html:is([data-chrome="awake"]:not(:where([data-panel="closed"])), :where([data-p padding: 5px 10px; border-radius: var(--radius-s); } +/* The strip also stops before the Places dock, which is an island centred over + this same bar. Nothing above holds it there: the strip's `margin-right: auto` + reaches for the corner, and the dock is out of the flow entirely (absolute, + z-index 20), so at fifteen loaded categories the row ran clean under the pill + and the browsed chips — measured 720px of overlap at 1440 and 319px at 768 — + and both surfaces became unreadable at once. + + The boundary is the gutter beside the dock, and it has to be measured + because the dock's width is content: the pill alone is 159px, the pill plus + three named browsed chips is about 720px, and a person can change which of + the two it is at any moment. `--dock-w` is the dock's own box, published by + `PlacesTray.tsx`; the halving is the dock being centred over this bar (in + agent chrome the lane shifts the dock 5px left of the bar's centre, which is + inside the 16px this leaves for the gap and the rounding). + + The strip keeps growing upward past the cap rather than being cut: more + rows of the same whole chips, which is the same choice `flex-wrap` above + already makes for the same reason. + + Only while the bar and the dock still share the band, and only where the + dock is a centred island. Below 641px the dock spans the bar and the bar is + lifted clear of it (`bottom: 62px`), and the same is true above 641px once a + browsed chip is on the dock (see the lift below) — in both cases there is no + gutter to compute and this would resolve to nothing. */ +@media (min-width: 641px) { + .map-wrap:not(:has(.dock-actives)) .poi-strip { + max-width: min(calc(100vw - 24px), calc((100% - var(--dock-w, 0px)) / 2 - 16px)); + } + /* The corner keeps the mirror image of that gutter, for a harder reason + than the strip's. Even the bare pill is 160px wide, and in agent chrome + the corridor it is centred on has lost a 300px lane — so at 921px the + attribution's own 295px was wider than the 216px left beside the dock and + ran under it, licence links and all. Capped, it wraps instead (below), and + above 1240 there is room for the whole line again so nothing changes. */ + .map-wrap:not(:has(.dock-actives)) .corner { + max-width: calc((100% - var(--dock-w, 0px)) / 2 - 16px); + } +} + +/* What the corner gives up when the gutter is narrower than the licence: the + line wraps. Two lines of licence beside the dock is the honest trade against + one line under it — and the tier below 921px already made exactly this + choice for exactly this reason. Above 1240px the gutter fits the whole line + again, so nothing wraps there and the corner reads as it always has. */ +@media (min-width: 921px) { + .map-wrap:not(:has(.dock-actives)) .attribution { + white-space: normal; + text-align: right; + } +} +/* The dock with browsed chips on it is too wide to share the band at all, and + what it covers is a licence condition. + + One tap paints a kind of place and puts a named chip on the dock; three of + them make it 320-815px wide, which at every width up to 1240 is more than + half the corridor — and in agent chrome more than the corridor itself (the + awake dock is centred on `calc((100% - var(--lane) - 10px) / 2)` with the + canvas, not the corridor, as its shrink-to-fit space). Measured with three + browsed kinds, the dock covered the OpenStreetMap attribution at every width + from 641 to 1024 in human chrome and from 641 to 1440 in agent chrome — by + 22 to 295px — the WebMCP badge by up to 255px and the corner whisper by up + to 87px, and the attribution's three links sat *under* the chips, so they + could not be clicked either. "Data © OpenStreetMap + contributors" is a licence condition and may never be covered; the same + sentence is already written at the phone tier, where this arrangement comes + from. + + So the bar takes the row above the dock, exactly as it does below 641px — + the design's own answer to the same collision, applied at the same moment + the collision appears rather than at a width. Nothing wraps, nothing + narrows, nothing is hidden: the licence, the badge, the whisper and the + disclosure all keep the form they have on the landing map, one band higher. + + `--dock-h` is the dock's own box (`PlacesTray.tsx`); the 28px is its bottom + inset (16px, 12px below 921) plus the gap the bar keeps from it. The + landing map in human chrome is untouched — with no browsed chip there is + no `.dock-actives`, and the bar stays in the corner. */ +@media (min-width: 641px) { + .map-wrap:has(.dock-actives) .bottom-bar { + bottom: calc(var(--dock-h, 0px) + 28px); + } +} .poi-strip-label { font-size: 10px; font-weight: 620; @@ -1091,6 +1173,12 @@ html:is([data-chrome="awake"]:not(:where([data-panel="closed"])), :where([data-p align-items: center; gap: 8px; padding: 7px 12px; + /* Allowed to wrap, so that the corner's cap beside the Places dock (see + `.corner` above) can narrow it instead of pushing it out to the left. Its + parts stay whole because each is `nowrap` on its own — what wraps is where + they sit, never a word. */ + flex-wrap: wrap; + justify-content: flex-end; } .badge .live-dot { width: 7px; @@ -1219,6 +1307,90 @@ html:is([data-chrome="awake"]:not(:where([data-panel="closed"])), :where([data-p display: none; } +/* Folded (T-107): the bubble goes, but the note does not vanish. What is left + is a chip carrying the source's own colour and the first word — small enough + to see the map past, big enough to click, which is the whole fix: folding + used to leave a 9px anchor whose only answer was "open the card about me". */ +.pin-chip { + display: none; + align-items: center; + gap: 5px; + padding: 3px 8px 3px 6px; + border-radius: 999px; + background: var(--glass-strong); + backdrop-filter: blur(12px); + -webkit-backdrop-filter: blur(12px); + border: 1px solid rgba(45, 212, 191, 0.4); + box-shadow: 0 6px 16px rgba(3, 7, 13, 0.4); + max-width: 150px; +} +.note-pin[data-annotation-source="user"] .pin-chip { + border-color: rgba(244, 143, 177, 0.45); +} +.note-pin[data-folded="true"] .pin-chip { + display: inline-flex; +} +.pin-chip-dot { + width: 6px; + height: 6px; + border-radius: 50%; + flex-shrink: 0; + background: var(--agent); +} +.note-pin[data-annotation-source="user"] .pin-chip-dot { + background: var(--human); +} +.pin-chip-label { + font-size: 10.5px; + line-height: 1.2; + color: var(--text-mid); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +/* The provisional pin (T-106): where the note in the popover would land. A + dashed rose ring on a dashed stem — hollow because it is not a note yet, and + click-through because the next click on the map is how it moves. */ +.note-draft-pin { + display: flex; + flex-direction: column; + align-items: center; + pointer-events: none; +} +.note-draft-pin .draft-stem { + width: 1.5px; + height: 13px; + background: repeating-linear-gradient( + to bottom, + var(--human) 0 3px, + transparent 3px 6px + ); +} +.note-draft-pin .draft-anchor { + width: 11px; + height: 11px; + border-radius: 50%; + background: transparent; + border: 1.6px dashed var(--human); + box-shadow: 0 1px 6px rgba(0, 0, 0, 0.4); + 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; @@ -1965,6 +2137,31 @@ html:is([data-chrome="awake"]:not(:where([data-panel="closed"])), :where([data-p font-weight: 650; line-height: 1.35; } +/* A note's headline is the note (T-108), so it wraps instead of being clipped: + this card is the only surface that carries every character of one, and the + card measures its own height, so a long note makes a taller card rather than + a truncated one. `anywhere` because a note may be one unbroken string — a URL, + or a language that does not space its words; `pre-wrap` because a note may + carry its own line breaks and they are the writer's. + + Bounded, though: `annotate` accepts 500 characters and every one of them may + be a newline, which is 250 lines of card. Above 640px that would run off the + top of the map; below it the card is `position: fixed` against the bottom bar + and could not be scrolled back into view at all. A scrollbar keeps the whole + note reachable on every tier, and 25vh is what makes the card placeable: the + rest of the card measures ~115px, and `cardPlacement` can only ever guarantee + a side that fits while the whole card is shorter than half the viewport minus + its margins. Measured at 1440x900 with 500 newline characters: 225px of note, + 340px of card, which fits above a tap in the middle of the map — at 40vh the + same card was 475px, fitted on neither side, and hung its Remove/Keep buttons + 41px below the fold. */ +.otm-card[data-kind="annotation"] .otm-name { + font-weight: 600; + white-space: pre-wrap; + overflow-wrap: anywhere; + max-height: 25vh; + overflow-y: auto; +} .otm-cat { margin-top: 3px; display: flex; @@ -2739,6 +2936,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/AddNoteForm.tsx b/src/components/AddNoteForm.tsx index 6c01c19..c1f59a3 100644 --- a/src/components/AddNoteForm.tsx +++ b/src/components/AddNoteForm.tsx @@ -5,6 +5,7 @@ import { ACTIVITY_NOTE_CHARS } from "@/lib/map-tools/activity"; import { truncate } from "@/lib/map-tools/shapes"; import { useMapStore } from "@/lib/store/map-store"; import { emitHumanFx } from "./fx/human-events"; +import { useNoteStore } from "./note-store"; /** ~1 m, the same precision the tools report coordinates in. */ const round5 = (n: number) => Math.round(n * 1e5) / 1e5; @@ -22,6 +23,16 @@ const round5 = (n: number) => Math.round(n * 1e5) / 1e5; * written to the store and echoed in `add-note-status`, which is also what an * agent reads back after submitting. * + * **Where the note lands depends on who submitted it** (T-106). An agent has no + * cursor, so an agent's submit pins at `view.center` — the place the tool has + * always named and the place its description still names. A person has one: + * while this popover is open, a click on the map places a provisional pin + * (`note-store.ts`, drawn by MapCanvas) and their submit pins there. Without a + * click a person gets the centre too, which is the behaviour this form shipped + * with — panning the map until the spot sits under an invisible crosshair is + * now the fallback rather than the only way. `add-note-target` reports which of + * the two is armed, and the status line names the coordinates actually used. + * * Who gets credit for the note comes from `SubmitEvent.agentInvoked`, the * spec's own discriminator. Without a WebMCP client there is no such flag and * the note is stored as `source: "user"` - the honest default for a form a @@ -43,6 +54,7 @@ const round5 = (n: number) => Math.round(n * 1e5) / 1e5; */ export function AddNoteForm({ focusable = true }: { focusable?: boolean }) { const [status, setStatus] = useState(""); + const draft = useNoteStore((s) => s.draft); const onSubmit = (event: React.FormEvent) => { event.preventDefault(); @@ -55,9 +67,16 @@ export function AddNoteForm({ focusable = true }: { focusable?: boolean }) { } const { view, addAnnotation, recordActivity } = useMapStore.getState(); const agentInvoked = (event.nativeEvent as SubmitEvent).agentInvoked === true; + // The draft is a person's answer to "where", so only a person's submit + // reads it: `add_note` promises an agent the map centre, and an agent that + // submits while a human has a pin half-placed must still get the place the + // tool description names. Read from the store rather than from the + // subscribed value, so a click that lands in the same tick as the submit + // cannot pin the note at the place before it. + const at = agentInvoked ? view.center : (useNoteStore.getState().draft ?? view.center); const stored = addAnnotation({ source: agentInvoked ? "agent" : "user", - at: view.center, + at, note, }); // An agent-submitted form is a tool call like any other, and the activity @@ -79,10 +98,14 @@ export function AddNoteForm({ focusable = true }: { focusable?: boolean }) { // drives its (teal) effect. emitHumanFx({ type: "note", annotation: stored }); } - setStatus( - `Pinned ${stored.id} at ${round5(view.center[0])}, ${round5(view.center[1])}.`, - ); + setStatus(`Pinned ${stored.id} at ${round5(at[0])}, ${round5(at[1])}.`); form.reset(); + // The place is spent with the note a person pinned: the next one starts + // unplaced rather than stacking silently on the last one's pin. An agent's + // submit never touches it - the draft belongs to the human who clicked it, + // and a tool call arriving mid-sentence must not take their pin off the map + // (it did not use it either: an agent pins at the centre). + if (!agentInvoked) useNoteStore.getState().clearDraft(); }; return ( @@ -94,7 +117,14 @@ export function AddNoteForm({ focusable = true }: { focusable?: boolean }) { onSubmit={onSubmit} className="note-form" > - + {/* The visible instruction follows the state; the `tooldescription` and + `toolparamdescription` around it do not, because they are the agent's + contract and an agent's note still goes to the centre. */} +
{status}

+ {/* Off screen: which of the two places the next human submit will use, + without reading a CSS class or measuring a marker. The draft's own + numbers are already rounded to ~1 m by the store that holds them. */} + + {draft ? `${draft[0]}, ${draft[1]}` : "centre"} + ); } 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 75c2105..ab51cc0 100644 --- a/src/components/MapCanvas.tsx +++ b/src/components/MapCanvas.tsx @@ -19,7 +19,7 @@ import { type LngLat, type MapView, } from "@/lib/store/map-store"; -import { createAnnotationElement } from "./annotation-marker"; +import { createAnnotationElement, createNoteDraftElement } from "./annotation-marker"; import { createBeadImages } from "./bead-sprite"; import { useCardStore } from "./card-store"; import { @@ -42,7 +42,9 @@ import { import { useBrowseStore } from "./browse-store"; 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, @@ -245,9 +247,22 @@ export default function MapCanvas() { const store = useMapStore; const draw = useDrawStore; + const note = useNoteStore; const browse = useBrowseStore; const card = useCardStore; + /** + * 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 or a walk is planned. + */ + const handOwnsClick = () => draw.getState().mode !== "none" || note.getState().open; + /** * No map, so nothing will ever report a viewport. Compute one instead: * without it `bounds` stays null forever and every viewport tool answers @@ -332,6 +347,12 @@ export default function MapCanvas() { * that is what the card is about — and because the pin is a tall element * whose top is nowhere near the place it points at. In draw mode a tap is * a vertex like any other, so the card stays out of the way. + * + * The guard is deliberately draw-only, and not `handOwnsClick()`: with the + * note popover open, a tap on a pin that is already on the map still opens + * its card. It cannot place a draft either way — the pin root stops the + * click from reaching the map (`annotation-marker.ts`) — so refusing here + * would only take an answer away and give nothing back. */ const tapAnnotation = (id: string) => { if (draw.getState().mode !== "none") return; @@ -789,7 +810,7 @@ export default function MapCanvas() { }; map.on("click", INTERACTIVE_LAYER_IDS, (event) => { // While drawing, a click is a vertex, not a selection. - if (draw.getState().mode !== "none") return; + if (handOwnsClick()) return; const id = event.features ?.map((f) => f.properties?.id) .find((value): value is string => typeof value === "string"); @@ -803,7 +824,7 @@ export default function MapCanvas() { // and cannot reach. const beadLayers = [...BEAD_LAYER_IDS]; map.on("click", beadLayers, (event) => { - if (draw.getState().mode !== "none") return; + if (handOwnsClick()) return; const feature = event.features?.[0]; if (!feature) return; const { id, cluster_id: cluster } = feature.properties as { @@ -840,7 +861,7 @@ export default function MapCanvas() { const drawingLayers = [...DRAWING_LAYER_IDS]; const overDrawing = [...INTERACTIVE_LAYER_IDS, ...beadLayers]; map.on("click", drawingLayers, (event) => { - if (draw.getState().mode !== "none") return; + if (handOwnsClick()) return; if (map.queryRenderedFeatures(event.point, { layers: overDrawing }).length > 0) return; const id = event.features ?.map((f) => f.properties?.id) @@ -850,11 +871,11 @@ export default function MapCanvas() { const pointerLayers = [...INTERACTIVE_LAYER_IDS, ...beadLayers, ...drawingLayers]; map.on("mouseenter", pointerLayers, () => { - if (draw.getState().mode !== "none") return; + if (handOwnsClick()) return; canvas.style.cursor = "pointer"; }); map.on("mouseleave", pointerLayers, () => { - if (draw.getState().mode !== "none") return; + if (handOwnsClick()) return; canvas.style.cursor = ""; }); @@ -876,15 +897,34 @@ export default function MapCanvas() { // arrives; the preview source is written through `setSourceData`, which is // a no-op until the style is up. + /** + * 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. 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" ? "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) { @@ -901,6 +941,60 @@ export default function MapCanvas() { draw.getState().finish(); }); + // --- Note draft (T-106) ----------------------------------------------- + // A person pins a note where they click. Before this, every note landed at + // `view.center`, so choosing a place meant panning the map until the place + // sat under an invisible crosshair — the map had to be moved to say + // something about it. The draft lives in `note-store.ts`, not in the map + // store: it has no id and no tool may see it. + + /** The provisional pin, while there is a place but not yet a note. */ + let draftMarker: Marker | null = null; + + const applyNoteDraft = (at: LngLat | null) => { + if (!at) { + draftMarker?.remove(); + draftMarker = null; + return; + } + if (draftMarker) draftMarker.setLngLat(at); + else { + draftMarker = new Marker({ element: createNoteDraftElement(), anchor: "bottom" }) + .setLngLat(at) + .addTo(map); + } + }; + + /** + * 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 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; + state.place([event.lngLat.lng, event.lngLat.lat]); + }); + const unsubscribe = store.subscribe((state, previous) => { if (state.view !== previous.view && !fromMap) applyView(state.view); // Whatever took a place off the map — an agent's `select_features`, a @@ -940,7 +1034,24 @@ export default function MapCanvas() { const unsubscribeDraw = draw.subscribe((state, previous) => { if (state.draft !== previous.draft) applyDraft(map, state.draft); - if (state.mode !== previous.mode) applyDrawCursor(state.mode); + // 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 + // the new polygon would be a pin nothing can move any more. + if (state.mode !== "none") note.getState().clearDraft(); + } + }); + + const unsubscribeNote = note.subscribe((state, previous) => { + if (state.draft !== previous.draft) applyNoteDraft(state.draft); + // Opening the popover is what turns the map into a place-picker, so it + // changes the cursor exactly as entering draw mode does. + if (state.open !== previous.open) applyDrawCursor(draw.getState().mode); }); const unsubscribeBrowse = browse.subscribe((state, previous) => { @@ -987,16 +1098,26 @@ 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 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); setFxMap(null); unsubscribe(); unsubscribeDraw(); + unsubscribeNote(); unsubscribeBrowse(); unsubscribeChrome(); for (const marker of markers.values()) marker.remove(); markers.clear(); + draftMarker?.remove(); + draftMarker = null; + routeMarker?.remove(); + routeMarker = null; try { map.remove(); } catch { diff --git a/src/components/PlacesTray.tsx b/src/components/PlacesTray.tsx index a5beb36..238cb66 100644 --- a/src/components/PlacesTray.tsx +++ b/src/components/PlacesTray.tsx @@ -1,6 +1,6 @@ "use client"; -import { useCallback, useMemo, useState } from "react"; +import { useCallback, useMemo, useRef, useState } from "react"; import { isAgentState } from "@/lib/awaken"; import { useMapStore } from "@/lib/store/map-store"; import type { Tier2Category } from "@/lib/store/tier2"; @@ -10,6 +10,7 @@ import { TIER2_PLURAL } from "./category-labels"; import { TRAY_ORDER, trayCount } from "./places-model"; import { loadedCategoryRows } from "./tier2-disclosure"; import { useAwakenMode } from "./useAwakenMode"; +import { usePublishedBox } from "./usePublishedBox"; const number = (n: number) => n.toLocaleString("en-US"); @@ -49,6 +50,18 @@ const number = (n: number) => n.toLocaleString("en-US"); */ export function PlacesDock() { const mode = useAwakenMode(); + /** + * The dock's own box, published to the stylesheet as `--dock-w`/`--dock-h`. + * + * Everything the bottom bar carries shares this band and none of it can know + * how big the dock is: nought to three browsed chips, each named, is a + * 159x39 to 815x177 range that no constant covers. The disclosure strip + * stops before the width; the bar takes the row above the height the moment + * a browsed chip makes the dock too wide to share the band. See + * `usePublishedBox`, `.poi-strip` and `.bottom-bar`. + */ + const dockRef = useRef(null); + usePublishedBox(dockRef, "--dock"); const [open, setOpen] = useState(false); const [failed, setFailed] = useState(null); /** The category a fourth pick pushed off the map, until the next pick. */ @@ -124,7 +137,7 @@ export function PlacesDock() { ); return ( -
+