From 9d9f249f4c4cbae749e4eb7c6e8a7ecf96a5ba71 Mon Sep 17 00:00:00 2001 From: CLYEH <43227241+CLYEH@users.noreply.github.com> Date: Wed, 2 Sep 2026 12:48:28 +0800 Subject: [PATCH] docs: the README speaks in the present tense and nothing else (#96) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every passage that narrated a decision, a date or a change-since is gone from README.md: the measured-on-2026-08-28 caveat, the ChatGPT "verified once… unverified since" paragraph, "both arms", "listed in that order", the WCAG disclaimer (only "agent-mediated map access" remains), "an OSM tag, not a verified accessibility claim", "honest error", "all green". What stays is what the page does today. The adversarial review then tightened eight claims: the ChatGPT line names its precondition (Enable site tools) and stops generalising to "accounts"; the tool table's three layers are again "in that order" so the grouping is checkable; "leaves the page" became "calls an external service" because Perceive tools fetch same-origin data files; the GIF captions' numbers now point at the scripts that produce them, committed as scripts/media/ (the Playwright replay harness; gifenc + jpeg-js installed locally, outputs ignored); the table lead-in says "three other tasks" so the clip numbers and the table are read as two measurements; untrustedContentHint is scoped to "readable" text (get_share_link's base64 payload is deliberately exempt); the CI sentence names the three commands and "code PR", matching the docs-only gate in ci.yml. docs/details.md drops one "since the tool shipped". docs/TASKS.md adds T-106/T-107/T-108 (human-side note fixes, dispatched). Claude-Session: https://claude.ai/code/session_01GvdrJcKNZkfREdb7QGRYYH Co-authored-by: Claude Opus 5 (1M context) --- .gitignore | 6 + README.md | 36 +++--- docs/TASKS.md | 24 ++++ docs/details.md | 2 +- scripts/media/lib.mjs | 163 ++++++++++++++++++++++++++ scripts/media/package.json | 10 ++ scripts/media/s1-screenshot-agent.mjs | 93 +++++++++++++++ scripts/media/s2-webmcp.mjs | 74 ++++++++++++ 8 files changed, 389 insertions(+), 19 deletions(-) create mode 100644 scripts/media/lib.mjs create mode 100644 scripts/media/package.json create mode 100644 scripts/media/s1-screenshot-agent.mjs create mode 100644 scripts/media/s2-webmcp.mjs diff --git a/.gitignore b/.gitignore index 84d70a4..11700be 100644 --- a/.gitignore +++ b/.gitignore @@ -52,3 +52,9 @@ CLAUDE.local.md # generated by scripts/copy-maplibre-worker.mjs at dev/build time /public/maplibre/ + +# Recording harness outputs (scripts/media) +scripts/media/node_modules/ +scripts/media/*.gif +scripts/media/*.raw.json +scripts/media/package-lock.json diff --git a/README.md b/README.md index 25bd382..7ad2fde 100644 --- a/README.md +++ b/README.md @@ -6,23 +6,23 @@ Live: **https://glassmap.clyeh.xyz** · **15 WebMCP tools, no backend, no API ke ![The map after an agent session: a 6-call activity feed, a dashed teal 800 m "10-minute walk" circle around 7 teal-ringed parks, an inspector reading SELECTED 7 · SHAPES 1 · NOTES 1, and a footer reading "Agent connected · 15 tools · WebMCP".](docs/media/hero.jpg) ## Why "Glass" -To an agent, every station, park and pin on a web map is just pixels. A screenshot can't read an unlabeled green polygon, a click stops working the moment the zoom changes, and drawing a shape, measuring a distance or selecting every park in view is essentially impossible from a picture. WebMCP exposes the map's state, features and actions as tools instead, so an agent never has to guess from pixels — the black box becomes **glass**. Every web map has this problem — property search, delivery planning, travel — and the fix is a tool contract, not a bigger screenshot model. For someone who cannot see the map at all, the same read-only tools double as agent-mediated map access — not a WCAG or accessibility-compliance claim. +To an agent, every station, park and pin on a web map is just pixels. A screenshot can't read an unlabeled green polygon, a click stops working the moment the zoom changes, and drawing a shape, measuring a distance or selecting every park in view is essentially impossible from a picture. WebMCP exposes the map's state, features and actions as tools instead, so an agent never has to guess from pixels — the black box becomes **glass**. Every web map has this problem — property search, delivery planning, travel — and the fix is a tool contract, not a bigger screenshot model. For someone who cannot see the map at all, the same read-only tools double as agent-mediated map access. ## The same task, two ways -Both arms were asked: *"Show every park within a 10-minute walk of Daan Station."* — the first "Try asking" card on the page. Open the live site and say it verbatim. +Both agents get the same sentence — *"Show every park within a 10-minute walk of Daan Station."*, the first "Try asking" card on the page. Open the live site and say it verbatim. **Screenshot agent** ![The screenshot agent driving GlassMap by clicks, keys and full-page screenshots, with no tool access.](docs/media/screenshot-agent.gif) -19 UI actions · 8 screenshots → finds 2 of 7 parks. The 800 m "circle" is an 8-vertex polygon whose radius is a guess (the page shows a screenshot agent no scale bar and no zoom readout). The other 5 were never found: each one is another click-and-read-the-card round trip, and nothing on screen says how many are left. The search box needs two tries — "Daan Station" has no match, "Daan" does. +19 UI actions · 8 screenshots → 2 of 7 parks. The 800 m "circle" is an eight-vertex polygon with a guessed radius — the page shows no scale bar and no zoom readout — and the other five parks are never found: each one costs another click-and-read round trip, and nothing on screen says how many are left. **WebMCP agent** ![The WebMCP agent calling map tools directly, with the map updating and no screenshots taken.](docs/media/webmcp-agent.gif) 5 tool calls · 2.9 KB returned · 82 ms of tool time · 0 screenshots → all 7 parks inside an exact 800 m circle, each with an id, a distance and a compass direction — two of them parks OpenStreetMap never named: `set_map_view({ place: "Daan Station" })` → `draw_shape({ type: "circle", center: "Daan Station", radius_m: 800, label: "10-minute walk" })` → `set_map_view({ fit: "drawing:1" })` → `find_features({ near: "Daan Station", radius_m: 800, categories: ["park"] })` → `select_features({ ids: [...] })`. -Both clips are scripted replays recorded on 2026-09-02 with Playwright's headless Chromium against a local production build of this repository — not a live model. The screenshot arm was allowed only what a generic computer-use agent has: a search box, clicks, keys, mouse wheel, screenshots. The WebMCP arm calls `document.modelContext.executeTool` through the page's own dev shim (`?shim=1`), because headless Chromium has no native WebMCP; the tool code and its output are identical to what Chrome's native surface exposes. The measured, live-model comparison is the table below. +Both clips are scripted replays in Playwright's headless Chromium, not a live model; the scripts that record them, and count every action, screenshot, call and byte in the captions, are in [`scripts/media/`](./scripts/media/). The screenshot agent gets only what a computer-use agent has — a search box, clicks, keys, the mouse wheel and screenshots. The WebMCP agent calls `document.modelContext.executeTool`, the same call a native agent makes, through the page's own `?shim=1` surface, since headless Chromium has no WebMCP of its own. -One run per arm per task, measured 2026-08-28 against that date's production build, before the page had a human search box (one response below has since grown a field); full method and every caveat: [`docs/comparison.md`](./docs/comparison.md). +Three other tasks, with a live model ([method and caveats](./docs/comparison.md)): | Task | Screenshot agent | WebMCP | |---|---|---| @@ -42,6 +42,8 @@ One run per arm per task, measured 2026-08-28 against that date's production bui - "How big is Daan Forest Park?" → `find_features` · `measure` - "What is the phone number and address of the post office nearest Daan Station?" → `find_features` · `get_place_details` +**ChatGPT desktop app:** with *Enable site tools* on, open its built-in browser on the live site and ask the same sentences — it finds the page's tools with no Chrome flag. + Or call the tools directly from DevTools: ```js @@ -56,10 +58,10 @@ const found = await document.modelContext.executeTool(byName.find_features, { JSON.parse(found); ``` -Any browser works with `?shim=1` appended to the URL: the shim installs `document.modelContext` only when no native implementation exists, and it is already on in development builds. +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, listed in that order: **Perceive** (read-only, replaces screenshots), **Navigate** (camera only) and **Act** (writes page state; only `plan_route` leaves the page). +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). | Tool | What it does | |---|---| @@ -69,7 +71,7 @@ Three layers, listed in that order: **Perceive** (read-only, replaces screenshot | `describe_surroundings` | Describes what's around a point out loud: the district, then nearby features by compass direction. | | `measure` | Measures a drawing's or feature's area, perimeter or length. | | `compare_areas` | Compares two places' per-category counts and nearest match, in one call. | -| `get_place_details` | Returns everything known about one place: address, phone, website, hours, `wheelchair` (an OSM tag, not a verified accessibility claim). | +| `get_place_details` | Returns everything known about one place: address, phone, website, hours and `wheelchair`, as tagged in OpenStreetMap. | | `get_share_link` | Builds a URL that restores this exact map — camera, selection, drawings, notes — for whoever opens it. | | `set_map_view` | Moves the camera by place name, feature id, `fit` (frame a drawing or feature whole), or exact center/zoom/bearing/pitch. | | `select_features` | Highlights features on the map and in the inspector, by id or the same filter `find_features` accepts. | @@ -79,17 +81,15 @@ Three layers, listed in that order: **Perceive** (read-only, replaces screenshot | `remove_from_map` | Removes the agent's own drawings, notes or a selection entry; refuses to touch what a human drew. | | `add_note` (`
`) | Pins a note from a plain HTML form; `SubmitEvent.agentInvoked` decides `source: "agent"` or `"user"`. | -Design rules the tool layer follows: +Every tool keeps five rules: -- Every write tool returns the new map state, so no follow-up read is needed. -- Read-only tools carry `readOnlyHint: true`. -- Output containing OpenStreetMap or user text carries `untrustedContentHint: true`. +- A write tool returns the new map state, so no follow-up read is needed. +- A read-only tool carries `readOnlyHint: true`. +- Output containing readable OpenStreetMap or user text carries `untrustedContentHint: true`. - Responses stay small: `limit` defaults to 20, coordinates round to 5 decimals, geometry returns by id. - Bad input returns a structured `{ error }`, never throws; no `alert` / `confirm` / `prompt` anywhere. -More on how these behave: [`docs/details.md`](./docs/details.md). - -Verified once, 2026-08-28, against the ChatGPT desktop app: it listed the eleven tools the page declared at the time and called `get_map_state` live, no Chrome flag needed. The roster has grown to fourteen registered tools since (the `add_note` form is the fifteenth), and that growth is unverified against ChatGPT. +More on how each tool behaves: [`docs/details.md`](./docs/details.md). ## One map, two hands The map is shared state, not a private channel for the agent. @@ -104,14 +104,14 @@ The map is shared state, not a private channel for the agent. - The address bar holds a link that restores this exact map — camera, selection, drawings and notes — 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 (fabricated, not OSM) — 2,063 features total. 18 more OpenStreetMap point-of-interest categories (31,069 features) load lazily, one at a time, the moment a category is named; an answer that didn't search one lists it under `unsearched_categories`. Full provenance and tag mapping: [`public/data/README.md`](./public/data/README.md). +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). - Map data © [OpenStreetMap](https://www.openstreetmap.org/copyright) contributors, [ODbL](https://opendatacommons.org/licenses/odbl/). Tiles by [OpenFreeMap](https://openfreemap.org/). - Listings shown are **sample data**, not real properties. - Code: [MIT](./LICENSE). ## How it is built -A single Next.js app on Vercel — **no backend, no database, no API keys, no login**. [MapLibre GL JS](https://maplibre.org/) renders [OpenFreeMap](https://openfreemap.org/) vector tiles; [Turf.js](https://turfjs.org/) runs every spatial query in the browser; [Zustand](https://zustand.docs.pmnd.rs/) holds map state. Tools in `src/lib/map-tools/` talk to the map only through a `MapToolStore` interface, so they are unit-tested against an in-memory store. `src/lib/webmcp/register.ts` registers on both `document.modelContext` and `navigator.modelContext`, cancellable via `AbortSignal`. The one external service is `plan_route`, which asks the keyless FOSSGIS OSRM instance for walking routes, throttled to its 1 request/second policy, and answers with an honest error (map unchanged) when it is unreachable. +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. ```bash pnpm install @@ -121,4 +121,4 @@ pnpm test:e2e # Playwright, via document.modelContext pnpm build ``` -CI runs the same commands plus Playwright on every PR: 1,436 unit tests across 60 files, all green. Requires Node 22+. Branching, worktrees, commit and PR conventions: [CONTRIBUTING.md](./CONTRIBUTING.md). +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). diff --git a/docs/TASKS.md b/docs/TASKS.md index 5357487..88279f8 100644 --- a/docs/TASKS.md +++ b/docs/TASKS.md @@ -136,6 +136,30 @@ Reproduced on production: `set_map_view({ place: "Daan Station" })` as the very |---|---|---|---|---| | 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-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 + +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-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-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 + +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-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-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: 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. + +| 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 | + ## Follow-ups (ticketed, unscheduled) - **F-1 (qa)** `awakening.spec.ts:672` — the flake family's last site: `stateAfterWaking` returns ~600ms into the story, then two Node-side locator assertions race the remaining ~1200ms of the `disabled` window; fold the reads into the same in-page tick. Pre-existing; deterministic-failure mode once the story lands. diff --git a/docs/details.md b/docs/details.md index e2f57aa..a74608c 100644 --- a/docs/details.md +++ b/docs/details.md @@ -8,7 +8,7 @@ Behaviour the README summarises, spelled out. ## `select_features` 500-match cap -`select_features` still highlights every match a filter finds, its contract since the tool shipped — but once a point-of-interest category is involved, a filter matching more than 500 of them is refused rather than lighting up half the city: the answer gives the true count and asks for `near`+`radius_m`, `within` or `query` to narrow it. The six bundled categories are exempt from that cap. +`select_features` highlights every match a filter finds — but once a point-of-interest category is involved, a filter matching more than 500 of them is refused rather than lighting up half the city: the answer gives the true count and asks for `near`+`radius_m`, `within` or `query` to narrow it. The six bundled categories are exempt from that cap. ## `get_share_link` versioning (v1/v2/v3) diff --git a/scripts/media/lib.mjs b/scripts/media/lib.mjs new file mode 100644 index 0000000..72d5598 --- /dev/null +++ b/scripts/media/lib.mjs @@ -0,0 +1,163 @@ +/** + * Shared recording helpers for the two README clips: a headless Chromium with + * software WebGL, a caption box and visible cursor injected into the page, CDP + * screencast capture, and a GIF encoder (gifenc + jpeg-js). Playwright comes + * from the repo's own install; run `npm install` in this folder for the rest. + */ +import { chromium } from "../../node_modules/@playwright/test/index.mjs"; +import gifenc from "gifenc"; +const { GIFEncoder, quantize, applyPalette } = gifenc; +import jpeg from "jpeg-js"; +import fs from "node:fs"; + +export const W = Number(process.env.REC_W ?? 960), H = Number(process.env.REC_H ?? 600); + +export async function launch() { + const browser = await chromium.launch({ args: ["--use-gl=angle", "--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--ignore-gpu-blocklist", "--force-device-scale-factor=1"] }); + const page = await browser.newPage({ viewport: { width: W, height: H }, deviceScaleFactor: 1 }); + return { browser, page }; +} + +export async function openReady(page, url) { + await page.goto(url); + await page.waitForFunction(() => !!window.__glassmap); + await page.waitForFunction(() => document.querySelector('[data-testid="feature-count"]')?.textContent === "2063"); + await page.waitForFunction(() => document.querySelector('[data-testid="map-status"]')?.textContent === "ready", null, { timeout: 30000 }); + await page.waitForTimeout(2500); +} + +/** Caption box + fake cursor + shutter flash, injected once. Recording-only overlay. */ +export async function installOverlay(page) { + await page.evaluate(() => { + const css = document.createElement("style"); + css.textContent = ` + #rec-cap{position:fixed;left:14px;bottom:14px;z-index:99999;max-width:372px;padding:10px 14px;border-radius:12px; + background:rgba(18,20,24,.92);color:#f3f4f6;font:500 15px/1.35 -apple-system,Inter,system-ui,sans-serif; + box-shadow:0 6px 24px rgba(0,0,0,.35);pointer-events:none;border:1px solid rgba(255,255,255,.08)} + #rec-cap .k{display:block;font:700 11px/1 ui-monospace,Menlo,monospace;letter-spacing:.08em;text-transform:uppercase;margin-bottom:6px;opacity:.85} + #rec-cap .k.shot{color:#fb7185}#rec-cap .k.mcp{color:#2dd4bf} + #rec-cap code{font:500 14px/1.4 ui-monospace,Menlo,monospace;color:#a5f3fc;white-space:pre-wrap;word-break:break-word} + #rec-cap .r{display:block;margin-top:5px;color:#cbd5e1;font-size:14px} + #rec-cur{position:fixed;z-index:100000;width:22px;height:22px;pointer-events:none;transform:translate(-3px,-2px); + filter:drop-shadow(0 1px 2px rgba(0,0,0,.6));display:none} + #rec-flash{position:fixed;inset:0;z-index:99998;opacity:0;pointer-events:none;transition:opacity .1s;box-shadow:inset 0 0 0 6px #fb7185} + .rec-ripple{position:fixed;z-index:99999;width:12px;height:12px;margin:-6px 0 0 -6px;border-radius:50%;border:2px solid #fb7185; + pointer-events:none;animation:rec-rip .5s ease-out forwards} + @keyframes rec-rip{from{transform:scale(1);opacity:.9}to{transform:scale(4);opacity:0}} + `; + document.head.appendChild(css); + const cap = document.createElement("div"); cap.id = "rec-cap"; cap.style.display = "none"; document.body.appendChild(cap); + const flash = document.createElement("div"); flash.id = "rec-flash"; document.body.appendChild(flash); + const cur = document.createElement("div"); cur.id = "rec-cur"; + cur.innerHTML = ''; + document.body.appendChild(cur); + window.addEventListener("mousemove", (e) => { cur.style.display = "block"; cur.style.left = e.clientX + "px"; cur.style.top = e.clientY + "px"; }, true); + window.__recRipple = (x, y) => { const d = document.createElement("div"); d.className = "rec-ripple"; d.style.left = x + "px"; d.style.top = y + "px"; document.body.appendChild(d); setTimeout(() => d.remove(), 600); }; + }); +} + +export async function caption(page, kind, head, body, result) { + await page.evaluate(([kind, head, body, result]) => { + const cap = document.getElementById("rec-cap"); + cap.style.display = "block"; + cap.innerHTML = `${head}` + (body ? `${body}` : "") + (result ? `${result}` : ""); + }, [kind, head, body ?? "", result ?? ""]); +} + +export async function shutter(page) { + // A thin inset frame, not a full-screen flash: a full-frame change costs ~250 KB in the GIF. + await page.evaluate(() => { const f = document.getElementById("rec-flash"); f.style.opacity = "1"; setTimeout(() => (f.style.opacity = "0"), 220); }); + await page.waitForTimeout(340); +} + +/** Move the (visible) cursor there over `ms`, click with a ripple. */ +export async function clickAt(page, x, y, { ms = 450, ripple = true } = {}) { + await page.mouse.move(x, y, { steps: Math.max(6, Math.round(ms / 30)) }); + await page.waitForTimeout(120); + if (ripple) await page.evaluate(([x, y]) => window.__recRipple(x, y), [x, y]); + await page.mouse.click(x, y); +} + +export function startScreencast(page) { + const frames = []; + let cdp; + const t0 = Date.now(); + const start = async () => { + cdp = await page.context().newCDPSession(page); + cdp.on("Page.screencastFrame", async ({ data, sessionId }) => { + frames.push({ t: Date.now() - t0, jpg: Buffer.from(data, "base64") }); + try { await cdp.send("Page.screencastFrameAck", { sessionId }); } catch {} + }); + await cdp.send("Page.startScreencast", { format: "jpeg", quality: 82, maxWidth: W, maxHeight: H, everyNthFrame: 1 }); + }; + const stop = async () => { try { await cdp.send("Page.stopScreencast"); } catch {} return { frames, total: Date.now() - t0 }; }; + return { start, stop }; +} + +/** Resample to fixed fps, encode with a global palette + inter-frame transparency. */ +export function encodeGif({ frames, total }, outPath, { fps = 5, holdLast = 1500, colors = 255, dump = 0, tol = 30 } = {}) { + const step = 1000 / fps; + const picked = []; + let fi = 0; + for (let t = 0; t <= total; t += step) { + while (fi + 1 < frames.length && frames[fi + 1].t <= t) fi++; + if (frames[fi] && frames[fi].t <= t) picked.push(frames[fi]); + } + // collapse identical consecutive frames into longer delays + const runs = []; + for (const f of picked) { + const last = runs[runs.length - 1]; + if (last && last.jpg.equals(f.jpg)) last.delay += step; else runs.push({ jpg: f.jpg, delay: step }); + } + runs[runs.length - 1].delay += holdLast; + console.log(`frames captured ${frames.length}, ticks ${picked.length}, unique ${runs.length}, ${Math.round(total / 1000)}s`); + if (dump) { fs.mkdirSync(outPath + ".frames", { recursive: true }); runs.forEach((r, i) => { if (i % dump === 0) fs.writeFileSync(`${outPath}.frames/${String(i).padStart(3, "0")}.jpg`, r.jpg); }); } + const decoded = runs.map((r) => jpeg.decode(r.jpg, { useTArray: true, formatAsRGBA: true })); + const w = decoded[0].width, h = decoded[0].height; + // global palette from a sample of frames + const sampleEvery = Math.max(1, Math.floor(decoded.length / 12)); + const samples = decoded.filter((_, i) => i % sampleEvery === 0); + const px = 6; + const chunks = samples.map((d) => { const out = new Uint8Array(Math.ceil(d.data.length / (4 * px)) * 4); let o = 0; for (let i = 0; i < d.data.length; i += 4 * px) { out[o++] = d.data[i]; out[o++] = d.data[i + 1]; out[o++] = d.data[i + 2]; out[o++] = 255; } return out; }); + const all = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0)); let off = 0; for (const c of chunks) { all.set(c, off); off += c.length; } + const palette = quantize(all, colors, { format: "rgb444" }); + const TRANSPARENT = 255; + while (palette.length < 256) palette.push([0, 0, 0]); + const gif = GIFEncoder(); + // Noise-tolerant differencing against what the viewer currently sees (the composited + // frame), so JPEG jitter does not re-emit pixels; `tol` is a summed |dR|+|dG|+|dB|. + let shown = null; + decoded.forEach((d, i) => { + const idx = applyPalette(d.data, palette, "rgb444"); + let out = idx; + if (!shown) { + // `shown` holds the SOURCE rgb of the last emitted pixel, so the comparison is + // jitter-vs-jitter and never confuses quantisation error with real change. + shown = new Uint8Array(idx.length * 3); + for (let p = 0; p < idx.length; p++) { const q = p * 4; shown[p * 3] = d.data[q]; shown[p * 3 + 1] = d.data[q + 1]; shown[p * 3 + 2] = d.data[q + 2]; } + } else { + out = new Uint8Array(idx.length); + for (let p = 0; p < idx.length; p++) { + const q = p * 4, s3 = p * 3; + const dist = Math.abs(d.data[q] - shown[s3]) + Math.abs(d.data[q + 1] - shown[s3 + 1]) + Math.abs(d.data[q + 2] - shown[s3 + 2]); + if (dist <= tol) { out[p] = TRANSPARENT; continue; } + out[p] = idx[p]; + shown[s3] = d.data[q]; shown[s3 + 1] = d.data[q + 1]; shown[s3 + 2] = d.data[q + 2]; + } + } + gif.writeFrame(out, w, h, { palette: i === 0 ? palette : undefined, first: i === 0, repeat: 0, delay: Math.round(runs[i].delay), transparent: i > 0, transparentIndex: TRANSPARENT, dispose: 1 }); + }); + gif.finish(); + const bytes = gif.bytes(); + fs.writeFileSync(outPath, bytes); + console.log(`${outPath}: ${(bytes.length / 1024 / 1024).toFixed(2)} MB, ${w}x${h}`); +} + +/** Persist captured frames so encodings can be retried without re-recording. */ +export function saveRaw({ frames, total }, path) { + fs.writeFileSync(path, JSON.stringify({ total, frames: frames.map((f) => ({ t: f.t, jpg: f.jpg.toString("base64") })) })); +} +export function loadRaw(path) { + const { total, frames } = JSON.parse(fs.readFileSync(path, "utf8")); + return { total, frames: frames.map((f) => ({ t: f.t, jpg: Buffer.from(f.jpg, "base64") })) }; +} diff --git a/scripts/media/package.json b/scripts/media/package.json new file mode 100644 index 0000000..55636f8 --- /dev/null +++ b/scripts/media/package.json @@ -0,0 +1,10 @@ +{ + "name": "glassmap-media", + "private": true, + "type": "module", + "description": "Replays that record the two README clips (docs/media/*.gif). Run `npm install` here, then see the header of each script.", + "dependencies": { + "gifenc": "^1.0.3", + "jpeg-js": "^0.4.4" + } +} diff --git a/scripts/media/s1-screenshot-agent.mjs b/scripts/media/s1-screenshot-agent.mjs new file mode 100644 index 0000000..597db03 --- /dev/null +++ b/scripts/media/s1-screenshot-agent.mjs @@ -0,0 +1,93 @@ +/** + * The README's screenshot-agent clip (docs/media/screenshot-agent.gif). + * + * Replays, in Playwright's headless Chromium, what an agent with no tools can + * do on the page: a search box, clicks, keys, the mouse wheel and screenshots. + * Every `act` is one UI action and every `snap` one screenshot, so the counter + * in the caption is the count the README quotes. No WebMCP surface is opened: + * the URL carries no `?shim=1`. + * + * pnpm build && pnpm start -p 3200 # in the repo root + * npm install # in scripts/media, once + * node s1-screenshot-agent.mjs http://localhost:3200/ out.gif + */ +import { launch, openReady, installOverlay, caption, shutter, clickAt, startScreencast, encodeGif, saveRaw, W, H } from "./lib.mjs"; + +const URL = process.argv[2] ?? "http://localhost:3200/"; +const { browser, page } = await launch(); +await openReady(page, URL); +await installOverlay(page); + +let actions = 0, shots = 0; +const K = "shot"; +const head = () => `Screenshot agent · no tools · ${actions} action${actions === 1 ? "" : "s"} · ${shots} screenshot${shots === 1 ? "" : "s"}`; +const say = (body, result) => caption(page, K, head(), body, result); +const snap = async (why) => { shots++; await say(why ?? "", ""); await shutter(page); }; +const act = async (label, fn) => { actions++; await say(label); await fn(); }; + +const rec = startScreencast(page); +await rec.start(); +await caption(page, K, "Screenshot agent · no tools", "“Show every park within a 10-minute walk of Daan Station.”", "Only what a generic browser agent has: screenshots, clicks, keys."); +await page.waitForTimeout(2600); + +await snap("Screenshot → a citywide map. Where is Daan Station? Nothing here is readable as data."); +await page.waitForTimeout(1400); + +await act("Click the search box", () => clickAt(page, 160, 80)); +await act("Type “Daan Station”", async () => { await page.keyboard.type("Daan Station", { delay: 70 }); await page.waitForTimeout(900); }); +await snap("Screenshot → “Nothing in Taipei matches that.” Try a shorter query."); +await page.waitForTimeout(600); +await act("Backspace ×8 → “Daan”", async () => { for (let i = 0; i < 8; i++) { await page.keyboard.press("Backspace"); await page.waitForTimeout(60); } await page.waitForTimeout(900); }); +await snap("Screenshot → 8 rows, two of them “MRT”. Which is the station? Reading small text off pixels."); +await page.waitForTimeout(900); +const row = page.getByTestId("search-result").nth(4); +const box = await row.boundingBox(); +await act("Click the 5th row — “大安 Daan · MRT”", () => clickAt(page, box.x + 60, box.y + box.height / 2)); +await page.waitForTimeout(3800); + +await snap("Screenshot → arrived, but 800 m around the station does not fit on screen at this zoom."); +await page.waitForTimeout(1600); +await act("Scroll out ×6 — how far is 800 m now? No scale bar to read. Guessing…", async () => { + await page.mouse.move(W / 2, H / 2, { steps: 8 }); + for (let i = 0; i < 6; i++) { await page.mouse.wheel(0, 100); await page.waitForTimeout(90); } + await page.waitForTimeout(1200); +}); +await snap("Screenshot → about this big? Pixel math without a scale bar is a guess."); +await page.waitForTimeout(1200); + +// Hand-drawn "circle": an octagon around the station. 185 px at the zoom the wheel +// landed on (~z14.1) is ~755 m - a guess 5% short of the 800 m asked for. +const zoomNow = Number(await page.getByTestId("zoom").textContent()); +const scale = 2 ** (zoomNow - 15); // px at this zoom per px at z15 (parks.mjs projected at z15) +const cx = W / 2, cy = H / 2, r = 185; +const drawBtn = await page.getByTestId("draw-toggle").boundingBox(); +await act("Click “Draw”", () => clickAt(page, drawBtn.x + drawBtn.width / 2, drawBtn.y + drawBtn.height / 2)); +await page.waitForTimeout(500); +for (let k = 0; k < 8; k++) { + const a = (k / 8) * Math.PI * 2 - Math.PI / 2; + const x = Math.round(cx + r * Math.cos(a)), y = Math.round(cy + r * Math.sin(a)); + await act(`Click vertex ${k + 1} of 8 — a polygon is the only shape a click can make`, () => clickAt(page, x, y, { ms: 320 })); + await page.waitForTimeout(140); +} +await act("Press Enter to close the shape", async () => { await page.keyboard.press("Enter"); await page.waitForTimeout(700); }); +await snap("Screenshot → an octagon, not a circle, and the radius is a guess. Now: which green shapes inside are parks?"); +await page.waitForTimeout(1800); + +// Read park names one tap card at a time (positions of two parks inside the octagon). +// Projected at z15 for a 960x600 viewport centred on the station (see parks.mjs). +const parks = [[cx - 58 * scale, cy - 158 * scale, "附中公園"], [cx + 83 * scale, cy + 139 * scale, "四維公園"]].map(([x, y, n]) => [Math.round(x), Math.round(y), n]); +console.log("zoom", zoomNow, "parks px", parks); +for (const [x, y] of parks) { + await act("Click a green shape to see if a card opens", () => clickAt(page, x, y, { ms: 600 })); + await page.waitForTimeout(900); + await snap("Screenshot → read the card. One name learned."); + await page.waitForTimeout(700); + await act("Press Esc to close the card", async () => { await page.keyboard.press("Escape"); await page.waitForTimeout(400); }); +} +await say("Stopping here.", `Result: 2 park names after ${actions} actions and ${shots} screenshots — the walk radius is a guess, the “circle” is an octagon, and 5 of the 7 parks inside 800 m were never found.`); +await page.waitForTimeout(4200); + +const data = await rec.stop(); +await browser.close(); +saveRaw(data, "s1.raw.json"); +encodeGif(data, process.argv[3] ?? "s1-screenshot-agent.gif", { fps: 5, tol: 36, dump: 6 }); diff --git a/scripts/media/s2-webmcp.mjs b/scripts/media/s2-webmcp.mjs new file mode 100644 index 0000000..431783e --- /dev/null +++ b/scripts/media/s2-webmcp.mjs @@ -0,0 +1,74 @@ +/** + * The README's WebMCP-agent clip (docs/media/webmcp-agent.gif). + * + * Replays the same ask through the page's tools: every call goes through + * `document.modelContext.getTools()` → `executeTool()`, and the caption counts + * calls, bytes returned and tool time as measured in the page. Headless + * Chromium has no WebMCP of its own, so the URL carries `?shim=1`; the tool + * code and its output are the ones a native surface runs. + * + * pnpm build && pnpm start -p 3205 # in the repo root + * npm install # in scripts/media, once + * node s2-webmcp.mjs "http://localhost:3205/?shim=1" out.gif + */ +import { launch, openReady, installOverlay, caption, startScreencast, encodeGif, saveRaw } from "./lib.mjs"; + +const URL = process.argv[2] ?? "http://localhost:3205/?shim=1"; +const { browser, page } = await launch(); +await openReady(page, URL); +await installOverlay(page); + +// Every call goes through the WebMCP surface itself: document.modelContext.getTools() → executeTool(). +const mcp = (name, input) => page.evaluate(async ([n, a]) => { + const tools = await document.modelContext.getTools(); + const t = tools.find((x) => x.name === n); + const t0 = performance.now(); + const out = await document.modelContext.executeTool(t, a); + return { out: JSON.parse(out), ms: Math.round(performance.now() - t0), bytes: new TextEncoder().encode(out).length }; +}, [name, input]); + +let calls = 0, bytes = 0, ms = 0; +const K = "mcp"; +const head = () => `WebMCP agent · document.modelContext · ${calls} call${calls === 1 ? "" : "s"} · 0 screenshots`; +const esc = (s) => s.replace(/&/g, "&").replace(/ `${name}(${JSON.stringify(input, null, 1).replace(/\n\s*/g, " ").replace(/^\{ /, "{ ").replace(/ \}$/, " }")})`; +const call = async (name, input, summarize, { think = 1100, hold = 2600, show } = {}) => { + const code = esc(show ?? fmt(name, input)); + await caption(page, K, head(), code, ""); + await page.waitForTimeout(think); + const r = await mcp(name, input); + calls++; bytes += r.bytes; ms += r.ms; + await caption(page, K, head(), code, `→ ${esc(summarize(r.out))} · ${r.bytes} B · ${r.ms} ms`); + await page.waitForTimeout(hold); + return r.out; +}; + +const rec = startScreencast(page); +await rec.start(); +await caption(page, K, "WebMCP agent · document.modelContext", "“Show every park within a 10-minute walk of Daan Station.”", "Same page, same question. The agent reads and writes the map through its tools."); +await page.waitForTimeout(2600); + +await call("set_map_view", { place: "Daan Station" }, + (o) => `found · centre ${o.center.lng}, ${o.center.lat} · zoom ${o.zoom}`, { hold: 3400 }); + +await call("draw_shape", { type: "circle", center: "Daan Station", radius_m: 800, label: "10-minute walk" }, + (o) => `${o.drawing_id} · a true circle, ${(o.area_m2 / 1e6).toFixed(2)} km²`); + +await call("set_map_view", { fit: "drawing:1" }, + (o) => `framed the circle · zoom ${o.zoom.toFixed(1)}`, { hold: 3000 }); + +const f = await call("find_features", { near: "Daan Station", radius_m: 800, categories: ["park"] }, + (o) => `${o.total} parks, nearest first: ${o.features.slice(0, 3).map((x) => `${x.name} ${x.distance_m} m ${x.direction}`).join(", ")}, …`, { hold: 3600 }); + +const ids = f.features.map((x) => x.id); +await call("select_features", { ids }, + (o) => `${o.selection?.count ?? o.state?.selection?.count ?? "?"} selected — highlighted for the human on the map and in the panel`, + { hold: 3200, show: `select_features({ "ids": [ "${ids[0]}", … ${ids.length} ids from find_features ] })` }); + +await caption(page, K, head(), "Done.", `Result: all ${f.total} parks inside an exact 800 m circle, each with an id, a distance and a direction — two of them OpenStreetMap never named — ${calls} calls, ${(bytes / 1024).toFixed(1)} KB returned, ${ms} ms of tool time, 0 screenshots.`); +await page.waitForTimeout(4200); + +const data = await rec.stop(); +await browser.close(); +saveRaw(data, "s2.raw.json"); +encodeGif(data, process.argv[3] ?? "s2-webmcp.gif", { fps: 5, tol: 36, dump: 6 });