The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.
JavaScript
Imagery: Sentinel-2, Google Maps JS (EEA), capture extension, panorama stitch modes (#13)
OsintMeThat62d60e6d4069
diff --git a/README.md b/README.mdindex 7d62733..56bdf04 100644--- a/README.md+++ b/README.md@@ -65,6 +65,16 @@ Frontend development (hot reload, proxied API):cd frontend && npm run dev # UI on :5173```+### Capture extension (optional)++A small browser extension (Chrome/Edge + Firefox) files the map you are+looking at straight into a case: external map sites (Google Maps & Earth,+Bing, Yandex, OSM, Apple Maps, Zoom Earth, Satellites.pro — one screenshot+per click, coordinates parsed from the URL), and it is also what powers the+Capture button on the Google (Maps JS) basemap. Install it from **Settings →+Capture extension** (download the zip, load unpacked, pair with the token+shown there) — full instructions in [extension/README.md](extension/README.md).+## Building & releasingThe Svelte frontend builds into `src/azimut/static/` (git-ignored) and isdiff --git a/docs/IMAGERY_PROVIDERS.md b/docs/IMAGERY_PROVIDERS.mdindex e60f8c3..c386297 100644--- a/docs/IMAGERY_PROVIDERS.md+++ b/docs/IMAGERY_PROVIDERS.md@@ -1,6 +1,6 @@-# Keyed imagery providers — Mapbox & Google+# Keyed imagery providers — Mapbox, Google (tiles & Maps JS) & Sentinel Hub-> Azimut ships two optional user-keyed basemaps alongside the key-less defaults+> Azimut ships optional user-keyed basemaps alongside the key-less defaults> (Esri, OSM, OpenTopoMap). The rules below are why their code looks the way it does — they come> from Google's and Mapbox's terms, not from taste. Read alongside SPEC.md §6> "v1 notes → Tile providers" (legal-only policy).@@ -30,6 +30,8 @@| OpenTopoMap | no | — | yes | yes | static string (CC-BY-SA² ) || **Mapbox Satellite** | yes | access token in URL | yes | yes¹ | `© Mapbox © OpenStreetMap` (+ Maxar) || **Google Satellite** | yes | **session token** | yes (flattened+attributed only) | **NO** | dynamic copyright from viewport endpoint |+| **Google Satellite (Maps JS)** | yes | key in script URL⁴ | screen crops only (user-initiated grab, attribution burned) | n/a (widget) | `Map data © Google` + the widget's own credits |+| **Sentinel-2 (Sentinel Hub)** | yes | instance ID in URL³ | yes | yes | `© Copernicus Sentinel data {year}` |¹ Display + static-image capture with attribution is permitted; plan-levelcaching/redistribution limits vary, so the cache stays modest (30-day TTL) and@@ -44,6 +46,237 @@ zooms with a constant "max zoom layer = 17" placard — registered in`PLACEHOLDER_TILE_SHA256`, and the live map caps its zoom at the provider maxso it is never requested. Verified 2026-07.+³ Open data (Copernicus free/full/open licence) — the licence asks only for+attribution, so no capture or cache restriction. The constraint is quota, not law.+The instance ID is the **whole credential**: OGC needs no OAuth token on top of it+(verified 2026-07 — a wrong id answers `400 Invalid instance id`, never a 401). It+is still the user's quota identity, so it lives in `api_keys` like any other key.++⁴ A Maps JS key is client-side **by design** (referrer-restricted, not secret), so+shipping it to the browser in the loader URL is the intended use — unlike every+tile key, which stays server-side behind the proxy.++## Google in the EEA (2025-07-08) — why there are two Google entries++Google stopped serving **satellite tiles** (Map Tiles API *and* Static Maps API)+to projects with an **EEA billing address**: 403 `PERMISSION_DENIED` with the+explanation in the error body ([Map Tiles notice](https://developers.google.com/maps/comms/eea/map-tiles),+[Static notice](https://developers.google.com/maps/comms/eea/maps-static) — a+Bundeskartellamt outcome, not a bug). Applies to projects created after that date+or that later left "Unmodified State". Non-EEA accounts keep the tile pipeline.++The one official Google satellite route left in the EEA is the **Maps JavaScript+API widget** — so Azimut ships both:++| | Google Satellite (tiles) | Google Satellite (Maps JS) |+|---|---|---|+| Works in the EEA | **no** (403) | yes |+| Rendering | XYZ tiles through our proxy | a real `google.maps.Map` under Leaflet (GoogleMutant plugin, Beerware licence) |+| Captures | stitched crop, attribution burned | **screen pixels only** — same Capture button, modes and frame; the crop comes from one tab screenshot taken by the **capture extension** (Settings → Capture extension; the button gates on it). Attribution burned, `method:"screenshot"` + `framed:true` |+| Capture frame | any size (tiles are fetched) | can't exceed the map view — screen pixels are the ceiling, so no resolution multiplier |+| Rotation / oversample / marquee | yes | **rotation + marquee yes**, oversample no |+| Meter | tiles | **map loads** (~10k free/month) — the widget layer is created once per *page life* and reused across tab and basemap switches, since every instantiation bills a load; this is also why eco mode is pinned off for it. Reloading the app is therefore a real +1, which is why the counter climbs while developing |+| Key test | `createSession` server-side | in-browser only (`gm_authFailure`), from Settings; a *changed* key needs an app reload — Google's script binds one key per page life. **Costs a map load** and reports it to the meter (a rejected key is free) |++Both keys can be saved at once: each lights its own basemap, and the EEA failure+path benches the tiles one automatically (below) leaving the widget on offer.+Leaflet keeps all interaction, so measure tools, places, reference windows and+the labels overlay work unchanged over the widget.++### The widget is a normal basemap, with one seam++GoogleMutant runs a **hidden** `google.maps.Map` and clones its `<img>` tiles into+an ordinary Leaflet `GridLayer`. Two consequences worth knowing:++- **Rotation works.** The visible tiles are Leaflet tiles in the rotatable tile+ pane, and leaflet-rotate already asks the grid for the rotated bounding box.+ The only catch is coverage: the hidden map renders the *unrotated* viewport, so+ a turned view wants corner tiles that were never rendered — blank corners.+ `lib/gmaps.js` sizes the hidden map to a **square of the container's diagonal,+ centred**, which covers every bearing at once. Extra tile renders inside one+ map load are free; the billing is per `google.maps.Map`.+- **Those cloned tiles are still off-limits.** Reading them back (canvas,+ html2canvas, refetching the URLs) is exactly the programmatic extraction+ Google's terms forbid — the fact that they sit in our DOM changes nothing. The+ capture path therefore goes through the **capture extension** (`extension/`,+ installed from Settings): one `tabs.captureVisibleTab` behind the user's+ click — the browser-blessed tab screenshot. No share prompt, no sharing bar,+ and fullscreen survives, which the earlier `getDisplayMedia` route broke+ (the share prompt drops fullscreen and relayouts the map under a+ just-measured frame). Without the extension the Capture button explains and+ points at Settings — never a half-working fallback.++What the screen-pixel route still forces, whatever supplies the frame:++| Trap | Rule |+|---|---|+| The tab frame is the **whole viewport** — our HUD, control clusters and reference windows paint *over* the map and would land in the crop | `.map-wrap.grabbing` hides our chrome for the grab (`:global`, or the reference windows — a child component — slip through scoped CSS). The marker stays: the tile path burns one in, so a screen crop keeps its own |+| A frame can silently be the **wrong surface** (browser zoom changed mid-flight, a stale frame from before a resize) and the crop math is one scale factor — it would crop real pixels off the wrong place and look fine doing it | Check registration (`lib/screenCrop.js isRegistered`, viewport aspect) on **every frame** before cropping; refuse on mismatch |+| `captureVisibleTab` needs **activeTab or `<all_urls>`** — host permissions are NOT enough (verified: both browsers refuse), so a page-initiated capture fails on a fresh tab | One extension click (icon or `Alt+Shift+A`) grants activeTab **for the tab's whole life** (the app is an SPA — no navigation, so once per session). The app turns the refusal into a "click the icon once" toast, and the popup pings back so the app can say "press Capture again". Never `<all_urls>` |++**Provenance:** `framed` says what the coordinates mean. `true` — the crop was+taken through the capture frame, so lat/lon is the crop centre. `false` — a+pasted/dropped image, so lat/lon is only the map view when it was filed.++**A failed capture is never downgraded into an import.** A frame that can't be+registered is refused with an error and nothing is filed — the paste dialog is a+deliberate choice from the capture menu, never an escape hatch offered after a+failure. Quietly proposing to file *some other image* instead is how an+unregistered picture ends up wearing a capture's provenance.++### The capture extension (`extension/`, api/ingest.py)++One MV3 extension (Chrome/Edge + Firefox), two flows:++| | Azimut's Maps JS basemap | External map sites |+|---|---|---|+| Trigger | the app's own Capture button (bridge content script relays) | toolbar click / `Alt+Shift+A` → popup → drag an area |+| Sites | localhost only | Google Maps/Earth, Bing, Yandex, OSM, Apple Maps, Zoom Earth, Satellites.pro, Copernicus Browser — **refuses non-map sites**, enforced by the endpoint too |+| Metadata | the app's own view (registered crop, `framed:true`) | parsed from the page **URL only**, never the DOM — coordinates, zoom, bearing, place name (→ title), imagery date where the URL carries one (Copernicus `toTime`, Zoom Earth `/date=`); correctable in the popup; may be empty |+| Filing | the app files same-origin — no pairing | `POST /api/ingest/screenshot`, gated by a **pairing token** (Settings → copy, extension options → paste) + CORS open to extension origins only; an SSE nudge (`/api/events`) makes the capture appear in any open app tab without a reload |+| Attribution | burned by the app | burned server-side per site (`api/ingest.py ATTRIBUTIONS`), source URL + site + timestamp always in provenance |++**The extension is deliberately dumb** (owner decision, same logic as the+unbounded yt-dlp ranges): it screenshots and sends the URL, and every URL+format rule lives in `engine/mapsites.py` — the popup's prefill is+`GET /api/ingest/parse`, and the POST re-derives site/attribution/metadata+from the URL itself, trusting the client for nothing but its own corrections.+URL formats race sites that change without notice, and the extension is the+one component that can't be updated remotely (loaded unpacked, no store) —+so a changed format must cost an app update, never a hand reinstall on every+machine. Don't add site knowledge to the extension.++Legal rails, encoded in both the extension and the endpoint: one screenshot per+explicit user action (nothing schedulable), URL-only metadata, on-screen+credits ride along inside the pixels, attribution burned on top.++## Dead keys bench their basemap++`settings.json → provider_status` holds each credential's last verdict. Written+by: the Settings key test (every provider), a `createSession` refusal or a tile+401/403 that survives the re-mint retry (with Google's own sentence as the+reason), and the browser's `gm_authFailure` for the JS key. **Never** by plain+network errors — a timeout says nothing about the key. A key marked bad is+withheld from `all_providers()`, so the basemap vanishes from the selector (the+live map falls back to Esri) until the key changes (verdict cleared) or a test+passes. Settings shows the stored reason inline.++## Per-provider eco thresholds++`eco_max_zooms` in settings.json lets each tile basemap carry its own eco+threshold (blank = provider default, else the global one; 0 = eco off for it).+Needed because one global value can't fit both a z22 basemap and Sentinel-2's+z14 ceiling — and the JS widget is excluded entirely (a swap re-bills a load).++## Sentinel-2 is a dated mosaic, not a basemap++Use the **OGC WMTS** endpoint — not Catalog (STAC metadata only, no pixels) and not+the Process API (POST + evalscript; buys band math, fits nothing in the XYZ+pipeline — deferred with Satellite Compare).++```+https://sh.dataspace.copernicus.eu/ogc/wmts/{key}?SERVICE=WMTS&REQUEST=GetTile+ &VERSION=1.0.0&LAYER=TRUE_COLOR&TILEMATRIXSET=PopularWebMercator512+ &TILEMATRIX={z}&TILECOL={x}&TILEROW={y}&FORMAT=image/jpeg+```++`{key}` is a **configuration instance** UUID (Dashboard → Configuration Utility),+built from the **Simple Sentinel-2 L2A template** — that template is what makes+`TRUE_COLOR` exist. L2A (bottom-of-atmosphere) over L1C: corrected colour, and the+120 m mosaic / 20 m Europe-only templates are too coarse or too regional to be a+basemap at all. **"Show logo" and "Show warnings" must be off in the instance** —+both are burned into every tile server-side, which would tile the map with+Copernicus logos and put one inside evidence captures.++`TIME` is a **mosaicking window**, so this layer is "mosaic over range X", not "the+imagery". Omitted, the layer's own default applies (the most recent pass).++**The layer and the window ride on the provider id** — `sentinel2~SWIR~2026-05-01~2026-05-31`+(`engine/sentinel.py`, mirrored in `frontend/src/lib/sentinel.js`). That is what+solves the cache trap this section used to warn about: the disk cache keys on+`provider.id`, so a window in the id *is* a window in the cache key and two dates+can never collide. It also means the tile proxy, `fetch_crop` and a capture's+provenance all inherit the choice for free — none of them can render from one+window and file under another. `tiles.get_provider()` parses the variant;+`parse_variant` is the validation boundary (the id becomes a URL path segment+*and* a cache directory, so the shape is an allowlist).++| Choice | UI | Notes |+|--------|----|-------|+| Layer | picker, populated from **GetCapabilities** on first open | `LAYERS` in `engine/sentinel.py` is a 4-entry *fallback*; the instance is the authority on what it serves — offering a layer it lacks just 400s on selection |+| Date | a **calendar**: only days with a real pass are selectable, coloured by cloud | one day, not a range — a range is a mosaic of several passes and can't be dated. Sent as `TIME=day/day` |++### Dates come from WFS, and cost one request++`GET /ogc/wfs/{instance}?TYPENAMES=DSS2&TIME=…&BBOX=…&OUTPUTFORMAT=application/json`+— same instance credential, no OAuth (Catalog would need one). `DSS2` is L2A: a+date list from L1C would be a plausible lie about a different collection.+`SRSNAME=EPSG:4326` puts **latitude first** in the BBOX.++Billed at **0.01 PU but one whole request**, so `record_usage` counts it as 1:+both quotas are 30k, the meter tracks requests exactly and over-states PU+slightly — the conservative direction. Hence the meter's unit is "request", not+"tile" (`meterUnit`).++**Granule footprints are checked against the point** (`_covers`). A granule's+bounding box is a square; its data is the slice of orbit swath inside it. WFS+answers on the box, so without the check a day gets listed, pinned, and renders+**black** — exactly the failure a date list exists to prevent. The footprint is+tested under both axis orders: read backwards, every granule on Earth would be+rejected.++**Its levels are numbered by resolution, not by grid width.** `TILEMATRIX=14` is+9.55 m/px on an 8192-wide grid — the same imagery Mapbox calls z13. Tile indices+stay at the repo's `tile_z` either way, so only the level's *name* differs:+`Provider.zoom_offset=1` re-adds what `z_shift` took off. Getting this wrong is not+subtle — the service answers `400 Invalid TILECOL`.++**Eco mode needs its own threshold here** (`Provider.eco_max_zoom=11`). The global+default (z15) is tuned for basemaps that run to z22; Sentinel-2's imagery stops at+z14, so sharing it would swap the layer away at most zooms it can serve. At z11 and out a+Sentinel-2 pixel is ~40 m of ground and Esri shows the same scene for free — the+swap costs a known date for an unknown one, which only pays where the resolution+adds nothing anyway.++| Limit | Value | Consequence |+|-------|-------|-------------|+| Native resolution | 10 m/px ≈ 9.55 m/px at `TILEMATRIX=14` | `max_native_zoom=14` — deeper is Sentinel Hub upsampling we'd pay full price for |+| Useful zoom | z18 | `max_zoom=18`, on **magnified native tiles** — see below |+| Free quota | **30 000 requests + 30 000 PU/month** (Copernicus General) | `meter="sentinelhub"`; per-account and **editable in Settings** — see below |+| Rate | 300 req/min, 300 PU/min | why tiles stay 512 |+| PU cost | 512×512, 3 bands, 8-bit = **exactly 1 PU** | one tile = 1 request = 1 PU, so the counter is faithful |++PU scales with **area**, so tile size is cost-neutral (1024 → 4 PU, 256 → 0.25 PU):+Google's big-tile trick buys nothing here. 512 wins on the requests/min limit alone.++### The view goes deeper than the pixels++`max_native_zoom` (14) and `max_zoom` (18) are different questions: where the+imagery *stops*, and where looking at it stops being useful. You cannot read a+ship at 10 m/px from three levels out, so the view runs to z18 while requests+stop at 14 and the last native tile is magnified — same pixels, larger, **zero+extra requests**. Asking Sentinel Hub for z18 would buy its upsampling of those+same pixels at 16× the tiles, every one billed: the identical image, paid for.++Leaflet's `maxNativeZoom` does it on the live map; `fetch_crop` mirrors it so a+capture matches the screen, and records `native_zoom` ++`native_meters_per_pixel` next to `zoom` — the image is real, its resolution is+not what the zoom implies, and a reader has to be able to tell. The tile proxy+refuses to fetch past the ceiling at all (`_native_grid_zoom`), for anything+that isn't the live map.++### Free tiers are facts about the account, not about us++Copernicus **documents 10 000** PU/month and **provisions 30 000** (observed+2026-07, `copernicus-general-quota`). So `config.FREE_TIER` is a *default*, and+`free_tiers` in settings.json overrides any meter (`config.free_tier()`,+editable per provider under Settings → Usage). A hardcoded number makes the+gauge and the 90% soft block lie about someone else's account — and the block+pausing a provider that is nowhere near its limit is a real failure, not a+cosmetic one.+[Quotas](https://documentation.dataspace.copernicus.eu/Quotas.html) ·+[PU definition](https://documentation.dataspace.copernicus.eu/APIs/SentinelHub/Overview/ProcessingUnit.html)+## Google is not a static `{key}` URLIt needs a session token, minted and refreshed transparently before the rest of thediff --git a/docs/SPEC.md b/docs/SPEC.mdindex 3d52700..463b8bc 100644--- a/docs/SPEC.md+++ b/docs/SPEC.md@@ -154,7 +154,7 @@ get media in, annotate the match, publish the proof.| Tab | What it does ||-----|--------------|| ✅ **Media Library** | The case's media shelf. Import local files (drag & drop) or download by URL (X, Telegram, TikTok, YouTube, … via yt-dlp, with a **gallery-dl fallback** for image-only posts yt-dlp's video-first extractors drop — photo tweets, direct image links, Instagram, Facebook photos; a small **Telegram photo scraper** additionally fills in photos on mixed video+photo albums, which yt-dlp's Telegram extractor silently ignores) → clean local file + metadata JSON + sha256, with a **Title** field auto-filled from the extracted title. A link with several attachments (e.g. a tweet with multiple photos/a video) opens a **picker** to choose which ones to fetch, each with its own editable Title before download; a single-item link downloads straight away as before. Every media becomes a `media` entity. A **facet bar** groups the shelf on the fly — auto **type/source facets** (Images, Videos, Collages, Imports, Downloads, Other, derived from `kind` + `source`) alongside the user's **virtual folders**. Items can be assigned a **virtual folder** (stored in sidecar) and annotated with **notes**; an info modal surfaces full provenance (source URL, title, uploader, duration) + editable notes + folder; images show a **lightbox** on click. |-| ✅ **Inspect** | A scratch workspace over any photo/video — **nothing enters the case until Save**. **Selection** (video): scrub, step, scan *sharpest* frames (**every** frame scored in one streamed pass, on a **contrast-invariant** focus measure so a soft-but-punchy frame can't outrank a sharp flat one; picks are spread across distinct moments), capture into a transient tray; a gear tunes the whole clip (brightness…) for an optional enhanced-video export. **Frame**: per-frame brightness/contrast/saturation/gamma/sharpness/grayscale/invert, a **view-only zoom/pan/rotate** viewer (never saved — middle-drag turns the image around the grabbed point, marked by a "target", Google-Earth style; composes over any prior zoom/pan/rotate), and an **editable crop** — draw or nudge its 8 handles, **aspect-lock presets + numeric px entry**, **Enter/Apply** commits to a cropped preview, re-open (button or **double-click**) to edit the original — with a fold-out **Analyze** (histogram, EXIF, ELA *hint*). **Collage**: **multiple collages per session** (tab strip to add/switch/delete). Per piece: drag, **round corner handles warp**, **square side handles uniform-scale** (composes with the warp, holds up on an already-warped piece), a **rotate knob** on a stem that **follows the piece**; a small top bar carries only the **ghost** preview + **±1 stacking**, while the right panel keeps precise scale/rotate (±/↺↻) and all-the-way **Front/Back**; **Delete** removes it. **Shift-click selects several pieces**: a dashed **block frame** then moves / corner-scales / rotates them as one rigid unit about the block's centre (right panel mirrors it with precise ±/↺↻ + bulk remove), a plain click collapses back to one, and **Delete** clears the block. **Per-piece crop** is the same editable box (handles, aspect lock, numeric) over the piece's snapshot, baked before the warp — the quad is re-projected to the crop so proportions stay correct and it stays in place. Tray frames (thumbnails show each frame's current adjustments) compose on a full-bleed scratch surface into a hand-made panorama. Each collage exports as a **transparent PNG of just its pieces, auto-trimmed to their bounds** — no manual canvas size. ✅ **Auto-stitch** solves the pieces' layout from the imagery itself (feature match → homography chain → a quad each) and drops them back as ordinary hand-tunable pieces — machine stitch first, hand-tune after; pieces it can't place are **left where they were, never guessed at**, and a coincidental match is refused rather than invented. **Save**: tick which of {enhanced video, adjusted frames, each collage} to file — each re-derived full-res on the backend with provenance back to its source, into an optional folder; every collage shows a **true-to-export composited miniature** (the real backend warp, on a transparency checker) in the picker. Frames captured from a tuned clip inherit its look; collage pieces are **frozen snapshots** taken when added. The whole workspace can be **saved as a reopenable session** (`inspect-session` entity, spec in `inspect/`) — reload it later from the sidebar with every frame/adjustment/collage (all of them) intact; re-saving a reopened session **overwrites it in place** (even after a rename). Adjust/analysis controls come from self-describing filter/analysis registries. |+| ✅ **Inspect** | A scratch workspace over any photo/video — **nothing enters the case until Save**. **Selection** (video): scrub, step, scan *sharpest* frames (**every** frame scored in one streamed pass, on a **contrast-invariant** focus measure so a soft-but-punchy frame can't outrank a sharp flat one; picks are spread across distinct moments), capture into a transient tray; a gear tunes the whole clip (brightness…) for an optional enhanced-video export. **Frame**: per-frame brightness/contrast/saturation/gamma/sharpness/grayscale/invert, a **view-only zoom/pan/rotate** viewer (never saved — middle-drag turns the image around the grabbed point, marked by a "target", Google-Earth style; composes over any prior zoom/pan/rotate), and an **editable crop** — draw or nudge its 8 handles, **aspect-lock presets + numeric px entry**, **Enter/Apply** commits to a cropped preview, re-open (button or **double-click**) to edit the original — with a fold-out **Analyze** (histogram, EXIF, ELA *hint*). **Collage**: **multiple collages per session** (tab strip to add/switch/delete). Per piece: drag, **round corner handles warp**, **square side handles uniform-scale** (composes with the warp, holds up on an already-warped piece), a **rotate knob** on a stem that **follows the piece**; a small top bar carries only the **ghost** preview + **±1 stacking**, while the right panel keeps precise scale/rotate (±/↺↻) and all-the-way **Front/Back**; **Delete** removes it. **Shift-click selects several pieces**: a dashed **block frame** then moves / corner-scales / rotates them as one rigid unit about the block's centre (right panel mirrors it with precise ±/↺↻ + bulk remove), a plain click collapses back to one, and **Delete** clears the block. **Per-piece crop** is the same editable box (handles, aspect lock, numeric) over the piece's snapshot, baked before the warp — the quad is re-projected to the crop so proportions stay correct and it stays in place. Tray frames (thumbnails show each frame's current adjustments) compose on a full-bleed scratch surface into a hand-made panorama. Each collage exports as a **transparent PNG of just its pieces, auto-trimmed to their bounds** — no manual canvas size. ✅ **Auto-stitch** solves the pieces' layout from the imagery itself and drops them back as ordinary pieces — machine stitch first, hand-tune after; a **mode** picks the projection (**Planar** quads, still corner-warpable, vs **Cylindrical**/**Spherical** for a panning camera — see § Panorama). Pieces it can't place are **left where they were, never guessed at**, and a coincidental match is refused rather than invented. **Save**: tick which of {enhanced video, adjusted frames, each collage} to file — each re-derived full-res on the backend with provenance back to its source, into an optional folder; every collage shows a **true-to-export composited miniature** (the real backend warp, on a transparency checker) in the picker. Frames captured from a tuned clip inherit its look; collage pieces are **frozen snapshots** taken when added. The whole workspace can be **saved as a reopenable session** (`inspect-session` entity, spec in `inspect/`) — reload it later from the sidebar with every frame/adjustment/collage (all of them) intact; re-saving a reopened session **overwrites it in place** (even after a rename). Adjust/analysis controls come from self-describing filter/analysis registries. || ✅ **Satellite** | Enter/click coordinates, then **Save place** (a navigable `place` — coordinates only, no image, clickable to fly back) **or Capture** (a sourced imagery crop → `capture` image entity, **filed in `media/`** so it also lists in the Media Library and opens in Inspect). A single **split capture button** re-runs whichever mode was used last — **Capture** for a centred **standard size** (Tweet 16:9 / Square / OG card / Wide / custom), or **Select area**, which arms a **mouse marquee** to drag a rectangle (live px/dimension readout) for an optional **ratio lock** (16:9 / 4:3 / 1:1 / free) — with its arrow opening a compact **mode/size/ratio/resolution popover** (closes on outside click) and a **resolution** control (1× / 2× / provider max-zoom, sized so 2×/max always yield a sharper file on every built-in preset) that captures a deeper zoom. **Marker style** (crosshair / Google-Maps pin / none) baked in; centred-Capture **frame outline** previewed on hover. **Map rotation** — **middle-drag turns the map around the grabbed point** (sober target marker, Google-Earth style), click the bearing to **type an exact angle**, click the compass rose to reset north (capture matches the on-screen heading, bearing in provenance). **Move-pin mode** decouples the marker from center — drag it anywhere in frame (e.g. bottom of shot) and the **recorded coordinates follow the pin** for both actions. **Two dates per capture**: the **capture timestamp** and the **imagery acquisition date** (Esri best-effort, if known) — both recorded and shown. **Map workspace**: toggle an **OSM labels overlay** (roads / place names over the imagery — disabled over a street base map, where it'd only double the labels), read the imagery acquisition date under the crosshair (shown as an unobtrusive corner pill), go **true browser fullscreen** (dialogs follow the map in, and actions that would leave it — another tool, another tab — grey out), **measure** distance / area / **angle** (reported as the acute + obtuse pair), and float **reference windows** over the map (pick any case **image or video**; drag / roll-up / resize — images wheel-zoom & pan, videos get a native player) to eyeball the shot you're geolocating against the imagery — a **session-only scratch aid, never captured or saved**. The tool's side panel lists both in **collapsible** sections — **Places** (fly the map back) and **Captures** (open the full image, or **go to** their coordinates — also from the case sidebar) — each with an inline **title + note editor**; the case sidebar's info panel is the same editor for any capture/place/media. A collapsible **Open in…** list jumps to external maps we can't embed (Google/Earth, Apple, Bing, Yandex, Satellites.pro, Copernicus, Zoom Earth) at the current target. Provenance (provider, zoom, both dates, bearing, marker, center) recorded — feeds the composer. XYZ tile-provider abstraction (see note below). Editable title + notes per capture. || ✅ **Proof Composer** | The heart of v1. Compose panels in a **multi-row grid** (frames, photos, satellite crops, imported screenshots) — arrange side by side *and* stack rows (select a panel — canvas click or side list — and move it with **on-canvas arrows**) so the composite stays near-square instead of a wide bandeau. Each panel can be **resized** (corner-drag the selected panel, or ± in the side list; 40–250%) — its drawn elements scale with it, and shorter panels bottom-align in their row. A grid/free **mode switcher** can drop the grid for a **free layout**: **drag panels anywhere** (their elements follow), **overlap allowed** with array order as **z-order** (front/back per panel), select a panel to **corner-drag resize** it (aspect locked, no rotation); saved per proof, magic tweet-fit snaps back to the grid. A toggleable **tweet-crop guide** (16:9 / 4:5) dims whatever X would centre-crop; a **magic tweet-fit** button auto-repacks the panels into rows to land closest to the active guide's aspect (16:9 default) and resets panel sizes. Draw colored boxes/ellipses/lines/arrows, multi-point **curves** (rounded, click points + double-click to finish) and **text labels** (optional **frame and/or background box**, from the Elements tab) with the mouse — same color = same feature across panels. Every element stays **editable after placing**: boxes/ellipses/text via transformer handles (text corner-drag = font size), lines/arrows/curves via draggable per-vertex handles; selecting an element lets you change its **color and stroke/font size live**, **copy/paste/duplicate** it (Ctrl+C/V/D, cascading offset), and **drag it onto any panel** (it re-binds to whatever panel it's dropped over). Palette presets **+ custom color picker**. Legend **annotations are written per color** (one note per feature), **manually reorderable** from the Annotations tab, and auto-flow into up to 3 columns; a separate **element list** (id + kind) selects/copies/deletes/**reorders** individual shapes (order = z-order within their panel). Optional per-panel captions (**off by default**; a satellite crop auto-captions with provider · coordinates · **imagery acquisition date** — the date omitted when unknown, never the fetch date). A **Coordinates + Source** header (above the panels) auto-fills from them: coordinates from the first satellite panel (falls back to the next if it's deleted), source **traced through the derivation chain** back to the downloaded original (a collage/frame from a video resolves to that video's link) — a source is **always a link**, so a disk-uploaded file counts as none; both are editable and flag a **!** while empty. These carry into the **Post Composer** (on *To Post* export or when attaching the proof there). An **Advanced** panel exposes the trickier knobs: independent **caption / legend / footer font sizes**, an **editable footer** (blank = automatic imagery/source attribution), and a **signature** tick that stamps your Settings logo on the composite — pick a **corner**, size (share of doc width) and opacity, then **drag it on canvas** to nudge; stored as an anchor + offset, so it holds its corner as the document grows. Feature legend (color dot only, numbered in the Annotations tab for reference); export `proof.png` + re-editable JSON spec (`notes`/`legendOrder` per color, `layout`, panel `row`/`scale`/`x,y`, `coords`/`coordsText`, `source`, `caption/legend/footerSize`, `footer`, `signature`) saved in `proofs/`. || ✅ **Post Composer** | Build a GeoConfirmed-style thread from a proof. Tweet 1 = `Place - Plus code`, description, decimal coordinates (6 digits — the posting convention, unaffected by the coordinate-format preference), mention (defaults to `@GeoConfirmed`, configurable in Settings → Preferences), source. Tweet 2 = optional media (Video / Image(s), removable), with media picked from the case library. Add extra context tweets; per-tweet character count; copy-per-tweet or copy-all. **Save drafts** (in `exports/`, reopenable from the sidebar as `post` entities) and **Publish** (copies the thread and opens X compose prefilled). Copy-paste ready — Azimut never posts on your behalf. |@@ -206,7 +206,7 @@ v1 notes:| **Reverse Search Launcher** | *Entry point in **Media Library**.* Any image/frame → reverse-search links for Google/Yandex/Bing/TinEye (opens browser tabs; no scraping). First orchestrator-pattern tool. Twist beyond plain links: an **age/origin hint** — surface the *oldest* dates the engines expose for a match so the analyst can spot recycled/old imagery and trace toward the original source. Analyst files what they pick as entities with provenance; no automated verdict. || **OCR** | Read signs/plates on a frame (tesseract), detect script/language. Suggests entities. || **Ground Imagery** | See ground-level photos around a coordinate. **Key-less open sources first** — Panoramax, Mapillary, KartaView — so it works for everyone (principle 7). **Street View**: a zero-config **easy link** (`google.com/maps?layer=c`) ships first; an optional user-keyed in-app view is gated by the settings usage counter. Picked shots file as sourced `media`/`capture` entities with provenance. |-| **Panorama** | Stitch a video time window (or a set of frames) into one wide view — `cv2.Stitcher` with fallbacks. ✅ **Pulled early into Inspect** (like Frame Extractor): an **auto-stitch** button on the collage that complements the existing hand-made warp collage — machine stitch first, hand-tune after. Still to come: **stitch a video time window** directly (auto-sample the frames), and optional **seam/exposure blending** — the collage path leaves piece edges hard. |+| **Panorama** | Stitch a video time window (or a set of frames) into one wide view. ✅ **Pulled early into Inspect** (like Frame Extractor): an **auto-stitch** button on the collage that complements the existing hand-made warp collage — machine stitch first, hand-tune after. ✅ A **mode** picks the projection: **Planar** (homography chain — one flat surface, pieces stay corner-warpable, but a wide pan blows the end pieces up) vs **Cylindrical**/**Spherical** (rotation + focal per piece, bundle-adjusted and wave-corrected, so a pan stays bounded and evenly sized however far it turns; the warp bakes into the piece's recipe as a `remap` op — full-res on export — and the piece places as an upright rectangle, draggable but no longer warpable). Per-piece **exposure gain** evens the brightness steps. Still to come: **stitch a video time window** directly (auto-sample the frames), and **seam blending** — piece edges are still hard. |### v3 — the investigation layer (entities take the front seat)@@ -237,10 +237,11 @@ not a commitment. Promote into a table above when a workflow firms up; delete ifit stops making sense. One line each.**Toward v2 (GEOINT suite) — mostly grow existing v2 tools:**-- **More satellite basemaps** — Sentinel-2 (date slider), user-keyed Bing (grows Satellite Compare). **OSM context** ✅. **OpenTopoMap** ✅ — key-less topographic base map (SRTM contour lines + hillshade) for reading relief; CC-BY-SA, caps at z17. User-keyed **Mapbox & Google** basemaps + API-keys settings tab + monthly usage counters ✅ — their legal rules, costs and quirks are in [IMAGERY_PROVIDERS.md](IMAGERY_PROVIDERS.md).-- **Keyed-provider cost controls** ✅ — per-provider enable/disable toggles; usage/limits page links in Settings; soft-block keyed maps at 90% of the free tier (clear message, explicit override); eco mode: auto-switch to free imagery when zoomed out (configurable, default z ≤ 15); Google hi-DPI 1024px tiles (1/16-cost captures; live map oversampled 2× — crisp mid-zoom imagery at ¼ cost); Mapbox/Esri disk tile cache (respect `cacheable`).+- **More satellite basemaps** — user-keyed **Sentinel-2** ✅ via Copernicus/Sentinel Hub WMTS (free open data, 10 m/px native to z14 but **viewable to z18** ✅ on magnified native tiles — no extra quota; own eco threshold; **layer picker** ✅ read from the user's own instance (true/false colour, SWIR — vessels at sea) and a **date calendar** ✅ where only days with a real pass are selectable, coloured by cloud cover, resolved free-ish over WFS; the pinned day becomes the capture's imagery date — see [IMAGERY_PROVIDERS.md](IMAGERY_PROVIDERS.md)), user-keyed Bing (grows Satellite Compare). **OSM context** ✅. **OpenTopoMap** ✅ — key-less topographic base map (SRTM contour lines + hillshade) for reading relief; CC-BY-SA, caps at z17. User-keyed **Mapbox & Google** basemaps + API-keys settings tab + monthly usage counters ✅ — their legal rules, costs and quirks are in [IMAGERY_PROVIDERS.md](IMAGERY_PROVIDERS.md).+- **Keyed-provider cost controls** ✅ — per-provider enable/disable toggles; usage/limits page links in Settings; soft-block keyed maps at 90% of the free tier (clear message, explicit override); eco mode: auto-switch to free imagery when zoomed out (configurable, default z ≤ 15, **per-provider thresholds** ✅); Google hi-DPI 1024px tiles (1/16-cost captures; live map oversampled 2× — crisp mid-zoom imagery at ¼ cost); Mapbox/Esri disk tile cache (respect `cacheable`); **dead keys bench their basemap** ✅ (failed key test / auth-shaped provider rejection hides it until re-tested).+- **Google in the EEA** ✅ — Google stopped serving satellite tiles to EEA billing accounts (2025-07-08); shipped the **Maps JS widget basemap** (GoogleMutant under Leaflet, billed per map load, widget reused). It captures and **rotates like any other basemap** — same button, modes, frame and marquee — only its pixels come off the screen (one tab screenshot via the capture extension — no share prompt, fullscreen kept; attribution burned, `method:"screenshot"` + `framed` provenance) instead of stitched tiles, so the frame can't exceed the map view and there's no resolution multiplier. Without the extension the button explains and points at Settings. Details in [IMAGERY_PROVIDERS.md](IMAGERY_PROVIDERS.md).- **Esri overzoom** ✅ — where World Imagery ends, upscale the parent tile instead of showing Esri's "not yet available" placeholder (live map + capture engine, noted in provenance).-- **Capture extension** — browser extension (MV3): screenshot the active map (Google Earth/Maps, …), parse coords/zoom from the URL, file into Azimut via a local ingest endpoint with provenance (ToS: user-initiated screenshot, attribution kept).+- **Capture extension** ✅ — browser extension (MV3): screenshot the active map (Google Earth/Maps, …), parse coords/zoom from the URL, file into Azimut via a local ingest endpoint with provenance (ToS: user-initiated screenshot, attribution kept).- **Copernicus easy link / viewer** — quick link into `browser.dataspace.copernicus.eu` (grows Satellite Compare).- **Sat-vs-screen compare** — overlay/swipe/pixel-diff alignment aid; assist, never an auto-verdict (principle 5). Grows Image Compare.- **Weather / METAR history** — corroborate a claimed date+coords from free archives; pairs with Shadow Clock into a chronolocation panel.@@ -305,10 +306,14 @@ it stops making sense. One line each.**Preferences** (coordinate format DD/DMS/MGRS, metric/imperial units,Satellite home view, default post mention, **signature** — your own PNG logo,≤ 2 MB, app-wide beside `settings.json`, reaching a case only as pixels in a- proof PNG you signed), **Imagery** (optional API- keys/secrets, stored locally and **never** bundled into a shared case),- **Usage** (per-provider **monthly counters** so a user tracks a keyed quota- before hitting it, + eco mode), **About** (version, workspace path, license,+ proof PNG you signed), **Imagery** (one **collapsible card per provider** ✅ —+ closed it's a single line: what it unlocks, a status chip, and either its+ cost or its usage meter; open it holds the key field, the setup steps, the+ **editable free tier** ✅ and its eco threshold. Keys save on change, stored+ locally and **never** bundled into a shared case. Per-provider **monthly+ counters** ✅ track a keyed quota before it's hit — an allowance belongs to+ the account and providers change it silently, so it's the user's to correct),+ **About** (version, workspace path, license,links, + **Downloaders** ✅ — one-click update for yt-dlp/gallery-dl, seebelow). Core features never require a key (principle 7); key-less providersare always the default.diff --git a/extension/README.md b/extension/README.mdnew file mode 100644index 0000000..649731f--- /dev/null+++ b/extension/README.md@@ -0,0 +1,62 @@+# Azimut Capture — browser extension++Files the map you are looking at into [Azimut](https://github.com/OsintMeThat/azimut)+as a `capture` with provenance: one screenshot per explicit click, coordinates+read from the page **URL only** (never scraped from the page), source URL ++site + timestamp always recorded, attribution burned into the image footer by+the app.++The extension is deliberately thin: it screenshots and it sends the URL —+**all URL parsing (sites, coordinates, place names, imagery dates) happens in+the Azimut app**, so when a map site changes its URL format, updating Azimut+fixes it and the extension never needs a reinstall.++It serves two flows:++- **External map sites** — Google Maps, Google Earth (web), Bing Maps, Yandex+ Maps, OpenStreetMap, Apple Maps, Zoom Earth, Copernicus Browser, and+ whatever Azimut learns to recognize later. Click the toolbar icon (or+ `Alt+Shift+A`): a popup shows what Azimut parsed from the URL (correctable),+ a case picker, and one button — drag the area to capture. The result+ appears in the open app instantly. On any other kind of site the extension+ refuses: it is for maps only.+- **Azimut's own Google (Maps JS) basemap** — the app's Capture button asks+ the extension for the tab's pixels instead of prompting for a screen share.+ No pairing needed for this: the app files everything itself, same-origin.++## Install++Get the zip from Azimut → **Settings → Capture extension** (or use this+folder directly from a repo checkout), unzip it somewhere permanent, then:++- **Chrome / Edge / Brave** (Windows, macOS, Linux): open+ `chrome://extensions`, enable **Developer mode** (top right), click+ **Load unpacked**, pick the unzipped folder. The folder must stay in place —+ Chrome loads it from there on every start.+- **Firefox**: open `about:debugging#/runtime/this-firefox`, click+ **Load Temporary Add-on…**, pick `manifest.json` inside the unzipped folder.+ Firefox drops temporary add-ons when it closes — reload it next session, or+ use Firefox Developer Edition / ESR with `xpinstall.signatures.required`+ set to `false` in `about:config` for a permanent install.++## Pair (external sites only)++1. Azimut → **Settings → Capture extension** → copy the pairing token.+2. Extension options (right-click the toolbar icon → Options) → paste the+ token → **Save & test**.++The token only authorizes filing captures into your local Azimut+(`127.0.0.1`) — nothing ever leaves your machine. Rotate it from Azimut+Settings at any time; every paired extension then needs the new one.++## Permissions, and why++| Permission | Why |+|---|---|+| `activeTab` | read the URL + screenshot the tab you pressed the button on — granted per click, per tab. This is also why the **first** capture from Azimut's own Capture button on a fresh tab asks you to click the extension icon once: browsers refuse tab screenshots (`captureVisibleTab`) until the extension has been invoked on that tab, and the alternative — the `<all_urls>` permission — would mean "read all data on all websites", which this extension will never request |+| `scripting` | inject the area-selection overlay when you choose "Select area" |+| `storage` | the backend URL, pairing token and last-used case |+| `notifications` | report the result of an area capture (the popup has closed by then) |+| `http://127.0.0.1/*`, `http://localhost/*` | talk to the local Azimut app and answer its Capture button |++No history access, no reading pages, no remote servers.diff --git a/extension/background.js b/extension/background.jsnew file mode 100644index 0000000..720ab20--- /dev/null+++ b/extension/background.js@@ -0,0 +1,152 @@+/**+ * Background worker: the only place pixels are grabbed.+ *+ * Chrome runs this as an MV3 service worker, Firefox as an event page (the+ * manifest declares both) — so it is a classic script with no imports, no DOM,+ * and no in-memory state that matters: anything that must survive a worker+ * restart lives in storage.session.+ *+ * Every capture is one captureVisibleTab behind one explicit user action+ * (repo legal rails): the popup's buttons, or the Azimut app's own Capture+ * button relayed by bridge.js. Nothing here is schedulable or repeatable+ * without a fresh user gesture.+ */++const api = typeof browser !== "undefined" ? browser : chrome;++const APP_ORIGINS = ["http://127.0.0.1", "http://localhost"];+const isAppUrl = (url) => APP_ORIGINS.some((o) => url === o || url?.startsWith(o + ":") || url?.startsWith(o + "/"));++function settings() {+ return api.storage.local+ .get({ backendUrl: "http://127.0.0.1:8477", token: "", lastCaseId: "" })+ .then((s) => ({ ...s, backendUrl: s.backendUrl.replace(/\/+$/, "") }));+}++function captureActiveTab(windowId) {+ // promise-form works on both browsers in MV3+ return api.tabs.captureVisibleTab(windowId, { format: "png" });+}++/** Crop a captured frame (dataURL) to a viewport-CSS-px rect. The scale is+ * measured (image width / viewport width), not assumed from devicePixelRatio,+ * so browser zoom can't silently shift the crop — same rule as the app. */+async function cropDataUrl(dataUrl, rect, viewportW) {+ const blob = await (await fetch(dataUrl)).blob();+ const bmp = await createImageBitmap(blob);+ const scale = bmp.width / viewportW;+ const sx = Math.max(0, Math.round(rect.x * scale));+ const sy = Math.max(0, Math.round(rect.y * scale));+ const sw = Math.min(bmp.width - sx, Math.round(rect.w * scale));+ const sh = Math.min(bmp.height - sy, Math.round(rect.h * scale));+ if (sw < 8 || sh < 8) throw new Error("selection too small");+ const canvas = new OffscreenCanvas(sw, sh);+ canvas.getContext("2d").drawImage(bmp, sx, sy, sw, sh, 0, 0, sw, sh);+ return canvas.convertToBlob({ type: "image/png" });+}++/** File one screenshot with the backend (POST /api/ingest/screenshot). */+async function ingest(blob, meta) {+ const { backendUrl, token } = await settings();+ if (!token) throw new Error("not paired — open the extension options and paste the token from Azimut Settings");+ // Thin on purpose: image + URL is a complete capture — the app parses the+ // URL itself (site, coordinates, title, imagery date). Everything else here+ // is either the user's popup corrections or plain context.+ const form = new FormData();+ form.append("image", blob, "screenshot.png");+ form.append("url", meta.url);+ form.append("case_id", meta.caseId || "");+ if (meta.title) form.append("title", meta.title);+ for (const k of ["lat", "lon", "zoom", "bearing"]) {+ if (meta[k] !== null && meta[k] !== undefined && meta[k] !== "") form.append(k, String(meta[k]));+ }+ form.append("captured_at", new Date().toISOString());+ form.append("extension", api.runtime.getManifest().version);+ let r;+ try {+ r = await fetch(`${backendUrl}/api/ingest/screenshot`, {+ method: "POST",+ headers: { "X-Azimut-Token": token },+ body: form,+ });+ } catch {+ throw new Error(`Azimut is not reachable at ${backendUrl} — is the app running?`);+ }+ if (r.status === 401) throw new Error("pairing token rejected — re-pair in the extension options");+ if (!r.ok) throw new Error(`Azimut refused the capture (${r.status}): ${(await r.text()).slice(0, 200)}`);+ const body = await r.json();+ if (meta.caseId) api.storage.local.set({ lastCaseId: meta.caseId });+ return body;+}++function notify(title, message) {+ // fire-and-forget: a failed toast must never fail a filed capture+ try {+ api.notifications.create({+ type: "basic",+ iconUrl: api.runtime.getURL("icons/icon128.png"),+ title,+ message: String(message).slice(0, 300),+ });+ } catch {+ /* notifications are best-effort */+ }+}++// --- message routes ------------------------------------------------------------++async function handle(msg, sender) {+ // The Azimut app's own Capture button (bridge.js relay): return the raw+ // frame — the app does its own registration, cropping and filing. Only the+ // app's localhost origin may ask for it.+ if (msg.type === "capture-tab") {+ if (!sender.tab || !isAppUrl(sender.tab.url)) return { ok: false, error: "not the Azimut app" };+ try {+ return { ok: true, dataUrl: await captureActiveTab(sender.tab.windowId) };+ } catch (e) {+ // captureVisibleTab needs activeTab (or <all_urls>, which this extension+ // deliberately never asks for) — a page-initiated capture is refused+ // until the user has invoked the extension once on this tab. Tell the+ // app which case this is, so it can explain the one-time step.+ const needsActivation = /activeTab|all_urls|permission/i.test(e.message || "");+ return { ok: false, needsActivation, error: e.message };+ }+ }++ // Popup: arm an area selection on the page. The popup closes right after,+ // so the meta waits in storage.session for the overlay's rect.+ if (msg.type === "start-area-select") {+ try {+ await api.storage.session.set({ [`pending:${msg.tabId}`]: msg.meta });+ await api.scripting.executeScript({ target: { tabId: msg.tabId }, files: ["overlay.js"] });+ return { ok: true };+ } catch (e) {+ return { ok: false, error: e.message };+ }+ }++ // Overlay: the user finished (or cancelled) the drag.+ if (msg.type === "area-selected" || msg.type === "area-cancelled") {+ const key = `pending:${sender.tab.id}`;+ const meta = (await api.storage.session.get(key))[key];+ await api.storage.session.remove(key);+ if (msg.type === "area-cancelled" || !meta) return { ok: true };+ try {+ const dataUrl = await captureActiveTab(sender.tab.windowId);+ const blob = await cropDataUrl(dataUrl, msg.rect, msg.viewportW);+ const body = await ingest(blob, meta);+ notify("Capture filed into Azimut", body.title);+ return { ok: true };+ } catch (e) {+ notify("Azimut capture failed", e.message);+ return { ok: false, error: e.message };+ }+ }++ return { ok: false, error: `unknown message '${msg.type}'` };+}++api.runtime.onMessage.addListener((msg, sender, sendResponse) => {+ handle(msg, sender).then(sendResponse, (e) => sendResponse({ ok: false, error: e.message }));+ return true; // async response+});diff --git a/extension/bridge.js b/extension/bridge.jsnew file mode 100644index 0000000..347590c--- /dev/null+++ b/extension/bridge.js@@ -0,0 +1,59 @@+/**+ * Bridge content script — runs only on the Azimut app's own localhost pages+ * (manifest matches) and does exactly two things:+ *+ * 1. announces the extension to the app (a dataset marker, set at+ * document_start so it is there before the app mounts, plus a ping+ * answer for later checks);+ * 2. relays the app's Capture requests to the background worker and hands+ * the captured frame back.+ *+ * The app keeps all judgment: registration, cropping, filing. The bridge+ * never touches the backend and never sees the pairing token — the app files+ * same-origin, so this path needs no pairing at all.+ */++(() => {+ const api = typeof browser !== "undefined" ? browser : chrome;+ const VERSION = api.runtime.getManifest().version;+ const CHANNEL = "azimut-capture-ext";++ document.documentElement.dataset.azimutCaptureExtension = VERSION;++ // The popup announces itself when opened on this tab: that click granted+ // activeTab, so the app's Capture button works from now on. Relay it so the+ // app can say "you're set — press Capture again".+ api.runtime.onMessage.addListener((msg) => {+ if (msg?.type === "app-activated") {+ window.postMessage({ channel: CHANNEL, type: "activated" }, location.origin);+ }+ });++ window.addEventListener("message", async (event) => {+ // same page, same origin, our channel — nothing else is listened to+ if (event.source !== window || event.origin !== location.origin) return;+ const msg = event.data;+ if (!msg || msg.channel !== CHANNEL) return;++ if (msg.type === "ping") {+ window.postMessage(+ { channel: CHANNEL, type: "pong", id: msg.id, version: VERSION },+ location.origin+ );+ return;+ }++ if (msg.type === "capture") {+ let result;+ try {+ result = await api.runtime.sendMessage({ type: "capture-tab" });+ } catch (e) {+ result = { ok: false, error: e.message };+ }+ window.postMessage(+ { channel: CHANNEL, type: "capture-result", id: msg.id, ...result },+ location.origin+ );+ }+ });+})();diff --git a/extension/icons/icon128.png b/extension/icons/icon128.pngnew file mode 100644index 0000000..d5f7ec5Binary files /dev/null and b/extension/icons/icon128.png differdiff --git a/extension/icons/icon16.png b/extension/icons/icon16.pngnew file mode 100644index 0000000..1a516cdBinary files /dev/null and b/extension/icons/icon16.png differdiff --git a/extension/icons/icon32.png b/extension/icons/icon32.pngnew file mode 100644index 0000000..26a93a7Binary files /dev/null and b/extension/icons/icon32.png differdiff --git a/extension/icons/icon48.png b/extension/icons/icon48.pngnew file mode 100644index 0000000..d69ec79Binary files /dev/null and b/extension/icons/icon48.png differdiff --git a/extension/manifest.json b/extension/manifest.jsonnew file mode 100644index 0000000..84c7b84--- /dev/null+++ b/extension/manifest.json@@ -0,0 +1,51 @@+{+ "manifest_version": 3,+ "name": "Azimut Capture",+ "version": "0.1.0",+ "description": "File the map you are looking at into Azimut: one user-initiated screenshot, coordinates parsed from the URL, provenance kept.",+ "permissions": ["activeTab", "scripting", "storage", "notifications"],+ "host_permissions": ["http://127.0.0.1/*", "http://localhost/*"],+ "background": {+ "service_worker": "background.js",+ "scripts": ["background.js"]+ },+ "action": {+ "default_popup": "popup.html",+ "default_title": "Capture this map into Azimut",+ "default_icon": {+ "16": "icons/icon16.png",+ "32": "icons/icon32.png",+ "48": "icons/icon48.png",+ "128": "icons/icon128.png"+ }+ },+ "icons": {+ "16": "icons/icon16.png",+ "32": "icons/icon32.png",+ "48": "icons/icon48.png",+ "128": "icons/icon128.png"+ },+ "options_ui": {+ "page": "options.html",+ "open_in_tab": false+ },+ "commands": {+ "_execute_action": {+ "suggested_key": { "default": "Alt+Shift+A" },+ "description": "Open the Azimut capture popup"+ }+ },+ "content_scripts": [+ {+ "matches": ["http://127.0.0.1/*", "http://localhost/*"],+ "js": ["bridge.js"],+ "run_at": "document_start"+ }+ ],+ "browser_specific_settings": {+ "gecko": {+ "id": "[email protected]",+ "strict_min_version": "115.0"+ }+ }+}diff --git a/extension/options.html b/extension/options.htmlnew file mode 100644index 0000000..52f4855--- /dev/null+++ b/extension/options.html@@ -0,0 +1,28 @@+<!doctype html>+<html>+<head>+ <meta charset="utf-8" />+ <link rel="stylesheet" href="ui.css" />+</head>+<body class="options">+ <h1>Pair with Azimut</h1>+ <p class="muted">+ In Azimut open <strong>Settings → Capture extension</strong>, copy the+ pairing token, and paste it here. The token only lets this extension file+ captures into your local Azimut — nothing leaves your machine.+ </p>+ <div class="row">+ <label for="backendUrl">Azimut URL</label>+ <input id="backendUrl" type="text" placeholder="http://127.0.0.1:8477" />+ </div>+ <div class="row">+ <label for="token">Pairing token</label>+ <input id="token" type="password" placeholder="paste from Azimut Settings" />+ </div>+ <div class="actions">+ <button id="save" class="primary">Save & test</button>+ </div>+ <p id="status" class="status" hidden></p>+ <script src="options.js"></script>+</body>+</html>diff --git a/extension/options.js b/extension/options.jsnew file mode 100644index 0000000..9ba2498--- /dev/null+++ b/extension/options.js@@ -0,0 +1,41 @@+/** Options: store the backend URL + pairing token, and prove them with one+ * /api/ingest/ping — the same call the popup will make, so "test passed"+ * means the real flow works. */++const api = typeof browser !== "undefined" ? browser : chrome;+const $ = (id) => document.getElementById(id);++function status(text, kind = "info") {+ const el = $("status");+ el.hidden = !text;+ el.textContent = text;+ el.className = `status ${kind}`;+}++async function init() {+ const stored = await api.storage.local.get({ backendUrl: "http://127.0.0.1:8477", token: "" });+ $("backendUrl").value = stored.backendUrl;+ $("token").value = stored.token;++ $("save").addEventListener("click", async () => {+ const backendUrl = $("backendUrl").value.trim().replace(/\/+$/, "") || "http://127.0.0.1:8477";+ const token = $("token").value.trim();+ await api.storage.local.set({ backendUrl, token });+ status("Testing…");+ try {+ const r = await fetch(`${backendUrl}/api/ingest/ping`, {+ headers: { "X-Azimut-Token": token },+ });+ if (r.status === 401) {+ status("Azimut answered but rejected the token — copy it again from Settings.", "error");+ return;+ }+ const body = await r.json();+ status(`Paired with Azimut ${body.version} — you're set.`, "ok");+ } catch {+ status(`No Azimut at ${backendUrl} — is the app running?`, "error");+ }+ });+}++init().catch((e) => status(e.message, "error"));diff --git a/extension/overlay.js b/extension/overlay.jsnew file mode 100644index 0000000..f422d1f--- /dev/null+++ b/extension/overlay.js@@ -0,0 +1,91 @@+/**+ * Area-select overlay — injected on demand (never declared for map sites),+ * draws one marquee, reports one rect, removes itself.+ *+ * The overlay dims the page while the user drags, so it removes itself and+ * waits two frames BEFORE asking the background to capture — otherwise its+ * own dimming would be burned into the capture. Esc cancels.+ */++(() => {+ if (window.__azimutOverlayActive) return;+ window.__azimutOverlayActive = true;++ const api = typeof browser !== "undefined" ? browser : chrome;++ const host = document.createElement("div");+ host.style.cssText =+ "position:fixed;inset:0;z-index:2147483647;cursor:crosshair;background:rgba(10,10,10,0.35)";+ const box = document.createElement("div");+ box.style.cssText =+ "position:fixed;display:none;border:1.5px dashed #e8a33d;background:rgba(232,163,61,0.10);" ++ "box-shadow:0 0 0 100vmax rgba(10,10,10,0.35);pointer-events:none";+ const hint = document.createElement("div");+ hint.textContent = "Drag to select the area to capture — Esc to cancel";+ hint.style.cssText =+ "position:fixed;top:14px;left:50%;transform:translateX(-50%);padding:6px 12px;" ++ "background:#141414;color:#e6e6e6;font:13px system-ui,sans-serif;border-radius:6px;" ++ "border:1px solid #333;pointer-events:none";+ host.append(box, hint);+ document.documentElement.appendChild(host);++ let start = null;++ function teardown() {+ host.remove();+ window.removeEventListener("keydown", onKey, true);+ window.__azimutOverlayActive = false;+ }++ function finish(rect) {+ teardown();+ // let the dimming actually leave the composited page before the grab+ requestAnimationFrame(() =>+ requestAnimationFrame(() => {+ api.runtime.sendMessage(+ rect+ ? { type: "area-selected", rect, viewportW: window.innerWidth }+ : { type: "area-cancelled" }+ );+ })+ );+ }++ function onKey(e) {+ if (e.key === "Escape") {+ e.preventDefault();+ e.stopPropagation();+ finish(null);+ }+ }+ window.addEventListener("keydown", onKey, true);++ host.addEventListener("mousedown", (e) => {+ if (e.button !== 0) return;+ e.preventDefault();+ start = { x: e.clientX, y: e.clientY };+ host.style.background = "transparent"; // the box's own shadow dims from now on+ box.style.display = "block";+ });++ host.addEventListener("mousemove", (e) => {+ if (!start) return;+ const x = Math.min(start.x, e.clientX);+ const y = Math.min(start.y, e.clientY);+ box.style.left = `${x}px`;+ box.style.top = `${y}px`;+ box.style.width = `${Math.abs(e.clientX - start.x)}px`;+ box.style.height = `${Math.abs(e.clientY - start.y)}px`;+ });++ host.addEventListener("mouseup", (e) => {+ if (!start || e.button !== 0) return;+ const rect = {+ x: Math.min(start.x, e.clientX),+ y: Math.min(start.y, e.clientY),+ w: Math.abs(e.clientX - start.x),+ h: Math.abs(e.clientY - start.y),+ };+ finish(rect.w < 8 || rect.h < 8 ? null : rect); // a stray click is a cancel+ });+})();diff --git a/extension/popup.html b/extension/popup.htmlnew file mode 100644index 0000000..3873f16--- /dev/null+++ b/extension/popup.html@@ -0,0 +1,69 @@+<!doctype html>+<html>+<head>+ <meta charset="utf-8" />+ <link rel="stylesheet" href="ui.css" />+</head>+<body class="popup">+ <header>+ <img src="icons/icon32.png" alt="" width="18" height="18" />+ <strong>Azimut Capture</strong>+ <span id="site" class="badge"></span>+ </header>++ <!-- one of these three states shows at a time -->+ <section id="state-nomap" hidden>+ <p>This doesn't look like a map site.</p>+ <p class="muted">+ Azimut Capture only works on the map sites Azimut recognizes (Google+ Maps/Earth, Bing, Yandex, OSM, Apple Maps, Zoom Earth, Copernicus, …) —+ one screenshot per click, coordinates read from the page URL by the app.+ </p>+ </section>++ <section id="state-azimut" hidden>+ <p>This is Azimut itself — you're set. Use the app's own <strong>Capture</strong> button.</p>+ <p class="muted">+ Opening this popup granted the capture permission for this tab (browsers+ require one click on the extension before it may screenshot a tab). It+ lasts until the tab is closed — you won't need to come back here.+ </p>+ </section>++ <section id="state-map" hidden>+ <div class="row">+ <label>Case</label>+ <select id="case"></select>+ </div>+ <div class="row coords">+ <label>Lat / Lon</label>+ <input id="lat" type="text" inputmode="decimal" placeholder="—" />+ <input id="lon" type="text" inputmode="decimal" placeholder="—" />+ </div>+ <div class="row coords">+ <label>Zoom / Bearing</label>+ <input id="zoom" type="text" inputmode="decimal" placeholder="—" />+ <input id="bearing" type="text" inputmode="decimal" placeholder="—" />+ </div>+ <div class="row">+ <label>Title</label>+ <input id="title" type="text" placeholder="optional" />+ </div>+ <p id="coords-note" class="muted" hidden>+ No coordinates in this URL — the capture files without them (fixable later+ in Azimut's sidebar).+ </p>+ <div class="actions">+ <button id="capture-area" class="primary">Select area to capture…</button>+ </div>+ </section>++ <p id="status" class="status" hidden></p>+ <footer>+ <a id="open-options" href="#">Extension options</a>+ <span class="muted">· one screenshot per click, URL only</span>+ </footer>++ <script type="module" src="popup.js"></script>+</body>+</html>diff --git a/extension/popup.js b/extension/popup.jsnew file mode 100644index 0000000..ba45a66--- /dev/null+++ b/extension/popup.js@@ -0,0 +1,159 @@+/**+ * Popup: the user-facing side of a capture on an external map site.+ *+ * Opening it (toolbar click or Alt+Shift+A) is the user gesture that grants+ * activeTab — every capture descends from that gesture.+ *+ * Deliberately thin (owner decision): the extension knows NOTHING about map+ * sites. The page URL goes to the app (GET /api/ingest/parse), which answers+ * with site, coordinates, place name — every rule that could rot when a site+ * changes its URL format lives in the app, where an update is one pip install+ * instead of a manual extension reinstall on every machine.+ */++const api = typeof browser !== "undefined" ? browser : chrome;+const $ = (id) => document.getElementById(id);++const status = (text, kind = "info") => {+ const el = $("status");+ el.hidden = !text;+ el.textContent = text;+ el.className = `status ${kind}`;+};++const numOrNull = (id) => {+ const raw = $(id).value.trim();+ if (!raw) return null;+ const v = parseFloat(raw.replace(",", "."));+ return Number.isFinite(v) ? v : null;+};++const origin = (url) => {+ try {+ return new URL(url).origin;+ } catch {+ return null;+ }+};++async function loadCases(select, stored) {+ const { backendUrl, token } = stored;+ let cases;+ try {+ const r = await fetch(`${backendUrl}/api/ingest/cases`, {+ headers: { "X-Azimut-Token": token },+ });+ if (r.status === 401) throw new Error("unpaired");+ cases = await r.json();+ } catch (e) {+ select.replaceChildren(new Option("Azimut unreachable — check options", ""));+ status(+ e.message === "unpaired"+ ? "Not paired: open the extension options and paste the token from Azimut Settings."+ : `Cannot reach Azimut at ${backendUrl} — is the app running?`,+ "error"+ );+ return false;+ }+ const options = cases.map(+ (c) => new Option(c.scratch ? `(scratch) ${c.name}` : c.name, c.id)+ );+ options.push(new Option("New scratch session", ""));+ select.replaceChildren(...options);+ select.value = cases.some((c) => c.id === stored.lastCaseId) ? stored.lastCaseId : options[0].value;+ return true;+}++async function init() {+ $("open-options").addEventListener("click", (e) => {+ e.preventDefault();+ api.runtime.openOptionsPage();+ });++ const stored = await api.storage.local.get({+ backendUrl: "http://127.0.0.1:8477",+ token: "",+ lastCaseId: "",+ });+ stored.backendUrl = stored.backendUrl.replace(/\/+$/, "");++ const [tab] = await api.tabs.query({ active: true, currentWindow: true });+ if (!tab?.url) {+ $("state-nomap").hidden = false;+ return;+ }++ // The app's own tab is recognized locally, by origin — it must work even+ // unpaired, because opening this popup is what grants the app capture access+ const tabOrigin = origin(tab.url);+ const isLocalhost = /^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/.test(tabOrigin || "");+ if (tabOrigin && (tabOrigin === origin(stored.backendUrl) || isLocalhost)) {+ $("site").textContent = "Azimut";+ $("state-azimut").hidden = false;+ // this click just granted activeTab for the tab — tell the app through+ // the bridge so its Capture button knows it can proceed+ api.tabs.sendMessage(tab.id, { type: "app-activated" }).catch(() => {});+ return;+ }++ // everything about the URL is the app's judgment, not ours+ let parsed;+ try {+ const r = await fetch(+ `${stored.backendUrl}/api/ingest/parse?url=${encodeURIComponent(tab.url)}`,+ { headers: { "X-Azimut-Token": stored.token } }+ );+ if (r.status === 401) {+ status("Not paired: open the extension options and paste the token from Azimut Settings.", "error");+ return;+ }+ parsed = await r.json();+ } catch {+ status(`Cannot reach Azimut at ${stored.backendUrl} — is the app running?`, "error");+ return;+ }++ if (!parsed.site) {+ $("state-nomap").hidden = false;+ return;+ }++ $("site").textContent = parsed.label;+ $("state-map").hidden = false;+ for (const k of ["lat", "lon", "zoom", "bearing"]) {+ if (parsed[k] !== null && parsed[k] !== undefined) $(k).value = String(parsed[k]);+ }+ // the URL's place name becomes the suggested title; with coordinates but no+ // name, the placeholder shows the fallback Azimut will use (the coordinates)+ if (parsed.title) $("title").value = parsed.title;+ else if (parsed.lat !== null) $("title").placeholder = `${parsed.lat}, ${parsed.lon}`;+ $("coords-note").hidden = parsed.lat !== null;++ const paired = await loadCases($("case"), stored);++ $("capture-area").addEventListener("click", async () => {+ if (!paired) return;+ // half a coordinate would 422 server-side; catch it where it's fixable+ if ((numOrNull("lat") === null) !== (numOrNull("lon") === null)) {+ status("Latitude and longitude go together — fill both or neither.", "error");+ return;+ }+ const r = await api.runtime.sendMessage({+ type: "start-area-select",+ tabId: tab.id,+ meta: {+ url: tab.url,+ caseId: $("case").value,+ title: $("title").value.trim(),+ lat: numOrNull("lat"),+ lon: numOrNull("lon"),+ zoom: numOrNull("zoom"),+ bearing: numOrNull("bearing"),+ },+ });+ if (r?.ok) window.close(); // the overlay takes over; a notification reports the result+ else status(r?.error || "could not start the selection", "error");+ });+}++init().catch((e) => status(e.message, "error"));diff --git a/extension/ui.css b/extension/ui.cssnew file mode 100644index 0000000..2c13e6e--- /dev/null+++ b/extension/ui.css@@ -0,0 +1,81 @@+/* Shared popup/options styling — matches the app's dark theme + amber accent. */++:root {+ --bg: #161616;+ --bg-2: #1f1f1f;+ --text: #e6e6e6;+ --muted: #9a9a9a;+ --accent: #e8a33d;+ --accent-text: #141414;+ --border: #333;+ --ok: #58b368;+ --error: #e5484d;+}++* { box-sizing: border-box; }++body {+ margin: 0;+ padding: 12px;+ background: var(--bg);+ color: var(--text);+ font: 13px/1.45 system-ui, sans-serif;+}+body.popup { width: 340px; }+body.options { max-width: 460px; }++h1 { font-size: 15px; margin: 0 0 8px; }+header { display: flex; align-items: center; gap: 7px; margin-bottom: 10px; }+header .badge {+ margin-left: auto;+ padding: 2px 8px;+ border: 1px solid var(--border);+ border-radius: 999px;+ font-size: 11px;+ color: var(--muted);+}++p { margin: 6px 0; }+.muted { color: var(--muted); font-size: 12px; }++.row { display: flex; align-items: center; gap: 8px; margin: 7px 0; }+.row label { width: 92px; flex: none; color: var(--muted); font-size: 12px; }+.row input, .row select {+ flex: 1;+ min-width: 0;+ padding: 5px 8px;+ background: var(--bg-2);+ color: var(--text);+ border: 1px solid var(--border);+ border-radius: 6px;+ font: inherit;+}+.row.coords input { width: 50%; }+.row input:focus, .row select:focus { outline: 1px solid var(--accent); }++.actions { display: flex; gap: 8px; margin-top: 12px; }+button {+ padding: 6px 12px;+ background: var(--bg-2);+ color: var(--text);+ border: 1px solid var(--border);+ border-radius: 6px;+ font: inherit;+ cursor: pointer;+}+button.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-text); font-weight: 600; }+button:disabled { opacity: 0.55; cursor: default; }++.status { padding: 7px 9px; border-radius: 6px; background: var(--bg-2); border: 1px solid var(--border); }+.status.ok { border-color: var(--ok); }+.status.error { border-color: var(--error); }++footer {+ display: flex;+ gap: 6px;+ margin-top: 12px;+ padding-top: 8px;+ border-top: 1px solid var(--border);+ font-size: 11px;+}+footer a { color: var(--accent); text-decoration: none; }diff --git a/frontend/package-lock.json b/frontend/package-lock.jsonindex 0a4b4a3..4982759 100644--- a/frontend/package-lock.json+++ b/frontend/package-lock.json@@ -1,20 +1,22 @@{"name": "azimut-frontend",- "version": "0.1.0",+ "version": "0.1.1","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "azimut-frontend",- "version": "0.1.0",+ "version": "0.1.1","dependencies": {"@fontsource/oxanium": "^5.2.8","konva": "^9.3.0","leaflet": "^1.9.4",- "leaflet-rotate": "^0.2.8"+ "leaflet-rotate": "^0.2.8",+ "leaflet.gridlayer.googlemutant": "^0.16.0"},"devDependencies": {"@sveltejs/vite-plugin-svelte": "^7.2.0",+ "happy-dom": "^20.10.6","svelte": "^5.0.0","vite": "^8.1.4","vitest": "^4.1.10"@@ -479,6 +481,16 @@"dev": true,"license": "MIT"},+ "node_modules/@types/node": {+ "version": "26.1.1",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-26.1.1.tgz",+ "integrity": "sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "undici-types": "~8.3.0"+ }+ },"node_modules/@types/trusted-types": {"version": "2.0.7","resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",@@ -486,6 +498,23 @@"dev": true,"license": "MIT"},+ "node_modules/@types/whatwg-mimetype": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/@types/whatwg-mimetype/-/whatwg-mimetype-3.0.2.tgz",+ "integrity": "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/ws": {+ "version": "8.18.1",+ "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",+ "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },"node_modules/@vitest/expect": {"version": "4.1.10","resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.10.tgz",@@ -642,6 +671,19 @@"node": ">= 0.4"}},+ "node_modules/buffer-image-size": {+ "version": "0.6.4",+ "resolved": "https://registry.npmjs.org/buffer-image-size/-/buffer-image-size-0.6.4.tgz",+ "integrity": "sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ },+ "engines": {+ "node": ">=4.0"+ }+ },"node_modules/chai": {"version": "6.2.2","resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz",@@ -696,6 +738,19 @@"dev": true,"license": "MIT"},+ "node_modules/entities": {+ "version": "7.0.1",+ "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",+ "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=0.12"+ },+ "funding": {+ "url": "https://github.com/fb55/entities?sponsor=1"+ }+ },"node_modules/es-module-lexer": {"version": "2.3.0","resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.0.tgz",@@ -781,6 +836,25 @@"node": "^8.16.0 || ^10.6.0 || >=11.0.0"}},+ "node_modules/happy-dom": {+ "version": "20.10.6",+ "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-20.10.6.tgz",+ "integrity": "sha512-6QD0ilzDDt93tX44y8tbmZdAcdTRYDhUP+Asgi6pC8Pp5IA3cvaZGyoVN/EGtlq9ziT65iPuBBn3ASLr6hCgVw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": ">=20.0.0",+ "@types/whatwg-mimetype": "^3.0.2",+ "@types/ws": "^8.18.1",+ "buffer-image-size": "^0.6.4",+ "entities": "^7.0.1",+ "whatwg-mimetype": "^3.0.0",+ "ws": "^8.21.0"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },"node_modules/is-reference": {"version": "3.0.3","resolved": "https://registry.npmjs.org/is-reference/-/is-reference-3.0.3.tgz",@@ -826,6 +900,12 @@"leaflet": "^1.9.3"}},+ "node_modules/leaflet.gridlayer.googlemutant": {+ "version": "0.16.0",+ "resolved": "https://registry.npmjs.org/leaflet.gridlayer.googlemutant/-/leaflet.gridlayer.googlemutant-0.16.0.tgz",+ "integrity": "sha512-wN8DxR5zplhZA6a5998AOluCL97H5lkr1yCLOT7siaQyc+hT6E8kcGqjAuSsEUSoaf/U3H25x8Avkp9OpgJpng==",+ "license": "Beerware"+ },"node_modules/lightningcss": {"version": "1.32.0","resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz",@@ -1338,6 +1418,13 @@"license": "0BSD","optional": true},+ "node_modules/undici-types": {+ "version": "8.3.0",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",+ "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==",+ "dev": true,+ "license": "MIT"+ },"node_modules/vite": {"version": "8.1.4","resolved": "https://registry.npmjs.org/vite/-/vite-8.1.4.tgz",@@ -1526,6 +1613,16 @@}}},+ "node_modules/whatwg-mimetype": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz",+ "integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12"+ }+ },"node_modules/why-is-node-running": {"version": "2.3.0","resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",@@ -1543,6 +1640,28 @@"node": ">=8"}},+ "node_modules/ws": {+ "version": "8.21.1",+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.1.tgz",+ "integrity": "sha512-+0NTnW77fFN/DjQi6k/Sq/Yvk4Sgajw7urW8V+asjXnRgDs9gyGkdb7EzgfhA4goXsRIZKE28fzIXBHEzhuiWw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=10.0.0"+ },+ "peerDependencies": {+ "bufferutil": "^4.0.1",+ "utf-8-validate": ">=5.0.2"+ },+ "peerDependenciesMeta": {+ "bufferutil": {+ "optional": true+ },+ "utf-8-validate": {+ "optional": true+ }+ }+ },"node_modules/zimmerframe": {"version": "1.1.4","resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.4.tgz",diff --git a/frontend/package.json b/frontend/package.jsonindex 2a76e7a..0f52e2b 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -11,6 +11,7 @@},"devDependencies": {"@sveltejs/vite-plugin-svelte": "^7.2.0",+ "happy-dom": "^20.10.6","svelte": "^5.0.0","vite": "^8.1.4","vitest": "^4.1.10"@@ -19,6 +20,7 @@"@fontsource/oxanium": "^5.2.8","konva": "^9.3.0","leaflet": "^1.9.4",- "leaflet-rotate": "^0.2.8"+ "leaflet-rotate": "^0.2.8",+ "leaflet.gridlayer.googlemutant": "^0.16.0"}}diff --git a/frontend/src/App.svelte b/frontend/src/App.svelteindex 2afb455..cded13d 100644--- a/frontend/src/App.svelte+++ b/frontend/src/App.svelte@@ -1,5 +1,6 @@<script>- import { uiState, initSession } from './lib/state.svelte.js';+ import { uiState, initSession, caseState, reloadCase, toast } from './lib/state.svelte.js';+ import { startEvents, onEvent } from './lib/events.js';import { WORKSPACES, workspaceOf, toolFromHash } from './lib/workspaces.js';import Icon from './components/Icon.svelte';import Logo from './components/Logo.svelte';@@ -60,6 +61,15 @@// Load the case list and reopen the last-used case (survives reloads).initSession().catch(() => {});++ // Live nudges from our own backend (SSE, same-origin — still local-first):+ // the capture extension files screenshots while this tab just sits here, and+ // they must show up without a reload. Refresh only what the nudge names.+ startEvents();+ onEvent('capture', (ev) => {+ toast(`Capture filed from ${ev.site}: ${ev.title}`, 'ok', 5000);+ if (caseState.current?.id === ev.case_id) reloadCase();+ });</script><div class="shell">diff --git a/frontend/src/lib/events.js b/frontend/src/lib/events.jsnew file mode 100644index 0000000..7fef261--- /dev/null+++ b/frontend/src/lib/events.js@@ -0,0 +1,48 @@+/**+ * App side of the server's SSE nudge channel (/api/events, api/events.py).+ *+ * The capture extension files screenshots while the app tab just sits there —+ * this subscription is how a capture shows up without a reload. Same-origin+ * only (the app's own backend), so the local-first rule holds: nothing here+ * ever leaves the machine.+ *+ * Events are nudges, not data: a handler reacts by re-fetching through the+ * normal API. EventSource reconnects by itself, and a missed nudge costs a+ * manual refresh, never correctness.+ */++const handlers = new Map(); // event type -> Set<callback>+let source = null;++/** Route one event object to its type's subscribers. Exported for tests. */+export function dispatch(event) {+ if (!event || typeof event.type !== 'string') return;+ for (const cb of handlers.get(event.type) ?? []) {+ try {+ cb(event);+ } catch {+ /* one broken handler must not starve the others */+ }+ }+}++/** Open the stream once per page life. No-op where EventSource is missing+ * (tests) or when already started. */+export function startEvents(EventSourceImpl = globalThis.EventSource) {+ if (source || !EventSourceImpl) return;+ source = new EventSourceImpl('/api/events');+ source.onmessage = (e) => {+ try {+ dispatch(JSON.parse(e.data));+ } catch {+ /* not our JSON — ignore */+ }+ };+}++/** Subscribe to one event type. Returns the unsubscribe function. */+export function onEvent(type, cb) {+ if (!handlers.has(type)) handlers.set(type, new Set());+ handlers.get(type).add(cb);+ return () => handlers.get(type)?.delete(cb);+}diff --git a/frontend/src/lib/events.test.js b/frontend/src/lib/events.test.jsnew file mode 100644index 0000000..3399f2d--- /dev/null+++ b/frontend/src/lib/events.test.js@@ -0,0 +1,69 @@+import { describe, it, expect } from 'vitest';+import { dispatch, onEvent, startEvents } from './events.js';++// The nudge channel drives live refresh: what must hold is the routing —+// handlers get exactly their type, unsubscribe really stops them, and a+// malformed event or a throwing handler never breaks the others.++describe('event routing', () => {+ it('routes events to their type and nothing else', () => {+ const seen = [];+ const off = onEvent('capture', (e) => seen.push(e.case_id));+ dispatch({ type: 'capture', case_id: 'c1' });+ dispatch({ type: 'other', case_id: 'nope' });+ expect(seen).toEqual(['c1']);+ off();+ });++ it('unsubscribe stops delivery', () => {+ let calls = 0;+ const off = onEvent('capture', () => calls++);+ dispatch({ type: 'capture' });+ off();+ dispatch({ type: 'capture' });+ expect(calls).toBe(1);+ });++ it('a throwing handler does not starve the next one', () => {+ let reached = false;+ const off1 = onEvent('capture', () => {+ throw new Error('boom');+ });+ const off2 = onEvent('capture', () => (reached = true));+ dispatch({ type: 'capture' });+ expect(reached).toBe(true);+ off1();+ off2();+ });++ it('ignores malformed events', () => {+ expect(() => {+ dispatch(null);+ dispatch({});+ dispatch({ type: 42 });+ }).not.toThrow();+ });+});++describe('startEvents', () => {+ it('opens one stream and feeds dispatch from onmessage', () => {+ const instances = [];+ class FakeEventSource {+ constructor(url) {+ this.url = url;+ instances.push(this);+ }+ }+ startEvents(FakeEventSource);+ startEvents(FakeEventSource); // second call must not open a second stream+ expect(instances.length).toBe(1);+ expect(instances[0].url).toBe('/api/events');++ const seen = [];+ const off = onEvent('capture', (e) => seen.push(e.title));+ instances[0].onmessage({ data: JSON.stringify({ type: 'capture', title: 'Spot' }) });+ instances[0].onmessage({ data: 'not json' }); // must not throw+ expect(seen).toEqual(['Spot']);+ off();+ });+});diff --git a/frontend/src/lib/extBridge.js b/frontend/src/lib/extBridge.jsnew file mode 100644index 0000000..e0e3c19--- /dev/null+++ b/frontend/src/lib/extBridge.js@@ -0,0 +1,75 @@+/**+ * App side of the capture-extension bridge (extension/bridge.js).+ *+ * The Google (Maps JS) widget basemap has no tiles to stitch and its DOM+ * imagery is off-limits (IMAGERY_PROVIDERS.md), so its Capture button needs+ * screen pixels. The extension supplies them through one tabs.captureVisibleTab+ * behind the user's click — no share prompt, no sharing bar, fullscreen kept —+ * and this module is the only place the app talks to it.+ *+ * Detection is synchronous: the extension's content script stamps+ * `data-azimut-capture-extension` on <html> at document_start, before the app+ * mounts. Installing the extension with the app already open therefore needs+ * one tab reload — Settings says so next to the install button.+ */++const CHANNEL = 'azimut-capture-ext';++/** The installed extension's version, or null. */+export function extensionVersion(doc = document) {+ return doc.documentElement.dataset.azimutCaptureExtension || null;+}++let seq = 0;++/**+ * One frame of this tab (a PNG data URL), via the extension.+ * Rejects when the extension is absent, silent (timeout) or refused by the+ * browser — the caller owns the user-facing explanation.+ */+export function captureTab({ timeoutMs = 4000, win = window } = {}) {+ return new Promise((resolve, reject) => {+ const id = `cap-${++seq}`;+ const timer = setTimeout(() => {+ win.removeEventListener('message', onMessage);+ reject(new Error('the capture extension did not answer'));+ }, timeoutMs);+ function onMessage(event) {+ // origin is the boundary that matters: the reply must come from our own+ // page (where only our bridge content script posts on this channel).+ // No event.source check — the app hosts no same-origin iframes, and+ // happy-dom (tests) never sets source to the window like browsers do.+ if (event.origin !== win.location.origin) return;+ const msg = event.data;+ if (!msg || msg.channel !== CHANNEL || msg.type !== 'capture-result' || msg.id !== id) return;+ clearTimeout(timer);+ win.removeEventListener('message', onMessage);+ if (msg.ok && msg.dataUrl) {+ resolve(msg.dataUrl);+ } else {+ const err = new Error(msg.error || 'the capture extension refused');+ // browsers refuse tab screenshots until the extension has been invoked+ // once on the tab (activeTab) — a distinct, one-time, fixable case+ err.needsActivation = !!msg.needsActivation;+ reject(err);+ }+ }+ win.addEventListener('message', onMessage);+ win.postMessage({ channel: CHANNEL, type: 'capture', id }, win.location.origin);+ });+}++/**+ * Subscribe to the extension's "activated" signal: the user just clicked the+ * extension on this tab (granting activeTab), so a previously refused capture+ * can now be retried. Returns an unsubscribe function.+ */+export function onActivated(cb, win = window) {+ const onMessage = (event) => {+ if (event.origin !== win.location.origin) return;+ const msg = event.data;+ if (msg && msg.channel === CHANNEL && msg.type === 'activated') cb();+ };+ win.addEventListener('message', onMessage);+ return () => win.removeEventListener('message', onMessage);+}diff --git a/frontend/src/lib/extBridge.test.js b/frontend/src/lib/extBridge.test.jsnew file mode 100644index 0000000..42b76a0--- /dev/null+++ b/frontend/src/lib/extBridge.test.js@@ -0,0 +1,88 @@+// @vitest-environment happy-dom+import { describe, it, expect, afterEach } from 'vitest';+import { extensionVersion, captureTab, onActivated } from './extBridge.js';++// The bridge protocol is the app's only path to widget pixels, so what these+// tests pin is the contract: detection reads the content script's marker, and+// captureTab resolves/rejects on exactly its own correlated reply — a wrong+// id, a foreign channel, or silence must never produce an image.++afterEach(() => {+ delete document.documentElement.dataset.azimutCaptureExtension;+});++describe('extensionVersion', () => {+ it('is null without the marker and the version with it', () => {+ expect(extensionVersion()).toBe(null);+ document.documentElement.dataset.azimutCaptureExtension = '0.1.0';+ expect(extensionVersion()).toBe('0.1.0');+ });+});++// A fake bridge.js: answers capture requests on the window like the content+// script does. Returns a disposer.+function fakeBridge(answer) {+ const onMessage = (event) => {+ const msg = event.data;+ if (!msg || msg.channel !== 'azimut-capture-ext' || msg.type !== 'capture') return;+ window.postMessage(+ { channel: 'azimut-capture-ext', type: 'capture-result', id: msg.id, ...answer(msg) },+ window.location.origin+ );+ };+ window.addEventListener('message', onMessage);+ return () => window.removeEventListener('message', onMessage);+}++describe('captureTab', () => {+ it('resolves with the frame the bridge returns', async () => {+ const off = fakeBridge(() => ({ ok: true, dataUrl: 'data:image/png;base64,AAAA' }));+ await expect(captureTab()).resolves.toBe('data:image/png;base64,AAAA');+ off();+ });++ it('rejects with the bridge error when the browser refused the grab', async () => {+ const off = fakeBridge(() => ({ ok: false, error: 'not the Azimut app' }));+ await expect(captureTab()).rejects.toThrow('not the Azimut app');+ off();+ });++ it('ignores replies with a foreign id and times out instead', async () => {+ // a stale or concurrent reply must not be mistaken for ours+ const off = fakeBridge(() => ({ ok: true, dataUrl: 'data:x', id: 'someone-else' }));+ const offWrong = fakeBridge((msg) => ({ ok: true, dataUrl: 'data:x', id: `${msg.id}-not` }));+ await expect(captureTab({ timeoutMs: 120 })).rejects.toThrow('did not answer');+ off();+ offWrong();+ });++ it('times out when no extension is installed', async () => {+ await expect(captureTab({ timeoutMs: 120 })).rejects.toThrow('did not answer');+ });++ it('marks a refusal that one extension click would fix (activeTab)', async () => {+ // browsers refuse tab screenshots until the extension is invoked once on+ // the tab; the app must be able to say "click the icon" instead of "failed"+ const off = fakeBridge(() => ({ ok: false, needsActivation: true, error: 'activeTab required' }));+ const err = await captureTab().catch((e) => e);+ expect(err.needsActivation).toBe(true);+ off();+ });+});++describe('onActivated', () => {+ it('fires when the bridge announces the activation click, until unsubscribed', async () => {+ let calls = 0;+ const off = onActivated(() => calls++);+ const announce = () =>+ new Promise((r) => {+ window.postMessage({ channel: 'azimut-capture-ext', type: 'activated' }, window.location.origin);+ setTimeout(r, 30);+ });+ await announce();+ expect(calls).toBe(1);+ off();+ await announce();+ expect(calls).toBe(1); // unsubscribed — no further calls+ });+});diff --git a/frontend/src/lib/gmaps.js b/frontend/src/lib/gmaps.jsnew file mode 100644index 0000000..1e053ca--- /dev/null+++ b/frontend/src/lib/gmaps.js@@ -0,0 +1,188 @@+/**+ * Google Maps JavaScript API — loader + GoogleMutant layer factory.+ *+ * The EEA-viable Google satellite route (docs/IMAGERY_PROVIDERS.md § Google in+ * the EEA): a real google.maps.Map rendered by the official JS API, synced+ * under Leaflet by the GoogleMutant plugin so every Leaflet overlay (measure+ * tools, markers, reference windows, labels) keeps working on top.+ *+ * Local-first: nothing here runs until the user actually selects the widget+ * basemap — the script load *is* the user action needing the network.+ *+ * Billing: one "dynamic map load" per google.maps.Map instantiation; pan/zoom+ * afterwards is free. The mutant layer must therefore be created once and+ * reused across basemap switches — see the layer cache in Satellite.svelte.+ */+// Import the plugin's ESM source and use its exported class directly. Both of+// its other integration surfaces are broken under a bundler (verified 2026-07):+// the bare specifier resolves to the "browser" IIFE build, which reads `this.L`+// and crashes the whole app at load (`this` is undefined in strict ESM), and+// the .mjs's own `L.gridLayer.googleMutant` factory binds to a global `L` it+// never imports, so `new L.GridLayer.GoogleMutant` is "not a constructor".+import GoogleMutant from 'leaflet.gridlayer.googlemutant/src/Leaflet.GoogleMutant.mjs';++/**+ * GoogleMutant, but able to survive a rotated map.+ *+ * The mutant works by running a hidden google.maps.Map and cloning its <img>+ * tile nodes into a plain Leaflet GridLayer — so the visible tiles rotate with+ * the tile pane like any other layer. What breaks is coverage: the hidden map+ * is sized to the Leaflet container, so Google only ever renders the tiles of+ * an unrotated viewport, while leaflet-rotate asks the grid for the rotated+ * bounding box. The corner tiles are never cloned and the view has holes.+ *+ * Sizing the hidden map to a square of the container's diagonal, centred on it,+ * covers every bearing at once — a rotated W×H rect always fits inside the+ * circle of its own diagonal — so no rotation handler is needed here. It costs+ * extra tile renders inside the hidden map, but not extra billing: the dynamic+ * map load is charged per google.maps.Map, and panning/rendering after it is+ * free.+ */+class RotatableGoogleMutant extends GoogleMutant {+ _initMutantContainer() {+ super._initMutantContainer();+ this._fitMutantToDiagonal();+ this._map.on('resize', this._fitMutantToDiagonal, this);+ }++ onRemove(map) {+ map.off('resize', this._fitMutantToDiagonal, this);+ return super.onRemove(map);+ }++ _fitMutantToDiagonal() {+ if (!this._map || !this._mutantContainer) return;+ const size = this._map.getSize();+ const side = Math.ceil(Math.sqrt(size.x * size.x + size.y * size.y));+ const style = this._mutantContainer.style;+ style.width = `${side}px`;+ style.height = `${side}px`;+ // the container is .leaflet-top.leaflet-left (pinned at 0,0) — pull it back+ // by half the overflow so the hidden map stays concentric with Leaflet's,+ // which is what makes the coverage symmetric on all four sides+ style.marginLeft = `${Math.round((size.x - side) / 2)}px`;+ style.marginTop = `${Math.round((size.y - side) / 2)}px`;+ if (this._mutant) window.google?.maps?.event?.trigger(this._mutant, 'resize');+ }+}++let loadPromise = null;+let loadedKey = null; // the key the script was loaded with — one per page life++/** The API key the Maps JS script is already bound to, if loaded. Google's+ * script can't be re-loaded with another key without a full page reload, so+ * a key change after load can only be tested by reloading the app. */+export function googleMapsLoadedKey() {+ return loadedKey;+}++/**+ * Load the Maps JS API from the provider's loader URL (key included — a JS+ * API key is client-side by design, referrer-restricted rather than secret).+ *+ * `onAuthFailure` fires if Google rejects the key — that can happen minutes+ * after a successful load (gm_authFailure is async), so the caller must+ * handle it as a runtime event, not a load error.+ */+export function loadGoogleMaps(loaderUrl, { onAuthFailure } = {}) {+ // gm_authFailure is Google's only key-rejection signal; keep it wired even+ // when the script is already loaded (a Settings re-test swaps the handler)+ window.gm_authFailure = () => onAuthFailure?.();+ if (window.google?.maps) return Promise.resolve();+ if (loadPromise) return loadPromise;+ loadedKey = keyFromLoaderUrl(loaderUrl);+ loadPromise = new Promise((resolve, reject) => {+ const cb = '__azimutGmapsReady';+ window[cb] = () => {+ delete window[cb];+ resolve();+ };+ const script = document.createElement('script');+ script.src = `${loaderUrl}&loading=async&callback=${cb}`;+ script.async = true;+ script.onerror = () => {+ loadPromise = null; // a network failure may be transient — allow retry+ delete window[cb];+ reject(new Error('could not load the Google Maps script'));+ };+ document.head.appendChild(script);+ });+ return loadPromise;+}++/**+ * Prove a Maps JS key in the only place it can be proven: a real map in this+ * browser. Loads the script, spins up a hidden 1-tile satellite map and races+ * `tilesloaded` (key works) against `gm_authFailure` (Google rejected it) and+ * a timeout. Because Google's script binds to one key per page life, a+ * *changed* key can only be re-probed after a reload — callers should check+ * googleMapsLoadedKey() first.+ *+ * The verdict carries `billed`: the probe's own map is a real dynamic map load+ * on the user's bill, and no backend proxy can see it, so the caller must+ * report it to the usage counter or the counter drifts under Google's number.+ */+export async function probeKey(loaderUrl, { timeoutMs = 12000 } = {}) {+ let rejected = false;+ try {+ await loadGoogleMaps(loaderUrl, { onAuthFailure: () => (rejected = true) });+ } catch (e) {+ // the script never loaded, so no map was ever constructed — nothing billed+ return { ok: false, detail: e.message, billed: false };+ }+ const holder = document.createElement('div');+ // Must stay INSIDE the viewport: Chrome culls rendering for off-screen+ // fixed elements, so an off-screen map never fires `tilesloaded` and the+ // probe times out on a perfectly good key (verified headless, 2026-07).+ // Near-zero opacity keeps it invisible without suppressing rendering.+ holder.style.cssText =+ 'position:fixed;left:0;bottom:0;width:128px;height:128px;opacity:0.01;pointer-events:none';+ document.body.appendChild(holder);+ try {+ const verdict = await new Promise((resolve) => {+ const timer = setTimeout(+ () => resolve({ ok: false, detail: 'no response from Google (timeout)' }),+ timeoutMs+ );+ window.gm_authFailure = () => {+ rejected = true;+ clearTimeout(timer);+ resolve({ ok: false, detail: 'Google rejected the key (gm_authFailure)' });+ };+ const map = new window.google.maps.Map(holder, {+ center: { lat: 0, lng: 0 },+ zoom: 1,+ mapTypeId: 'satellite',+ disableDefaultUI: true,+ });+ map.addListener('tilesloaded', () => {+ clearTimeout(timer);+ resolve(+ rejected+ ? { ok: false, detail: 'Google rejected the key (gm_authFailure)' }+ : { ok: true, detail: 'satellite map rendered' }+ );+ });+ });+ // A google.maps.Map was constructed above, and Google bills one dynamic map+ // load for every one it accepts — this throwaway included. Only a key it+ // rejected is free: there is no valid project to bill it to. A timeout still+ // counts, since the map was built and we cannot prove it was not served.+ return { ...verdict, billed: !rejected };+ } finally {+ holder.remove();+ }+}++function keyFromLoaderUrl(url) {+ try {+ return new URL(url).searchParams.get('key');+ } catch {+ return null;+ }+}++/** A GoogleMutant satellite layer — one billed map load per creation. */+export function createSatelliteMutant(maxZoom = 21, attribution = 'Map data © Google') {+ return new RotatableGoogleMutant({ type: 'satellite', maxZoom, attribution });+}diff --git a/frontend/src/lib/gmaps.test.js b/frontend/src/lib/gmaps.test.jsnew file mode 100644index 0000000..a491552--- /dev/null+++ b/frontend/src/lib/gmaps.test.js@@ -0,0 +1,103 @@+// @vitest-environment happy-dom+import { describe, it, expect, afterEach } from 'vitest';++/**+ * Stand in for the Maps JS API: a google.maps.Map that either renders+ * (`tilesloaded`) or gets rejected (`gm_authFailure`), on the next microtask so+ * probeKey has installed its handlers first.+ */+function stubGoogleMaps({ reject = false } = {}) {+ window.google = {+ maps: {+ Map: class {+ constructor() {+ this._listeners = {};+ queueMicrotask(() => {+ if (reject) window.gm_authFailure?.();+ else this._listeners.tilesloaded?.();+ });+ }+ addListener(event, cb) {+ this._listeners[event] = cb;+ }+ },+ },+ };+}++describe('gmaps module', () => {+ it('imports cleanly and constructs a real GridLayer mutant', async () => {+ // Regression guards for the plugin's two broken integration surfaces+ // (each one shipped a real bug): the "browser" IIFE entry crashes the+ // whole bundle at load (`this.L`, `this` undefined in strict ESM), and+ // its `L.gridLayer.googleMutant` factory binds to a global L it never+ // imports ("GoogleMutant is not a constructor" at layer creation). We+ // construct the exported class directly — this test fails if the import+ // path or the constructor ever regresses.+ const { createSatelliteMutant, googleMapsLoadedKey } = await import('./gmaps.js');+ const L = (await import('leaflet')).default;+ const layer = createSatelliteMutant(21, 'Map data © Google');+ expect(layer instanceof L.GridLayer).toBe(true);+ expect(layer.options.maxZoom).toBe(21);+ expect(layer.options.attribution).toBe('Map data © Google');+ expect(googleMapsLoadedKey()).toBe(null); // nothing loaded in tests+ });++ it('sizes the hidden mutant map to the container diagonal, centred', async () => {+ // What makes the Google basemap rotatable. The mutant clones tiles out of a+ // hidden google.maps.Map sized to the Leaflet container, so a rotated view+ // (leaflet-rotate asks the grid for the rotated bounding box) wants corner+ // tiles Google never rendered — blank corners. A square of the diagonal,+ // centred, covers every bearing at once. If this regresses, rotation still+ // "works" but silently eats the corners of the map.+ const { createSatelliteMutant } = await import('./gmaps.js');+ const layer = createSatelliteMutant();+ const container = document.createElement('div');+ layer._mutantContainer = container;+ layer._map = { getSize: () => ({ x: 800, y: 600 }) };++ layer._fitMutantToDiagonal();++ const side = Math.ceil(Math.sqrt(800 ** 2 + 600 ** 2)); // 1000+ expect(container.style.width).toBe(`${side}px`);+ expect(container.style.height).toBe(`${side}px`);+ // pulled back by half the overflow, so it stays concentric with the map+ expect(container.style.marginLeft).toBe(`${(800 - side) / 2}px`);+ expect(container.style.marginTop).toBe(`${(600 - side) / 2}px`);+ // the square must cover the container's own diagonal, whatever the bearing+ expect(side).toBeGreaterThanOrEqual(Math.hypot(800, 600));+ });++ describe('probeKey billing', () => {+ afterEach(() => {+ delete window.google;+ delete window.gm_authFailure;+ });++ it('flags the map load it costs when Google accepts the key', async () => {+ // The probe builds a real google.maps.Map, which Google bills as a dynamic+ // map load. It happens in the browser, so the backend tile proxy cannot+ // see it — only this flag makes Settings report it. If it regresses,+ // testing a key silently drifts the counter under Google's real number.+ const { probeKey } = await import('./gmaps.js');+ stubGoogleMaps();++ const verdict = await probeKey('https://maps.googleapis.com/maps/api/js?key=good');++ expect(verdict.ok).toBe(true);+ expect(verdict.billed).toBe(true);+ });++ it('bills nothing for a key Google rejects', async () => {+ // A rejected key renders no map and has no valid project to bill, so+ // counting it would push the counter above Google's real number.+ const { probeKey } = await import('./gmaps.js');+ stubGoogleMaps({ reject: true });++ const verdict = await probeKey('https://maps.googleapis.com/maps/api/js?key=bad');++ expect(verdict.ok).toBe(false);+ expect(verdict.billed).toBe(false);+ });+ });+});diff --git a/frontend/src/lib/inspect.js b/frontend/src/lib/inspect.jsindex a5e9f24..c7a3876 100644--- a/frontend/src/lib/inspect.js+++ b/frontend/src/lib/inspect.js@@ -69,6 +69,18 @@ export function buildOps(filters, values, crop = null) {return ops;}+/**+ * A collage piece's recipe stripped back to its unprojected pixels.+ *+ * Auto-stitch's panorama modes bake their warp into the piece as a `remap` op,+ * and that op is only valid for the pixels it was solved on: a cylinder is not a+ * pinhole view, so re-stitching a remapped piece would measure the wrong scene+ * and compound one projection onto the last. Every stitch therefore starts here.+ */+export function pinholeOps(save) {+ return (save?.ops ?? []).filter((o) => o.op !== 'remap');+}+// ---------------------------------------------------------------------------// Collage perspective: map an image's box to a 4-point quad via a CSS matrix3d.// Classic homography-from-4-corners (general 2D projection). The same quad isdiff --git a/frontend/src/lib/inspect.test.js b/frontend/src/lib/inspect.test.jsindex d31bef4..31591ba 100644--- a/frontend/src/lib/inspect.test.js+++ b/frontend/src/lib/inspect.test.js@@ -2,11 +2,30 @@ import { describe, it, expect } from 'vitest';import {clampCrop, moveCrop, resizeCropByHandle,QUAD_SIDES, quadEdgeMidpoints, moveQuadEdge, quadCentroid,- quadsBounds, translateQuad, moveQuads, rotateQuads, scaleQuads,+ quadsBounds, translateQuad, moveQuads, rotateQuads, scaleQuads, pinholeOps,} from './inspect.js';const near = (a, b, eps = 1e-6) => Math.abs(a - b) < eps;+describe('pinholeOps', () => {+ const remap = { op: 'remap', params: { warp: 'cylindrical' } };+ const bright = { op: 'brightness', params: { amount: 1.2 } };++ it('leaves a piece that was never stitched alone', () => {+ expect(pinholeOps({ ops: [bright] })).toEqual([bright]);+ });+ it('drops a solved warp so a re-stitch never compounds two projections', () => {+ expect(pinholeOps({ ops: [bright, remap] })).toEqual([bright]);+ });+ it('drops every warp, however many stitches a piece has been through', () => {+ expect(pinholeOps({ ops: [remap, bright, remap] })).toEqual([bright]);+ });+ it('handles a recipe with no ops at all', () => {+ expect(pinholeOps({})).toEqual([]);+ expect(pinholeOps(null)).toEqual([]);+ });+});+describe('clampCrop', () => {it('keeps a valid crop untouched', () => {expect(clampCrop({ x: 0.1, y: 0.2, w: 0.5, h: 0.4 })).toEqual({ x: 0.1, y: 0.2, w: 0.5, h: 0.4 });diff --git a/frontend/src/lib/maplinks.js b/frontend/src/lib/maplinks.jsindex 71ccf84..61e4807 100644--- a/frontend/src/lib/maplinks.js+++ b/frontend/src/lib/maplinks.js@@ -28,11 +28,6 @@ export function mapLinks(lat, lon, zoom = 17) {label: 'Yandex Satellite',url: `https://yandex.com/maps/?ll=${lon},${lat}&z=${z}&l=sat`,},- {- id: 'satellites_pro',- label: 'Satellites.pro',- url: `https://satellites.pro/#${lat},${lon},${z}`,- },{id: 'sentinel',label: 'Copernicus Browser',diff --git a/frontend/src/lib/maplinks.test.js b/frontend/src/lib/maplinks.test.jsindex 639f1ed..75cce32 100644--- a/frontend/src/lib/maplinks.test.js+++ b/frontend/src/lib/maplinks.test.js@@ -13,7 +13,6 @@ describe('mapLinks', () => {'google','google_earth','google_sat',- 'satellites_pro','sentinel','yandex','zoom_earth',@@ -21,9 +20,11 @@ describe('mapLinks', () => {);});- it('deliberately excludes the in-tool tile providers (Esri, OSM)', () => {+ it('deliberately excludes the in-tool tile providers (Esri, OSM) and duplicates', () => {expect(byId.esri).toBeUndefined();expect(byId.osm).toBeUndefined();+ // Satellites.pro was dropped: its basemaps are the other links' imagery+ expect(byId.satellites_pro).toBeUndefined();});it('embeds the coordinates in each URL', () => {diff --git a/frontend/src/lib/screenCrop.js b/frontend/src/lib/screenCrop.jsnew file mode 100644index 0000000..602af22--- /dev/null+++ b/frontend/src/lib/screenCrop.js@@ -0,0 +1,60 @@+/**+ * Screen-crop geometry for widget basemaps (Google Maps JS).+ *+ * Widget basemaps have no tiles to stitch — Google's terms allow nothing+ * programmatic out of the widget — so their captures are cropped out of a+ * frame of the tab supplied by the capture extension (lib/extBridge.js).+ * That makes the crop only as trustworthy as the mapping from CSS px to+ * captured px, which is what lives here: a single scale factor, valid only+ * while the frame really is this tab's viewport.+ */++/** Fractional aspect-ratio slack allowed when checking a frame is the surface+ * we expect. Generous enough for rounding and odd pixel sizes, tight enough+ * that a foreign or stale frame can't pass. */+export const REGISTRATION_TOLERANCE = 0.02;++/**+ * Is this frame really the surface we're about to map onto?+ *+ * The crop math is a single scale factor, so it fails silently — cropping+ * real pixels off the wrong surface — if the frame isn't what we assumed+ * (browser zoom changed mid-flight, a stale frame from before a resize).+ * Aspect ratio is the one property we can check without trusting anyone's+ * labelling, so a mismatch is the caller's cue to refuse.+ */+export function isRegistered(videoW, videoH, expectedW, expectedH, tol = REGISTRATION_TOLERANCE) {+ if (!videoW || !videoH || !expectedW || !expectedH) return false;+ const expected = expectedW / expectedH;+ const got = videoW / videoH;+ return Math.abs(got - expected) <= tol * expected;+}++/**+ * Map `rect` (map-container CSS px) onto a captured viewport frame's pixels.+ * The map element's own position (`mapRect`) is the offset into the viewport;+ * the scale is measured from the frame itself, so device pixel ratio never+ * has to be guessed.+ *+ * Returns null when the mapped rect would fall outside the frame: better no+ * capture than one padded with whatever happened to be at the edge.+ */+export function sourceRect(rect, { mapRect, viewportWidth, videoWidth, videoHeight }) {+ const scale = videoWidth / viewportWidth;+ const sx = Math.round((mapRect.left + rect.x) * scale);+ const sy = Math.round((mapRect.top + rect.y) * scale);+ const sw = Math.round(rect.w * scale);+ const sh = Math.round(rect.h * scale);+ if (sx < 0 || sy < 0 || sw <= 0 || sh <= 0) return null;+ if (sx + sw > videoWidth || sy + sh > videoHeight) return null;+ return { sx, sy, sw, sh };+}++/**+ * Screen pixels are the ceiling here: a frame bigger than the map view has no+ * pixels to come from. Tile basemaps have no such limit — they just fetch more+ * tiles — which is why this check is widget-only.+ */+export function frameFitsView(rect, mapRect) {+ return rect.w <= mapRect.width && rect.h <= mapRect.height;+}diff --git a/frontend/src/lib/screenCrop.test.js b/frontend/src/lib/screenCrop.test.jsnew file mode 100644index 0000000..b1fc231--- /dev/null+++ b/frontend/src/lib/screenCrop.test.js@@ -0,0 +1,87 @@+import { describe, it, expect } from 'vitest';+import { isRegistered, sourceRect, frameFitsView, REGISTRATION_TOLERANCE } from './screenCrop.js';++// A widget capture crops real pixels out of a tab frame, so every bug in here+// produces a plausible-looking image of the wrong thing — which is the one+// failure a proof tool cannot ship. These tests pin the mapping and the refusals.++describe('isRegistered', () => {+ it('accepts the viewport the crop math assumes, at any pixel density', () => {+ expect(isRegistered(1440, 900, 1440, 900)).toBe(true); // 1:1+ expect(isRegistered(2880, 1800, 1440, 900)).toBe(true); // 2× dpr+ });++ it('refuses a frame whose shape is not the expected viewport', () => {+ // a stale frame from before a resize, or browser zoom changing mid-flight:+ // the same scale factor applied to different pixels would crop the wrong+ // thing and look fine doing it+ expect(isRegistered(1920, 1080, 800, 600)).toBe(false);+ });++ it('tolerates rounding but not a real mismatch', () => {+ const w = 800, h = 600;+ const ratio = w / h;+ const justInside = ratio * (1 + REGISTRATION_TOLERANCE * 0.9);+ const justOutside = ratio * (1 + REGISTRATION_TOLERANCE * 1.1);+ expect(isRegistered(justInside * 600, 600, w, h)).toBe(true);+ expect(isRegistered(justOutside * 600, 600, w, h)).toBe(false);+ });++ it('treats a frame with no dimensions as unregistered', () => {+ // an image that hasn't decoded yet must never pass+ expect(isRegistered(0, 0, 800, 600)).toBe(false);+ });+});++describe('sourceRect', () => {+ const mapRect = { left: 100, top: 50, width: 800, height: 600 };++ it('offsets by the map element rect within the viewport frame', () => {+ const out = sourceRect(+ { x: 10, y: 20, w: 400, h: 300 },+ { mapRect, viewportWidth: 1440, videoWidth: 1440, videoHeight: 900 }+ );+ expect(out).toEqual({ sx: 110, sy: 70, sw: 400, sh: 300 });+ });++ it('scales a frame taken at a higher device pixel ratio', () => {+ const out = sourceRect(+ { x: 10, y: 20, w: 400, h: 300 },+ { mapRect, viewportWidth: 1440, videoWidth: 2880, videoHeight: 1800 }+ );+ expect(out).toEqual({ sx: 220, sy: 140, sw: 800, sh: 600 });+ });++ it('refuses a frame that runs past the captured pixels', () => {+ // rather than return a crop padded with whatever sat at the edge+ expect(+ sourceRect(+ { x: 700, y: 500, w: 900, h: 600 },+ { mapRect, viewportWidth: 1440, videoWidth: 1440, videoHeight: 900 }+ )+ ).toBe(null);+ });++ it('refuses a rect that starts off-surface', () => {+ expect(+ sourceRect(+ { x: -200, y: 0, w: 100, h: 100 },+ { mapRect, viewportWidth: 1440, videoWidth: 1440, videoHeight: 900 }+ )+ ).toBe(null);+ });+});++describe('frameFitsView', () => {+ const mapRect = { left: 0, top: 0, width: 800, height: 600 };++ it('accepts a frame the screen can actually supply', () => {+ expect(frameFitsView({ x: 0, y: 0, w: 800, h: 600 }, mapRect)).toBe(true);+ });++ it('rejects a preset larger than the map view', () => {+ // screen pixels are the ceiling for a widget basemap: a 1200×675 preset has+ // nowhere to come from in an 800×600 view (a tile basemap would just fetch)+ expect(frameFitsView({ x: 0, y: 0, w: 1200, h: 675 }, mapRect)).toBe(false);+ });+});diff --git a/frontend/src/lib/sentinel.js b/frontend/src/lib/sentinel.jsnew file mode 100644index 0000000..b9b956b--- /dev/null+++ b/frontend/src/lib/sentinel.js@@ -0,0 +1,137 @@+/**+ * Sentinel-2 basemap choices: which layer, and over which window.+ *+ * Both ride on the provider id as a variant — `sentinel2~SWIR~2026-05-01~2026-05-31`+ * — which is what the tile URL, the capture and the disk cache all key on+ * (engine/sentinel.py owns the same format on the backend). The map only ever+ * has to know the id; nothing downstream can forget the window.+ */++export const SENTINEL_ID = 'sentinel2';+const SEP = '~';++/** Layer ids we know the reason for. The real list comes from the backend+ * (/api/satellite/sentinel/layers) — a user's instance serves whatever its+ * configuration says, and only the instance knows. */+export const DEFAULT_LAYER = 'TRUE_COLOR';++/**+ * Pack a layer + window into a provider id. The plain default (true colour,+ * most recent) stays the bare id: it must not read as a second provider.+ */+export function variantId(baseId, { layer = DEFAULT_LAYER, from = '', to = '' } = {}) {+ if (baseId !== SENTINEL_ID) return baseId;+ const windowed = from && to;+ if ((layer || DEFAULT_LAYER) === DEFAULT_LAYER && !windowed) return baseId;+ const parts = [baseId, layer || DEFAULT_LAYER];+ if (windowed) parts.push(from, to);+ return parts.join(SEP);+}++/** ISO date (YYYY-MM-DD) for a Date, in UTC — the calendar Sentinel-2 passes+ * are dated by, not the viewer's timezone. */+export function isoDay(date) {+ return date.toISOString().slice(0, 10);+}++/** `n` days before `date`, as an ISO day. */+export function daysBefore(n, date = new Date()) {+ const out = new Date(date.getTime());+ out.setUTCDate(out.getUTCDate() - n);+ return isoDay(out);+}++/** True when both ends are ISO days in order — the shape the backend accepts,+ * checked here so a half-typed date never becomes a request. */+export function validWindow(from, to) {+ const iso = /^\d{4}-\d{2}-\d{2}$/;+ if (!iso.test(from || '') || !iso.test(to || '')) return false;+ if (Number.isNaN(Date.parse(from)) || Number.isNaN(Date.parse(to))) return false;+ return from <= to;+}++/** True for a single well-formed ISO day. */+export function validDay(day) {+ return validWindow(day, day);+}++/** How a window reads in the UI: a day, a range, or the layer's own default. */+export function windowLabel(from, to) {+ if (!validWindow(from, to)) return 'most recent';+ return from === to ? from : `${from} → ${to}`;+}++/**+ * The calendar month a day belongs to, and month arithmetic on 'YYYY-MM'.+ * Day 1 of the target month, so a 31st can never spill into the next one.+ */+export function monthOf(day) {+ return (day || isoDay(new Date())).slice(0, 7);+}++export function addMonths(month, delta) {+ const [y, m] = month.split('-').map(Number);+ const d = new Date(Date.UTC(y, m - 1 + delta, 1));+ return isoDay(d).slice(0, 7);+}++export function monthLabel(month) {+ const [y, m] = month.split('-').map(Number);+ return new Date(Date.UTC(y, m - 1, 1)).toLocaleDateString('en-US', {+ month: 'long',+ year: 'numeric',+ timeZone: 'UTC',+ });+}++/** First and last day of a month, as ISO days — the span a pass lookup covers. */+export function monthBounds(month) {+ const [y, m] = month.split('-').map(Number);+ return {+ from: `${month}-01`,+ to: isoDay(new Date(Date.UTC(y, m, 0))), // day 0 of next month = last of this+ };+}++/**+ * A month as calendar cells, Monday-first, padded with nulls so the first day+ * lands under its weekday. Trailing padding is left out — an empty last row is+ * just whitespace.+ */+export function monthGrid(month) {+ const { to } = monthBounds(month);+ const days = Number(to.slice(8));+ const [y, m] = month.split('-').map(Number);+ const firstWeekday = (new Date(Date.UTC(y, m - 1, 1)).getUTCDay() + 6) % 7; // Mon = 0+ const cells = Array(firstWeekday).fill(null);+ for (let d = 1; d <= days; d++) cells.push(`${month}-${String(d).padStart(2, '0')}`);+ return cells;+}++/**+ * How usable a pass is, at a glance. Sentinel-2 revisits every ~5 days but most+ * passes are cloud: the point of showing cover is to skip the ones that cost a+ * tile to discover are white.+ */+export function cloudClass(cloud) {+ if (cloud === null || cloud === undefined) return 'unknown';+ if (cloud < 20) return 'clear';+ if (cloud < 60) return 'part';+ return 'cloudy';+}++/** Cloud cover as a short badge — the reason to skip a date without paying for+ * a tile to find out. */+export function cloudLabel(cloud) {+ if (cloud === null || cloud === undefined) return '';+ return `${Math.round(cloud)}% cloud`;+}++/**+ * The date range a date search should default to: the last `days` days, ending+ * today. Sentinel-2 revisits every ~5 days, so a month is several passes —+ * enough that the list is never empty, short enough to stay readable.+ */+export function defaultSearchWindow(days = 30, now = new Date()) {+ return { from: daysBefore(days, now), to: isoDay(now) };+}diff --git a/frontend/src/lib/sentinel.test.js b/frontend/src/lib/sentinel.test.jsnew file mode 100644index 0000000..16fffab--- /dev/null+++ b/frontend/src/lib/sentinel.test.js@@ -0,0 +1,169 @@+import { describe, it, expect } from 'vitest';+import {+ variantId,+ isoDay,+ daysBefore,+ validWindow,+ validDay,+ windowLabel,+ cloudLabel,+ cloudClass,+ monthOf,+ addMonths,+ monthLabel,+ monthBounds,+ monthGrid,+ defaultSearchWindow,+ DEFAULT_LAYER,+ SENTINEL_ID,+} from './sentinel.js';++describe('variantId', () => {+ it('leaves the plain default basemap as the bare id', () => {+ // a second name for the same thing would cache twice and read as two+ // providers in a capture's provenance+ expect(variantId(SENTINEL_ID)).toBe('sentinel2');+ expect(variantId(SENTINEL_ID, { layer: DEFAULT_LAYER })).toBe('sentinel2');+ expect(variantId(SENTINEL_ID, { layer: '' })).toBe('sentinel2');+ });++ it('packs the layer and the window into the id', () => {+ expect(variantId(SENTINEL_ID, { layer: 'SWIR' })).toBe('sentinel2~SWIR');+ expect(variantId(SENTINEL_ID, { layer: 'SWIR', from: '2026-05-01', to: '2026-05-31' })).toBe(+ 'sentinel2~SWIR~2026-05-01~2026-05-31'+ );+ // a window on the default layer still needs naming+ expect(variantId(SENTINEL_ID, { from: '2026-05-01', to: '2026-05-01' })).toBe(+ 'sentinel2~TRUE_COLOR~2026-05-01~2026-05-01'+ );+ });++ it('ignores half a window (both ends or neither)', () => {+ expect(variantId(SENTINEL_ID, { layer: 'SWIR', from: '2026-05-01' })).toBe('sentinel2~SWIR');+ });++ it('never touches another provider', () => {+ expect(variantId('esri-world-imagery', { layer: 'SWIR' })).toBe('esri-world-imagery');+ });+});++describe('isoDay / daysBefore', () => {+ it('dates by the UTC calendar, not the viewer timezone', () => {+ expect(isoDay(new Date(Date.UTC(2026, 6, 14, 23, 30)))).toBe('2026-07-14');+ });++ it('walks back across a month boundary', () => {+ expect(daysBefore(14, new Date(Date.UTC(2026, 6, 7)))).toBe('2026-06-23');+ expect(daysBefore(0, new Date(Date.UTC(2026, 6, 7)))).toBe('2026-07-07');+ });+});++describe('validWindow', () => {+ it('accepts a well-formed range in order', () => {+ expect(validWindow('2026-05-01', '2026-05-31')).toBe(true);+ expect(validWindow('2026-05-01', '2026-05-01')).toBe(true); // a single day+ });++ it('rejects what the backend would reject, before it costs a request', () => {+ expect(validWindow('2026-05-31', '2026-05-01')).toBe(false); // reversed+ expect(validWindow('2026-05-01', '')).toBe(false);+ expect(validWindow('05/01/2026', '2026-05-31')).toBe(false);+ expect(validWindow('2026-5-1', '2026-05-31')).toBe(false); // half-typed+ expect(validWindow(undefined, undefined)).toBe(false);+ });+});++describe('windowLabel', () => {+ it('reads as a day, a range, or the layer default', () => {+ expect(windowLabel('2026-05-01', '2026-05-01')).toBe('2026-05-01');+ expect(windowLabel('2026-05-01', '2026-05-31')).toBe('2026-05-01 → 2026-05-31');+ expect(windowLabel('', '')).toBe('most recent');+ expect(windowLabel('2026-05-31', '2026-05-01')).toBe('most recent');+ });+});++describe('cloudLabel', () => {+ it('is the reason to skip a date without paying to find out', () => {+ expect(cloudLabel(3.4)).toBe('3% cloud');+ expect(cloudLabel(0)).toBe('0% cloud');+ });++ it('is empty when the service gave no figure', () => {+ expect(cloudLabel(null)).toBe('');+ expect(cloudLabel(undefined)).toBe('');+ });+});++describe('validDay', () => {+ it('accepts one well-formed day and nothing else', () => {+ expect(validDay('2026-05-01')).toBe(true);+ expect(validDay('2026-5-1')).toBe(false);+ expect(validDay('')).toBe(false);+ });+});++describe('cloudClass', () => {+ it('grades a pass by how much of it is cloud', () => {+ expect(cloudClass(0)).toBe('clear');+ expect(cloudClass(19.9)).toBe('clear');+ expect(cloudClass(20)).toBe('part');+ expect(cloudClass(59)).toBe('part');+ expect(cloudClass(60)).toBe('cloudy');+ // a pass with no figure is still a pass — it must not read as clear+ expect(cloudClass(null)).toBe('unknown');+ expect(cloudClass(undefined)).toBe('unknown');+ });+});++describe('month arithmetic', () => {+ it('reads the month off a day, defaulting to now', () => {+ expect(monthOf('2026-05-14')).toBe('2026-05');+ expect(monthOf('')).toMatch(/^\d{4}-\d{2}$/);+ });++ it('steps months without a 31st spilling into the next one', () => {+ expect(addMonths('2026-01', 1)).toBe('2026-02');+ expect(addMonths('2026-03', -1)).toBe('2026-02');+ expect(addMonths('2026-12', 1)).toBe('2027-01');+ expect(addMonths('2026-01', -1)).toBe('2025-12');+ });++ it('labels a month for a human', () => {+ expect(monthLabel('2026-07')).toBe('July 2026');+ });++ it('bounds a month, leap years included', () => {+ expect(monthBounds('2026-07')).toEqual({ from: '2026-07-01', to: '2026-07-31' });+ expect(monthBounds('2026-02')).toEqual({ from: '2026-02-01', to: '2026-02-28' });+ expect(monthBounds('2028-02').to).toBe('2028-02-29'); // leap+ });+});++describe('monthGrid', () => {+ it('pads the first day onto its weekday, Monday-first', () => {+ // 2026-07-01 is a Wednesday → two blanks before it+ const cells = monthGrid('2026-07');+ expect(cells.slice(0, 4)).toEqual([null, null, '2026-07-01', '2026-07-02']);+ expect(cells.at(-1)).toBe('2026-07-31');+ expect(cells.filter(Boolean)).toHaveLength(31);+ });++ it('needs no padding when a month opens on a Monday', () => {+ // 2026-06-01 is a Monday+ expect(monthGrid('2026-06')[0]).toBe('2026-06-01');+ });++ it('handles a Sunday start (the last Monday-first column)', () => {+ // 2026-02-01 is a Sunday → six blanks+ const cells = monthGrid('2026-02');+ expect(cells.slice(0, 6)).toEqual([null, null, null, null, null, null]);+ expect(cells[6]).toBe('2026-02-01');+ });+});++describe('defaultSearchWindow', () => {+ it('covers several revisits (Sentinel-2 passes every ~5 days)', () => {+ const now = new Date(Date.UTC(2026, 6, 14));+ expect(defaultSearchWindow(30, now)).toEqual({ from: '2026-06-14', to: '2026-07-14' });+ });+});diff --git a/frontend/src/lib/usage.js b/frontend/src/lib/usage.jsindex c5a3366..7b917a6 100644--- a/frontend/src/lib/usage.js+++ b/frontend/src/lib/usage.js@@ -8,16 +8,43 @@*//**- * Documented monthly free allowances, in tile requests — a yardstick for the+ * Default monthly free allowances, in billed requests — a yardstick for the* counter, not a guarantee (providers change their pricing; verify on their* pricing pages — links below). Verified 2026-07: Mapbox Static Tiles* 200k/month then $0.50 per extra 1,000 (billed to the account's card);* Google 2D Map Tiles 100k/month then $0.60 per extra 1,000, plus hard* server-side limits of 15,000 tiles/day and 6,000/min per project — a quota* cap set in the Cloud Console makes it stop instead of bill.- * Mirror of config.FREE_TIER on the backend (which enforces the soft block).+ * Sentinel Hub bills processing units, not tiles, but our 512×512 3-band 8-bit+ * tiles are 1 PU each, so the tile counter *is* the PU counter: 30,000 PU and+ * 30,000 requests/month on a free Copernicus General account (also 300/min).+ * google_js counts *map loads* (Maps JS dynamic maps — one per widget+ * instantiation, pan/zoom free): 10k/month on the 2025 Essentials tier.+ *+ * These are defaults only. A free tier belongs to the *account*, and providers+ * hand out more than they document without saying so (Copernicus still+ * documents 10k while provisioning 30k), so every function here takes the live+ * `free_tier` map from /api/settings — the user's own correction included — and+ * falls back to these. Mirror of config.FREE_TIER (which enforces the block).*/-export const FREE_TIER = { mapbox: 200_000, google: 100_000 };+export const FREE_TIER = { mapbox: 200_000, google: 100_000, google_js: 10_000, sentinelhub: 30_000 };++/** This account's allowance for a meter: the served figure, else the default. */+export function freeTier(meter, tiers = null) {+ return tiers?.[meter] ?? FREE_TIER[meter];+}++/** What one metered unit is, per meter — most bill tiles, the JS widget bills+ * whole map loads, and Sentinel Hub bills requests of any kind (a tile, but+ * also a date lookup). The wrong word would make the counter read as broken. */+export function meterUnit(meter) {+ if (meter === 'google_js') return 'map load';+ // Copernicus counts requests and PU against the same 30k allowance; a tile is+ // 1 of each, a WFS date query is 1 request and ~0.01 PU. "request" is the+ // word their own dashboard uses, and the only one true of both.+ if (meter === 'sentinelhub') return 'request';+ return 'tile';+}/** Share of the free tier past which the backend pauses a provider. */export const BLOCK_SHARE = 0.9;@@ -30,15 +57,42 @@ export const ECO_MAX_ZOOM = 15;export const USAGE_LINKS = {mapbox: 'https://console.mapbox.com/account/statistics/',google: 'https://console.cloud.google.com/google/maps-apis/quotas',+ google_js: 'https://console.cloud.google.com/google/maps-apis/quotas',+ sentinelhub: 'https://shapps.dataspace.copernicus.eu/dashboard/#/account/usage',};/** True when a metered provider is paused: past the soft block, no override. */-export function usageBlocked(count, meter, overrides = {}) {- const free = FREE_TIER[meter];+export function usageBlocked(count, meter, overrides = {}, tiers = null) {+ const free = freeTier(meter, tiers);if (!free || overrides[meter]) return false;return count >= free * BLOCK_SHARE;}+/**+ * The one-word verdict a collapsed provider card shows, so the whole Imagery+ * tab reads at a glance and only the card you open spends any text on itself.+ * Worst news first: a key that can't work is more urgent than a quota, and a+ * quota is more urgent than an untested key.+ */+export function providerStatus({+ key = '',+ enabled = true,+ status = null,+ count = 0,+ meter,+ overrides = {},+ tiers = null,+} = {}) {+ if (!key.trim()) return { tone: 'idle', label: 'Not set' };+ if (status && !status.ok) return { tone: 'bad', label: 'Key failed' };+ if (!enabled) return { tone: 'idle', label: 'Off' };+ if (usageBlocked(count, meter, overrides, tiers)) return { tone: 'bad', label: 'Paused' };+ // past the pause but explicitly overridden — the provider is billing now+ if (freeTierShare(count, meter, tiers) >= BLOCK_SHARE) return { tone: 'warn', label: 'Billing' };+ if (!status) return { tone: 'idle', label: 'Untested' };+ return { tone: 'ok', label: 'Key works' };+}+/*** CSS grid-cell size for a provider's live tile layer at a view zoom: the* tile edge shrunk by its display oversample. Oversampled providers (Google)@@ -57,6 +111,12 @@ export function layerCell(provider, zoom) {* aside for free imagery when paused (soft block) or zoomed out (eco mode —* paid detail only matters up close); captures follow the display, so* provenance stays honest.+ *+ * A provider's own `eco_max_zoom` wins over the user's global one, which is+ * tuned for basemaps that run to z22. Sentinel-2 stops at z14, so the global+ * z15 rule would swap it away at every zoom it can serve — it carries its own+ * shallower threshold instead. The soft block ignores all of this: it's a quota+ * guard, and a paused provider has nothing to show at any zoom.*/export function displayProviderId(provider,@@ -65,7 +125,8 @@ export function displayProviderId() {if (!provider?.meter) return provider?.id;if (blocked) return 'esri-world-imagery';- if (eco && zoom <= ecoMaxZoom) return 'esri-world-imagery';+ const threshold = provider.eco_max_zoom ?? ecoMaxZoom;+ if (eco && zoom <= threshold) return 'esri-world-imagery';return provider.id;}@@ -79,20 +140,21 @@ export function monthCount(usage, meter, month = monthKey()) {return Number(usage?.[meter]?.[month] ?? 0);}-/** Compact readout for the map pill: "767 tiles". */-export function tilesShort(count) {- return `${count.toLocaleString('en-US')} tile${count === 1 ? '' : 's'}`;+/** Compact readout for the map pill: "767 tiles" / "3 map loads". */+export function tilesShort(count, meter) {+ const unit = meterUnit(meter);+ return `${count.toLocaleString('en-US')} ${unit}${count === 1 ? '' : 's'}`;}/** Settings readout against the free allowance: "767 / 200,000 free tiles". */-export function tilesOfFree(count, meter) {- const free = FREE_TIER[meter];- if (!free) return tilesShort(count);- return `${count.toLocaleString('en-US')} / ${free.toLocaleString('en-US')} free tiles`;+export function tilesOfFree(count, meter, tiers = null) {+ const free = freeTier(meter, tiers);+ if (!free) return tilesShort(count, meter);+ return `${count.toLocaleString('en-US')} / ${free.toLocaleString('en-US')} free ${meterUnit(meter)}s`;}/** Share of the free allowance used this month, 0–1 (can exceed 1). */-export function freeTierShare(count, meter) {- const free = FREE_TIER[meter];+export function freeTierShare(count, meter, tiers = null) {+ const free = freeTier(meter, tiers);return free ? count / free : 0;}diff --git a/frontend/src/lib/usage.test.js b/frontend/src/lib/usage.test.jsindex f64080f..3e524ef 100644--- a/frontend/src/lib/usage.test.js+++ b/frontend/src/lib/usage.test.js@@ -5,8 +5,10 @@ import {tilesShort,tilesOfFree,freeTierShare,+ freeTier,usageBlocked,displayProviderId,+ providerStatus,layerCell,FREE_TIER,BLOCK_SHARE,@@ -41,12 +43,23 @@ describe('tilesShort', () => {expect(tilesShort(12430)).toBe('12,430 tiles');expect(tilesShort(1)).toBe('1 tile');});++ it('the Maps JS meter counts map loads, not tiles', () => {+ expect(tilesShort(3, 'google_js')).toBe('3 map loads');+ expect(tilesShort(1, 'google_js')).toBe('1 map load');+ });++ it('the Sentinel Hub meter counts requests — a tile is one, so is a date lookup', () => {+ expect(tilesShort(767, 'sentinelhub')).toBe('767 requests');+ expect(tilesShort(1, 'sentinelhub')).toBe('1 request');+ });});describe('tilesOfFree', () => {it('shows the count against the documented free allowance', () => {expect(tilesOfFree(767, 'mapbox')).toBe('767 / 200,000 free tiles');expect(tilesOfFree(12430, 'google')).toBe('12,430 / 100,000 free tiles');+ expect(tilesOfFree(42, 'google_js')).toBe('42 / 10,000 free map loads');});it('falls back to the plain count for meters without a known allowance', () => {@@ -64,6 +77,33 @@ describe('freeTierShare', () => {it('free tiers stay in sync with the label helper', () => {expect(FREE_TIER.mapbox).toBe(200_000);expect(FREE_TIER.google).toBe(100_000);+ // Copernicus documents 10k but provisions 30k to a General account+ // (observed 2026-07) — the default follows the account, not the doc+ expect(FREE_TIER.sentinelhub).toBe(30_000);+ });+});++describe("the account's own free tier", () => {+ // a free tier belongs to the account: providers grant more than they document+ // and change it silently, so the served figure always wins over our default+ const served = { sentinelhub: 50_000 };++ it('resolves to the served figure, falling back to the default', () => {+ expect(freeTier('sentinelhub', served)).toBe(50_000);+ expect(freeTier('mapbox', served)).toBe(200_000); // not overridden+ expect(freeTier('sentinelhub', null)).toBe(30_000);+ expect(freeTier('bing', served)).toBe(undefined);+ });++ it('moves the readout, the gauge and the block together', () => {+ expect(tilesOfFree(100, 'sentinelhub', served)).toBe('100 / 50,000 free requests');+ expect(freeTierShare(25_000, 'sentinelhub', served)).toBe(0.5);+ // 28k is past 90% of the shipped 30k default but nowhere near 90% of the+ // 50k this account really has: the correction is what keeps the block from+ // pausing a provider that is still well inside its allowance+ expect(usageBlocked(28_000, 'sentinelhub', {}, served)).toBe(false);+ expect(usageBlocked(28_000, 'sentinelhub', {}, null)).toBe(true);+ expect(usageBlocked(45_000, 'sentinelhub', {}, served)).toBe(true);});});@@ -104,6 +144,27 @@ describe('displayProviderId', () => {expect(displayProviderId(google, 15, { ecoMaxZoom: 12 })).toBe('google-satellite');});+ it('the Maps JS widget never eco-swaps (a swap re-bills a map load)', () => {+ const widget = { id: 'google-js', meter: 'google_js', widget: 'google-maps-js', eco_max_zoom: 0 };+ expect(displayProviderId(widget, 3)).toBe('google-js');+ expect(displayProviderId(widget, 15, { ecoMaxZoom: 21 })).toBe('google-js');+ // the soft block still protects the quota, eco or not+ expect(displayProviderId(widget, 18, { blocked: true })).toBe('esri-world-imagery');+ });++ it("a provider's own eco threshold wins over the global one", () => {+ // Sentinel-2 caps at z14, so the global z15 would hide it at every zoom it+ // can serve; its own z11 keeps the useful z12-14 band alive.+ const s2 = { id: 'sentinel2', meter: 'sentinelhub', eco_max_zoom: 11 };+ expect(displayProviderId(s2, 11)).toBe('esri-world-imagery');+ expect(displayProviderId(s2, 12)).toBe('sentinel2');+ expect(displayProviderId(s2, 14)).toBe('sentinel2');+ // the user's global setting doesn't drag it back under+ expect(displayProviderId(s2, 14, { ecoMaxZoom: 15 })).toBe('sentinel2');+ // and eco off still means off+ expect(displayProviderId(s2, 3, { eco: false })).toBe('sentinel2');+ });+it('a paused meter always falls back, even zoomed in', () => {expect(displayProviderId(google, 19, { blocked: true })).toBe('esri-world-imagery');});@@ -135,6 +196,64 @@ describe('layerCell', () => {});});+describe('providerStatus', () => {+ const ok = { ok: true };+ const bad = { ok: false, detail: 'HTTP 403' };++ it('an unconfigured provider is idle, whatever else is true of it', () => {+ expect(providerStatus({ meter: 'mapbox' })).toEqual({ tone: 'idle', label: 'Not set' });+ // a stale verdict from a key that has since been cleared can't shout+ expect(providerStatus({ key: ' ', meter: 'mapbox', status: bad }).label).toBe('Not set');+ });++ it('reports a working key, and an untested one as untested', () => {+ expect(providerStatus({ key: 'pk.x', meter: 'mapbox', status: ok })).toEqual({+ tone: 'ok',+ label: 'Key works',+ });+ expect(providerStatus({ key: 'pk.x', meter: 'mapbox' })).toEqual({+ tone: 'idle',+ label: 'Untested',+ });+ });++ it('a failed key outranks every other state — it is why the basemap is benched', () => {+ expect(providerStatus({ key: 'pk.x', meter: 'mapbox', status: bad })).toEqual({+ tone: 'bad',+ label: 'Key failed',+ });+ // even switched off, and even at a quota that would otherwise pause it+ expect(providerStatus({ key: 'pk.x', meter: 'mapbox', status: bad, enabled: false }).label).toBe(+ 'Key failed'+ );+ expect(+ providerStatus({ key: 'pk.x', meter: 'mapbox', status: bad, count: 199_000 }).label+ ).toBe('Key failed');+ });++ it('a disabled provider reads as off rather than as a quota state', () => {+ expect(+ providerStatus({ key: 'pk.x', meter: 'mapbox', status: ok, enabled: false, count: 199_000 })+ ).toEqual({ tone: 'idle', label: 'Off' });+ });++ it('separates the pause from a deliberate overrun', () => {+ const at90 = { key: 'pk.x', meter: 'mapbox', status: ok, count: 180_000 };+ expect(providerStatus(at90)).toEqual({ tone: 'bad', label: 'Paused' });+ expect(providerStatus({ ...at90, overrides: { mapbox: true } })).toEqual({+ tone: 'warn',+ label: 'Billing',+ });+ });++ it("measures against this account's corrected allowance, not the default", () => {+ const half = { key: 'x', meter: 'sentinelhub', status: ok, count: 9_500 };+ expect(providerStatus(half).label).toBe('Key works'); // 9.5k of the 30k default+ // the account Copernicus only documents 10k for: the same count is a pause+ expect(providerStatus({ ...half, tiers: { sentinelhub: 10_000 } }).label).toBe('Paused');+ });+});+describe('USAGE_LINKS', () => {it('points each billed meter at its provider dashboard', () => {expect(Object.keys(USAGE_LINKS).sort()).toEqual(Object.keys(FREE_TIER).sort());diff --git a/frontend/src/tools/Inspector.svelte b/frontend/src/tools/Inspector.svelteindex 37c911a..c1ac0b2 100644--- a/frontend/src/tools/Inspector.svelte+++ b/frontend/src/tools/Inspector.svelte@@ -264,8 +264,10 @@if (filters.length) return;const ops = await api.get('/api/inspect/ops');// `crop` is driven by the interactive box; `rotate` is a view-only tilt in- // the Frame tab (never baked) — neither belongs in the slider pipeline.- filters = ops.filters.filter((f) => f.id !== 'crop' && f.id !== 'rotate');+ // the Frame tab (never baked); `remap` is solved by auto-stitch — none of the+ // three belongs in the slider pipeline.+ const solved = ['crop', 'rotate', 'remap'];+ filters = ops.filters.filter((f) => !solved.includes(f.id));analyses = ops.analyses;}@@ -493,6 +495,23 @@}}+ // Re-derive a collage piece's pixels for a new op pipeline — auto-stitch's+ // panorama modes bake their warp into the recipe, so the piece the analyst sees+ // is the piece the backend will export. A crop rect is relative to the piece's+ // own snapshot, and that snapshot has just changed underneath it, so the+ // re-derived piece starts crop-free: whatever it was showing is now baked in.+ async function renderPiece(node, ops) {+ const url = await renderUrl(node.save.path, node.save.time, ops);+ const dim = await imageSize(url);+ node.url = url;+ node.baseUrl = url;+ node.w = dim.w;+ node.h = dim.h;+ node.frameOps = ops;+ node.crop = null;+ node.save = { ...node.save, ops };+ }+// Open the piece crop editor, or clear the crop directly (clear=true).function requestCrop(node, clear = false) {if (clear) {@@ -1034,7 +1053,7 @@{:else if activeTab === 'frame'}<FrameMenu {session} {filters} {analyses} {activeFrame} {shared} {removeFrame} bind:cropAspect={frameAspect} bind:cropEditing {beginCrop} {commitCrop} setActive={(id) => (session.activeFrameId = id)} />{:else if activeTab === 'collage'}- <CollageMenu {session} {filters} bind:selectedIds={collageSelectedIds} {addToCollage} {requestCrop} />+ <CollageMenu {session} {filters} bind:selectedIds={collageSelectedIds} {addToCollage} {requestCrop} {renderPiece} />{:else if activeTab === 'save'}<SaveMenu {savables} {saveUi} {saving} save={saveSelected} />{/if}diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelteindex d4c112f..0ee84b0 100644--- a/frontend/src/tools/Satellite.svelte+++ b/frontend/src/tools/Satellite.svelte@@ -10,6 +10,8 @@import * as measure from '../lib/measure.js';import { dragBearing, pivotPanOffset } from '../lib/satRotate.js';import { SIZE_MIN, SIZE_MAX, clampSize, scaledCapture } from '../lib/captureSize.js';+ import { isRegistered, sourceRect, frameFitsView } from '../lib/screenCrop.js';+ import { extensionVersion, captureTab, onActivated } from '../lib/extBridge.js';import {monthCount,tilesShort,@@ -17,7 +19,22 @@displayProviderId,layerCell,} from '../lib/usage.js';+ import {+ SENTINEL_ID,+ DEFAULT_LAYER,+ variantId,+ validDay,+ cloudLabel,+ cloudClass,+ isoDay,+ monthOf,+ monthLabel,+ monthBounds,+ monthGrid,+ addMonths,+ } from '../lib/sentinel.js';import { createViewer, nextZ, restack } from '../lib/refViewers.js';+ import { loadGoogleMaps, createSatelliteMutant } from '../lib/gmaps.js';import Icon from '../components/Icon.svelte';import Modal from '../components/Modal.svelte';import ConfirmDialog from '../components/ConfirmDialog.svelte';@@ -46,6 +63,7 @@let rotatePivot = $state({ x: 0, y: 0 }); // grabbed point, map-wrap-local pxlet capturing = $state(false);let captureHover = $state(false); // previewing the crop frame (capture group hover)+ let hideOverlays = $state(false); // frame/marquee outlines must not land in a screen croplet captures = $state([]);let capturesFor = $state(null);let capturesCollapsed = $state(false);@@ -63,8 +81,54 @@const currentProvider = $derived(providers.find((p) => p.id === providerId));const baseIsImagery = $derived(currentProvider?.imagery ?? true);// view-only basemaps (capturable=false) keep the map but not the capture- // button (IMAGERY_PROVIDERS.md) — none built-in today, gate wired anyway- const captureBlocked = $derived(currentProvider?.capturable === false);+ // button (IMAGERY_PROVIDERS.md). Widget basemaps are also capturable=false —+ // there are no tiles to stitch — but they are *not* blocked: they capture the+ // same way through the same button, from screen pixels rather than tiles.+ const isWidgetBase = $derived(!!currentProvider?.widget);+ const captureBlocked = $derived(currentProvider?.capturable === false && !isWidgetBase);++ // --- Sentinel-2: which layer, and over which window (lib/sentinel.js) ---+ // Sentinel-2 is the one basemap with choices in it. Both live here and are+ // packed onto the provider id, which is what the map, the capture and the+ // cache all key on.+ let s2Layer = $state(DEFAULT_LAYER);+ // One date, not a range: a Sentinel-2 image *is* a pass on a day. (The WMTS+ // window underneath is a range, so we send day/day — but a range is a mosaic+ // of several passes, which is not a thing you can point at and date.)+ let s2Date = $state(''); // '' = the layer's default, i.e. the most recent pass+ let s2MenuOpen = $state(false);+ let s2MenuEl; // bound to the popover wrapper — outside-click detection+ let s2Layers = $state([]); // [{id,label,hint}] — catalogue until the instance is asked+ let s2LayersSource = $state('');+ let s2LayersAsked = false; // the instance is asked once per session, on first open+ // The month the calendar is showing, and the passes found in it:+ // { 'YYYY-MM-DD': {cloud, granules} }. A day with no entry has no imagery and+ // is not selectable — the same rule the Copernicus browser follows.+ let s2Month = $state(monthOf(''));+ let s2Passes = $state({});+ let s2PassesFor = $state(''); // the month+place s2Passes describes+ let s2PassesBusy = $state(false);+ let s2PassesNote = $state('');+ // The newest pass over this point — what "most recent" is actually showing.+ // The layer's default window renders the latest acquisition, so naming it is+ // the difference between a dated image and an undated one.+ let s2Latest = $state('');+ let s2LatestFor = $state(''); // the place s2Latest was resolved for+ const isSentinel = $derived(currentProvider?.id === SENTINEL_ID);+ // A half-typed date is not a date: it stays "most recent" rather than+ // becoming a request the backend would refuse.+ const s2Window = $derived(+ validDay(s2Date) ? { from: s2Date, to: s2Date } : { from: '', to: '' }+ );+ // A pinned day *is* the acquisition date — the one provider that can answer+ // "when was this taken?" without being asked.+ const s2PinnedDate = $derived(isSentinel && s2Window.from ? s2Window.from : null);+ const s2LayerHint = $derived(s2Layers.find((l) => l.id === s2Layer)?.hint ?? '');+ const s2LayerLabel = $derived(+ s2Layers.find((l) => l.id === s2Layer)?.label ?? s2Layer.replace(/_/g, ' ').toLowerCase()+ );+ // the pill is small: "false colour (infrared)" doesn't fit, "FALSE COLOR" does+ const s2LayerShort = $derived(s2Layer.replace(/_/g, ' '));// --- keyed-provider usage (IMAGERY_PROVIDERS.md) ---// Metered tiles are proxied through the backend, which counts each one it@@ -73,7 +137,9 @@let usageMonth = $state('');// keyed-provider prefs mirrored from Settings: overrides lift the 90% soft// block, eco swaps billed basemaps for free imagery when zoomed out- let usagePrefs = $state({ overrides: {}, eco: true, ecoMaxZoom: 15 });+ // `tiers` is this account's real allowance per meter (the user's correction+ // where they made one) — a provider's free tier is not ours to hardcode+ let usagePrefs = $state({ overrides: {}, eco: true, ecoMaxZoom: 15, tiers: null });async function refreshUsage() {try {const s = await api.get('/api/settings');@@ -83,6 +149,7 @@overrides: s.usage_overrides ?? {},eco: s.eco_zoom_fallback !== false,ecoMaxZoom: s.eco_max_zoom ?? 15,+ tiers: s.free_tier ?? null,};} catch {/* readout only — never blocks the map */@@ -91,7 +158,7 @@// small readout near the basemap selector, billed providers onlyconst usagePill = $derived(currentProvider?.meter- ? tilesShort(monthCount(usageTotals, currentProvider.meter, usageMonth))+ ? tilesShort(monthCount(usageTotals, currentProvider.meter, usageMonth), currentProvider.meter): null);@@ -103,18 +170,25 @@? usageBlocked(monthCount(usageTotals, currentProvider.meter, usageMonth),currentProvider.meter,- usagePrefs.overrides+ usagePrefs.overrides,+ usagePrefs.tiers): false);- const displayedProviderId = $derived(+ // the basemap on screen, before Sentinel-2's layer/window choices are folded in+ const displayedBaseId = $derived(displayProviderId(currentProvider, center.zoom, {eco: usagePrefs.eco,blocked: meterBlocked,ecoMaxZoom: usagePrefs.ecoMaxZoom,}));- const displayedProvider = $derived(providers.find((p) => p.id === displayedProviderId));+ const displayedProvider = $derived(providers.find((p) => p.id === displayedBaseId));+ // What every downstream consumer asks for: the tile URL, the capture, the+ // disk cache. For Sentinel-2 the layer and window ride *on the id*+ // (lib/sentinel.js), so none of them can be rendered from one window and+ // filed as another.+ const displayedProviderId = $derived(variantId(displayedBaseId, { layer: s2Layer, ...s2Window }));// memoized so the layer is only rebuilt when the cell actually changes// (i.e. crossing the z17 boost bracket), not on every zoom stepconst displayedCell = $derived(@@ -238,10 +312,15 @@mapEl.addEventListener('mousedown', onSelectStart, true);window.addEventListener('keydown', onKeydown);document.addEventListener('fullscreenchange', onFullscreenChange);+ // the user clicked the extension after a refused capture — close the loop+ const offActivated = onActivated(() =>+ toast('Extension ready — press Capture again', 'ok', 5000)+ );mapReady = true;return () => {window.removeEventListener('keydown', onKeydown);document.removeEventListener('fullscreenchange', onFullscreenChange);+ offActivated();map.remove();};});@@ -285,6 +364,159 @@setOverlay();});+ // --- Sentinel-2 layers & passes ---+ // The catalogue costs nothing and reaches no network (the backend answers it+ // from its own list); `check` asks the user's instance what it really serves,+ // which is the only authority — a configuration can rename or drop any layer.+ async function loadS2Layers(check = false, quiet = false) {+ try {+ const r = await api.get(`/api/satellite/sentinel/layers${check ? '?check=true' : ''}`);+ s2Layers = r.layers ?? [];+ s2LayersSource = r.source ?? '';+ // a layer that vanished with the list can't stay selected+ if (s2Layers.length && !s2Layers.some((l) => l.id === s2Layer)) s2Layer = s2Layers[0].id;+ if (quiet) return;+ if (check && r.detail) toast(r.detail, 'warn', 6000);+ else if (check && r.source === 'instance') {+ toast(`${r.layers.length} layers read from your instance`, 'ok');+ }+ } catch (e) {+ toast(`Sentinel-2 layers: ${e.message}`, 'danger');+ }+ }++ function toggleS2Menu() {+ s2MenuOpen = !s2MenuOpen;+ if (!s2MenuOpen) return;+ // Ask the instance what it actually serves, once per session. The built-in+ // list is only a fallback: a configuration serves whatever it was built+ // with, and offering a layer that isn't there just 400s when picked.+ if (!s2LayersAsked) {+ s2LayersAsked = true;+ loadS2Layers(true, true);+ } else if (!s2Layers.length) {+ loadS2Layers(false);+ }+ loadS2Passes();+ }++ // Passes are looked up per month *and* per place — Sentinel-2's swath means+ // the answer genuinely differs a few km away. Cached so paging back to a+ // month already seen is free; the key is the map centre rounded to ~100 m,+ // because a nudge of the map is not a new question.+ const s2PassCache = new Map();+ const s2PlaceKey = () => `${center.lat.toFixed(3)},${center.lon.toFixed(3)}`;++ /**+ * One month's passes over one place: `{ 'YYYY-MM-DD': {cloud, granules} }`,+ * or null when the lookup failed. Cached — paging back to a month already+ * seen must not spend a second request.+ */+ async function fetchS2Month(month, place, force = false) {+ const key = `${month}@${place}`;+ if (!force && s2PassCache.has(key)) return s2PassCache.get(key);+ const { from, to } = monthBounds(month);+ try {+ const r = await api.get(+ `/api/satellite/sentinel/dates?lat=${center.lat}&lon=${center.lon}` ++ `&start=${from}&end=${to}`+ );+ const byDay = {};+ for (const d of r.dates) byDay[d.date] = { cloud: d.cloud, granules: d.granules };+ s2PassCache.set(key, byDay);+ refreshUsage(); // the lookup is billed: keep the pill honest+ return byDay;+ } catch {+ return null;+ }+ }++ /**+ * Which days Sentinel-2 actually passed over this point, and how cloudy each+ * was. This is what makes the calendar honest: a day with no pass is not+ * selectable, so you can't pick a date, pay for a tile and discover it was a+ * coverage gap. One metadata request per month (~1/100th of a tile's+ * processing units), only while the picker is open.+ */+ async function loadS2Passes(force = false) {+ if (s2PassesBusy) return;+ const place = s2PlaceKey();+ const key = `${s2Month}@${place}`;+ s2PassesBusy = true;+ s2PassesNote = '';+ const days = await fetchS2Month(s2Month, place, force);+ if (days) {+ s2Passes = days;+ s2PassesFor = key;+ if (!Object.keys(days).length) s2PassesNote = 'No Sentinel-2 pass here this month.';+ } else {+ // an empty month and a failed lookup are different facts. Never blur them:+ // greying every day out because the network hiccuped would be a lie about+ // what exists.+ s2Passes = {};+ s2PassesFor = '';+ s2PassesNote = 'Could not read this month’s passes — the days below are not a coverage answer.';+ }+ s2PassesBusy = false;+ }++ function stepS2Month(delta) {+ s2Month = addMonths(s2Month, delta);+ loadS2Passes();+ }++ /**+ * Which pass "most recent" is showing. Sentinel-2 revisits every ~5 days, so+ * this month usually answers it; early in a month it may not, and one step+ * back does. Two requests at worst, once per place — the alternative is a+ * basemap that can't say what date it is showing, which for satellite+ * imagery is most of the point.+ */+ async function resolveS2Latest() {+ const place = s2PlaceKey();+ if (s2LatestFor === place) return;+ const today = isoDay(new Date());+ for (const month of [monthOf(today), addMonths(monthOf(today), -1)]) {+ const days = await fetchS2Month(month, place);+ if (days === null) return; // lookup failed — say nothing rather than guess+ const past = Object.keys(days).filter((d) => d <= today).sort();+ if (past.length) {+ s2Latest = past.at(-1);+ s2LatestFor = place;+ return;+ }+ }+ // no pass in ~2 months: real (deep polar winter, persistent gaps) — the+ // pill falls back to "most recent" rather than inventing a date+ s2Latest = '';+ s2LatestFor = place;+ }++ function pickS2Date(day) {+ if (!s2Passes[day]) return; // no pass, nothing to render — the cell is dead+ s2Date = day === s2Date ? '' : day; // clicking the pinned day unpins it+ }++ // The passes on screen describe the place they were fetched for; once the map+ // has moved somewhere else they are stale and must not grey out real imagery.+ const s2PassesStale = $derived(+ !!s2PassesFor && s2PassesFor !== `${s2Month}@${s2PlaceKey()}`+ );++ // Naming the date of what's on screen is why you'd pick this basemap, so the+ // latest pass is resolved as soon as Sentinel-2 is actually being displayed —+ // one metadata request, on the user's own action (choosing the basemap), and+ // only once per place. Not on mount: no tab may phone out by being opened.+ $effect(() => {+ if (!mapReady || displayedBaseId !== SENTINEL_ID) return;+ center.lat;+ center.lon;+ clearTimeout(s2LatestTimer);+ // debounced: panning must not spend a request per frame+ s2LatestTimer = setTimeout(() => resolveS2Latest().catch(() => {}), 900);+ });+ let s2LatestTimer;+// --- imagery date under the crosshair (item 2) ---async function refreshImageryDate() {const id = ++dateReqId;@@ -382,8 +614,15 @@try {await toolEl.requestFullscreen();return; // state + resize handled by onFullscreenChange- } catch {- /* blocked — fall through to the CSS fallback */+ } catch (e) {+ // The CSS fallback only fills the *window* — the browser's tabs and+ // toolbar stay visible — so degrading into it silently reads as a+ // broken fullscreen button rather than a refusal. Name the reason.+ toast(+ `Real fullscreen refused (${e.name}: ${e.message}) — filling the window instead`,+ 'warn',+ 8000+ );}}fullscreen = !fullscreen;@@ -475,7 +714,8 @@// fly the map to a capture's recorded point (item 7)function flyToCapture(item) {- if (!map) return;+ // ingest captures can arrive without coordinates (nothing in the URL)+ if (!map || item.lat == null || item.lon == null) return;map.setView([item.lat, item.lon], item.zoom || map.getZoom());setBearing(item.bearing || 0);}@@ -519,21 +759,76 @@}}+ // The Google widget layer is created ONCE and reused across basemap+ // switches: every google.maps.Map instantiation is a billed dynamic map+ // load, while re-adding the same layer costs nothing. Never destroyed+ // until the tool unmounts, for the same reason.+ let mutantLayer = null;++ async function setWidgetLayer(p) {+ try {+ await loadGoogleMaps(p.url, {+ onAuthFailure: async () => {+ // Google's only key-rejection signal — can fire minutes after a+ // clean load. Persist the verdict (benches the basemap), tell the+ // user, and let the provider refetch fall the map back to Esri.+ try {+ await api.post(`/api/settings/keys/${p.meter}/status`, {+ ok: false,+ detail: 'Google rejected the Maps JavaScript key (gm_authFailure)',+ });+ } catch { /* the toast still tells the user */ }+ toast('Google rejected the Maps JavaScript key — basemap disabled (see Settings)', 'danger', 8000);+ providers = await api.get('/api/satellite/providers');+ },+ });+ } catch (e) {+ toast(`Google Maps failed to load: ${e.message}`, 'danger', 6000);+ providerId = 'esri-world-imagery';+ return;+ }+ if (displayedProvider?.id !== p.id) return; // user moved on while loading+ if (!mutantLayer) {+ mutantLayer = createSatelliteMutant(p.max_zoom, p.attribution);+ // one billed map load, counted where it happens (the proxy can't see it)+ api.post(`/api/satellite/usage/${p.meter}`).then(refreshUsage).catch(() => {});+ }+ // Already the live layer — leave it alone. Returning to this tab refetches+ // the providers, and the fresh objects re-run the layer effect, so this is+ // the common path rather than an edge case. Re-adding costs no map load+ // (the mutant reuses its google.maps.Map), but Leaflet drops and re-clones+ // every tile in the grid, which reads on screen as a reloading map.+ if (tileLayer === mutantLayer) return;+ if (tileLayer) tileLayer.remove();+ if (map.getZoom() > p.max_zoom) map.setZoom(p.max_zoom);+ tileLayer = mutantLayer.addTo(map);+ }+function setLayer() {const p = displayedProvider;if (!p || !map) return;+ if (p.widget) {+ setWidgetLayer(p);+ return;+ }// every provider goes through the backend tile proxy: keys and session// tokens stay server-side, every billed tile is counted exactly once// (browser cache hits never reach the proxy), cacheable providers share// the disk tile cache, and coverage gaps come back overzoomed instead of// as "not yet available" placards. Only {s} subdomain templates (custom// providers) stay direct — the proxy can't expand those.- const url = p.url.includes('{s}') ? p.url : `/api/tiles/${p.id}/{z}/{x}/{y}`;+ const url = p.url.includes('{s}') ? p.url : `/api/tiles/${displayedProviderId}/{z}/{x}/{y}`;// maxZoom caps the map itself (no map-level maxZoom is set), which is what// keeps a shallower provider (OpenTopoMap, z17) from ever being asked for// tiles it would answer with a "max zoom layer" placard — and keeps the// view zoom at or under the provider max, which capture sizing relies on.const opts = { attribution: p.attribution, maxZoom: p.max_zoom };+ // Where a provider's pixels stop short of its useful view (Sentinel-2:+ // native z14, view z18), Leaflet keeps requesting the native level and+ // scales those tiles up in CSS. The extra zoom therefore costs nothing —+ // asking Sentinel Hub for z18 would buy its upsampling of the same pixels,+ // 16× the tiles, every one billed.+ if (p.max_native_zoom != null) opts.maxNativeZoom = p.max_native_zoom;// grid cell in CSS px (lib/usage.js layerCell): bigger tiles offset the// URL z down (512 → -1, 1024 → -2); an oversample halves the cell so each// tile is shown downscaled — deeper zoom on screen. Google's mid-zoom@@ -568,7 +863,8 @@}$effect(() => {- displayedProviderId; // track provider changes (incl. eco/block fallbacks)+ displayedProviderId; // track provider changes (incl. eco/block fallbacks,+ // and Sentinel-2's layer/window — a new window is a new set of tiles)displayedCell; // and the z17 detail-boost bracketsetLayer();});@@ -774,10 +1070,14 @@// The single capture path. `centerLL` frames the crop (a Leaflet LatLng);// `baseW`/`baseH` are the crop size at the current view zoom, then scaled to- // the chosen output resolution. The recorded point is the moved pin (if any),- // else the crop centre.- async function doCapture(centerLL, baseW, baseH) {+ // the chosen output resolution. `rectCss` is the same frame as a rectangle in+ // map-container px — only the widget path needs it, since it crops screen+ // pixels rather than stitching tiles. The recorded point is the moved pin (if+ // any), else the crop centre.+ async function doCapture(centerLL, baseW, baseH, rectCss) {if (capturing) return;+ // widget basemaps have no tiles to stitch: same frame, screen pixels+ if (isWidgetBase) return doWidgetCapture(centerLL, rectCss);capturing = true;const { zoom, width, height, mult } = scaledCapture(baseW, baseH, resolution, center.zoom, providerMaxZoom@@ -811,7 +1111,9 @@marker_lat,marker_lon,// second date on the capture: the imagery's acquisition date, if known- imagery_date: imageryDate?.date ?? null,+ // a pinned Sentinel-2 window is the acquisition date outright; every+ // other provider's is Esri's best-effort estimate or nothing+ imagery_date: s2PinnedDate ?? imageryDate?.date ?? null,});captures = [result, ...captures];await reloadCase();@@ -833,18 +1135,237 @@// Centred Capture button: the standard preset size, framed on the map centre.function captureCentered() {const [w, h] = presetSize;- doCapture(map.getCenter(), w, h);+ const r = mapEl.getBoundingClientRect();+ doCapture(map.getCenter(), w, h, {+ x: (r.width - w) / 2,+ y: (r.height - h) / 2,+ w,+ h,+ });}// The main capture button runs whichever mode is currently selected —// captureMode itself *is* the "last used mode" memory, so nothing else// needs to track it.- function runCapture() {- if (captureBlocked) return; // view-only basemap+ async function runCapture() {+ if (captureBlocked || capturing) return; // view-only basemap+ // The widget basemap captures from screen pixels via the browser extension+ // (extBridge.js). Without it there is nothing legitimate to capture with —+ // gate here, before any frame is drawn, and explain instead of half-working.+ if (isWidgetBase && !extensionVersion()) {+ extGateOpen = true;+ return;+ }if (captureMode === 'select') toggleSelect();else captureCentered();}+ // --- widget capture: the same crop frame, filled with screen pixels ---+ //+ // Google's terms allow a user-taken screenshot with attribution and nothing+ // programmatic out of the widget: the cloned tiles in the DOM are off-limits,+ // so the pixels come from the capture extension — one tabs.captureVisibleTab+ // behind the user's click, the browser-blessed way to screenshot the tab.+ // No share prompt, no sharing bar, fullscreen stays. That's the only+ // difference from a tile capture: the frame, the modes (centred preset /+ // free marquee) and the filing are identical, so the widget goes through+ // doCapture() like every other basemap.+ let extGateOpen = $state(false); // "you need the extension" explainer++ // One frame of this tab as a drawable image, via the extension. The frame is+ // exactly the viewport, so registration is the viewport aspect check — a+ // mismatch means browser zoom mid-flight or a foreign frame, both refusals.+ async function extFrame() {+ const dataUrl = await captureTab();+ const img = new window.Image();+ await new Promise((resolve, reject) => {+ img.onload = resolve;+ img.onerror = () => reject(new Error('unreadable frame from the extension'));+ img.src = dataUrl;+ });+ if (!isRegistered(img.naturalWidth, img.naturalHeight, window.innerWidth, window.innerHeight)) {+ throw new Error('the captured frame does not match this view — try again');+ }+ return img;+ }++ // Map a rect in map-container CSS px onto the captured frame, and render it+ // at exactly outW × outH (default: the native source pixels). Source pixels+ // are usually denser than CSS px (devicePixelRatio, Region Capture), so a+ // requested size is a supersampled downscale rather than a blur-up.+ async function shotCropCanvas(img, rect, outW, outH) {+ const src = sourceRect(rect, {+ mapRect: mapEl.getBoundingClientRect(),+ viewportWidth: window.innerWidth,+ videoWidth: img.naturalWidth,+ videoHeight: img.naturalHeight,+ });+ if (!src) {+ throw new Error('the frame runs past the captured area — resize the window or pick a smaller size');+ }+ const { sx, sy, sw, sh } = src;+ const canvas = document.createElement('canvas');+ canvas.width = Math.round(outW ?? sw);+ canvas.height = Math.round(outH ?? sh);+ const ctx = canvas.getContext('2d');+ ctx.imageSmoothingQuality = 'high';+ ctx.drawImage(img, sx, sy, sw, sh, 0, 0, canvas.width, canvas.height);+ return canvas;+ }++ // The widget arm of doCapture: grab the tab via the extension, crop, file.+ async function doWidgetCapture(centerLL, rect) {+ if (!extensionVersion()) {+ extGateOpen = true;+ return;+ }+ const mapRect = mapEl.getBoundingClientRect();+ if (!frameFitsView(rect, mapRect)) {+ toast(+ `The ${Math.round(rect.w)}×${Math.round(rect.h)} frame is bigger than the map view — screen pixels are the ceiling here. Pick a smaller size or enlarge the window`,+ 'warn', 7000+ );+ return;+ }+ capturing = true;+ // The tab frame is the whole viewport, so our own chrome painted over the+ // map (HUD, controls, reference windows, the frame outline itself) would+ // land inside the crop. Hide it for the grab — a capture must show the+ // map, not the app. Only the marker stays: the tile path burns one into+ // its crop, so dropping it here would be the odd one out.+ hideOverlays = true;+ try {+ // let the hidden chrome actually leave the composited frame+ await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));+ await new Promise((r) => setTimeout(r, 60));+ const img = await extFrame();+ const canvas = await shotCropCanvas(img, rect, Math.round(rect.w), Math.round(rect.h));+ const blob = await new Promise((r) => canvas.toBlob(r, 'image/png'));+ await fileScreenshot(blob, centerLL, true);+ } catch (e) {+ if (e.needsActivation) {+ // one-time per tab: the browser only lets the extension screenshot a+ // tab it has been invoked on (activeTab) — not an error, a step+ toast(+ 'One-time step: click the Azimut Capture icon in the toolbar (or press Alt+Shift+A), then press Capture again',+ 'warn',+ 10000+ );+ } else {+ // Never fall back to the import dialog: a capture that couldn't be+ // taken must stay untaken. Quietly offering to file some other image+ // instead is how an unregistered picture ends up wearing a capture's+ // provenance.+ toast(`Capture failed: ${e.message}`, 'danger', 7000);+ }+ } finally {+ hideOverlays = false;+ capturing = false;+ }+ }++ // File a screenshot blob as a capture. `framed` records whether the+ // coordinates are the centre of a registered crop (the frame paths) or just+ // the map view at filing time (a pasted screenshot) — the backend keeps that+ // distinction in provenance.+ async function fileScreenshot(blob, centerLL, framed) {+ const c = await ensureCase();+ const form = new FormData();+ form.append('image', blob, 'screenshot.png');+ form.append('lat', String(centerLL ? centerLL.lat : center.lat));+ form.append('lon', String(centerLL ? centerLL.lng : center.lon));+ form.append('zoom', String(center.zoom));+ form.append('bearing', String(bearing));+ form.append('provider', currentProvider.id);+ form.append('framed', String(!!framed));+ const result = await api.post(`/api/cases/${c.id}/satellite/screenshot`, form);+ captures = [result, ...captures];+ await reloadCase();+ toast(+ framed+ ? 'Screen crop captured & filed (attribution burned in)'+ : 'Screenshot filed as a capture (attribution burned in)',+ 'ok'+ );+ return result;+ }++ // --- manual screenshot dialog (fallback: paste / drop) ---+ let shotOpen = $state(false);+ let shotBlob = $state(null);+ let shotPreview = $state(''); // object URL for the <img> preview+ let shotBusy = $state(false);++ function shotReset() {+ if (shotPreview) URL.revokeObjectURL(shotPreview);+ shotBlob = null;+ shotPreview = '';+ }+ function shotClose() {+ shotReset();+ shotOpen = false;+ }+ function shotTake(file) {+ if (!file || !file.type?.startsWith('image/')) return;+ shotReset();+ shotBlob = file;+ shotPreview = URL.createObjectURL(file);+ }+ function onShotPaste(e) {+ const item = [...(e.clipboardData?.items ?? [])].find((i) => i.type.startsWith('image/'));+ if (item) {+ e.preventDefault();+ shotTake(item.getAsFile());+ }+ }+ function onShotDrop(e) {+ e.preventDefault();+ shotTake(e.dataTransfer?.files?.[0]);+ }++ // One-click grab of the whole map view into the dialog's preview: the same+ // extension frame as a framed capture, minus the crop, at native resolution.+ // The preview is what lets the user judge it before filing. Only offered+ // when the extension is present — without it the dialog is paste/drop only.+ let shotGrabbing = $state(false);+ async function shotGrab() {+ if (shotGrabbing) return;+ shotGrabbing = true;+ try {+ const img = await extFrame();+ const r0 = mapEl.getBoundingClientRect();+ const canvas = await shotCropCanvas(img, { x: 0, y: 0, w: r0.width, h: r0.height });+ const blob = await new Promise((r) => canvas.toBlob(r, 'image/png'));+ if (blob) shotTake(new File([blob], 'screenshot.png', { type: 'image/png' }));+ } catch (e) {+ // extension missing or refused — the paste path still works+ toast(`Screen capture unavailable (${e.message}) — paste a screenshot instead`, 'warn', 6000);+ } finally {+ shotGrabbing = false;+ }+ }+ // paste works anywhere while the dialog is open — no need to focus a zone+ $effect(() => {+ if (!shotOpen) return;+ window.addEventListener('paste', onShotPaste);+ return () => window.removeEventListener('paste', onShotPaste);+ });++ async function shotSave() {+ if (!shotBlob || shotBusy) return;+ shotBusy = true;+ try {+ // a pasted image is not registered to any frame: its coordinates are the+ // map view at filing time, and provenance says so (framed: false)+ await fileScreenshot(shotBlob, null, false);+ shotClose();+ } catch (e) {+ toast(`Could not file the screenshot: ${e.message}`, 'danger', 6000);+ } finally {+ shotBusy = false;+ }+ }+// clicking outside the open size/ratio/resolution popover closes it$effect(() => {if (!sizeMenuOpen) return;@@ -855,6 +1376,16 @@return () => document.removeEventListener('mousedown', onDocMousedown, true);});+ // …and the Sentinel-2 layer/date popover+ $effect(() => {+ if (!s2MenuOpen) return;+ const onDocMousedown = (e) => {+ if (s2MenuEl && !s2MenuEl.contains(e.target)) s2MenuOpen = false;+ };+ document.addEventListener('mousedown', onDocMousedown, true);+ return () => document.removeEventListener('mousedown', onDocMousedown, true);+ });+// --- marquee: drag a rectangle on the map to capture exactly that area ---function toggleSelect() {selectArmed = !selectArmed;@@ -910,7 +1441,12 @@L.point((r.x0 + r.x1) / 2, (r.y0 + r.y1) / 2));selectArmed = false; // one box per arm — re-arm to draw another- doCapture(centerLL, Math.round(w), Math.round(h));+ doCapture(centerLL, Math.round(w), Math.round(h), {+ x: Math.min(r.x0, r.x1),+ y: Math.min(r.y0, r.y1),+ w,+ h,+ });}// save just the point (pin if moved, else center) as a navigable place — no image@@ -1134,7 +1670,12 @@</div><div class="body">- <div class="map-wrap" class:measuring={measureMode} class:selecting={selectArmed}>+ <div+ class="map-wrap"+ class:measuring={measureMode}+ class:selecting={selectArmed}+ class:grabbing={hideOverlays}+ ><div class="map" bind:this={mapEl}></div><!-- top-left control cluster: fullscreen, OSM labels overlay, measure tools -->@@ -1296,7 +1837,29 @@<!-- imagery acquisition date: a compact, unobtrusive pill in the corner soit doesn't crowd the coordinates readout (item 2) -->- {#if imageryDate?.supported}+ {#if isSentinel && displayedBaseId === SENTINEL_ID}+ <!-- Sentinel-2 says what it is showing: a pinned day is the window the+ tiles were rendered from; otherwise the layer's default renders the+ most recent pass, which the calendar lookup has already named. -->+ <span+ class="date-pill mono"+ class:exact={!!s2PinnedDate}+ title={s2PinnedDate+ ? `Sentinel-2 ${s2LayerLabel} from this exact date`+ : s2Latest+ ? `Sentinel-2 ${s2LayerLabel} — most recent pass over this point`+ : `Sentinel-2 ${s2LayerLabel} — most recent pass (open the picker to date it)`}+ >+ <Icon name="clock" size={11} />+ {s2PinnedDate ?? s2Latest ?? ''}+ {#if !s2PinnedDate}+ <span class="tag">{s2Latest ? 'latest' : 'most recent'}</span>+ {/if}+ {#if s2Layer !== DEFAULT_LAYER}+ <span class="tag layer">{s2LayerShort}</span>+ {/if}+ </span>+ {:else if imageryDate?.supported}<spanclass="date-pill mono"title={imageryDate.source@@ -1354,13 +1917,114 @@</option>{/each}</select>+ {#if isSentinel}+ <div class="s2-wrap" bind:this={s2MenuEl}>+ <!-- icon-only: the bar is shared with the capture controls and has a+ finite width — the chosen layer and date read from the pill in+ the map's corner, where they don't cost the bar a row -->+ <button+ class="btn btn-icon"+ class:on={s2MenuOpen}+ onclick={toggleS2Menu}+ title="Sentinel-2 — layer & date"+ aria-label="Sentinel-2 layer and date"+ >+ <Icon name="layers" size={14} />+ </button>+ {#if s2MenuOpen}+ <div class="s2-menu card">+ <div class="menu-row">+ <span class="menu-label">Layer</span>+ <select class="select" bind:value={s2Layer}>+ {#each s2Layers as l (l.id)}+ <option value={l.id}>{l.label}</option>+ {/each}+ </select>+ </div>+ {#if s2LayerHint}+ <div class="menu-hint">{s2LayerHint}</div>+ {/if}+ <div class="menu-hint dim">+ {s2LayersSource === 'instance'+ ? 'Read from your configuration — these are the layers it serves.'+ : 'Could not read your configuration; showing the standard layers.'}+ <button class="linkish" onclick={() => loadS2Layers(true)}>Refresh</button>+ </div>++ <div class="menu-sep" aria-hidden="true"></div>++ <div class="menu-row">+ <span class="menu-label">Date</span>+ <div class="chips">+ <button class="chip" class:on={!s2Date} onclick={() => (s2Date = '')}>+ Most recent+ </button>+ </div>+ </div>++ <div class="cal">+ <div class="cal-head">+ <button class="cal-nav" onclick={() => stepS2Month(-1)} aria-label="Previous month">+ <Icon name="chevronLeft" size={13} />+ </button>+ <span class="cal-month">{monthLabel(s2Month)}</span>+ <button class="cal-nav" onclick={() => stepS2Month(1)} aria-label="Next month">+ <Icon name="chevronRight" size={13} />+ </button>+ </div>+ <div class="cal-grid" class:busy={s2PassesBusy}>+ {#each ['M', 'T', 'W', 'T', 'F', 'S', 'S'] as d, i (i)}+ <span class="cal-dow" aria-hidden="true">{d}</span>+ {/each}+ {#each monthGrid(s2Month) as day, i (day ?? `pad${i}`)}+ {#if !day}+ <span class="cal-pad" aria-hidden="true"></span>+ {:else}+ {@const pass = s2Passes[day]}+ <button+ class="cal-day {pass ? cloudClass(pass.cloud) : ''}"+ class:has={!!pass}+ class:on={s2Date === day}+ disabled={!pass}+ onclick={() => pickS2Date(day)}+ title={pass+ ? `${day} — ${cloudLabel(pass.cloud) || 'cloud cover unknown'}`+ : `${day} — no Sentinel-2 pass`}+ >+ {Number(day.slice(8))}+ </button>+ {/if}+ {/each}+ </div>+ </div>++ {#if s2PassesBusy}+ <div class="menu-hint dim">Reading this month's passes…</div>+ {:else if s2PassesNote}+ <div class="menu-hint warn">{s2PassesNote}</div>+ {:else if s2PassesStale}+ <div class="menu-hint">+ <span class="warn">The map moved — these passes are for where you were.</span>+ <button class="linkish" onclick={() => loadS2Passes(true)}>Refresh</button>+ </div>+ {:else}+ <div class="menu-hint dim">+ Only days Sentinel-2 passed over this point are selectable; the colour is+ cloud cover. A pinned day shows that pass alone — near a swath edge it can+ still be black (no data), so try the neighbouring date.+ </div>+ {/if}+ </div>+ {/if}+ </div>+ {/if}{#if usagePill}<spanclass="usage-pill mono"- title="Tiles requested from this billed provider this month — local counter, see Settings"+ title="Requests made to this billed provider this month — local counter, see Settings">{usagePill}</span>{/if}- {#if currentProvider?.meter && displayedProviderId !== providerId}+ {#if currentProvider?.meter && displayedBaseId !== providerId}<spanclass="fallback-pill"class:paused={meterBlocked}@@ -1424,8 +2088,8 @@title={captureBlocked? 'View-only basemap — this provider cannot be captured': captureMode === 'select'- ? 'Draw a rectangle on the map to capture exactly that area'- : 'Capture the centred preset size'}+ ? `Draw a rectangle on the map to capture exactly that area${isWidgetBase ? ' (grabbed from the screen)' : ''}`+ : `Capture the centred preset size${isWidgetBase ? ' (grabbed from the screen)' : ''}`}>{#if capturing}<span class="spinner"></span> Capturing…@@ -1441,7 +2105,9 @@class="btn btn-icon capture-arrow"class:on={sizeMenuOpen}onclick={() => (sizeMenuOpen = !sizeMenuOpen)}- title="Capture mode, size, ratio & resolution"+ title={isWidgetBase+ ? 'Capture mode, size & ratio'+ : 'Capture mode, size, ratio & resolution'}aria-label="Capture options"><Icon name="chevronDown" size={13} />@@ -1513,15 +2179,40 @@{/if}{/if}- <div class="menu-row">- <span class="menu-label">Resolution</span>- <div class="chips">- <button class="chip" class:on={resolution === 1} onclick={() => (resolution = 1)}>1×</button>- <button class="chip" class:on={resolution === 2} onclick={() => (resolution = 2)}>2×</button>- <button class="chip" class:on={resolution === 'max'} onclick={() => (resolution = 'max')}>Max</button>+ <!-- the widget's one real difference: its pixels come off the+ screen, so there is no deeper zoom to capture and no+ resolution to choose -->+ {#if isWidgetBase}+ <div class="menu-row">+ <span class="menu-label">Source</span>+ <div class="chips">+ <button+ class="chip"+ onclick={() => {+ sizeMenuOpen = false;+ shotOpen = true;+ }}+ >+ Paste a screenshot…+ </button>+ </div></div>- </div>- <div class="menu-hint">Captures a deeper zoom for a sharper file.</div>+ <div class="menu-hint">+ This basemap is captured from the screen (Google's terms allow nothing+ programmatic out of it), so the frame can't go past the map view and screen+ pixels are the ceiling.+ </div>+ {:else}+ <div class="menu-row">+ <span class="menu-label">Resolution</span>+ <div class="chips">+ <button class="chip" class:on={resolution === 1} onclick={() => (resolution = 1)}>1×</button>+ <button class="chip" class:on={resolution === 2} onclick={() => (resolution = 2)}>2×</button>+ <button class="chip" class:on={resolution === 'max'} onclick={() => (resolution = 'max')}>Max</button>+ </div>+ </div>+ <div class="menu-hint">Captures a deeper zoom for a sharper file.</div>+ {/if}</div>{/if}</div>@@ -1580,6 +2271,16 @@{/each}</div><div class="links-note mono">{readout}</div>+ <!-- the way back: the capture extension files what you find over+ there straight into the case, coordinates parsed from the URL -->+ <button type="button" class="links-advert" onclick={() => (uiState.tool = 'settings')}>+ <Icon name="crop" size={12} />+ <span>+ {extensionVersion()+ ? 'Capture these sites into the case with the browser extension'+ : 'Get the capture extension to file these sites into the case'}+ </span>+ </button>{/if}<!-- Places: navigable points (no image) -->@@ -1677,7 +2378,8 @@<div class="cap-meta"><span class="title">{item.title ?? coordsLabel(item)}</span><span class="mono coords">{coordsLabel(item)}</span>- <span class="prov">z{item.zoom}{item.bearing ? ` · ${Math.round(item.bearing)}°` : ''} · {item.provider_label}</span>+ <!-- ingest captures may have no zoom (URL carried none) -->+ <span class="prov">{item.zoom != null ? `z${item.zoom}` : '—'}{item.bearing ? ` · ${Math.round(item.bearing)}°` : ''} · {item.provider_label ?? item.site}</span><span class="prov dates" title="Capture date · imagery acquisition date"><Icon name="crosshair" size={10} /> {item.fetched_at?.slice(0, 10)}{#if item.imagery_date}<span class="img-date"><Icon name="satellite" size={10} /> {item.imagery_date}</span>{/if}@@ -1687,11 +2389,29 @@<div class="cap-actions"><buttonclass="btn btn-ghost btn-sm"- title="Go to these coordinates on the map"+ disabled={item.lat == null}+ title={item.lat == null+ ? 'No coordinates recorded for this capture'+ : 'Go to these coordinates on the map'}onclick={() => flyToCapture(item)}><Icon name="crosshair" size={14} /></button>+ {#if item.source_url}+ <!-- straight back to the page this was captured from — the+ recorded URL itself, not a reconstruction -->+ <a+ class="btn btn-ghost btn-sm"+ class:disabled={fullscreen}+ href={fullscreen ? undefined : item.source_url}+ target="_blank"+ rel="noreferrer"+ aria-disabled={fullscreen}+ title={leavesFullscreen ?? `Open the source page (${item.site})`}+ >+ <Icon name="external" size={13} />+ </a>+ {/if}<buttonclass="btn btn-ghost btn-sm"title="Edit title & note"@@ -1807,6 +2527,94 @@</Modal>{/if}+<!-- The manual way in, for when the Capture button's extension grab can't be+ used or the screenshot came from somewhere else entirely. -->+{#if shotOpen && !shotGrabbing}+ <Modal title="File a screenshot" onclose={shotClose} width="520px">+ <p class="shot-hint">+ The <strong>Capture</strong> button already crops this basemap off the screen+ through the usual frame. Use this when it can't:+ {#if extensionVersion()}grab the whole map view below, or paste{:else}paste{/if}+ (<span class="mono">Ctrl+V</span>) / drop your own OS screenshot.+ Unlike a framed capture, this is filed at the current <em>view</em>+ (<span class="mono">{fmtCoords(center.lat, center.lon)}</span>, z{center.zoom}) —+ the coordinates describe the map, not a registered crop. The Google attribution+ is burned into a footer either way; keep Google's on-screen credits inside the+ frame too.+ </p>+ {#if extensionVersion()}+ <div style="display:flex;justify-content:center;margin-bottom:10px">+ <button class="btn btn-primary" onclick={shotGrab} disabled={shotGrabbing}>+ {#if shotGrabbing}<span class="spinner"></span> Grabbing…{:else}+ <Icon name="satellite" size={14} /> Capture the view{/if}+ </button>+ </div>+ {/if}+ <div+ class="shot-zone"+ class:has-image={!!shotPreview}+ role="button"+ tabindex="0"+ ondrop={onShotDrop}+ ondragover={(e) => e.preventDefault()}+ >+ {#if shotPreview}+ <img src={shotPreview} alt="screenshot to file" />+ {:else}+ <span>Paste (Ctrl+V) or drop the screenshot here</span>+ {/if}+ </div>+ <div style="display:flex;gap:8px;justify-content:flex-end;margin-top:12px">+ {#if shotPreview}+ <button class="btn" onclick={shotReset}>Clear</button>+ {/if}+ <button class="btn" onclick={shotClose}>Cancel</button>+ <button class="btn btn-primary" onclick={shotSave} disabled={!shotBlob || shotBusy}>+ {shotBusy ? 'Filing…' : 'File as capture'}+ </button>+ </div>+ </Modal>+{/if}++<!-- Google JS capture gate: this basemap can only be captured through the+ browser extension (screen pixels are the only thing Google's terms allow+ out of the widget, and the extension is the promptless way to get them).+ Explain briefly and point at Settings; never a half-working share flow. -->+{#if extGateOpen}+ <Modal title="Capture needs the browser extension" onclose={() => (extGateOpen = false)} width="460px">+ <p class="shot-hint">+ Google's terms allow nothing programmatic out of this basemap — a capture+ here is a <strong>screenshot of the tab</strong>, and the Azimut Capture+ extension is what takes it (one grab per click, no screen-share prompt,+ works in fullscreen). Other basemaps are not affected.+ </p>+ <p class="shot-hint">+ Install it from <strong>Settings → Capture extension</strong>, then reload+ this tab. You can also paste an OS screenshot instead.+ </p>+ <div style="display:flex;gap:8px;justify-content:flex-end;margin-top:12px">+ <button+ class="btn"+ onclick={() => {+ extGateOpen = false;+ shotOpen = true;+ }}+ >+ Paste a screenshot…+ </button>+ <button+ class="btn btn-primary"+ onclick={() => {+ extGateOpen = false;+ uiState.tool = 'settings';+ }}+ >+ Open Settings+ </button>+ </div>+ </Modal>+{/if}+<!-- place edit / save-with-details modal -->{#if placeModal}<Modal@@ -1913,6 +2721,18 @@inset: 0;background: var(--bg-2);}+ /* Mid screen-grab: a widget capture crops the map element's *rectangle*, so+ everything we paint over the map (HUD, control clusters, capture bar,+ reference windows, the frame outline itself) would land in the capture.+ Hide our chrome for the grab and leave the map — Google's own credits live+ inside it and must ride along. The marker is the deliberate exception: the+ tile path burns one into its crop, so a screen crop keeps its own.+ :global is load-bearing — the reference windows are a child component, so+ a scoped selector would skip exactly the overlay the spec says must never+ be captured. */+ .map-wrap.grabbing > :global(:not(.map):not(.marker-overlay)) {+ visibility: hidden;+ }.frame-overlay {position: absolute;top: 50%;@@ -2204,12 +3024,25 @@.capture-bar {position: absolute;bottom: 34px;- left: 50%;- transform: translateX(-50%);+ /* Centred by auto margins across the full width, NOT by left:50% ++ translateX: an absolutely positioned box with `left: 50%` may only be as+ wide as the half it starts at, so the bar was being squeezed to half the+ map and cut off (or, once it could wrap, folded into a stack of rows).+ Spanning left:0/right:0 gives it the whole width to size against, and+ fit-content keeps it hugging its controls. */+ left: 0;+ right: 0;+ margin: 0 auto;+ width: fit-content;+ max-width: calc(100% - 20px);z-index: 600;display: flex;align-items: center;- gap: 10px;+ justify-content: center;+ /* only ever reached on a genuinely narrow map — a second row beats+ controls that are off-screen */+ flex-wrap: wrap;+ gap: 8px 10px;padding: 10px 12px;background: rgba(24, 24, 24, 0.92);backdrop-filter: blur(6px);@@ -2217,6 +3050,8 @@}.capture-bar .select {width: auto;+ /* "OpenTopoMap (topographic · contour lines)" is not worth a row of bar */+ max-width: 190px;}/* billed-provider tile counter (IMAGERY_PROVIDERS.md) — full readout in Settings */.usage-pill {@@ -2361,6 +3196,163 @@color: var(--text-3);margin: -1px 0 5px;}+ .menu-hint.dim {+ opacity: 0.75;+ }+ .menu-hint .warn,+ .menu-hint.warn {+ color: var(--warn, #e2a03f);+ }+ .menu-sep {+ height: 1px;+ background: var(--border);+ margin: 4px 0 6px;+ }++ /* --- Sentinel-2 layer + date popover --- */+ .s2-wrap {+ position: relative;+ display: flex;+ }+ .s2-menu {+ position: absolute;+ bottom: calc(100% + 8px);+ left: 0;+ width: max-content;+ max-width: 320px;+ display: flex;+ flex-direction: column;+ gap: 4px;+ padding: 12px;+ background: rgba(24, 24, 24, 0.96);+ backdrop-filter: blur(6px);+ box-shadow: var(--shadow-2);+ z-index: 700;+ }+ .s2-menu .select {+ max-width: 190px;+ }+ .linkish {+ background: none;+ border: 0;+ padding: 0;+ color: var(--accent);+ font-size: 10px;+ cursor: pointer;+ text-decoration: underline;+ }+ /* --- the pass calendar --- */+ .cal {+ display: flex;+ flex-direction: column;+ gap: 6px;+ margin: 2px 0 6px;+ }+ .cal-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 8px;+ }+ .cal-month {+ font-size: var(--fs-xs);+ font-weight: 600;+ color: var(--text-1);+ }+ .cal-nav {+ display: flex;+ padding: 3px 5px;+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ background: var(--bg-2);+ color: var(--text-2);+ cursor: pointer;+ }+ .cal-nav:hover {+ color: var(--text-1);+ border-color: var(--text-3);+ }+ .cal-grid {+ display: grid;+ grid-template-columns: repeat(7, 1fr);+ gap: 2px;+ }+ .cal-grid.busy {+ opacity: 0.5;+ pointer-events: none;+ }+ .cal-dow {+ text-align: center;+ font-size: 9px;+ color: var(--text-3);+ padding-bottom: 2px;+ }+ .cal-day {+ aspect-ratio: 1;+ display: flex;+ align-items: center;+ justify-content: center;+ border: 1px solid transparent;+ border-radius: var(--r-sm);+ background: transparent;+ color: var(--text-3);+ font-size: 10px;+ font-family: var(--font-mono);+ cursor: pointer;+ }+ /* a day with no pass isn't dimmed decoration — there is nothing to render, so+ it cannot be chosen (the same rule the Copernicus browser follows) */+ .cal-day:disabled {+ opacity: 0.28;+ cursor: default;+ }+ .cal-day.has {+ color: var(--text-1);+ background: var(--bg-2);+ border-color: var(--border);+ }+ /* cloud cover, at a glance: most passes are white and cost a tile to find out */+ .cal-day.clear {+ border-color: color-mix(in srgb, var(--ok, #46a758) 65%, transparent);+ color: var(--ok, #46a758);+ }+ .cal-day.part {+ border-color: color-mix(in srgb, var(--warn, #e2a03f) 55%, transparent);+ color: var(--warn, #e2a03f);+ }+ .cal-day.cloudy,+ .cal-day.unknown {+ border-color: var(--border);+ color: var(--text-2);+ }+ .cal-day.has:hover {+ border-color: var(--text-1);+ }+ .cal-day.on {+ background: var(--accent);+ border-color: var(--accent);+ color: var(--accent-text);+ font-weight: 700;+ }+ /* a pinned date is a fact about the pixels; "latest" is an inference from the+ pass list — they must not look identical */+ .date-pill.exact {+ border-color: var(--ok, #46a758);+ }+ .date-pill .tag {+ font-family: var(--font-sans);+ font-size: 9px;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ color: var(--text-3);+ border: 1px solid var(--border);+ border-radius: 3px;+ padding: 0 3px;+ }+ .date-pill .tag.layer {+ color: var(--accent);+ border-color: color-mix(in srgb, var(--accent) 45%, transparent);+ }.menu-row + .custom-size {justify-content: flex-end;padding: 2px 0;@@ -2540,6 +3532,24 @@font-size: var(--fs-xs);color: var(--text-3);}+ /* the capture-extension pointer under the external links — quiet, one line */+ .links-advert {+ display: flex;+ align-items: center;+ gap: 6px;+ width: 100%;+ padding: 4px;+ margin: 0 0 6px;+ border: none;+ background: none;+ font-size: var(--fs-xs);+ color: var(--text-3);+ text-align: left;+ cursor: pointer;+ }+ .links-advert:hover {+ color: var(--accent);+ }.place-notes {padding: 0 10px 8px 30px;font-size: var(--fs-xs);@@ -2744,6 +3754,30 @@color: var(--text-2);margin: 0 0 12px;}+ .shot-hint {+ font-size: var(--fs-sm);+ color: var(--text-2);+ margin: 0 0 12px;+ }+ .shot-zone {+ display: flex;+ align-items: center;+ justify-content: center;+ min-height: 180px;+ border: 1px dashed var(--border);+ border-radius: 6px;+ color: var(--text-3);+ font-size: var(--fs-sm);+ overflow: hidden;+ }+ .shot-zone.has-image {+ border-style: solid;+ }+ .shot-zone img {+ max-width: 100%;+ max-height: 320px;+ display: block;+ }.ref-empty {padding: 24px 4px;text-align: center;diff --git a/frontend/src/tools/Settings.svelte b/frontend/src/tools/Settings.svelteindex 19a5fef..56dfb64 100644--- a/frontend/src/tools/Settings.svelte+++ b/frontend/src/tools/Settings.svelte@@ -9,16 +9,22 @@tilesOfFree,freeTierShare,usageBlocked,+ providerStatus,USAGE_LINKS,BLOCK_SHARE,ECO_MAX_ZOOM,+ FREE_TIER,} from '../lib/usage.js';+ import { probeKey, googleMapsLoadedKey } from '../lib/gmaps.js';+ import { extensionVersion } from '../lib/extBridge.js';import Icon from '../components/Icon.svelte';+ // Imagery and Usage were the same four objects seen from two rooms: the key+ // here, the meter it feeds there. One tab, one card per provider.const TABS = [{ id: 'preferences', label: 'Preferences', icon: 'sliders' },{ id: 'imagery', label: 'Imagery', icon: 'key' },- { id: 'usage', label: 'Usage', icon: 'chart' },+ { id: 'extension', label: 'Capture extension', icon: 'crop' },{ id: 'about', label: 'About', icon: 'compass' },];let tab = $state('preferences');@@ -29,31 +35,86 @@// The keyed imagery providers the app knows how to light up (IMAGERY_PROVIDERS.md).// Keys are app-wide, stored locally in settings.json, never written into a// case folder or export bundle — they're the user's own billing identity.+ //+ // Each provider is one collapsed row until you open it: `gives` and `cost`+ // are all a closed card says, so the tab reads at a glance and only the+ // provider you're actually setting up spends any text. Everything below them+ // (`steps`, `warning`, `overage`) lives in the opened body — the nuance is+ // still here, it just isn't charged to the other three providers.const KEYED = [{id: 'mapbox',label: 'Mapbox',+ gives: 'Satellite basemap',+ cost: '$0.50 / 1,000 past the tier',field: 'Mapbox public access token',placeholder: 'pk.…',help: 'https://account.mapbox.com/access-tokens/',usage: USAGE_LINKS.mapbox,- unlocks: 'Mapbox Satellite basemap',overage:- 'Beyond 200k free tiles/month, Mapbox bills extra tiles automatically ($0.50 per 1,000, pay-as-you-go, no hard cap). Set a spending alert in your Mapbox account.',+ 'Past the free tier Mapbox bills extra tiles automatically — pay-as-you-go, no hard cap. Set a spending alert in your Mapbox account.',},{id: 'google',label: 'Google',+ gives: 'Satellite basemap',+ cost: '$0.60 / 1,000 past the tier',field: 'Google Maps Platform API key',placeholder: 'AIza…',help: 'https://developers.google.com/maps/documentation/tile/get-api-key',usage: USAGE_LINKS.google,- unlocks: 'Google Satellite basemap (Map Tiles API)',+ warning:+ 'EEA billing accounts: since 8 July 2025 Google no longer serves satellite tiles to Europe (403). Use a Maps JavaScript API key instead.',overage:- 'Beyond 100k free tiles/month, Google bills extra tiles to your Cloud project ($0.60 per 1,000; Google also enforces 15k tiles/day). A quota cap in the Cloud Console makes it stop serving instead of billing.',+ 'Extra tiles are billed to your Cloud project, and Google also enforces 15k tiles/day. A quota cap in the Cloud Console makes it stop serving instead of billing.',+ },+ {+ id: 'google_js',+ label: 'Google (Maps JS)',+ gives: 'Satellite basemap · works in the EEA',+ cost: 'Billed per map load, not per tile',+ field: 'Google Maps JavaScript API key',+ placeholder: 'AIza…',+ help: 'https://developers.google.com/maps/documentation/javascript/get-api-key',+ usage: USAGE_LINKS.google_js,+ // a JS key proves itself only in a browser — Test loads a real 1-tile map+ browserTest: true,+ steps: [+ 'In the Google Cloud Console, enable the "Maps JavaScript API" on your project.',+ 'Create an API key (Credentials) and restrict it to that API.',+ 'Optional but recommended: restrict the key to your own referrers.',+ ],+ overage:+ 'A map load is one widget instantiation (~10k free/month) — pan and zoom on an open map are free. Azimut builds the widget once per session and reuses it, so normal use stays far under the tier.',+ },+ {+ id: 'sentinelhub',+ label: 'Sentinel Hub',+ gives: 'Sentinel-2 · free · 10 m/px',+ cost: 'Never billed',+ field: 'Copernicus configuration instance ID',+ placeholder: 'a1b2c3d4-0000-0000-0000-000000000000',+ help: 'https://shapps.dataspace.copernicus.eu/dashboard/#/configurations',+ usage: USAGE_LINKS.sentinelhub,+ // Not a token you're issued but a configuration you build, so the field+ // needs the recipe, not just a "get one here" link.+ steps: [+ 'Register (free) on dataspace.copernicus.eu, then open the Sentinel Hub Dashboard.',+ 'Configuration Utility → New configuration, based on "Simple Sentinel-2 L2A template".',+ 'Open it and turn Show logo and Show warnings OFF — both are burned into every tile.',+ 'Copy the ID under "Service endpoints" and paste it here.',+ ],+ overage:+ 'A free Copernicus account gets 30,000 requests and 30,000 processing units a month (one tile = 1 request = 1 PU; a date lookup is 1 request but ~0.01 PU) and simply stops serving until the 1st — it never bills you.',+ // the correction the free-allowance box exists for, told where it's useful+ tierNote:+ 'Copernicus still documents 10,000 while provisioning 30,000, and the figure is per-account — check yours on the dashboard.',},];+ /** A per-provider map over KEYED — the shape every key/pref state uses. */+ const perProvider = (value) => Object.fromEntries(KEYED.map((k) => [k.id, value(k)]));+const COORD_CHOICES = [{ id: 'dd', label: 'Decimal' },{ id: 'dms', label: 'DMS' },@@ -64,19 +125,56 @@{ id: 'imperial', label: 'Imperial' },];- let keys = $state({ mapbox: '', google: '' });- let shown = $state({ mapbox: false, google: false });+ let keys = $state(perProvider(() => ''));+ let shown = $state(perProvider(() => false));+ // every card starts closed: four providers' worth of setup is four walls of+ // text, and you only ever set up one at a time+ let open = $state(perProvider(() => false));+ let termsOpen = $state(false);let usage = $state({});let month = $state('');- let saving = $state(false);- let testing = $state({ mapbox: false, google: false });- let testResult = $state({ mapbox: null, google: null }); // { ok, detail } | null+ let testing = $state(perProvider(() => false));+ let testResult = $state(perProvider(() => null)); // { ok, detail } | null// keyed-provider preferences (IMAGERY_PROVIDERS.md) — saved on toggle- let enabled = $state({ mapbox: true, google: true });- let overrides = $state({ mapbox: false, google: false });+ let enabled = $state(perProvider(() => true));+ let overrides = $state(perProvider(() => false));let eco = $state(true);let ecoMaxZoom = $state(ECO_MAX_ZOOM);+ // per-provider eco thresholds ('' = inherit, '0' = eco off for that basemap);+ // the Maps JS widget is absent — an eco swap would re-bill a map load+ let ecoZooms = $state(perProvider(() => ''));+ // The account's real monthly allowance per meter ('' = the shipped default).+ // A free tier belongs to the provider's account, not to us: they hand out+ // more than they document and change it silently (Copernicus documents 10k+ // and provisions 30k), so the number the counter and the soft block measure+ // against has to be the user's to correct. `tiers` is the resolved figure the+ // helpers read; `tierEdits` is what's in the boxes.+ let tiers = $state(null);+ let tierEdits = $state(perProvider(() => ''));let about = $state({ version: '', workspace_root: '' });++ // --- capture extension: pairing token + detection (lib/extBridge.js) ---+ let ingestToken = $state('');+ let tokenShown = $state(false);+ // read once per mount: the marker is stamped before the app loads, so a+ // mid-session install genuinely needs a tab reload (the text says so)+ const extDetected = extensionVersion();++ async function copyToken() {+ try {+ await navigator.clipboard.writeText(ingestToken);+ toast('Pairing token copied', 'ok');+ } catch {+ tokenShown = true; // clipboard blocked — show it for manual copy+ toast('Could not copy — the token is shown for manual copy', 'warn');+ }+ }++ async function rotateToken() {+ const r = await api.post('/api/settings/ingest-token/rotate');+ ingestToken = r.ingest_token;+ toast('New token minted — every paired extension must re-pair', 'ok', 6000);+ }// the home-view fields are edited as text, so a half-typed "-" or "48." isn't// fought by the number parser mid-keystroke; committed on changelet home = $state({ lat: '', lon: '', zoom: '' });@@ -153,14 +251,28 @@async function load() {const s = await api.get('/api/settings');signature = !!s.signature;- keys = { mapbox: s.api_keys.mapbox ?? '', google: s.api_keys.google ?? '' };+ keys = perProvider((k) => s.api_keys[k.id] ?? '');usage = s.usage;month = s.month;- enabled = { mapbox: s.providers_enabled.mapbox ?? true, google: s.providers_enabled.google ?? true };- overrides = { mapbox: !!s.usage_overrides.mapbox, google: !!s.usage_overrides.google };+ enabled = perProvider((k) => s.providers_enabled[k.id] ?? true);+ overrides = perProvider((k) => !!s.usage_overrides[k.id]);+ // a stored verdict (key test, or a live auth failure) shows up like a+ // fresh test result — it's also what benches the basemap, so it must be+ // visible, not buried in settings.json+ testResult = perProvider((k) => s.provider_status?.[k.id] ?? null);eco = s.eco_zoom_fallback;ecoMaxZoom = s.eco_max_zoom ?? ECO_MAX_ZOOM;+ ecoZooms = perProvider((k) => {+ const v = s.eco_max_zooms?.[k.id];+ return v === undefined || v === null ? '' : String(v);+ });+ tiers = s.free_tier ?? null;+ tierEdits = perProvider((k) => {+ const v = s.free_tiers?.[k.id];+ return v === undefined || v === null ? '' : String(v);+ });about = { version: s.version ?? '', workspace_root: s.workspace_root ?? '' };+ ingestToken = s.ingest_token ?? '';home = { lat: String(s.home_view.lat), lon: String(s.home_view.lon), zoom: String(s.home_view.zoom) };mention = s.post_mention ?? '';applyPrefs(s); // the rest of the app reads these live@@ -217,11 +329,43 @@}async function saveEcoZoom() {+ // per-provider thresholds ride along: '' = inherit (server drops the+ // override on null), a number (0 included — eco off) sets it+ const perProviderZooms = {};+ for (const [id, v] of Object.entries(ecoZooms)) {+ perProviderZooms[id] = v === '' ? null : Number(v);+ }const saved = await savePrefs({eco_zoom_fallback: eco,eco_max_zoom: Number(ecoMaxZoom) || ECO_MAX_ZOOM,+ eco_max_zooms: perProviderZooms,});- if (saved) ecoMaxZoom = saved.eco_max_zoom; // reflect the server's clamping+ if (saved) {+ ecoMaxZoom = saved.eco_max_zoom; // reflect the server's clamping+ ecoZooms = perProvider((k) => {+ const v = saved.eco_max_zooms?.[k.id];+ return v === undefined || v === null ? '' : String(v);+ });+ }+ }++ async function saveFreeTier() {+ // '' = back to the documented default (the server drops the override on null)+ const patch = {};+ for (const [id, v] of Object.entries(tierEdits)) {+ patch[id] = v.trim() === '' ? null : Number(v);+ }+ const saved = await savePrefs({ free_tiers: patch });+ if (saved) {+ // re-read the *resolved* tiers: the server clamps, and a cleared+ // override has to fall back to the default in the readout too+ const s = await api.get('/api/settings').catch(() => null);+ if (s) tiers = s.free_tier ?? null;+ tierEdits = perProvider((k) => {+ const v = saved.free_tiers?.[k.id];+ return v === undefined || v === null ? '' : String(v);+ });+ }}async function saveHome() {@@ -251,17 +395,15 @@load().catch((e) => toast(`Could not load settings: ${e.message}`, 'danger'));});- async function saveKeys() {- if (saving) return;- saving = true;+ // Keys save on change like every other preference here — no Save button to+ // forget. The status chip flipping to "Untested" is the receipt, which beats+ // a toast: it also says what to do next.+ async function saveKey(id) {try {- await api.put('/api/settings/keys', { mapbox: keys.mapbox, google: keys.google });- testResult = { mapbox: null, google: null }; // stale verdicts for new keys- toast('Keys saved. Keyed basemaps now appear in the Satellite tab', 'ok');+ await api.put('/api/settings/keys', { [id]: keys[id] });+ testResult[id] = null; // the old verdict was about the old key (so does the server)} catch (e) {- toast(`Could not save keys: ${e.message}`, 'danger');- } finally {- saving = false;+ toast(`Could not save the key: ${e.message}`, 'danger');}}@@ -273,7 +415,30 @@testResult[id] = null;try {await api.put('/api/settings/keys', { [id]: keys[id] }); // test what's in the field- testResult[id] = await api.post(`/api/settings/keys/${id}/test`);+ const def = KEYED.find((k) => k.id === id);+ if (def?.browserTest) {+ // a Maps JS key only proves itself in a browser; Google's script also+ // binds to one key per page life, so a changed key needs a reload+ const bound = googleMapsLoadedKey();+ if (bound && bound !== keys[id].trim()) {+ testResult[id] = {+ ok: false,+ detail: 'Google Maps is already loaded with the previous key — reload the app (F5), then test',+ };+ } else {+ const url = `https://maps.googleapis.com/maps/api/js?key=${encodeURIComponent(keys[id].trim())}&v=weekly`;+ const { billed, ...verdict } = await probeKey(url);+ testResult[id] = verdict;+ // The probe is a real map load on the user's bill, and it happens in+ // this browser where no backend proxy can count it — report it, or+ // testing a key silently drifts the counter under Google's number.+ if (billed) await api.post(`/api/satellite/usage/${id}`).catch(() => {});+ }+ // persist the browser's verdict — it's what benches/unbenches the basemap+ await api.post(`/api/settings/keys/${id}/status`, testResult[id]).catch(() => {});+ } else {+ testResult[id] = await api.post(`/api/settings/keys/${id}/test`);+ }} catch (e) {testResult[id] = { ok: false, detail: e.message };} finally {@@ -427,111 +592,58 @@{#if tab === 'imagery'}<section class="group">- <h3>API keys</h3>+ <h3>Providers</h3><p class="intro">- Optional. Azimut's built-in basemaps (Esri, OSM, OpenTopoMap) never need a key — your own- Mapbox / Google keys just unlock extra official basemaps in the Satellite tab.- Keys stay in <span class="mono">settings.json</span> on this machine.+ Optional. The built-in basemaps (Esri, OSM, OpenTopoMap) never need a key — your own+ Mapbox / Google / Copernicus accounts just unlock extra ones in the Satellite tab.+ Keys stay in <span class="mono">settings.json</span> on this machine, never in a case+ or an export, and Azimut counts every request it sends so a free tier is never a+ surprise.</p>- {#each KEYED as k (k.id)}- <div class="key-row">- <label for="key-{k.id}">- {k.field}- <a href={k.help} target="_blank" rel="noreferrer" title="How to get one">- how to get one <Icon name="external" size={11} />- </a>- </label>- <div class="key-line">- <input- id="key-{k.id}"- class="input"- type={shown[k.id] ? 'text' : 'password'}- placeholder={k.placeholder}- bind:value={keys[k.id]}- autocomplete="off"- spellcheck="false"- />- <button- class="btn btn-ghost btn-sm"- onclick={() => (shown[k.id] = !shown[k.id])}- title={shown[k.id] ? 'Hide key' : 'Show key'}- aria-label={shown[k.id] ? 'Hide key' : 'Show key'}- >- <Icon name={shown[k.id] ? 'eyeOff' : 'eye'} size={14} />- </button>- <button- class="btn btn-sm"- onclick={() => testKey(k.id)}- disabled={testing[k.id] || !keys[k.id].trim()}- title="Save this key, then exercise it against the real service"- >- {testing[k.id] ? 'Testing…' : 'Test'}- </button>- </div>- <div class="key-foot">- <span class="unlocks">Unlocks: {k.unlocks}</span>- {#if keys[k.id]}- <label- class="toggle"- title="Hide or show this basemap in the Satellite tab — the key stays saved"+ <div class="cards">+ {#each KEYED as k (k.id)}+ {@const count = monthCount(usage, k.id, month)}+ {@const share = freeTierShare(count, k.id, tiers)}+ {@const st = providerStatus({+ key: keys[k.id],+ enabled: enabled[k.id],+ status: testResult[k.id],+ count,+ meter: k.id,+ overrides,+ tiers,+ })}+ <div class="card" class:open={open[k.id]}>+ <div class="card-head">+ <button+ class="card-toggle"+ onclick={() => (open[k.id] = !open[k.id])}+ aria-expanded={open[k.id]}>- <input type="checkbox" bind:checked={enabled[k.id]} onchange={saveProviderPrefs} />- enabled- </label>- {/if}- {#if testResult[k.id]}- <span class="verdict" class:ok={testResult[k.id].ok} class:bad={!testResult[k.id].ok}>- <Icon name={testResult[k.id].ok ? 'check' : 'alert'} size={12} />- {testResult[k.id].ok ? 'Key works' : testResult[k.id].detail}- </span>- {/if}- </div>- </div>- {/each}-- <div class="actions">- <button class="btn btn-primary" onclick={saveKeys} disabled={saving}>- {saving ? 'Saving…' : 'Save keys'}- </button>- </div>- </section>-- <section class="group">- <h3><Icon name="shield" size={14} /> Provider terms, encoded</h3>- <ul class="rules">- <li>Google tiles are never cached to disk, and a Google capture is a flattened screenshot with the copyright line burned into its footer; both are conditions of Google's Map Tiles API terms.</li>- <li>Mapbox captures keep the © Mapbox © OpenStreetMap attribution in their provenance.</li>- <li>Keys are never bundled into a shared case or export.</li>- </ul>- </section>- {/if}+ <Icon name={open[k.id] ? 'chevronDown' : 'chevronRight'} size={13} />+ <span class="card-name">{k.label}</span>+ <span class="card-gives">{k.gives}</span>+ </button>+ <span+ class="chip {st.tone}"+ title={st.tone === 'bad' ? testResult[k.id]?.detail : undefined}+ >{st.label}</span>+ {#if keys[k.id]}+ <input+ class="card-enable"+ type="checkbox"+ bind:checked={enabled[k.id]}+ onchange={saveProviderPrefs}+ title="Show or hide this basemap in the Satellite tab — the key stays saved"+ aria-label="Show {k.label} in the Satellite tab"+ />+ {/if}+ </div>- {#if tab === 'usage'}- <section class="group">- <h3>Tile usage · {month}</h3>- <p class="intro">- Keyed providers bill per tile served. Azimut counts exactly what goes out to- each provider (live map + captures, browser cache hits excluded), so this- matches their billing as closely as possible. Local bookkeeping only — the- counter never leaves this machine.- </p>- {#if KEYED.some((k) => keys[k.id] || monthCount(usage, k.id, month))}- <div class="usage">- {#each KEYED as k (k.id)}- {#if keys[k.id] || monthCount(usage, k.id, month)}- {@const count = monthCount(usage, k.id, month)}- {@const share = freeTierShare(count, k.id)}- <div class="usage-row">- <div class="usage-line">- <span class="usage-name">- {k.label}- <a href={k.usage} target="_blank" rel="noreferrer"- title="The provider's own usage & limits dashboard — the counter that actually bills"- >usage & limits <Icon name="external" size={11} /></a>- </span>- <span class="mono">{tilesOfFree(count, k.id)}</span>- </div>+ <!-- one line either way: what it would cost, or what it has cost -->+ {#if keys[k.id] || count}+ <div class="card-meter"><div class="meter-track" aria-hidden="true"><divclass="meter-fill"@@ -539,35 +651,172 @@style="width:{Math.min(share * 100, 100)}%"></div></div>- {#if usageBlocked(count, k.id, overrides)}- <p class="blocked">+ <span class="mono meter-read">{tilesOfFree(count, k.id, tiers)}</span>+ </div>+ {:else if !open[k.id]}+ <!-- open, the body's overage already leads with the cost -->+ <p class="card-cost">{k.cost}</p>+ {/if}++ {#if open[k.id]}+ <div class="card-body">+ {#if k.warning}+ <p class="key-warning"><Icon name="alert" size={12} /> {k.warning}</p>+ {/if}+ {#if k.steps}+ <ol class="key-steps">+ {#each k.steps as step (step)}+ <li>{step}</li>+ {/each}+ </ol>+ {/if}++ <label class="key-label" for="key-{k.id}">+ {k.field}+ <a href={k.help} target="_blank" rel="noreferrer" title="How to get one">+ how to get one <Icon name="external" size={11} />+ </a>+ </label>+ <div class="key-line">+ <input+ id="key-{k.id}"+ class="input"+ type={shown[k.id] ? 'text' : 'password'}+ placeholder={k.placeholder}+ bind:value={keys[k.id]}+ onchange={() => saveKey(k.id)}+ autocomplete="off"+ spellcheck="false"+ />+ <button+ class="btn btn-ghost btn-sm"+ onclick={() => (shown[k.id] = !shown[k.id])}+ title={shown[k.id] ? 'Hide key' : 'Show key'}+ aria-label={shown[k.id] ? 'Hide key' : 'Show key'}+ >+ <Icon name={shown[k.id] ? 'eyeOff' : 'eye'} size={14} />+ </button>+ <button+ class="btn btn-sm"+ onclick={() => testKey(k.id)}+ disabled={testing[k.id] || !keys[k.id].trim()}+ title="Exercise this key against the real service"+ >+ {testing[k.id] ? 'Testing…' : 'Test'}+ </button>+ </div>+ {#if testResult[k.id] && !testResult[k.id].ok}+ <p class="verdict bad"><Icon name="alert" size={12} />- Paused at {Math.round(BLOCK_SHARE * 100)}% of the free tier — the map and- captures fall back to free imagery until next month, or:+ {testResult[k.id].detail}</p>{/if}- {#if share >= BLOCK_SHARE || overrides[k.id]}- <label class="toggle override" title="Serve past the pause — extra tiles are billed by the provider">- <input type="checkbox" bind:checked={overrides[k.id]} onchange={saveProviderPrefs} />- keep serving past {Math.round(BLOCK_SHARE * 100)}% (billed)- </label>++ <p class="overage">{k.cost} — {k.overage}</p>++ {#if keys[k.id] || count}+ {#if usageBlocked(count, k.id, overrides, tiers)}+ <p class="blocked">+ <Icon name="alert" size={12} />+ Paused at {Math.round(BLOCK_SHARE * 100)}% of the free tier — the map and+ captures fall back to free imagery until next month, or:+ </p>+ {/if}+ {#if share >= BLOCK_SHARE || overrides[k.id]}+ <label+ class="toggle override"+ title="Serve past the pause — extra tiles are billed by the provider"+ >+ <input+ type="checkbox"+ bind:checked={overrides[k.id]}+ onchange={saveProviderPrefs}+ />+ keep serving past {Math.round(BLOCK_SHARE * 100)}% (billed)+ </label>+ {/if}++ <div class="card-controls">+ <label+ class="ctrl"+ title={k.tierNote ??+ "What this account's monthly free allowance really is — check the provider's dashboard"}+ >+ <span>Free allowance</span>+ <input+ class="input num mono"+ type="number"+ min="1"+ step="1000"+ placeholder={String(FREE_TIER[k.id] ?? '')}+ bind:value={tierEdits[k.id]}+ onchange={saveFreeTier}+ />+ <span class="ctrl-note">+ {tierEdits[k.id].trim() === ''+ ? 'blank = the documented default'+ : `default is ${(FREE_TIER[k.id] ?? 0).toLocaleString('en-US')}`}+ </span>+ </label>++ {#if k.browserTest}+ <p class="ctrl-note">+ No eco mode: swapping the widget out and back would bill a fresh map load.+ </p>+ {:else}+ <label+ class="ctrl"+ title="Own threshold for this basemap — blank inherits the global one, 0 turns eco off for it"+ >+ <span>Eco below z ≤</span>+ <input+ class="input num mono"+ type="number"+ min="0"+ max="21"+ placeholder={k.id === 'sentinelhub' ? '11' : String(ecoMaxZoom)}+ bind:value={ecoZooms[k.id]}+ onchange={saveEcoZoom}+ disabled={!eco}+ aria-label="Eco threshold for {k.label}"+ />+ <span class="ctrl-note">+ {k.id === 'sentinelhub'+ ? 'blank = 11 (it caps at z14)'+ : 'blank = the global threshold'}+ </span>+ </label>+ {/if}+ </div>++ <a class="card-link" href={k.usage} target="_blank" rel="noreferrer">+ {k.label} usage & limits <Icon name="external" size={11} />+ </a>{/if}- <p class="overage">{k.overage}</p></div>{/if}- {/each}- </div>- {:else}- <p class="none">No keyed provider configured yet.</p>- {/if}+ </div>+ {/each}+ </div>++ <div class="cards-foot">+ <span class="row-hint">Counters for {month} — local bookkeeping, never sent anywhere.</span>+ <button class="btn btn-ghost btn-sm" onclick={() => load()} title="Refresh counters">+ <Icon name="reset" size={13} /> Refresh+ </button>+ </div>+ </section>++ <section class="group">+ <h3>Eco mode</h3><labelclass="toggle eco"title="Zoomed out this far, billed basemaps silently swap to free imagery — paid detail only matters up close"><input type="checkbox" bind:checked={eco} onchange={saveEcoZoom} />- Eco mode: use free imagery when zoomed out, up to z ≤+ Use free imagery when zoomed out, up to z ≤<input- class="input eco-zoom"+ class="input num mono"type="number"min="1"max="21"@@ -577,9 +826,103 @@aria-label="Eco mode zoom threshold"/></label>- <button class="btn btn-ghost btn-sm" onclick={() => load()} title="Refresh counters">- <Icon name="reset" size={13} /> Refresh- </button>+ <p class="note">+ Paid detail only matters up close. Each provider can override this from its card.+ </p>+ </section>++ <section class="group">+ <div class="card">+ <div class="card-head">+ <button+ class="card-toggle"+ onclick={() => (termsOpen = !termsOpen)}+ aria-expanded={termsOpen}+ >+ <Icon name={termsOpen ? 'chevronDown' : 'chevronRight'} size={13} />+ <span class="card-name">Provider terms</span>+ <span class="card-gives">Encoded — nothing to do</span>+ </button>+ </div>+ {#if termsOpen}+ <ul class="rules">+ <li>Google tiles are never cached to disk, and a Google capture is a flattened screenshot with the copyright line burned into its footer; both are conditions of Google's Map Tiles API terms.</li>+ <li>Mapbox captures keep the © Mapbox © OpenStreetMap attribution in their provenance.</li>+ <li>Keys are never bundled into a shared case or export.</li>+ </ul>+ {/if}+ </div>+ </section>+ {/if}++ {#if tab === 'extension'}+ <section class="group">+ <h3>Capture extension</h3>+ <p class="note">+ A small browser extension (Chrome/Edge and Firefox) that files the map you+ are looking at into Azimut as a capture — one screenshot per click,+ coordinates parsed from the page URL, source and timestamp recorded. It+ serves two things: <strong>capturing external map sites</strong> (Google+ Maps & Earth, Bing, Yandex, OpenStreetMap, Apple Maps, Zoom Earth,+ Satellites.pro), and the <strong>Capture button on the Google (Maps JS)+ basemap</strong>, whose imagery may only leave the widget as a screenshot.+ </p>+ <div class="row">+ <div class="row-label">+ <span>Status in this browser</span>+ <span class="row-hint">+ {#if extDetected}+ detected · <span class="mono">v{extDetected}</span>+ {:else}+ not detected — after installing, reload this tab+ {/if}+ </span>+ </div>+ <a class="btn btn-sm btn-primary" href="/api/ingest/extension.zip" download>+ <Icon name="download" size={13} /> Download extension (.zip)+ </a>+ </div>+ <p class="note">+ Browsers do not let an app install extensions for you — it's two manual+ steps, once: <strong>Chrome/Edge</strong>: unzip somewhere permanent →+ <span class="mono">chrome://extensions</span> → enable Developer mode →+ "Load unpacked" → pick the folder. <strong>Firefox</strong>:+ <span class="mono">about:debugging</span> → "This Firefox" → "Load+ Temporary Add-on" → pick <span class="mono">manifest.json</span> (Firefox+ forgets temporary add-ons on exit — see the README in the zip for a+ permanent install). Then reload this tab.+ </p>+ </section>++ <section class="group">+ <h3>Pairing</h3>+ <p class="note">+ Pairing lets the extension file captures from <em>external</em> map sites+ into your local Azimut. Paste this token once into the extension's+ options page. The Google (Maps JS) capture inside Azimut does not need+ pairing. Rotating the token instantly unpairs every extension.+ </p>+ <div class="row">+ <div class="row-label">+ <span>Pairing token</span>+ <span class="row-hint mono">{tokenShown ? ingestToken : '•'.repeat(24)}</span>+ </div>+ <div class="scraper-actions">+ <button class="btn btn-sm" onclick={() => (tokenShown = !tokenShown)}>+ {tokenShown ? 'Hide' : 'Show'}+ </button>+ <button class="btn btn-sm btn-primary" onclick={copyToken}>+ <Icon name="copy" size={13} /> Copy+ </button>+ <button class="btn btn-sm" onclick={rotateToken}>Rotate</button>+ </div>+ </div>+ <p class="note">+ The token only authorizes filing captures into this Azimut on+ <span class="mono">127.0.0.1</span> — nothing leaves your machine. The+ extension takes one screenshot per explicit click, reads only the page+ URL, and refuses non-map sites.+ </p></section>{/if}@@ -775,6 +1118,26 @@font-size: var(--fs-xs);line-height: 1.4;}+ /* Recipe for a provider whose "key" is a configuration you build yourself */+ .key-steps {+ margin: 4px 0 8px;+ padding-left: 18px;+ color: var(--text-3);+ font-size: var(--fs-xs);+ line-height: 1.5;+ }+ .key-steps li {+ margin: 1px 0;+ }+ .key-warning {+ display: flex;+ align-items: baseline;+ gap: 5px;+ margin: 4px 0 8px;+ color: var(--warn, #d8a03d);+ font-size: var(--fs-xs);+ line-height: 1.45;+ }.scraper-actions {display: flex;align-items: center;@@ -914,10 +1277,146 @@text-decoration: none;}- .key-row {- margin-bottom: 14px;+ /* --- provider cards: one row each until you open one --------------------+ A closed card answers the only two questions you have from across the+ room — what does it give me, and is it working — in one line. Setting a+ provider up is the rare act; reading the tab is the common one. */+ .cards {+ display: flex;+ flex-direction: column;+ gap: 6px;}- .key-row label {+ .card {+ border: 1px solid var(--border);+ border-radius: var(--r-md);+ padding: 8px 10px;+ background: var(--bg-2);+ transition: border-color 0.12s var(--ease);+ }+ .card.open {+ border-color: var(--text-3);+ background: none;+ }+ .card-head {+ display: flex;+ align-items: center;+ gap: 10px;+ }+ .card-toggle {+ flex: 1;+ min-width: 0;+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 0;+ border: 0;+ background: none;+ color: var(--text-3);+ font: inherit;+ text-align: left;+ cursor: pointer;+ }+ .card-name {+ font-size: var(--fs-sm);+ font-weight: 600;+ color: var(--text-1);+ flex-shrink: 0;+ }+ .card-gives {+ font-size: var(--fs-xs);+ color: var(--text-3);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .card-enable {+ accent-color: var(--accent);+ margin: 0;+ flex-shrink: 0;+ cursor: pointer;+ }+ /* the verdict, in one word — the detail is a tooltip, and the fix is inside */+ .chip {+ flex-shrink: 0;+ padding: 1px 7px;+ border-radius: 999px;+ border: 1px solid var(--border);+ font-size: var(--fs-xs);+ color: var(--text-3);+ white-space: nowrap;+ }+ .chip.ok {+ color: var(--ok);+ border-color: color-mix(in srgb, var(--ok) 40%, transparent);+ }+ .chip.bad {+ color: var(--danger);+ border-color: color-mix(in srgb, var(--danger) 40%, transparent);+ }+ .chip.warn {+ color: var(--warn, #d8a03d);+ border-color: color-mix(in srgb, var(--warn, #d8a03d) 40%, transparent);+ }+ .card-meter {+ display: flex;+ align-items: center;+ gap: 9px;+ margin: 7px 0 1px;+ }+ .card-meter .meter-track {+ flex: 1;+ }+ .meter-read,+ .card-cost {+ font-size: var(--fs-xs);+ color: var(--text-3);+ white-space: nowrap;+ }+ .card-cost {+ margin: 5px 0 1px 21px; /* aligned under the name, past the chevron */+ }+ .card-body {+ margin-top: 12px;+ padding-top: 12px;+ border-top: 1px solid var(--border);+ }+ .card-controls {+ display: flex;+ flex-direction: column;+ gap: 7px;+ margin-top: 9px;+ }+ .ctrl {+ display: flex;+ align-items: center;+ gap: 8px;+ font-size: var(--fs-xs);+ color: var(--text-3);+ }+ /* both control rows put their box at the same x — they read as a column */+ .ctrl > span:first-child {+ min-width: 104px;+ color: var(--text-2);+ }+ .ctrl-note {+ opacity: 0.8;+ }+ .card-link {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ margin-top: 10px;+ color: var(--accent);+ font-size: var(--fs-xs);+ }+ .cards-foot {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ margin-top: 12px;+ }+ .key-label {display: flex;align-items: baseline;gap: 10px;@@ -926,7 +1425,7 @@font-weight: 600;margin-bottom: 5px;}- .key-row label a {+ .key-label a {color: var(--accent);font-weight: 400;display: inline-flex;@@ -942,48 +1441,17 @@flex: 1;font-family: var(--font-mono);}- .key-foot {- display: flex;- gap: 12px;- align-items: center;- margin-top: 4px;- font-size: var(--fs-xs);- }- .unlocks {- color: var(--text-3);- }.verdict {- display: inline-flex;+ display: flex;align-items: center;gap: 4px;- }- .verdict.ok {- color: var(--ok);+ margin-top: 5px;+ font-size: var(--fs-xs);+ line-height: 1.4;}.verdict.bad {color: var(--danger);}- .actions {- margin-top: 4px;- }- .usage {- margin: 0 0 10px;- display: flex;- flex-direction: column;- gap: 14px;- font-size: var(--fs-sm);- }- .usage-line {- display: flex;- justify-content: space-between;- align-items: baseline;- gap: 10px;- margin-bottom: 5px;- }- .usage-name {- font-weight: 600;- color: var(--text-2);- }.meter-track {height: 5px;border-radius: var(--r-sm);@@ -1001,19 +1469,10 @@background: var(--danger);}.overage {- margin-top: 5px;+ margin-top: 9px;color: var(--text-3);font-size: var(--fs-xs);- line-height: 1.4;- }- .usage-name a {- color: var(--accent);- font-weight: 400;- font-size: var(--fs-xs);- margin-left: 8px;- display: inline-flex;- align-items: center;- gap: 3px;+ line-height: 1.45;}.toggle {display: inline-flex;@@ -1034,12 +1493,13 @@}.toggle.eco {display: flex;- margin: 2px 0 10px;+ margin: 2px 0;}- .eco-zoom {- width: 58px;+ /* every small numeric box in this tab: eco thresholds, free allowances */+ .num {+ width: 92px;padding: 2px 6px;- font-family: var(--font-mono);+ flex-shrink: 0;}.blocked {margin-top: 6px;@@ -1050,16 +1510,11 @@gap: 5px;line-height: 1.4;}- .none {- color: var(--text-3);- font-size: var(--fs-sm);- margin-bottom: 10px;- }.rules {- margin: 0;+ margin: 12px 0 2px;padding-left: 18px;color: var(--text-2);- font-size: var(--fs-sm);+ font-size: var(--fs-xs);display: flex;flex-direction: column;gap: 6px;diff --git a/frontend/src/tools/inspect/CollageMenu.svelte b/frontend/src/tools/inspect/CollageMenu.svelteindex c98c013..c494aae 100644--- a/frontend/src/tools/inspect/CollageMenu.svelte+++ b/frontend/src/tools/inspect/CollageMenu.svelte@@ -1,7 +1,7 @@<script>import {previewStyle, scaleQuad, rotateQuad, quadCentroid, cropImgStyle, styleText, uid,- rotateQuads, scaleQuads,+ rotateQuads, scaleQuads, pinholeOps,} from '../../lib/inspect.js';import { api } from '../../lib/api.js';import { caseState, toast } from '../../lib/state.svelte.js';@@ -11,7 +11,7 @@// to the active one, and act on the selected piece. A session holds several// collages (session.collages / session.activeCollageId); each is saved as its// own PNG. Each added piece is a frozen snapshot of the frame (addToCollage).- let { session, filters, selectedIds = $bindable([]), addToCollage, requestCrop } = $props();+ let { session, filters, selectedIds = $bindable([]), addToCollage, requestCrop, renderPiece } = $props();const active = $derived(session.collages.find((c) => c.id === session.activeCollageId) ?? session.collages[0]@@ -104,25 +104,56 @@}// ---- auto-stitch ----------------------------------------------------------- // The backend solves each piece's quad from the imagery itself and hands the- // geometry back — the pieces stay ordinary, hand-tunable pieces (spec § v2- // Panorama: machine stitch first, hand-tune after). Pieces it can't place are- // left exactly where they were, for the analyst to place by hand.+ // The backend solves each piece's placement from the imagery itself and hands+ // back a recipe, never pixels (spec § v2 Panorama: machine stitch first,+ // hand-tune after). Pieces it can't place are left exactly where they were, for+ // the analyst to place by hand.+ //+ // The mode picks the projection, and the two are genuinely different bargains:+ // `planar` returns a quad per piece and they stay corner-warpable, but it models+ // the scene as one flat surface, so a wide pan blows the end pieces up. The+ // panorama modes solve the camera's rotation instead and bake the resulting warp+ // into each piece's recipe — bounded and undistorted however far you panned, at+ // the cost of the corner handles.+ const MODES = [+ { id: 'planar', label: 'Planar', hint: 'One flat surface — a facade, the ground, a map. Pieces stay warpable.' },+ { id: 'cylindrical', label: 'Cylindrical', hint: 'A camera panning sideways. Bounded and even end to end.' },+ { id: 'spherical', label: 'Spherical', hint: 'A camera that pans *and* tilts. Same, over both axes.' },+ ];+ let mode = $state('cylindrical');let stitching = $state(false);- let undoQuads = $state(null);+ let undoSnap = $state(null);++ const snapshot = (n) => ({+ id: n.id, quad: n.quad.map(([x, y]) => [x, y]), url: n.url, baseUrl: n.baseUrl,+ w: n.w, h: n.h, frameOps: n.frameOps, crop: n.crop, save: n.save,+ });async function autoStitch() {if (!active || active.nodes.length < 2) return;stitching = true;try {- const before = active.nodes.map((n) => ({ id: n.id, quad: n.quad.map(([x, y]) => [x, y]) }));+ const nodes = active.nodes;+ const before = nodes.map(snapshot);const res = await api.post(`/api/cases/${caseState.current.id}/inspect/auto-stitch`, {width: active.width,height: active.height,- nodes: active.nodes.map((n) => n.save), // frozen snapshot recipes (path/time/ops)+ mode,+ // frozen snapshot recipes (path/time/ops), stripped back to pinhole pixels+ nodes: nodes.map((n) => ({ ...n.save, ops: pinholeOps(n.save) })),});- for (const { index, quad } of res.nodes) active.nodes[index].quad = quad;- undoQuads = before;+ for (const { index, quad, op } of res.nodes) {+ const node = nodes[index];+ const base = pinholeOps(node.save);+ const ops = op ? [...base, op] : base;+ // Planar leaves the pixels alone; only re-derive when the recipe moved+ // (a panorama warp arriving, or dropping off on the way back to planar).+ if (JSON.stringify(ops) !== JSON.stringify(node.save.ops ?? [])) {+ await renderPiece(node, ops);+ }+ node.quad = quad;+ }+ undoSnap = before;selectedIds = [];const placed = res.nodes.length;if (res.dropped.length) {@@ -138,11 +169,11 @@}function undoStitch() {- for (const { id, quad } of undoQuads) {- const node = active.nodes.find((n) => n.id === id);- if (node) node.quad = quad;+ for (const snap of undoSnap) {+ const node = active.nodes.find((n) => n.id === snap.id);+ if (node) Object.assign(node, snap);}- undoQuads = null;+ undoSnap = null;}</script>@@ -245,8 +276,16 @@<div class="section-head"><span>Auto panorama</span></div><p class="hint">Solves the layout from the overlapping imagery itself, then drops the pieces back on the- canvas — still draggable and warpable, so you can hand-tune the machine's guess.+ canvas — still draggable, so you can hand-tune the machine's guess.</p>+ <div class="modes">+ {#each MODES as m (m.id)}+ <button class="mode" class:on={mode === m.id} onclick={() => (mode = m.id)} title={m.hint}>+ {m.label}+ </button>+ {/each}+ </div>+ <p class="hint sub-hint">{MODES.find((m) => m.id === mode).hint}</p><buttonclass="btn btn-sm w-full"disabled={stitching || !active || active.nodes.length < 2}@@ -258,7 +297,7 @@<Icon name={stitching ? 'clock' : 'hash'} size={14} />{stitching ? 'Stitching…' : 'Auto-stitch pieces'}</button>- {#if undoQuads}+ {#if undoSnap}<button class="btn btn-ghost btn-xs w-full" onclick={undoStitch}><Icon name="reset" size={12} /> Undo auto-stitch</button>@@ -379,6 +418,33 @@display: flex;padding: 1px;}+ .modes {+ display: flex;+ gap: 0;+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ overflow: hidden;+ background: var(--bg-1);+ }+ .mode {+ flex: 1;+ padding: 5px 4px;+ font-size: var(--fs-xs);+ color: var(--text-2);+ background: transparent;+ border: none;+ border-left: 1px solid var(--border);+ }+ .mode:first-child {+ border-left: none;+ }+ .mode.on {+ background: var(--bg-3);+ color: var(--accent);+ }+ .sub-hint {+ margin-top: -2px;+ }.scale-row {display: flex;align-items: center;diff --git a/pyproject.toml b/pyproject.tomlindex 1e9b635..8312711 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -61,6 +61,22 @@ artifacts = ["src/azimut/static/**"][tool.hatch.build.targets.wheel]packages = ["src/azimut"]+# The capture extension (repo root extension/) ships inside the wheel so the+# app can serve it for install (GET /api/ingest/extension.zip) — a pip/binary+# user has no repo checkout to load it from. Runtime files only: the dev+# harness (vitest, package.json, node_modules) stays out.+[tool.hatch.build.targets.wheel.force-include]+"extension/manifest.json" = "azimut/extension/manifest.json"+"extension/background.js" = "azimut/extension/background.js"+"extension/bridge.js" = "azimut/extension/bridge.js"+"extension/overlay.js" = "azimut/extension/overlay.js"+"extension/popup.html" = "azimut/extension/popup.html"+"extension/popup.js" = "azimut/extension/popup.js"+"extension/options.html" = "azimut/extension/options.html"+"extension/options.js" = "azimut/extension/options.js"+"extension/ui.css" = "azimut/extension/ui.css"+"extension/icons" = "azimut/extension/icons"+"extension/README.md" = "azimut/extension/README.md"[tool.pytest.ini_options]testpaths = ["tests"]diff --git a/src/azimut/api/events.py b/src/azimut/api/events.pynew file mode 100644index 0000000..ce265ff--- /dev/null+++ b/src/azimut/api/events.py@@ -0,0 +1,83 @@+"""Server-sent events: the app hears about things that happen behind its back.++The capture extension files screenshots through /api/ingest while the app tab+just sits there — without a push channel the user would have to reload to see+their own capture. This is that channel: an in-process pub/sub (no broker, no+persistence — spec §4) streamed over SSE. Same-origin only, so it stays inside+the local-first rule: the browser talks to its own backend, nothing else.++Events are advisory nudges ("case X gained a capture"), never the data itself:+a consumer reacts by re-fetching through the normal API, so a missed event+costs a refresh, not correctness.+"""++from __future__ import annotations++import asyncio+import json+from typing import Any++from fastapi import APIRouter, Request+from fastapi.responses import StreamingResponse++router = APIRouter(prefix="/api", tags=["events"])++# One queue per connected listener. Bounded so one stuck consumer can't grow+# memory — events are droppable nudges (see module docstring), so a full queue+# just loses a refresh hint, never data.+_subscribers: set[asyncio.Queue] = set()+_QUEUE_SIZE = 64+++def subscribe() -> asyncio.Queue:+ q: asyncio.Queue = asyncio.Queue(maxsize=_QUEUE_SIZE)+ _subscribers.add(q)+ return q+++def unsubscribe(q: asyncio.Queue) -> None:+ _subscribers.discard(q)+++def publish(event: dict[str, Any]) -> None:+ """Fan an event out to every listener. Non-blocking by design: called from+ request handlers that must never wait on a slow consumer."""+ for q in list(_subscribers):+ try:+ q.put_nowait(event)+ except asyncio.QueueFull:+ pass # a saturated listener misses a nudge, nothing more+++# How long the stream waits for an event before emitting a keepalive comment.+# The ping doubles as the disconnect probe: a closed client is only noticed at+# a write, so this bounds how long a dead connection can linger. Tests shrink it.+_PING_SECONDS = 15.0+++async def sse_stream(q: asyncio.Queue, is_disconnected):+ """The SSE generator, separated from the route so it is testable without+ a live transport (TestClient deadlocks on infinite streams). One `data:`+ line per event; `: ping` comments double as keepalive and as the moment a+ dead connection gets noticed (a closed client only fails at a write)."""+ try:+ # an immediate comment line lets EventSource settle the connection+ yield ": connected\n\n"+ while not await is_disconnected():+ try:+ event = await asyncio.wait_for(q.get(), timeout=_PING_SECONDS)+ except asyncio.TimeoutError:+ yield ": ping\n\n"+ continue+ yield f"data: {json.dumps(event)}\n\n"+ finally:+ unsubscribe(q)++[email protected]("/events")+async def events(request: Request) -> StreamingResponse:+ return StreamingResponse(+ sse_stream(subscribe(), request.is_disconnected),+ media_type="text/event-stream",+ headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},+ )diff --git a/src/azimut/api/ingest.py b/src/azimut/api/ingest.pynew file mode 100644index 0000000..c08e0c5--- /dev/null+++ b/src/azimut/api/ingest.py@@ -0,0 +1,315 @@+"""REST API for the capture browser extension (extension/ at the repo root).++The extension screenshots a map the user is looking at — an external site+(Google Earth, Google Maps, Bing, Yandex, OSM) or this app's own Maps JS+widget basemap — and files it here as a ``capture`` entity, riding the same+media pipeline as a satellite crop so it lists, opens and exports like one.++Trust model: the server already binds localhost only, so the pairing token+(``config.ingest_token``, shown in Settings, pasted once into the extension)+exists to stop *other* local pages and processes from filing images into+cases — CSRF-by-token, not network security. CORS is opened for these routes+only, and only to browser-extension origins: no web page origin is ever+allowed, whatever token it presents.++Legal rails (docs/IMAGERY_PROVIDERS.md §0): every capture is one user-initiated+screenshot of what was already on screen — the extension never crawls,+repeats, or touches tile servers — and provenance always records the source+URL, site and timestamp. Attribution is burned into a footer band, the same+treatment the widget screenshot endpoint applies.+"""++from __future__ import annotations++import io+import secrets+import zipfile+from datetime import datetime, timezone+from pathlib import Path+from typing import Any+from urllib.parse import urlsplit++from fastapi import APIRouter, Depends, Form, Header, HTTPException, Request, Response, UploadFile+from PIL import Image++from .. import __version__, config+from ..engine import geo, mapsites, media as media_engine, satellite as satellite_engine, tiles+from ..workspace import Case+from . import events+from .cases import get_case++router = APIRouter(prefix="/api/ingest", tags=["ingest"])++# Screenshots are viewport-sized PNGs — a 4K display lands well under this.+MAX_IMAGE_BYTES = 25 * 1024 * 1024++# Browser extensions are the only cross-origin callers these routes accept.+EXTENSION_ORIGIN_SCHEMES = ("chrome-extension://", "moz-extension://", "safari-web-extension://")++# Attribution burned under an ingested screenshot, by parsed site id. The+# source site's own on-screen credits ride along inside the pixels; this band+# restates the operator so a cropped capture can never shed it.+ATTRIBUTIONS = {+ "google-maps": "Map data © Google",+ "google-earth": "Google Earth",+ "bing-maps": "© Microsoft — Bing Maps",+ "yandex-maps": "© Yandex Maps",+ "openstreetmap": "© OpenStreetMap contributors",+ "apple-maps": "© Apple Maps",+ "zoom-earth": "© Zoom Earth",+ "satellites-pro": "© Satellites.pro",+ "copernicus-browser": "© Copernicus Sentinel data",+}+++def require_token(x_azimut_token: str = Header(default="")) -> None:+ """401 unless the request carries the pairing token. Constant-time compare;+ an unminted token ("") matches nothing."""+ expected = config.load_settings().get("ingest_token") or ""+ if not expected or not secrets.compare_digest(x_azimut_token, expected):+ raise HTTPException(status_code=401, detail="missing or invalid pairing token")+++def install_cors(app) -> None:+ """CORS for /api/ingest/* only, and only for extension origins.++ Deliberately not Starlette's CORSMiddleware: that is app-wide, and opening+ the whole API to extension origins would let any installed extension call+ every route. Here the allowance is scoped twice — path prefix and origin+ scheme — and everything else keeps the browser's same-origin default.+ """+ allow_headers = {+ "Access-Control-Allow-Methods": "GET, POST, OPTIONS",+ "Access-Control-Allow-Headers": "X-Azimut-Token, Content-Type",+ "Access-Control-Max-Age": "600",+ }++ @app.middleware("http")+ async def ingest_cors(request: Request, call_next):+ origin = request.headers.get("origin", "")+ allowed = request.url.path.startswith("/api/ingest/") and origin.startswith(+ EXTENSION_ORIGIN_SCHEMES+ )+ if allowed and request.method == "OPTIONS":+ # the custom token header makes every extension call preflight+ return Response(+ status_code=204,+ headers={"Access-Control-Allow-Origin": origin, "Vary": "Origin", **allow_headers},+ )+ response = await call_next(request)+ if allowed:+ response.headers["Access-Control-Allow-Origin"] = origin+ response.headers["Vary"] = "Origin"+ return response++[email protected]("/ping", dependencies=[Depends(require_token)])+def ping() -> dict[str, Any]:+ """Pairing check: the extension options page proves URL + token in one call."""+ return {"app": "azimut", "version": __version__}++[email protected]("/cases", dependencies=[Depends(require_token)])+def cases() -> list[dict[str, Any]]:+ """The case picker for the extension popup — ids and names, nothing more."""+ return [+ {"id": c["id"], "name": c["name"], "scratch": bool(c.get("scratch"))}+ for c in Case.list_all()+ ]++[email protected]("/parse", dependencies=[Depends(require_token)])+def parse(url: str) -> dict[str, Any]:+ """Parse a map URL for the popup's prefill (engine/mapsites.py).++ The extension deliberately contains no URL knowledge — formats race sites+ that change without notice, and an app update is easy where an extension+ update is manual. ``{"site": null}`` means "not a map: don't capture here".+ """+ return mapsites.parse_map_url(url) or {"site": None}++[email protected]("/screenshot", dependencies=[Depends(require_token)])+async def ingest_screenshot(+ image: UploadFile,+ url: str = Form(min_length=1, max_length=4000),+ case_id: str = Form(default=""),+ site: str = Form(default="", max_length=64),+ lat: float | None = Form(default=None, ge=-90, le=90),+ lon: float | None = Form(default=None, ge=-180, le=180),+ zoom: float | None = Form(default=None, ge=0, le=23),+ bearing: float | None = Form(default=None, ge=0, lt=360),+ captured_at: str = Form(default=""),+ title: str = Form(default="", max_length=200),+ # which extension build took the shot — provenance, nothing else keys on it+ extension: str = Form(default="", max_length=32),+) -> dict[str, Any]:+ """File one user-initiated screenshot of an external map as a capture.++ The URL is the source of truth: site, coordinates, place name and imagery+ date are parsed HERE (engine/mapsites.py), never in the extension — URL+ formats race sites that change without notice, and a changed format must+ be an app update, not a manual extension reinstall. The optional form+ fields are the user's popup corrections and win over the parse; anything+ the client doesn't send, the URL fills. Coordinates stay optional as a+ pair — a URL with no position still files, fixable later in the sidebar.+ A URL that isn't a recognized map site is refused: captures are for maps+ only (legal rails). An empty ``case_id`` files into a fresh scratch+ session, the same place the app's own tools start.+ """+ parsed = mapsites.parse_map_url(url)+ if parsed is None:+ raise HTTPException(+ status_code=422, detail="not a recognized map site — captures are for maps only"+ )++ # popup corrections win; the URL fills whatever the client didn't send+ lat = lat if lat is not None else parsed["lat"]+ lon = lon if lon is not None else parsed["lon"]+ zoom = zoom if zoom is not None else parsed["zoom"]+ bearing = bearing if bearing is not None else parsed["bearing"]+ title = title.strip() or (parsed["title"] or "")+ if (lat is None) != (lon is None):+ raise HTTPException(status_code=422, detail="lat and lon come as a pair")++ raw = await image.read(MAX_IMAGE_BYTES + 1)+ if len(raw) > MAX_IMAGE_BYTES:+ raise HTTPException(+ status_code=413,+ detail=f"screenshot must be under {MAX_IMAGE_BYTES // 1024 // 1024} MB",+ )+ try:+ img = Image.open(io.BytesIO(raw)).convert("RGB")+ except Exception as exc:+ raise HTTPException(status_code=422, detail=f"not a readable image: {exc}") from exc++ site = parsed["site"]+ attribution = ATTRIBUTIONS.get(site, f"© {urlsplit(url).netloc.lower()}")+ img = tiles.burn_attribution(img, attribution)++ case = get_case(case_id) if case_id else Case.create("Scratch session", scratch=True)++ # the client's clock is honest context, not truth — recorded alongside+ # fetched_at (the server's), never instead of it+ try:+ captured = datetime.fromisoformat(captured_at).astimezone(timezone.utc)+ except ValueError:+ captured = None++ has_coords = lat is not None and lon is not None+ label = title or (+ satellite_engine.coords_label(lat, lon) if has_coords else parsed["label"]+ )++ provenance: dict[str, Any] = {+ "method": "screenshot", # user-taken screen pixels of an external map+ "framed": False, # URL-derived view coords, not a registered crop+ "source_url": url,+ "site": site,+ "extension": extension.strip() or None,+ # the same slots a satellite capture fills, so every panel renders an+ # ingested screenshot identically (provider chip, imagery date)+ "provider": site,+ "provider_label": parsed["label"],+ "imagery_date": parsed["imagery_date"],+ "lat": lat,+ "lon": lon,+ "zoom": zoom,+ "bearing": bearing,+ "captured_at": captured.isoformat(timespec="seconds") if captured else None,+ "attribution": attribution,+ "attribution_burned": True,+ "fetched_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),+ "width": img.width,+ "height": img.height,+ }+ if has_coords:+ provenance["plus_code"] = geo.plus_code(lat, lon)+ provenance["dms"] = geo.to_dms(lat, lon)++ extra_attrs: dict[str, Any] = {"site": site, "source_url": url}+ if has_coords:+ extra_attrs.update(+ {+ "coords": satellite_engine.coords_label(lat, lon, "dd"),+ "lat": lat,+ "lon": lon,+ "plus_code": provenance["plus_code"],+ }+ )+ if zoom is not None:+ extra_attrs["zoom"] = zoom+ if bearing is not None:+ extra_attrs["bearing"] = bearing++ stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")+ result = media_engine.import_image(+ case,+ img,+ f"ingest_{stamp}_{site.replace('/', '_')}.png",+ {"type": "screenshot", **provenance},+ by="ingest",+ entity_type="capture",+ extra_attrs=extra_attrs,+ title=label,+ dedupe=False,+ )+ # nudge any open app tab so the capture shows up without a reload+ events.publish(+ {"type": "capture", "case_id": case.id, "path": result["item"]["path"],+ "title": label, "site": site}+ )+ return {+ "path": result["item"]["path"],+ "case_id": case.id,+ "title": label,+ **provenance,+ }+++# ---- extension download: the packaged source, zipped on request ---------------++# Repo checkout first (development), then the copy hatchling ships inside the+# wheel (azimut/extension) — same dual-home pattern as the built frontend.+_EXTENSION_DIRS = (+ Path(__file__).parents[3] / "extension",+ Path(__file__).parents[1] / "extension",+)+# Runtime files only: the extension's own dev harness (vitest, package.json,+# lockfile) has no business in an installed browser.+_ZIP_EXCLUDE_DIRS = {"node_modules", "tests", ".git"}+_ZIP_EXCLUDE_FILES = {"package.json", "package-lock.json", "vitest.config.js", ".gitignore"}+++def _extension_dir() -> Path | None:+ for candidate in _EXTENSION_DIRS:+ if (candidate / "manifest.json").is_file():+ return candidate+ return None++[email protected]("/extension.zip")+def extension_zip() -> Response:+ """The capture extension, zipped for Settings' install flow.++ Unauthenticated on purpose: it is the installer, it contains no secrets+ (the token is pasted in *after* install), and gating it on the token would+ make pairing circular.+ """+ src = _extension_dir()+ if src is None:+ raise HTTPException(status_code=404, detail="extension not bundled with this build")+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:+ for path in sorted(src.rglob("*")):+ rel = path.relative_to(src)+ if not path.is_file() or path.name in _ZIP_EXCLUDE_FILES:+ continue+ if any(part in _ZIP_EXCLUDE_DIRS or part.endswith(".test.js") for part in rel.parts):+ continue+ zf.write(path, str(rel))+ return Response(+ content=buf.getvalue(),+ media_type="application/zip",+ headers={"Content-Disposition": 'attachment; filename="azimut-capture-extension.zip"'},+ )diff --git a/src/azimut/api/inspect.py b/src/azimut/api/inspect.pyindex f2a9b3a..0a38ab0 100644--- a/src/azimut/api/inspect.py+++ b/src/azimut/api/inspect.py@@ -10,7 +10,7 @@ from __future__ import annotationsimport jsonimport refrom datetime import datetime, timezone-from typing import Any+from typing import Any, Literalfrom fastapi import APIRouter, HTTPException, Responsefrom pydantic import BaseModel, Field@@ -110,6 +110,9 @@ class StitchIn(BaseModel):width: int = Field(ge=16, le=8192)height: int = Field(ge=16, le=8192)nodes: list[NodeSrc] = Field(min_length=2)+ # 'planar' keeps pieces hand-warpable; the panorama modes trade that for a+ # bounded, undistorted strip (see engine/stitch).+ mode: Literal["planar", "cylindrical", "spherical"] = "planar"class EnhanceVideoIn(BaseModel):@@ -289,10 +292,11 @@ def compose(case_id: str, body: ComposeIn) -> dict[str, Any]:@router.post("/cases/{case_id}/inspect/auto-stitch")def auto_stitch(case_id: str, body: StitchIn) -> dict[str, Any]:- """Solve collage quads for overlapping pieces — layout only, nothing is filed.+ """Solve collage placement for overlapping pieces — nothing is filed.The pieces stay live on the canvas afterwards (spec § v2 Panorama: machine- stitch first, hand-tune after), so this returns geometry, not pixels.+ stitch first, hand-tune after), so this returns a recipe, not pixels: a quad+ each, plus — in the panorama modes — the remap op that shapes the piece."""case = get_case(case_id)srcs = [@@ -301,7 +305,7 @@ def auto_stitch(case_id: str, body: StitchIn) -> dict[str, Any]:]try:return inspect_engine.solve_collage_layout(- case, srcs=srcs, width=body.width, height=body.height+ case, srcs=srcs, width=body.width, height=body.height, mode=body.mode)except CaseError as exc:raise HTTPException(status_code=400, detail=str(exc)) from excdiff --git a/src/azimut/api/satellite.py b/src/azimut/api/satellite.pyindex 9547f52..7fb2630 100644--- a/src/azimut/api/satellite.py+++ b/src/azimut/api/satellite.py@@ -6,7 +6,7 @@ from datetime import datetime, timezonefrom typing import Anyimport httpx-from fastapi import APIRouter, HTTPException+from fastapi import APIRouter, Form, HTTPException, UploadFilefrom fastapi.responses import Responsefrom PIL import Imagefrom pydantic import BaseModel, Field@@ -17,6 +17,7 @@ from ..engine import (google_tiles,media as media_engine,satellite as satellite_engine,+ sentinel,tilecache,tiles,)@@ -66,6 +67,9 @@ class SatelliteUpdateIn(BaseModel):@router.get("/satellite/providers")def providers() -> list[dict[str, Any]]:+ # the user's per-provider eco threshold (Settings) beats the provider's+ # own default; the frontend falls back to the global one when both absent+ eco_overrides = config.load_settings().get("eco_max_zooms", {})return [{"id": p.id,@@ -73,6 +77,10 @@ def providers() -> list[dict[str, Any]]:"url": p.url,"attribution": p.attribution,"max_zoom": p.max_zoom,+ # deepest zoom with real pixels; null = same as max_zoom. The live+ # map hands it to Leaflet's maxNativeZoom, which magnifies the last+ # native tile instead of requesting one that doesn't exist.+ "max_native_zoom": p.max_native_zoom,"needs_key": p.needs_key,"imagery": p.imagery,"capturable": p.capturable,@@ -81,11 +89,96 @@ def providers() -> list[dict[str, Any]]:"meter": p.meter,"tile_size": p.tile_size,"oversample": p.oversample,+ "widget": p.widget,+ "eco_max_zoom": (+ p.eco_max_zoom+ if p.widget # the widget's pinned 0 is not user-tunable+ else eco_overrides.get(p.meter, p.eco_max_zoom)+ ),}for p in tiles.all_providers()]+def _sentinel_instance() -> str:+ key = (config.load_settings().get("api_keys") or {}).get("sentinelhub")+ if not key:+ raise HTTPException(status_code=404, detail="no Sentinel Hub key saved")+ return key++[email protected]("/satellite/sentinel/layers")+def sentinel_layers(check: bool = False) -> dict[str, Any]:+ """The Sentinel-2 layers on offer.++ Without ``check`` this is the built-in catalogue and touches nothing —+ opening the Satellite tab must never phone out (local-first). ``check=true``+ asks the user's own instance what it really serves (GetCapabilities), which+ is the only authority: a configuration can rename or drop any of them.+ """+ if not check:+ return {+ "layers": [{"id": e.id, "label": e.label, "hint": e.hint} for e in sentinel.LAYERS],+ "source": "catalogue",+ }+ try:+ found = sentinel.capabilities_layers(_sentinel_instance())+ except HTTPException:+ raise+ except Exception as exc:+ # the catalogue still works — say why the real list is missing, don't fail+ return {+ "layers": [{"id": e.id, "label": e.label, "hint": e.hint} for e in sentinel.LAYERS],+ "source": "catalogue",+ "detail": f"could not read the instance's layers: {exc}",+ }+ if not found:+ return {+ "layers": [{"id": e.id, "label": e.label, "hint": e.hint} for e in sentinel.LAYERS],+ "source": "catalogue",+ "detail": "the instance listed no layers",+ }+ return {"layers": found, "source": "instance"}++[email protected]("/satellite/sentinel/dates")+def sentinel_dates(lat: float, lon: float, start: str, end: str) -> dict[str, Any]:+ """Sentinel-2 acquisition dates over a point, newest first.++ User-triggered only (a date picker being opened/moved) — never on mount.+ Billed as one request on the sentinelhub meter: a WFS query is ~0.01 PU+ against a tile's 1 PU, but it is one request against the request quota, and+ the meter's job is to count what the account is charged for.+ """+ instance = _sentinel_instance()+ if config.usage_blocked("sentinelhub"):+ raise HTTPException(+ status_code=429,+ detail=f"Sentinel Hub is paused: {int(config.BLOCK_SHARE * 100)}% of the monthly "+ "free tier is used — enable the override in Settings to keep going",+ )+ try:+ found = sentinel.dates(instance, lat, lon, start, end)+ except Exception as exc:+ raise HTTPException(status_code=502, detail=f"date lookup failed: {exc}") from exc+ config.record_usage("sentinelhub", 1)+ return {"dates": found, "start": start, "end": end}++[email protected]("/satellite/usage/{meter}")+def record_widget_usage(meter: str) -> dict[str, Any]:+ """Count one billed *map load* for a widget basemap.++ Tile meters are counted server-side by the proxy, but a widget (Maps JS)+ instantiates in the browser — the frontend reports each instantiation+ here so the Settings counter stays a faithful mirror of Google's billing.+ """+ known = {p.meter for p in tiles.all_providers() if p.widget}+ if meter not in known:+ raise HTTPException(status_code=404, detail=f"no widget meter '{meter}'")+ return {"count": config.record_usage(meter, 1)}++def _serve_tile(provider: tiles.Provider, z: int, x: int, y: int) -> tuple[bytes, str, dict[str, str]] | Response | None:@@ -104,8 +197,15 @@ def _serve_tile(upstream: httpx.Response | None = Nonefor attempt in (1, 2):try:- url = tiles.resolve_url(provider).format(x=x, y=y, z=z)+ url = tiles.tile_url(tiles.resolve_url(provider), z, x, y, provider.zoom_offset)except tiles.TileFetchError as exc:+ # a session mint that the provider *refused* (not a network hiccup)+ # is an auth verdict — Google's EEA policy block lands here with+ # its own sentence. Bench the basemap so it isn't offered dead.+ if provider.meter and isinstance(+ exc.__cause__, google_tiles.GoogleSessionError+ ):+ config.record_provider_status(provider.meter, False, str(exc.__cause__))raise HTTPException(status_code=502, detail=str(exc)) from exctry:upstream = httpx.get(@@ -123,6 +223,13 @@ def _serve_tile(if upstream.status_code == 404:return Noneif upstream.status_code >= 400:+ # a 401/403 that survived the re-mint retry names the key, not the+ # tile: record it (with the provider's own sentence when it sent one)+ # so the basemap stops being offered until the key changes or re-tests+ if provider.meter and upstream.status_code in (401, 403):+ config.record_provider_status(+ provider.meter, False, google_tiles.error_message(upstream)+ )return Response(content=upstream.content,status_code=upstream.status_code,@@ -141,6 +248,21 @@ def _serve_tile(return upstream.content, media_type, headers+def _native_grid_zoom(provider: tiles.Provider) -> int | None:+ """The provider's native ceiling in *tile-grid* levels, or None if it has+ pixels everywhere it can be viewed.++ ``max_native_zoom`` is a view zoom, like ``max_zoom``; the proxy speaks the+ grid, which a big tile shifts down (512px → one level).+ """+ if provider.max_native_zoom is None:+ return None+ import math++ z_shift = int(math.log2(provider.tile_size // tiles.TILE_SIZE))+ return provider.max_native_zoom - z_shift++@router.get("/tiles/{provider_id}/{z}/{x}/{y}")def tile_proxy(provider_id: str, z: int, x: int, y: int) -> Response:"""Live-map tiles for every provider, proxied through the app.@@ -163,7 +285,14 @@ def tile_proxy(provider_id: str, z: int, x: int, y: int) -> Response:"monthly free tier is used — enable the override in Settings to keep going",)- served = _serve_tile(provider, z, x, y)+ # Past the provider's native ceiling there is nothing new upstream: Sentinel+ # Hub would upsample its own z14 pixels and bill every tile of it. Skip the+ # fetch and let the climb below magnify the native tile instead — same+ # pixels, no quota. The live map already stops asking (Leaflet's+ # maxNativeZoom), so this is the guard for anything that doesn't.+ native_z = _native_grid_zoom(provider)+ beyond_native = max(0, z - native_z) if native_z is not None else 0+ served = None if beyond_native else _serve_tile(provider, z, x, y)if isinstance(served, Response):return servedif served is not None:@@ -173,7 +302,8 @@ def tile_proxy(provider_id: str, z: int, x: int, y: int) -> Response:# no imagery at this zoom — climb parents and upscale the matching quadrantimport io- for up in range(1, tiles.OVERZOOM_LEVELS + 1):+ first = max(1, beyond_native)+ for up in range(first, first + tiles.OVERZOOM_LEVELS):if z - up < 0:breakparent = _serve_tile(provider, z - up, x >> up, y >> up)@@ -304,6 +434,96 @@ def capture(case_id: str, body: CaptureIn) -> dict[str, Any]:return {"path": result["item"]["path"], "title": label, **provenance}[email protected]("/cases/{case_id}/satellite/screenshot")+async def capture_screenshot(+ case_id: str,+ image: UploadFile,+ lat: float = Form(ge=-90, le=90),+ lon: float = Form(ge=-180, le=180),+ zoom: int = Form(ge=1, le=22),+ provider: str = Form(),+ bearing: float = Form(default=0.0, ge=0, le=360),+ framed: bool = Form(default=False),+) -> dict[str, Any]:+ """File a user-made screenshot of a widget basemap as a capture.++ Widget providers (Google Maps JS) have no tiles to stitch, and the only+ image Google's terms allow out of the widget is a screenshot the user took+ themselves (Geo Guidelines: permitted with attribution). So the frontend+ grabs the screen and this endpoint files it like any capture — attribution+ burned into a footer band (never optional for Google), provenance marked+ ``method: "screenshot"``.++ ``framed`` is what keeps that provenance honest, and the two paths differ:+ a screen crop taken through the capture frame is registered, so ``lat``/+ ``lon`` are the *centre of the crop*; a pasted or dropped screenshot is+ not, so they only describe the *map view when it was filed*. Readers of the+ provenance must be able to tell which they are holding.+ """+ case = get_case(case_id)+ try:+ prov = tiles.get_provider(provider)+ except KeyError as exc:+ raise HTTPException(status_code=404, detail=str(exc)) from exc+ if not prov.widget:+ # tile providers have the real capture path — a screenshot would only+ # launder away its provenance+ raise HTTPException(status_code=422, detail="screenshot captures are for widget basemaps")++ import io++ raw = await image.read()+ try:+ img = Image.open(io.BytesIO(raw)).convert("RGB")+ except Exception as exc:+ raise HTTPException(status_code=422, detail=f"not a readable image: {exc}") from exc++ year = datetime.now(timezone.utc).year+ attribution = f"Map data ©{year} Google"+ img = tiles.burn_attribution(img, attribution)++ label = satellite_engine.coords_label(lat, lon)+ coords_dd = satellite_engine.coords_label(lat, lon, "dd")+ plus_code = geo.plus_code(lat, lon)+ provenance: dict[str, Any] = {+ "provider": prov.id,+ "provider_label": prov.label,+ "method": "screenshot", # user-taken screen pixels, not a stitched crop+ # True: lat/lon are the centre of a registered crop frame.+ # False: they are only the map view at filing time (pasted image).+ "framed": framed,+ "lat": lat,+ "lon": lon,+ "zoom": zoom,+ "bearing": bearing,+ "attribution": attribution,+ "attribution_burned": True,+ "plus_code": plus_code,+ "dms": geo.to_dms(lat, lon),+ "fetched_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),+ "width": img.width,+ "height": img.height,+ }++ stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")+ filename = f"sat_{stamp}_z{zoom}_{prov.id}_screenshot.png"+ result = media_engine.import_image(+ case,+ img,+ filename,+ {"type": "satellite", **provenance},+ by="satellite",+ entity_type="capture",+ extra_attrs={+ "coords": coords_dd, "lat": lat, "lon": lon,+ "plus_code": plus_code, "zoom": zoom, "bearing": bearing,+ },+ title=label,+ dedupe=False,+ )+ return {"path": result["item"]["path"], "title": label, **provenance}++@router.post("/cases/{case_id}/satellite/place")def save_place(case_id: str, body: PlaceIn) -> dict[str, Any]:"""Save just a point (the pin, or the crop center) as a navigable ``place`` —diff --git a/src/azimut/api/settings.py b/src/azimut/api/settings.pyindex 3ecf7a0..9017527 100644--- a/src/azimut/api/settings.py+++ b/src/azimut/api/settings.py@@ -9,6 +9,7 @@ settings.json, reaching a case only as pixels in a rendered proof PNG.from __future__ import annotations+import refrom typing import Anyimport httpx@@ -17,13 +18,16 @@ from fastapi.responses import FileResponsefrom pydantic import BaseModel, Fieldfrom .. import __version__, config-from ..engine import google_tiles, scrapers, tiles+from ..engine import google_tiles, scrapers, sentinel, tilesrouter = APIRouter(prefix="/api", tags=["settings"])# the keyed providers the settings tab manages — matching api_keys entries# light up the built-in basemaps (engine/tiles.py all_providers)-KEYED_PROVIDERS = ("mapbox", "google")+KEYED_PROVIDERS = ("mapbox", "google", "google_js", "sentinelhub")+# tile APIs whose eco threshold the user may tune per provider; the Maps JS+# widget is deliberately absent (eco re-bills a map load per swap — never worth it)+ECO_TUNABLE = ("mapbox", "google", "sentinelhub")DEFAULT_HOME_VIEW = config.DEFAULT_SETTINGS["home_view"]DEFAULT_POST_MENTION = config.DEFAULT_SETTINGS["post_mention"]@@ -33,6 +37,10 @@ class KeysIn(BaseModel):# None = leave untouched; "" (or whitespace) = remove the stored keymapbox: str | None = Nonegoogle: str | None = None+ # Maps JavaScript API key — the EEA-viable Google route (widget basemap)+ google_js: str | None = None+ # Sentinel Hub's "key" is a configuration-instance UUID, not a secret token+ sentinelhub: str | None = Noneclass HomeView(BaseModel):@@ -53,6 +61,12 @@ class PrefsIn(BaseModel):# swap billed basemaps for free imagery at low zoom (≤ eco_max_zoom)eco_zoom_fallback: bool | None = Noneeco_max_zoom: int | None = None # clamped to a sane zoom range+ # per-provider eco thresholds: {"mapbox": 15, "sentinelhub": 0, ...} —+ # value None removes the override (back to provider default / global)+ eco_max_zooms: dict[str, int | None] | None = None+ # per-meter monthly free allowance: {"sentinelhub": 30000} — value None+ # restores the documented default (config.FREE_TIER)+ free_tiers: dict[str, int | None] | None = None# display preferences — presentation only, never touches stored artifactscoord_format: str | None = None # one of config.COORD_FORMATSunits: str | None = None # one of config.UNIT_SYSTEMS@@ -67,6 +81,9 @@ def _prefs(settings: dict[str, Any]) -> dict[str, Any]:"usage_overrides": settings.get("usage_overrides", {}),"eco_zoom_fallback": bool(settings.get("eco_zoom_fallback", True)),"eco_max_zoom": int(settings.get("eco_max_zoom", config.ECO_MAX_ZOOM)),+ "eco_max_zooms": settings.get("eco_max_zooms", {}),+ # the user's corrections only; `free_tier` below is the resolved figure+ "free_tiers": settings.get("free_tiers", {}),"coord_format": settings.get("coord_format", "dd"),"units": settings.get("units", "metric"),"home_view": settings.get("home_view", DEFAULT_HOME_VIEW),@@ -81,16 +98,24 @@ def get_settings() -> dict[str, Any]:"api_keys": settings.get("api_keys", {}),"usage": settings.get("usage", {}),"month": config.month_key(),+ # last known health per keyed credential — Settings shows a stored+ # failure inline, and a failing key withholds its basemap (tiles.py)+ "provider_status": settings.get("provider_status", {}),# whether a logo is on disk — the proof composer's signature control is# dead until one is, so it needs to know without fetching the pixels"signature": config.signature_path().is_file(),**_prefs(settings),- # server-side constants the UI mirrors- "free_tier": config.FREE_TIER,+ # what the soft block actually measures against: the documented default+ # per meter, or the user's own figure where they corrected it+ "free_tier": config.free_tiers(settings),+ # the shipped defaults, so Settings can show what it's departing from+ "free_tier_default": config.FREE_TIER,"block_share": config.BLOCK_SHARE,# About tab: what this build is, and where it keeps its files"version": __version__,"workspace_root": str(config.workspace_root()),+ # capture-extension pairing token (api/ingest.py) — minted on first read+ "ingest_token": config.ingest_token(),}@@ -109,6 +134,28 @@ def put_prefs(body: PrefsIn) -> dict[str, Any]:settings["eco_zoom_fallback"] = bool(body.eco_zoom_fallback)if body.eco_max_zoom is not None:settings["eco_max_zoom"] = max(1, min(21, int(body.eco_max_zoom)))+ if body.eco_max_zooms is not None:+ merged = dict(settings.get("eco_max_zooms", {}))+ for name, value in body.eco_max_zooms.items():+ if name not in ECO_TUNABLE:+ continue+ if value is None:+ merged.pop(name, None) # back to provider default / global+ else:+ merged[name] = max(0, min(21, int(value))) # 0 = eco off for it+ settings["eco_max_zooms"] = merged+ if body.free_tiers is not None:+ merged = dict(settings.get("free_tiers", {}))+ for name, value in body.free_tiers.items():+ if name not in config.FREE_TIER:+ continue+ if value is None:+ merged.pop(name, None) # back to the documented default+ else:+ # a free tier is a positive count of requests; the ceiling is+ # only there to keep a typo from disabling the guard entirely+ merged[name] = max(1, min(10_000_000, int(value)))+ settings["free_tiers"] = mergedif body.coord_format is not None:if body.coord_format not in config.COORD_FORMATS:raise HTTPException(status_code=422, detail=f"unknown coord_format '{body.coord_format}'")@@ -129,11 +176,17 @@ def put_prefs(body: PrefsIn) -> dict[str, Any]:def put_keys(body: KeysIn) -> dict[str, Any]:settings = config.load_settings()keys = settings.setdefault("api_keys", {})+ status = settings.setdefault("provider_status", {})for name in KEYED_PROVIDERS:value = getattr(body, name)if value is None:continuevalue = value.strip()+ if value != keys.get(name):+ # a different credential gets a clean slate: the old verdict was+ # about the old key, and a stale failure would keep the basemap+ # benched (tiles.key_for) with no way back but a manual re-test+ status.pop(name, None)if value:keys[name] = valueelse:@@ -142,31 +195,98 @@ def put_keys(body: KeysIn) -> dict[str, Any]:return {"api_keys": keys}+class StatusIn(BaseModel):+ """A browser-side key verdict (Maps JS API keys can only fail in the+ browser — `gm_authFailure` has no server-side equivalent)."""++ ok: bool+ detail: str = ""++[email protected]("/settings/ingest-token/rotate")+def rotate_ingest_token() -> dict[str, Any]:+ """Mint a fresh capture-extension pairing token, orphaning every extension+ paired with the old one (each must paste the new token to reconnect)."""+ return {"ingest_token": config.ingest_token(rotate=True)}++[email protected]("/settings/keys/{provider}/status")+def report_key_status(provider: str, body: StatusIn) -> dict[str, Any]:+ """Persist a key verdict the frontend established itself.++ Two callers: the Settings Test button for the Maps JS key (loads the real+ widget and listens for gm_authFailure), and the live map when a widget+ fails auth mid-session — both make tiles.all_providers withhold the dead+ basemap until the key changes or a later test passes.+ """+ if provider not in KEYED_PROVIDERS:+ raise HTTPException(status_code=404, detail=f"unknown keyed provider '{provider}'")+ config.record_provider_status(provider, body.ok, body.detail)+ return {"ok": body.ok, "detail": body.detail}++@router.post("/settings/keys/{provider}/test")def test_key(provider: str) -> dict[str, Any]:"""Exercise the saved key against the real service — never raises on a bad- key, so the settings tab can show the provider's error message inline."""+ key, so the settings tab can show the provider's error message inline.+ Every verdict is persisted (record_provider_status): a failing key benches+ its basemap, a passing test puts it back."""key = (config.load_settings().get("api_keys") or {}).get(provider)if not key:raise HTTPException(status_code=404, detail=f"no {provider} key saved")++ def verdict(ok: bool, detail: str) -> dict[str, Any]:+ config.record_provider_status(provider, ok, detail)+ return {"ok": ok, "detail": detail}+if provider == "google":try:google_tiles.invalidate(key) # force a fresh mint — that's the testgoogle_tiles.session_token(key)- return {"ok": True, "detail": "session token created"}+ return verdict(True, "session token created")except Exception as exc:- return {"ok": False, "detail": str(exc)}+ return verdict(False, str(exc))+ if provider == "google_js":+ # A JS-API key only proves itself in a browser (gm_authFailure); the+ # Settings tab runs that test and reports through /status above.+ return {"ok": None, "detail": "tested in the browser"}if provider == "mapbox":url = tiles.MAPBOX_SATELLITE_URL.replace("{key}", key).format(z=0, x=0, y=0)try:response = httpx.get(url, headers={"User-Agent": tiles.USER_AGENT}, timeout=10)response.raise_for_status()- return {"ok": True, "detail": "tile fetched"}+ return verdict(True, "tile fetched")+ except Exception as exc:+ return verdict(False, str(exc))+ if provider == "sentinelhub":+ # One real tile over Paris (grid level 13 → TILEMATRIX 14). This checks+ # the instance id *and* that the instance actually has a TRUE_COLOR+ # layer — the wrong template answers 400 rather than a blank tile, so+ # the two mistakes a user can make here are both caught.+ url = tiles.tile_url(+ sentinel.wmts_url().replace("{key}", key), 13, 4151, 2818, zoom_offset=1+ )+ try:+ response = httpx.get(url, headers={"User-Agent": tiles.USER_AGENT}, timeout=10)+ if response.status_code == 400:+ return verdict(False, _wmts_error(response.text))+ response.raise_for_status()+ return verdict(True, "tile fetched")except Exception as exc:- return {"ok": False, "detail": str(exc)}+ return verdict(False, str(exc))raise HTTPException(status_code=404, detail=f"unknown keyed provider '{provider}'")+def _wmts_error(body: str) -> str:+ """The human half of an OGC ExceptionReport ("Invalid instance id: …").++ Sentinel Hub says exactly what is wrong; showing that beats "400 Bad+ Request". Falls back to the raw body if it isn't the XML we expect.+ """+ match = re.search(r"<ows:ExceptionText>(.*?)</ows:ExceptionText>", body, re.S)+ return match.group(1).strip() if match else body.strip()[:200]++# ---- signature: the analyst's logo, stamped onto proofs they choose to sign ---diff --git a/src/azimut/config.py b/src/azimut/config.pyindex 3dec051..361a6f5 100644--- a/src/azimut/config.py+++ b/src/azimut/config.py@@ -43,8 +43,26 @@ DEFAULT_SETTINGS: dict[str, Any] = {# billed basemap for free imagery; paid detail only matters zoomed in."providers_enabled": {},"usage_overrides": {},+ # Per-meter monthly free allowance, overriding config.FREE_TIER:+ # {"sentinelhub": 30000}. A free tier is a fact about the user's account,+ # not about the app — providers grant more than they document (and change+ # it), so the number the soft block measures against has to be theirs to+ # correct. Absent = the FREE_TIER default.+ "free_tiers": {},+ # Last known health of each keyed credential: {"<key_id>": {"ok": bool,+ # "detail": str, "at": iso}}. Written by the Settings key test and by+ # *auth-shaped* provider rejections (never plain network errors); cleared+ # when the key changes. A key marked bad withholds its basemap from the+ # selector until it tests good again — a dead map should not be on offer.+ "provider_status": {},"eco_zoom_fallback": True,"eco_max_zoom": 15,+ # Per-provider eco thresholds: {"<key_id>": zoom}. Overrides the provider's+ # own default and the global eco_max_zoom for that basemap; 0 = eco never+ # fires for it. Absent = inherit (provider default, else global). The+ # Maps JS widget is not configurable here — swapping it out and back+ # re-bills a map load, so eco is pinned off for it in engine/tiles.py.+ "eco_max_zooms": {},# Display preferences, app-wide (Settings → Preferences):# - coord_format: how every tool renders a latitude/longitude — "dd"# (decimal degrees), "dms" (degrees/minutes/seconds), "mgrs" (grid ref).@@ -58,6 +76,10 @@ DEFAULT_SETTINGS: dict[str, Any] = {"home_view": {"lat": 48.8584, "lon": 2.2945, "zoom": 16},# The handle a new post draft is addressed to. Empty means no mention."post_mention": "@GeoConfirmed",+ # Pairing token for the capture browser extension (api/ingest.py). Minted+ # lazily on first use, shown once in Settings, pasted into the extension.+ # Empty means "not minted yet" — never a valid credential.+ "ingest_token": "",}# Accepted values for the display preferences above — mirror of@@ -65,11 +87,22 @@ DEFAULT_SETTINGS: dict[str, Any] = {COORD_FORMATS = ("dd", "dms", "mgrs")UNIT_SYSTEMS = ("metric", "imperial")-# Documented monthly free allowances per meter, in tile requests (verified+# Documented monthly free allowances per meter, in billed requests (verified# 2026-07: Google 2D Map Tiles 100k then $0.60/1k, and ≤15k/day; Mapbox Static-# Tiles 200k then $0.50/1k). A yardstick, not a guarantee — mirror of-# frontend/src/lib/usage.js FREE_TIER.-FREE_TIER = {"mapbox": 200_000, "google": 100_000}+# Tiles 200k then $0.50/1k; Sentinel Hub 30k requests *and* 30k processing units+# for a Copernicus General account, and its 512px tiles are 1 PU each — see+# docs/IMAGERY_PROVIDERS.md, which is why tiles are a faithful unit here).+# A yardstick, not a guarantee — mirror of frontend/src/lib/usage.js FREE_TIER.+# google_js counts *map loads* (Maps JavaScript API dynamic maps), not tiles:+# 10k free/month on the 2025 Essentials tier, then ~$7/1k. One load per widget+# instantiation; pan/zoom on an open map is free, so the unit is coarse but honest.+#+# These are *defaults*, not facts: a free tier is per-account and providers move+# it without touching their docs (Copernicus still documents 10k while actually+# provisioning 30k — observed 2026-07). `free_tiers` in settings.json overrides+# any of them, which is what free_tier() below resolves; a hardcoded number+# would make the counter lie about someone else's account.+FREE_TIER = {"mapbox": 200_000, "google": 100_000, "google_js": 10_000, "sentinelhub": 30_000}# Share of the free tier past which metered providers stop serving unless the# user flips the per-provider override in Settings.BLOCK_SHARE = 0.9@@ -179,13 +212,80 @@ def month_usage(meter: str, settings: dict[str, Any] | None = None) -> int:return int((settings.get("usage", {}).get(meter) or {}).get(month_key(), 0))+def free_tier(meter: str, settings: dict[str, Any] | None = None) -> int | None:+ """This account's monthly free allowance for a meter: the user's own figure+ when they corrected it in Settings, else the documented default.++ None means "unmetered" — no allowance is known, so nothing to block on.+ """+ settings = settings or load_settings()+ override = (settings.get("free_tiers") or {}).get(meter)+ if isinstance(override, (int, float)) and int(override) > 0:+ return int(override)+ return FREE_TIER.get(meter)+++def free_tiers(settings: dict[str, Any] | None = None) -> dict[str, int]:+ """Every meter's live allowance — what the UI mirrors (api/settings.py)."""+ settings = settings or load_settings()+ resolved = {}+ for meter in FREE_TIER:+ value = free_tier(meter, settings)+ if value:+ resolved[meter] = value+ return resolved++def usage_blocked(meter: str, settings: dict[str, Any] | None = None) -> bool:"""True when a metered provider passed BLOCK_SHARE of its free tier and theuser hasn't opted into overage billing for it (docs/IMAGERY_PROVIDERS.md)."""- free = FREE_TIER.get(meter)+ settings = settings or load_settings()+ free = free_tier(meter, settings)if not free:return False- settings = settings or load_settings()if settings.get("usage_overrides", {}).get(meter):return Falsereturn month_usage(meter, settings) >= free * BLOCK_SHARE+++def record_provider_status(key_id: str, ok: bool, detail: str = "") -> None:+ """Persist a keyed credential's last known health (DEFAULT_SETTINGS note).++ Only call this for *auth-shaped* verdicts — a key test, or a provider+ rejection that names the key/account (Google's PERMISSION_DENIED, Sentinel+ Hub's "Invalid instance id"). A timeout or DNS hiccup says nothing about+ the key and must never bench a basemap.+ """+ with _usage_lock: # same file as the counters — same writer lock+ settings = load_settings()+ settings.setdefault("provider_status", {})[key_id] = {+ "ok": bool(ok),+ "detail": str(detail)[:300],+ "at": datetime.now(timezone.utc).isoformat(timespec="seconds"),+ }+ save_settings(settings)+++def provider_key_bad(key_id: str, settings: dict[str, Any] | None = None) -> bool:+ """True when the key's last recorded verdict was a failure."""+ settings = settings or load_settings()+ status = (settings.get("provider_status") or {}).get(key_id)+ return bool(status) and not status.get("ok", True)+++def ingest_token(rotate: bool = False) -> str:+ """The capture extension's pairing token — minted lazily, kept in settings.json.++ Guards /api/ingest/* (api/ingest.py): the server binds localhost, so the+ token's job is to stop *other local pages and processes* from filing+ images into cases, not to survive a hostile network. ``rotate=True``+ mints a fresh one (Settings), instantly orphaning every paired extension.+ """+ import secrets++ with _usage_lock: # same file as the counters — same writer lock+ settings = load_settings()+ if rotate or not settings.get("ingest_token"):+ settings["ingest_token"] = secrets.token_urlsafe(24)+ save_settings(settings)+ return settings["ingest_token"]diff --git a/src/azimut/engine/google_tiles.py b/src/azimut/engine/google_tiles.pyindex 5175627..5c84f98 100644--- a/src/azimut/engine/google_tiles.py+++ b/src/azimut/engine/google_tiles.py@@ -46,11 +46,32 @@ class GoogleSessionError(Exception):pass+def error_message(response: Any) -> str:+ """The human sentence inside a Google Maps Platform error response.++ Falls back to the HTTP status line when the body isn't the usual+ ``{"error": {"message": …}}`` JSON envelope.+ """+ try:+ message = (response.json().get("error") or {}).get("message")+ if message:+ return str(message)+ except Exception:+ pass+ text = (getattr(response, "text", "") or "").strip()+ return text[:300] if text else f"HTTP {response.status_code}"++def _mint(key: str, post: Callable[..., Any] | None) -> dict[str, Any]:response = (post or httpx.post)(CREATE_SESSION_URL, params={"key": key}, json=SESSION_BODY, timeout=15)- response.raise_for_status()+ if response.status_code >= 400:+ # Google's error body carries the actual sentence ("satellite tiles …+ # are not available for your account and region" for EEA accounts,+ # "API key expired", …) — raise that, not a bare "403 Forbidden",+ # because for a policy block the message *is* the diagnosis.+ raise GoogleSessionError(error_message(response))data = response.json()if not data.get("session"):raise GoogleSessionError("createSession response carried no session token")diff --git a/src/azimut/engine/inspect.py b/src/azimut/engine/inspect.pyindex 3128ebc..18d2fb8 100644--- a/src/azimut/engine/inspect.py+++ b/src/azimut/engine/inspect.py@@ -162,15 +162,43 @@ def _apply_crop(img: Image.Image, params: dict[str, Any]) -> Image.Image:_register_filter(Filter("crop", "Crop", _apply_crop)) # driven by an interactive box, no sliders+# Auto-stitch's panorama modes bake their projection into the piece's recipe, so+# the full-res export re-derives the very warp the solver measured. Solved by+# machine, never by slider — like crop, it has no params of its own.+_register_filter(Filter("remap", "Panorama warp", lambda img, params: stitch.apply_warp(img, params)))++# Filters that speak RGBA themselves: the remap *produces* the alpha, and a crop+# carries whatever it is handed straight through.+_ALPHA_NATIVE = {"remap", "crop"}+++def _apply_keeping_alpha(flt: Filter, img: Image.Image, params: dict[str, Any]) -> Image.Image:+ """Run a filter on RGB pixels, carrying an alpha channel across untouched.++ Once a piece has been remapped onto a cylinder its transparent corners are+ load-bearing — they are what stops it painting black wedges over its+ neighbours. The colour filters know nothing about that channel and would+ happily scale it, so hold it aside and put it back.+ """+ if img.mode != "RGBA" or flt.id in _ALPHA_NATIVE:+ return flt.apply(img, params)+ alpha = img.getchannel("A")+ out = flt.apply(img.convert("RGB"), params)+ if out.size != alpha.size: # a resizing filter (rotate expands) — footprint lost+ return out.convert("RGBA")+ out = out.convert("RGB")+ out.putalpha(alpha)+ return out+def apply_ops(image: Image.Image, ops: list[dict[str, Any]]) -> Image.Image:"""Run an ordered list of ``{"op": id, "params": {...}}`` through the pipeline."""- out = image.convert("RGB")+ out = image if image.mode == "RGBA" else image.convert("RGB")for op in ops:flt = FILTERS.get(op.get("op"))if flt is None:raise ValueError(f"unknown filter {op.get('op')!r}")- out = flt.apply(out, op.get("params") or {})+ out = _apply_keeping_alpha(flt, out, op.get("params") or {})return out@@ -613,9 +641,14 @@ def render_preview_png("""Render a recipe (video frame or image + ops) to PNG bytes — no filing.Backs collage snapshots and rebuilding previews when a saved session reopens.+ A remapped (panorama) piece keeps its alpha, so the canvas shows the same+ curved footprint the export will paint."""+ img = _source_image(case, rel_path, time_s, ops)+ if img.mode != "RGBA":+ img = img.convert("RGB")buf = io.BytesIO()- _source_image(case, rel_path, time_s, ops).convert("RGB").save(buf, "PNG")+ img.save(buf, "PNG")return buf.getvalue()@@ -715,15 +748,18 @@ def _compose_canvas(rel = spec.get("path")if not rel:raise ValueError("collage node is missing a source path")- img = _source_image(case, rel, spec.get("time"), spec.get("ops")).convert("RGB")+ img = _source_image(case, rel, spec.get("time"), spec.get("ops"))+ # A piece remapped onto a panorama's cylinder arrives with its footprint in+ # the alpha channel — paint through that rather than over it, or its+ # transparent corners land as black wedges on the neighbour underneath.+ footprint = img.getchannel("A") if img.mode == "RGBA" else Image.new("L", img.size, 255)+ img = img.convert("RGB")w, h = img.sizesrc_corners = [[0, 0], [w, 0], [w, h], [0, h]]quad = [[float(x) * scale, float(y) * scale] for x, y in node["quad"]]coeffs = _perspective_coeffs(quad, src_corners)warped = img.transform((width, height), Image.PERSPECTIVE, coeffs, Image.BICUBIC)- mask = Image.new("L", (w, h), 255).transform(- (width, height), Image.PERSPECTIVE, coeffs, Image.BICUBIC- )+ mask = footprint.transform((width, height), Image.PERSPECTIVE, coeffs, Image.BILINEAR)canvas.paste(warped, (0, 0), mask)sources.append(rel)return canvas, sources@@ -786,27 +822,51 @@ def compose_perspective(return result+STITCH_MODES = ("planar", *stitch.WARPS)++def solve_collage_layout(- case: Case, *, srcs: list[dict[str, Any]], width: int, height: int+ case: Case, *, srcs: list[dict[str, Any]], width: int, height: int, mode: str = "planar") -> dict[str, Any]:- """Auto-stitch: solve each piece's quad from the imagery itself (no filing).+ """Auto-stitch: solve each piece's placement from the imagery itself (no filing).``srcs`` are the same ``{path, time?, ops[]}`` recipes the collage alreadyspeaks, so pieces stitch *as adjusted* — what the analyst sees is what getsmatched. The returned quads are canvas pixels, ready to drop onto the canvas- as ordinary (still hand-tunable) pieces; ``dropped`` lists the pieces that- matched nothing, which the caller leaves where they were.+ as ordinary pieces; ``dropped`` lists the pieces that matched nothing, which+ the caller leaves where they were.++ ``mode`` picks the projection (see :mod:`azimut.engine.stitch`). ``planar``+ returns quads alone — the pieces keep their pixels and stay hand-warpable. The+ panorama modes also return a per-piece ``op``: the remap to append to that+ piece's recipe, which is how the warp survives to the full-res export. Callers+ must hand in *un-remapped* recipes; a cylinder is not a pinhole view, so+ solving cameras from already-warped pixels would measure the wrong scene."""+ if mode not in STITCH_MODES:+ raise ValueError(f"unknown panorama mode {mode!r}")images = [_source_image(case, s["path"], s.get("time"), s.get("ops")) for s in srcs]try:- solved = stitch.solve_layout(images, width=width, height=height)+ if mode == "planar":+ solved = stitch.solve_layout(images, width=width, height=height)+ else:+ solved = stitch.solve_rotation_layout(images, width=width, height=height, warp=mode)finally:for img in images:img.close()+ remaps = solved.get("remaps") or {}return {- "nodes": [{"index": i, "quad": q} for i, q in sorted(solved["quads"].items())],+ "mode": mode,+ "nodes": [+ {+ "index": i,+ "quad": q,+ "op": ({"op": "remap", "params": remaps[i]} if i in remaps else None),+ }+ for i, q in sorted(solved["quads"].items())+ ],"dropped": solved["dropped"],}diff --git a/src/azimut/engine/mapsites.py b/src/azimut/engine/mapsites.pynew file mode 100644index 0000000..aefc6a8--- /dev/null+++ b/src/azimut/engine/mapsites.py@@ -0,0 +1,236 @@+"""Map-site URL parsing — coordinates, place name and imagery date from a URL.++This lives in the backend ON PURPOSE (owner decision, same logic as the+unbounded yt-dlp/gallery-dl ranges): URL formats race sites that change+without notice, and the capture extension is the hardest component to update+(installed by hand, no store, no auto-update). So the extension stays dumb —+screenshot + send the URL — and every format rule lives here, where a normal+app update fixes it.++Deliberately URL-only (legal rails): the page DOM is never read, so a+capture's coordinates are exactly what the address bar says the view is —+verifiable by anyone with the recorded source URL.++``parse_map_url(url)`` returns None for a non-map URL (the extension refuses+to capture there — maps only), else a dict with ``site``/``label`` always set+and ``lat``/``lon``/``zoom``/``bearing``/``title``/``imagery_date`` set to+values when the URL carries them, None when it doesn't. A malformed URL on a+known host degrades to "known site, nothing parsed" — parsers never raise.+"""++from __future__ import annotations++import re+from datetime import date+from typing import Any, Callable+from urllib.parse import parse_qs, unquote, urlsplit++_NUM = r"-?\d+(?:\.\d+)?"+++def _num(s: str | None) -> float | None:+ try:+ v = float(s) # type: ignore[arg-type]+ except (TypeError, ValueError):+ return None+ return v if v == v and abs(v) != float("inf") else None+++def _in_world(lat: float | None, lon: float | None) -> bool:+ return lat is not None and lon is not None and abs(lat) <= 90 and abs(lon) <= 180+++def _no_view() -> dict[str, Any]:+ return {"lat": None, "lon": None, "zoom": None, "bearing": None,+ "title": None, "imagery_date": None}+++def _view(lat, lon, zoom=None, bearing=None) -> dict[str, Any]:+ if not _in_world(lat, lon):+ return _no_view()+ if bearing is not None:+ bearing = bearing % 360+ return {"lat": lat, "lon": lon, "zoom": zoom, "bearing": bearing,+ "title": None, "imagery_date": None}+++def _place_name(raw: str | None) -> str | None:+ """A place name lifted from a path segment or query param — the capture's+ suggested title. Sites encode spaces as + or %20; both come back out."""+ if not raw:+ return None+ s = unquote(str(raw).replace("+", " "), errors="replace")+ s = re.sub(r"\s+", " ", s).strip()[:120]+ return s or None+++def _iso_date(raw: str | None) -> str | None:+ """Normalize a date-ish fragment to YYYY-MM-DD, or None. Zoom Earth writes+ single-digit parts (2025-7-4); anything that isn't a real calendar date is+ dropped — a wrong imagery date on a proof is worse than none."""+ m = re.match(r"^(\d{4})-(\d{1,2})-(\d{1,2})", str(raw or ""))+ if not m:+ return None+ try:+ return date(int(m[1]), int(m[2]), int(m[3])).isoformat()+ except ValueError:+ return None+++def _param(u, name: str) -> str | None:+ values = parse_qs(u.query).get(name)+ return values[0] if values else None+++# --- per-site parsers (each takes a SplitResult) -------------------------------+++def _google_maps(u) -> dict[str, Any]:+ # /maps/place/Tour+Eiffel/@48.8583701,2.2944813,17z/… — the @ block is the+ # viewport; the place/search segment is the name the user looked up.+ # The z suffix is zoom; an m (metres) or a (streetview) suffix is not.+ name = re.search(r"/maps/(?:place|search)/([^/@]+)", u.path)+ title = _place_name(name[1]) if name else None+ m = re.search(rf"@({_NUM}),({_NUM})(?:,(\d+(?:\.\d+)?)z)?", u.path)+ if m:+ return {**_view(_num(m[1]), _num(m[2]), _num(m[3]) if m[3] else None), "title": title}+ # fallback: a pinned place without an @ viewport — !3d<lat>!4d<lon>+ m = re.search(rf"!3d({_NUM})!4d({_NUM})", u.geturl())+ if m:+ return {**_view(_num(m[1]), _num(m[2])), "title": title}+ return {**_no_view(), "title": title}+++def _google_earth(u) -> dict[str, Any]:+ # /web/search/Tour+Eiffel/@48.858,2.294,146.7a,666.6d,35y,12.3h,45.1t,0r+ # a=altitude, d=camera distance, y=fov, h=heading, t=tilt, r=roll+ name = re.search(r"/web/search/([^/@]+)", u.path)+ title = _place_name(name[1]) if name else None+ m = re.search(rf"@({_NUM}),({_NUM})(?:,[^/]*?({_NUM})h)?", u.path)+ if m:+ bearing = _num(m[3]) if m[3] else None+ return {**_view(_num(m[1]), _num(m[2]), None, bearing), "title": title}+ return {**_no_view(), "title": title}+++def _bing_maps(u) -> dict[str, Any]:+ # ?cp=48.8584~2.2945&lvl=17.0&q=tour+eiffel+ title = _place_name(_param(u, "q") or _param(u, "where1"))+ cp = _param(u, "cp") or ""+ m = re.fullmatch(rf"({_NUM})~({_NUM})", cp)+ if m:+ return {**_view(_num(m[1]), _num(m[2]), _num(_param(u, "lvl"))), "title": title}+ return {**_no_view(), "title": title}+++def _yandex_maps(u) -> dict[str, Any]:+ # ?ll=2.2945,48.8584&z=17&text=eiffel — Yandex is longitude-first+ title = _place_name(_param(u, "text"))+ ll = _param(u, "ll") or ""+ m = re.fullmatch(rf"({_NUM}),({_NUM})", ll)+ if m:+ return {**_view(_num(m[2]), _num(m[1]), _num(_param(u, "z"))), "title": title}+ return {**_no_view(), "title": title}+++def _openstreetmap(u) -> dict[str, Any]:+ # #map=17/48.8584/2.2945 (zoom first); /search?query=eiffel carries the name+ title = _place_name(_param(u, "query"))+ m = re.search(rf"map=(\d+(?:\.\d+)?)/({_NUM})/({_NUM})", u.fragment)+ if m:+ return {**_view(_num(m[2]), _num(m[3]), _num(m[1])), "title": title}+ return {**_no_view(), "title": title}+++def _apple_maps(u) -> dict[str, Any]:+ # ?ll=48.8584,2.2945&z=17&q=Tour+Eiffel (also ¢er= on some share links)+ title = _place_name(_param(u, "q") or _param(u, "name"))+ ll = _param(u, "ll") or _param(u, "center") or ""+ m = re.fullmatch(rf"({_NUM}),({_NUM})", ll)+ if m:+ return {**_view(_num(m[1]), _num(m[2]), _num(_param(u, "z"))), "title": title}+ return {**_no_view(), "title": title}+++def _zoom_earth(u) -> dict[str, Any]:+ # #view=48.8584,2.2945,17z (older: /maps/satellite/@48.8584,2.2945,17z);+ # daily imagery carries its date in the hash: …/date=2025-7-14+ d = re.search(r"date=([\d-]+)", u.fragment)+ imagery = _iso_date(d[1]) if d else None+ m = re.search(rf"view=({_NUM}),({_NUM})(?:,(\d+(?:\.\d+)?)z)?", u.fragment) or re.search(+ rf"@({_NUM}),({_NUM})(?:,(\d+(?:\.\d+)?)z)?", u.path+ )+ if m:+ return {**_view(_num(m[1]), _num(m[2]), _num(m[3]) if m[3] else None),+ "imagery_date": imagery}+ return {**_no_view(), "imagery_date": imagery}+++def _satellites_pro(u) -> dict[str, Any]:+ # #48.8584,2.2945,17+ m = re.match(rf"^({_NUM}),({_NUM})(?:,(\d+(?:\.\d+)?))?", u.fragment)+ if m:+ return _view(_num(m[1]), _num(m[2]), _num(m[3]) if m[3] else None)+ return _no_view()+++def _copernicus(u) -> dict[str, Any]:+ # ?zoom=17&lat=48.8584&lng=2.2945; a chosen acquisition sets fromTime /+ # toTime — toTime's date IS the imagery date+ imagery = _iso_date(_param(u, "toTime") or _param(u, "fromTime"))+ lat, lon = _num(_param(u, "lat")), _num(_param(u, "lng"))+ if lat is not None and lon is not None:+ return {**_view(lat, lon, _num(_param(u, "zoom"))), "imagery_date": imagery}+ return {**_no_view(), "imagery_date": imagery}+++# --- site table ----------------------------------------------------------------++# (id, label, host predicate, extra path gate or None, parser). The gate keeps+# e.g. google.com/search from counting as a map. Attribution lives in+# api/ingest.py next to the burn — this table is purely about reading URLs.+SITES: list[tuple[str, str, Callable, Callable | None, Callable]] = [+ ("google-earth", "Google Earth",+ lambda h: h == "earth.google.com", None, _google_earth),+ ("google-maps", "Google Maps",+ lambda h: re.search(r"(^|\.)google\.[a-z.]+$", h) or h == "maps.app.goo.gl",+ lambda u: u.hostname == "maps.app.goo.gl" or u.path.startswith("/maps"), _google_maps),+ ("bing-maps", "Bing Maps",+ lambda h: re.search(r"(^|\.)bing\.com$", h),+ lambda u: u.path.startswith("/maps"), _bing_maps),+ ("yandex-maps", "Yandex Maps",+ lambda h: re.search(r"(^|\.)yandex\.[a-z.]+$", h),+ lambda u: u.path.startswith("/maps"), _yandex_maps),+ ("openstreetmap", "OpenStreetMap",+ lambda h: re.search(r"(^|\.)openstreetmap\.org$", h), None, _openstreetmap),+ ("apple-maps", "Apple Maps",+ lambda h: h == "maps.apple.com", None, _apple_maps),+ ("zoom-earth", "Zoom Earth",+ lambda h: re.search(r"(^|\.)zoom\.earth$", h), None, _zoom_earth),+ ("satellites-pro", "Satellites.pro",+ lambda h: re.search(r"(^|\.)satellites\.pro$", h), None, _satellites_pro),+ ("copernicus-browser", "Copernicus Browser",+ lambda h: h == "browser.dataspace.copernicus.eu", None, _copernicus),+]+++def parse_map_url(url: str) -> dict[str, Any] | None:+ """Parse a page URL. None = not a map site (the extension stays out)."""+ try:+ u = urlsplit(url)+ except ValueError:+ return None+ if u.scheme not in ("http", "https") or not u.hostname:+ return None+ host = u.hostname.lower()+ for site_id, label, host_ok, gate, parse in SITES:+ if not host_ok(host):+ continue+ if gate and not gate(u):+ continue+ try:+ parsed = parse(u)+ except Exception:+ parsed = _no_view() # a weird URL on a known site still captures+ return {"site": site_id, "label": label, **parsed}+ return Nonediff --git a/src/azimut/engine/satellite.py b/src/azimut/engine/satellite.pyindex c481bf5..06d686c 100644--- a/src/azimut/engine/satellite.py+++ b/src/azimut/engine/satellite.py@@ -36,8 +36,10 @@ def coords_label(lat: float, lon: float, fmt: str | None = None) -> str:def is_capture(item: dict[str, Any]) -> bool:- """True if a media listing item is a satellite capture."""- return (item.get("source") or {}).get("type") == "satellite"+ """True if a media listing item is a capture: a satellite crop, or an+ external-map screenshot filed by the capture extension (api/ingest.py) —+ the latter rides the same panel so its coordinates stay one click away."""+ return (item.get("source") or {}).get("type") in ("satellite", "screenshot")def list_captures(case: Case) -> list[dict[str, Any]]:diff --git a/src/azimut/engine/sentinel.py b/src/azimut/engine/sentinel.pynew file mode 100644index 0000000..3190440--- /dev/null+++ b/src/azimut/engine/sentinel.py@@ -0,0 +1,349 @@+"""Sentinel Hub specifics: layers, the mosaicking window, and date discovery.++Everything here is about one basemap (``sentinel2`` in engine/tiles.py) but is+kept out of it because Sentinel Hub is the only provider with *choices* in it:+what to render (a layer) and when (a mosaicking window). Both ride on the+provider id as a **variant** — ``sentinel2~SWIR~2026-05-01~2026-05-31`` — so the+existing machinery keeps working untouched: the tile proxy resolves it through+``tiles.get_provider``, the disk cache keys on it (a window in the id is a+window in the cache key, which is the trap docs/IMAGERY_PROVIDERS.md warns+about), and a capture's provenance records exactly which layer and window the+pixels came from.++The layer catalogue below mirrors the "Simple Sentinel-2 L2A template" every+setup guide points at, but it is a *default*, not a fact: the layers an instance+serves are whatever its configuration says. ``capabilities_layers`` asks the+instance itself, which is the only authority (user-triggered — local-first).+"""++from __future__ import annotations++import re+import xml.etree.ElementTree as ET+from dataclasses import dataclass+from datetime import date+from typing import Any, Callable++import httpx++BASE = "https://sh.dataspace.copernicus.eu/ogc"+USER_AGENT = "Azimut/0.1 (+local OSINT workbench; single-user)"++# Sentinel-2 L2A in Sentinel Hub's WFS type vocabulary (DSS1 = L1C, DSS3 = S1).+# The basemap renders L2A, so date discovery must ask about L2A: L1C passes the+# same orbit but a date list from the wrong collection would be a plausible lie.+WFS_TYPENAME = "DSS2"+++@dataclass(frozen=True)+class Layer:+ id: str+ label: str+ hint: str+++# The layers the standard template is relied on to ship, and only those. This+# list is a *fallback*, used when the instance can't be asked — so it holds the+# four that are near-universal rather than everything a configuration might+# have. Offering a layer the instance doesn't serve buys nothing: it 400s on+# selection, and a dropdown of entries that may or may not work is worse than a+# short one that does. Anything else a user configured arrives through+# capabilities_layers, which is the authority.+#+# `hint` is the reason to pick one — this is a workbench, and "SWIR" tells a+# user nothing about why they'd want it.+LAYERS: tuple[Layer, ...] = (+ Layer("TRUE_COLOR", "True colour", "Natural colour (B04/B03/B02) — what the eye would see."),+ Layer(+ "FALSE_COLOR",+ "False colour (infrared)",+ "Near-infrared (B08/B04/B03): water goes near-black, so vessels, wakes and "+ "structures on water stand out. Vegetation reads red.",+ ),+ Layer(+ "SWIR",+ "SWIR (short-wave infrared)",+ "B12/B8A/B04: water is darkest of all — the strongest contrast for vessels at "+ "sea, and the band that sees through thin haze and smoke to fires and flares.",+ ),+ Layer("NDVI", "NDVI (vegetation index)", "Vegetation vigour — crops, clearing, seasonal change."),+)++# Hints for layers we know but don't offer by default — a configuration that+# ships them gets the explanation, not a bare identifier.+KNOWN_HINTS: dict[str, str] = {+ "HIGHLIGHT_OPTIMIZED": "Natural colour with the highlights pulled back — bright objects on "+ "dark water keep their shape instead of blowing out.",+ "NDWI": "Water/land boundary as an index — the shoreline, flooding, and what is water at "+ "all on a given date.",+ "SCENE_CLASSIFICATION": "The scene's own per-pixel classes (cloud, shadow, water, "+ "vegetation) — whether a date is worth looking at before you look.",+ "MOISTURE_INDEX": "Surface/vegetation water content — irrigation, drought, burn scars.",+ "FALSE_COLOR_URBAN": "B12/B11/B04: built-up surfaces separate from bare ground and vegetation.",+ "NDSI": "Snow index — snow and ice against cloud, which they otherwise resemble.",+}+DEFAULT_LAYER = LAYERS[0].id++# A layer id is a URL parameter *and* a path segment (the variant id reaches the+# tile proxy as one) *and* a directory name (the disk cache). Anything outside+# this shape is refused rather than escaped: no separators, no traversal, no+# surprises on any of the three OSes we ship.+_LAYER_RE = re.compile(r"^[A-Z0-9_]{1,40}$")+_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")++VARIANT_SEP = "~"+++def wmts_url(layer: str = DEFAULT_LAYER, start: str | None = None, end: str | None = None) -> str:+ """The WMTS GetTile template for one layer and window: ``{key}``/``{z}``/``{x}``/``{y}``.++ ``start``/``end`` (YYYY-MM-DD) become the ``TIME`` mosaicking window, which+ is inclusive of both days. Omitted, no TIME is sent and the layer's own+ default applies — "most recent", the honest default for "just show me it".+ """+ url = (+ f"{BASE}/wmts/{{key}}"+ "?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0"+ f"&LAYER={layer}&TILEMATRIXSET=PopularWebMercator512"+ "&TILEMATRIX={z}&TILECOL={x}&TILEROW={y}&FORMAT=image/jpeg"+ )+ if start and end:+ url += f"&TIME={start}/{end}"+ return url+++def variant_id(base_id: str, layer: str | None = None, start: str | None = None,+ end: str | None = None) -> str:+ """Pack a layer + window into a provider id. Mirror of ``parse_variant``.++ The default layer with no window is just the base id: the plain basemap must+ not get a second name, or it would cache twice and read as two providers in+ provenance.+ """+ layer = layer or DEFAULT_LAYER+ if layer == DEFAULT_LAYER and not (start and end):+ return base_id+ parts = [base_id, layer]+ if start and end:+ parts += [start, end]+ return VARIANT_SEP.join(parts)+++def parse_variant(spec: str) -> tuple[str, str | None, str | None]:+ """``"SWIR~2026-05-01~2026-05-31"`` → ``("SWIR", "2026-05-01", "2026-05-31")``.++ Raises ValueError on anything that isn't a layer-shaped name and a pair of+ ISO dates in order. This is the validation boundary for a string that+ arrives from a URL path and ends up as a directory name, so the *shape* is+ an allowlist: no separators, no traversal, no free-form text, no reversed+ windows. Membership of LAYERS deliberately isn't checked — an instance+ serves whatever its configuration says (capabilities_layers), and a layer+ the catalogue never heard of is the user's to ask for. A wrong one comes+ back as Sentinel Hub's own 400, which says more than we could.+ """+ parts = spec.split(VARIANT_SEP)+ if len(parts) not in (1, 3):+ raise ValueError(f"malformed Sentinel-2 variant '{spec}'")+ layer = parts[0]+ if not _LAYER_RE.match(layer):+ raise ValueError(f"malformed Sentinel-2 layer '{layer}'")+ if len(parts) == 1:+ return layer, None, None+ start, end = parts[1], parts[2]+ for value in (start, end):+ if not _DATE_RE.match(value):+ raise ValueError(f"malformed date '{value}' (expected YYYY-MM-DD)")+ try:+ date.fromisoformat(value)+ except ValueError as exc:+ raise ValueError(f"impossible date '{value}'") from exc+ if start > end:+ raise ValueError(f"window ends before it starts ({start} → {end})")+ return layer, start, end+++def variant_label(layer: str, start: str | None, end: str | None) -> str:+ """How a variant reads to a human: "SWIR · 2026-05-01 → 2026-05-31"."""+ known = next((entry.label for entry in LAYERS if entry.id == layer), layer)+ if start and end:+ window = start if start == end else f"{start} → {end}"+ return f"{known} · {window}"+ return f"{known} · most recent"+++# -- date discovery (WFS) ------------------------------------------------------++# How wide a box around the point to ask about, in degrees (~1 km): big enough+# that a point near a granule edge still finds the granule, small enough that+# the answer is about *here* and not the next province.+_BBOX_PAD = 0.005+# WFS caps MAXFEATURES at 100, and one date can return several granules, so this+# is "up to 100 granules" rather than "100 dates" — the caller sees how many+# dates that collapsed to.+_MAX_FEATURES = 100+++def _cloud(props: dict[str, Any]) -> float | None:+ for name in ("cloudCoverPercentage", "tileCloudCoverPercentage"):+ value = props.get(name)+ if isinstance(value, (int, float)):+ return round(float(value), 1)+ return None+++def _rings(geometry: dict[str, Any] | None) -> list[list[list[float]]]:+ """Outer rings of a (Multi)Polygon, or [] for anything else."""+ if not isinstance(geometry, dict):+ return []+ kind, coords = geometry.get("type"), geometry.get("coordinates")+ if not isinstance(coords, list):+ return []+ try:+ if kind == "Polygon":+ return [coords[0]]+ if kind == "MultiPolygon":+ return [polygon[0] for polygon in coords]+ except (IndexError, TypeError):+ return []+ return []+++def _in_ring(x: float, y: float, ring: list[list[float]]) -> bool:+ """Ray casting: is (x, y) inside this ring?"""+ inside = False+ count = len(ring)+ for i in range(count):+ x1, y1 = ring[i][0], ring[i][1]+ x2, y2 = ring[(i + 1) % count][0], ring[(i + 1) % count][1]+ if (y1 > y) != (y2 > y) and x < (x2 - x1) * (y - y1) / ((y2 - y1) or 1e-12) + x1:+ inside = not inside+ return inside+++def _covers(lat: float, lon: float, geometry: dict[str, Any] | None) -> bool:+ """Does this granule's footprint actually contain the point?++ Why it matters: a granule's *bounding box* is a square, but its data is the+ slice of orbit swath inside it — the rest is nodata. WFS answers on the box,+ so a day can be listed while the pixels over your point are black. Pinned to+ that day the map has nothing to show and goes dark, which is the "why is+ this date black?" a date list exists to prevent.++ GeoJSON says longitude first, but an OGC service asked for EPSG:4326 may+ honour the CRS's latitude-first axis order instead, and getting it backwards+ would reject every granule on Earth. So a granule counts as covering the+ point if it does under *either* reading: a footprint genuinely 100 km away+ contains it under neither, which is the case worth acting on. Unparseable+ geometry keeps the granule — never drop a real pass over a guess.+ """+ rings = _rings(geometry)+ if not rings:+ return True+ return any(_in_ring(lon, lat, ring) or _in_ring(lat, lon, ring) for ring in rings)+++def dates(+ instance: str,+ lat: float,+ lon: float,+ start: str,+ end: str,+ *,+ get: Callable[..., Any] | None = None,+) -> list[dict[str, Any]]:+ """Sentinel-2 acquisition dates over a point, newest first.++ Each entry: ``{"date", "cloud", "granules"}`` — ``cloud`` is the least+ cloudy granule covering the point that day (None when the service didn't+ say), ``granules`` how many covered it.++ This is what makes a date picker honest: without it the user guesses a date,+ pays a tile, and finds out it was cloud or a gap. A WFS query is billed as+ one request (~0.01 PU, versus a tile's 1 PU), so the caller counts it on the+ meter — cheap, but not free, and the meter never lies by omission.++ Raises httpx.HTTPError / ValueError upward: a date list that failed must not+ read as "no imagery here".+ """+ fetch = get or httpx.get+ params = {+ "SERVICE": "WFS",+ "REQUEST": "GetFeature",+ "VERSION": "2.0.0",+ "TYPENAMES": WFS_TYPENAME,+ "OUTPUTFORMAT": "application/json",+ # EPSG:4326 puts latitude first — the axis order the CRS declares, not+ # the lon/lat habit. Swapped, the box lands in the ocean off Somalia.+ "SRSNAME": "EPSG:4326",+ "BBOX": f"{lat - _BBOX_PAD},{lon - _BBOX_PAD},{lat + _BBOX_PAD},{lon + _BBOX_PAD}",+ "TIME": f"{start}/{end}",+ "MAXFEATURES": str(_MAX_FEATURES),+ }+ response = fetch(+ f"{BASE}/wfs/{instance}", params=params,+ headers={"User-Agent": USER_AGENT}, timeout=15,+ )+ response.raise_for_status()+ features = (response.json() or {}).get("features") or []++ by_date: dict[str, dict[str, Any]] = {}+ for feature in features:+ props = feature.get("properties") or {}+ day = str(props.get("date") or "")[:10]+ if not _DATE_RE.match(day):+ continue+ # the granule's box may reach the point while its imagery doesn't+ if not _covers(lat, lon, feature.get("geometry")):+ continue+ cloud = _cloud(props)+ entry = by_date.setdefault(day, {"date": day, "cloud": cloud, "granules": 0})+ entry["granules"] += 1+ # the granule that actually covers the point may be the clearer of two+ if cloud is not None and (entry["cloud"] is None or cloud < entry["cloud"]):+ entry["cloud"] = cloud+ return sorted(by_date.values(), key=lambda entry: entry["date"], reverse=True)+++# -- layer discovery (GetCapabilities) -----------------------------------------++_WMTS_NS = {"ows": "http://www.opengis.net/ows/1.1", "wmts": "http://www.opengis.net/wmts/1.0"}+++def capabilities_layers(+ instance: str, *, get: Callable[..., Any] | None = None+) -> list[dict[str, str]]:+ """The layers this instance actually serves, asked of the instance itself.++ LAYERS above is only the reliable core; a user's configuration can add,+ rename or drop any of it, and only the instance knows. Entries we recognise+ keep their hint, the rest come back with an empty one — an unknown layer is+ still offerable, we just have nothing useful to say about it.++ Raises upward on failure: the caller falls back to the catalogue.+ """+ fetch = get or httpx.get+ response = fetch(+ f"{BASE}/wmts/{instance}",+ params={"SERVICE": "WMTS", "REQUEST": "GetCapabilities", "VERSION": "1.0.0"},+ headers={"User-Agent": USER_AGENT},+ timeout=15,+ )+ response.raise_for_status()+ root = ET.fromstring(response.text)+ known = {entry.id: entry for entry in LAYERS}++ found: list[dict[str, str]] = []+ for node in root.iterfind(".//wmts:Contents/wmts:Layer", _WMTS_NS):+ identifier = (node.findtext("ows:Identifier", default="", namespaces=_WMTS_NS) or "").strip()+ if not identifier or not _LAYER_RE.match(identifier):+ continue # unrenderable as a variant id — never offer what can't be asked for+ title = (node.findtext("ows:Title", default="", namespaces=_WMTS_NS) or "").strip()+ entry = known.get(identifier)+ found.append(+ {+ "id": identifier,+ "label": entry.label if entry else (title or identifier),+ "hint": entry.hint if entry else KNOWN_HINTS.get(identifier, ""),+ }+ )+ return founddiff --git a/src/azimut/engine/stitch.py b/src/azimut/engine/stitch.pyindex 1ba09c5..9e50217 100644--- a/src/azimut/engine/stitch.py+++ b/src/azimut/engine/stitch.py@@ -2,23 +2,31 @@The hand-made collage lets an analyst drag and warp pieces into a panorama by eye(``engine/inspect.compose_perspective``). This module does the same job by machine-— *but it deliberately stops at the layout*. It returns each piece's quad rather-than a flattened panorama, so the result drops straight back onto the collage-canvas as ordinary pieces: still draggable, still warpable, still exported by the-same compositor. Machine stitch first, hand-tune after.--The pipeline is the classic one:--1. Detect + describe features per image, match every pair (Lowe ratio test).-2. ``findHomography(..., RANSAC)`` per pair that matches well enough — the edges- of a match graph, weighted by inlier count.-3. Chain homographies from the best-connected image (the anchor) outward, so- every reachable image lands in the anchor's plane. Unreachable images are- *dropped*, never guessed at: the caller hand-places them.-4. Project each image's corners through its homography → a quad; fit the whole- constellation into the canvas.--Only step 1-3 need OpenCV; the fitting math is pure so it stays testable and+— *but it deliberately stops at the layout*. It returns each piece's geometry+rather than a flattened panorama, so the result drops straight back onto the+collage canvas as ordinary pieces: still draggable, still exported by the same+compositor. Machine stitch first, hand-tune after.++Two projection models, because one cannot serve both jobs (:func:`solve_layout`+and :func:`solve_rotation_layout`):++**Planar** assumes the pieces show one flat surface — a facade, the ground, a map.+Homographies chain from the best-connected image (the anchor) outward and every+piece lands in the anchor's *plane*, so a piece stays an ordinary 4-point quad the+analyst can keep warping by hand. The catch is that a panning camera is a rotation,+not a plane: re-expressing it as one divides every piece by ``cos(angle)`` from the+anchor, so pieces blow up towards the edges and run to infinity at 90°.++**Rotation** (cylindrical / spherical) is the model for a camera that turns. It+solves a rotation + focal length per piece, refines them all together (bundle+adjustment, so pairwise error can't accumulate into a banana), and projects onto a+cylinder or a sphere — which unrolls to a *bounded* strip however far the camera+pans, keeping verticals vertical and pieces the same size end to end. The price is+that a curved warp is not a quad: the piece's pixels are remapped (a ``remap`` op+baked into its recipe, so the full-res export re-derives it) and the piece is+placed as an upright rectangle. It stays draggable — it is no longer corner-warpable.++The heavy lifting is OpenCV's; the fitting math is pure so it stays testable andhonest about coordinates."""@@ -46,6 +54,25 @@ WORK_DIM = 1000_RATIO = 0.75 # Lowe ratio test_RANSAC_PX = 4.0+# The rotation model's projections. "planar" is the other solver's model and is+# deliberately absent: it needs no remap, because a plane projection *is* a quad.+WARPS = ("cylindrical", "spherical")++# OpenCV scores a pair as ``inliers / (8 + 0.3 * matches)`` and calls 1.0 confident.+# Same bet as MIN_INLIERS above: a false stitch invents geometry an analyst may+# then reason about, so refuse the pair rather than guess at it.+STITCH_CONF = 1.0+_MATCH_CONF = 0.3 # per-descriptor, OpenCV's default for its panorama pipeline++# A cylinder/sphere projection roughly *preserves* a piece's area however far it+# sits from the anchor — that is the whole point of it. So a piece that lands+# wildly bigger than it started has a broken camera behind it, not a wide angle.+_MAX_WARP_AREA = 25.0++# Gain read-back probe level: mid-grey, so a gain up to ~2.5 stays representable+# in uint8 while quantisation keeps the recovered scalar within ~1%.+_PROBE = 100+Quad = list[list[float]]@@ -293,3 +320,294 @@ def solve_layout(images: list[Image.Image], *, width: int, height: int) -> dict["dropped": sorted(dropped),"anchor": anchor,}+++# ---------------------------------------------------------------------------+# Rotation model — the panorama projections (cylindrical / spherical)+# ---------------------------------------------------------------------------+++def _work_array(img: Image.Image):+ """The image as an RGB array, downscaled to ``WORK_DIM`` for speed.++ Every camera this module solves is therefore expressed in *work* pixels. That+ is not a rounding error to correct later: intrinsics scale with the image, so+ the params are stored as fractions of the work width and multiply straight back+ up at export time (:func:`apply_warp`).+ """+ import numpy as np++ rgb = img.convert("RGB")+ if max(rgb.size) > WORK_DIM:+ scale = WORK_DIM / max(rgb.size)+ rgb = rgb.resize(+ (max(1, round(rgb.width * scale)), max(1, round(rgb.height * scale))),+ Image.BILINEAR,+ )+ return np.asarray(rgb)+++def _detail_features(cv2, arrays: list[Any]) -> list[Any]:+ det, _ = _detector(cv2)+ return [cv2.detail.computeImageFeatures2(det, arr) for arr in arrays]+++def _match_component(cv2, feats: list[Any]) -> tuple[list[Any], list[int]]:+ """Match every pair, then return the matches + the biggest agreeing group.++ Pieces outside that group are not stitched to anything we trust, so the caller+ leaves them exactly where the analyst put them.+ """+ matcher = cv2.detail.BestOf2NearestMatcher_create(False, _MATCH_CONF)+ pairwise = matcher.apply2(feats)+ matcher.collectGarbage()++ adjacency: dict[int, list[int]] = {i: [] for i in range(len(feats))}+ for m in pairwise:+ if m.src_img_idx < 0 or m.dst_img_idx < 0 or m.H is None:+ continue+ if m.confidence < STITCH_CONF:+ continue+ adjacency[m.src_img_idx].append(m.dst_img_idx)+ adjacency[m.dst_img_idx].append(m.src_img_idx)++ best: set[int] = set()+ seen: set[int] = set()+ for i in range(len(feats)):+ if i in seen:+ continue+ comp = {i}+ queue = deque([i])+ while queue:+ cur = queue.popleft()+ for nxt in adjacency[cur]:+ if nxt not in comp:+ comp.add(nxt)+ queue.append(nxt)+ seen |= comp+ if len(comp) > len(best):+ best = comp+ return pairwise, sorted(best)+++def _solve_cameras(cv2, feats: list[Any], pairwise: list[Any]) -> list[Any]:+ """A rotation + focal per image, refined against every match at once.++ The estimator seeds the cameras from the pairwise homographies; the ray-space+ bundle adjuster is what keeps a long pan from drifting, since it answers to all+ the matches jointly rather than to one chain of pairs.+ """+ import numpy as np++ ok, cameras = cv2.detail_HomographyBasedEstimator().apply(feats, pairwise, None)+ if not ok:+ raise RuntimeError("auto-stitch could not estimate the camera rotations")+ for cam in cameras:+ cam.R = cam.R.astype(np.float32)++ adjuster = cv2.detail_BundleAdjusterRay()+ adjuster.setConfThresh(STITCH_CONF)+ adjuster.setRefinementMask(np.ones((3, 3), np.uint8))+ ok, cameras = adjuster.apply(feats, pairwise, cameras)+ if not ok:+ raise RuntimeError("auto-stitch could not refine the camera rotations")++ # Wave correction pulls the panorama's horizon back level: chained rotations+ # are free to roll as a group, and a whole-strip tilt reads as a "banana".+ try:+ rmats = [np.copy(cam.R) for cam in cameras]+ for cam, R in zip(cameras, cv2.detail.waveCorrect(rmats, cv2.detail.WAVE_CORRECT_HORIZ)):+ cam.R = R+ except cv2.error:+ pass # too few / too parallel views to define a horizon; leave them be+ return cameras+++def _median(values: list[float]) -> float:+ ordered = sorted(values)+ mid = len(ordered) // 2+ if len(ordered) % 2:+ return ordered[mid]+ return (ordered[mid - 1] + ordered[mid]) / 2.0+++def _gains(cv2, warper, warped: list[Any], masks: list[Any], corners: list[Any]) -> list[float]:+ """One exposure scalar per piece, so neighbours stop stepping in brightness.++ OpenCV solves the classic overlap-mean system but its Python binding exposes+ only ``apply`` (which multiplies an image in place), not the gains themselves —+ so each scalar is read back by applying it to a flat probe patch, where+ ``out / in`` *is* the gain. Falls back to 1.0 (no correction) rather than+ failing the stitch: a brightness step is a blemish, not a wrong answer.+ """+ import numpy as np++ compensator = cv2.detail_GainCompensator()+ try:+ compensator.feed(corners, warped, masks)+ except cv2.error:+ return [1.0] * len(warped)++ probe = np.full((4, 4, 3), _PROBE, np.uint8)+ probe_mask = np.full((4, 4), 255, np.uint8)+ out: list[float] = []+ for i, corner in enumerate(corners):+ try:+ got = compensator.apply(i, corner, probe.copy(), probe_mask)+ except cv2.error:+ out.append(1.0)+ continue+ out.append(float(np.mean(got)) / _PROBE)+ return out+++def _remap_params(warp: str, cam: Any, scale: float, size: tuple[int, int], gain: float) -> dict[str, Any]:+ """The piece's warp, as a recipe op — resolution-independent by construction.++ Lengths are stored as fractions of the *work* image the camera was solved on,+ so re-deriving at full res just multiplies them back up: same shape, more+ pixels. The compositor then fits that shape into the piece's quad, which is why+ each piece may normalise against its own width without breaking the shared+ warp space.+ """+ import numpy as np++ w, h = size+ return {+ "warp": warp,+ "focal": float(cam.focal) / w,+ "aspect": float(cam.aspect),+ "ppx": float(cam.ppx) / w,+ "ppy": float(cam.ppy) / h,+ "r": [float(v) for v in np.asarray(cam.R, dtype=float).reshape(9)],+ "scale": float(scale) / w,+ "gain": round(float(gain), 4),+ }+++def _camera_at(params: dict[str, Any], width: int, height: int):+ """Rebuild ``(K, R, scale)`` from a stored remap op, at this image's size."""+ import numpy as np++ focal = float(params["focal"]) * width+ aspect = float(params.get("aspect", 1.0))+ K = np.array(+ [+ [focal, 0.0, float(params["ppx"]) * width],+ [0.0, focal * aspect, float(params["ppy"]) * height],+ [0.0, 0.0, 1.0],+ ],+ dtype=np.float32,+ )+ R = np.asarray(params["r"], dtype=np.float32).reshape(3, 3)+ return K, R, float(params["scale"]) * width+++def apply_warp(img: Image.Image, params: dict[str, Any]) -> Image.Image:+ """Remap one piece onto the cylinder/sphere the solver picked → RGBA.++ Alpha marks the warped footprint: the projection is curved, so the corners of+ the output rectangle fall outside the piece and must stay transparent rather+ than paint black wedges over its neighbours.+ """+ import numpy as np++ warp = str(params.get("warp") or "")+ if warp not in WARPS:+ raise ValueError(f"unknown panorama warp {warp!r}")+ cv2 = _cv2()++ src = np.asarray(img.convert("RGB"))+ height, width = src.shape[:2]+ K, R, scale = _camera_at(params, width, height)+ warper = cv2.PyRotationWarper(warp, scale)+ _, warped = warper.warp(src, K, R, cv2.INTER_LINEAR, cv2.BORDER_CONSTANT)+ _, mask = warper.warp(+ np.full((height, width), 255, np.uint8), K, R, cv2.INTER_NEAREST, cv2.BORDER_CONSTANT+ )++ gain = float(params.get("gain", 1.0))+ if gain != 1.0:+ warped = np.clip(warped.astype(np.float32) * gain, 0, 255).astype(np.uint8)++ out = Image.fromarray(warped, "RGB").convert("RGBA")+ out.putalpha(Image.fromarray(mask, "L"))+ return out+++def solve_rotation_layout(+ images: list[Image.Image], *, width: int, height: int, warp: str = "cylindrical"+) -> dict[str, Any]:+ """Solve a panorama layout under the rotation model — geometry *and* a remap.++ Returns ``{"quads": {index: quad}, "remaps": {index: params}, "dropped": [...]}``.+ Each quad is the upright rectangle the piece's remapped pixels fill, in canvas+ pixels; each remap is the op that produces those pixels from the piece's+ recipe. ``dropped`` holds the pieces no trusted match reached — the caller+ leaves them untouched, exactly as in :func:`solve_layout`.+ """+ import numpy as np++ if len(images) < 2:+ raise ValueError("auto-stitch needs at least two pieces")+ if warp not in WARPS:+ raise ValueError(f"unknown panorama warp {warp!r}")++ cv2 = _cv2()+ arrays = [_work_array(img) for img in images]+ feats = _detail_features(cv2, arrays)++ pairwise, keep = _match_component(cv2, feats)+ if len(keep) < 2:+ raise RuntimeError(+ "auto-stitch found no overlap between these pieces — do they show the same scene?"+ )+ if len(keep) < len(images):+ # Re-match on the subset alone: the estimator indexes cameras by position+ # in the features it is handed, so the group has to be re-numbered first.+ feats = [feats[i] for i in keep]+ pairwise, _ = _match_component(cv2, feats)++ cameras = _solve_cameras(cv2, feats, pairwise)+ scale = _median([float(cam.focal) for cam in cameras])+ warper = cv2.PyRotationWarper(warp, scale)++ corners, warped, masks = [], [], []+ for pos, idx in enumerate(keep):+ cam = cameras[pos]+ K = cam.K().astype("float32")+ src = arrays[idx]+ corner, img_w = warper.warp(src, K, cam.R, cv2.INTER_LINEAR, cv2.BORDER_CONSTANT)+ _, mask_w = warper.warp(+ np.full(src.shape[:2], 255, np.uint8), K, cam.R, cv2.INTER_NEAREST, cv2.BORDER_CONSTANT+ )+ corners.append(corner)+ warped.append(img_w)+ masks.append(mask_w)++ gains = _gains(cv2, warper, warped, masks, corners)++ quads: dict[int, Quad] = {}+ remaps: dict[int, dict[str, Any]] = {}+ dropped = [i for i in range(len(images)) if i not in set(keep)]+ for pos, idx in enumerate(keep):+ src_h, src_w = arrays[idx].shape[:2]+ out_h, out_w = warped[pos].shape[:2]+ x, y = float(corners[pos][0]), float(corners[pos][1])+ quad = [[x, y], [x + out_w, y], [x + out_w, y + out_h], [x, y + out_h]]+ if not quad_ok(quad) or (out_w * out_h) > _MAX_WARP_AREA * src_w * src_h:+ dropped.append(idx)+ continue+ quads[idx] = quad+ remaps[idx] = _remap_params(warp, cameras[pos], scale, (src_w, src_h), gains[pos])++ if not quads:+ raise RuntimeError("auto-stitch could not place any piece")++ order = sorted(quads)+ fitted = fit_quads_to_canvas([quads[i] for i in order], width, height)+ return {+ "quads": {i: q for i, q in zip(order, fitted)},+ "remaps": remaps,+ "dropped": sorted(dropped),+ }diff --git a/src/azimut/engine/tiles.py b/src/azimut/engine/tiles.pyindex 75206ae..f978e07 100644--- a/src/azimut/engine/tiles.py+++ b/src/azimut/engine/tiles.py@@ -11,8 +11,9 @@ from __future__ import annotationsimport hashlibimport math+import refrom concurrent.futures import ThreadPoolExecutor-from dataclasses import dataclass, field+from dataclasses import dataclass, field, replacefrom datetime import datetime, timezonefrom typing import Any, Callable@@ -20,7 +21,7 @@ import httpxfrom PIL import Image, ImageDraw, ImageFontfrom .. import config-from . import google_tiles+from . import google_tiles, sentinelTILE_SIZE = 256SIZE_MAX = 4096 # hard cap on a capture's width/height, in px@@ -39,6 +40,16 @@ class Provider:url: str # template with {x} {y} {z}, optionally {key}attribution: strmax_zoom: int = 19+ # Deepest zoom the provider has *pixels* for, when that is shallower than+ # the deepest zoom worth showing. None = they're the same (the usual case).+ # Sentinel-2 resolves 10 m/px and stops at z14, but a z14 ceiling makes the+ # basemap unusable for its actual job — you cannot look at a ship at 10 m/px+ # from three levels out. So the view runs to z18 while requests stop at 14+ # and the last native tile is upscaled: identical pixels, magnified, for+ # zero extra requests. Asking Sentinel Hub for z18 instead would buy their+ # upsampling of the same pixels at 256× the quota (16× the tiles, each+ # billed) — the same image, paid for.+ max_native_zoom: int | None = Noneneeds_key: bool = Falsesubdomains: tuple[str, ...] = field(default_factory=tuple) # for {s} templates# True for satellite/aerial imagery, False for street/base maps. Drives the UI:@@ -64,6 +75,24 @@ class Provider:# requests (still ¼ of plain 256px tiles) for crisp imagery. Captures are# unaffected: they stay 1:1 provider pixels for evidential integrity.oversample: int = 1+ # Levels to re-add to the URL z after tile_size shifted it down. WMTS+ # services number their 512px levels by *resolution* where Mapbox numbers+ # them by *grid width*: Sentinel Hub's TILEMATRIX=14 and Mapbox's z13 are+ # both 9.55 m/px on an 8192-wide grid. The tile indices stay at tile_z+ # either way — only the level's name differs.+ zoom_offset: int = 0+ # Non-XYZ basemap rendered by a frontend widget (e.g. "google-maps-js"):+ # no tiles, no proxy, no fetch_crop — `url` is the widget's script loader+ # and the frontend does the rest. Backend still owns key storage + meter.+ widget: str | None = None+ # Eco-mode threshold for *this* provider: the visual zoom at or below which+ # free imagery replaces it. None = the user's global eco_max_zoom, which is+ # tuned for providers that run to z22. A shallow provider needs its own: at+ # Sentinel-2's z14 ceiling the global z15 rule would fire everywhere and the+ # basemap could never be seen at all. Its threshold is instead set where its+ # imagery stops earning the quota — the swap costs a known date for an+ # unknown one, which is only worth it where 10 m/px adds nothing anyway.+ eco_max_zoom: int | None = None# Built-in keyed providers (docs/IMAGERY_PROVIDERS.md): only surfaced from@@ -75,6 +104,18 @@ MAPBOX_SATELLITE_URL = ("https://api.mapbox.com/styles/v1/mapbox/satellite-v9/tiles/512/{z}/{x}/{y}?access_token={key}")GOOGLE_SATELLITE_URL = "https://tile.googleapis.com/v1/2dtiles/{z}/{x}/{y}?session={session}&key={key}"+# Maps JavaScript API loader (docs/IMAGERY_PROVIDERS.md § Google in the EEA):+# the official Google satellite route left to EEA billing accounts since+# 2025-07-08 (Map Tiles + Static satellite are policy-blocked there). A JS-API+# key is client-side by design (referrer-restricted, not secret), so shipping+# it to the browser in this loader URL is the intended use, unlike tile keys.+GOOGLE_JS_LOADER_URL = "https://maps.googleapis.com/maps/api/js?key={key}&v=weekly"+# Sentinel Hub OGC WMTS (docs/IMAGERY_PROVIDERS.md): {key} is the user's+# configuration-instance UUID, which is the whole credential — no token to mint.+# The layer and the mosaicking window are choices, not constants, so the+# template is built per variant in engine/sentinel.py; this is the plain one+# (TRUE_COLOR, the layer's own default window = most recent).+SENTINELHUB_WMTS_URL = sentinel.wmts_url()BUILTIN_PROVIDERS: tuple[Provider, ...] = (Provider(@@ -118,7 +159,17 @@ def all_providers() -> list[Provider]:# a keyed basemap can be switched off in Settings without deleting the keyenabled = settings.get("providers_enabled", {})- mapbox_key = keys.get("mapbox") if enabled.get("mapbox", True) else None+ def key_for(key_id: str) -> str | None:+ """The credential, unless switched off or last seen failing auth — a+ basemap whose key is known-dead is withheld from the selector until+ the key changes or a test passes (Settings shows why)."""+ if not enabled.get(key_id, True):+ return None+ if config.provider_key_bad(key_id, settings):+ return None+ return keys.get(key_id)++ mapbox_key = key_for("mapbox")if mapbox_key:providers.append(Provider(@@ -135,7 +186,7 @@ def all_providers() -> list[Provider]:))- google_key = keys.get("google") if enabled.get("google", True) else None+ google_key = key_for("google")if google_key:providers.append(Provider(@@ -157,6 +208,63 @@ def all_providers() -> list[Provider]:))+ # Google Satellite via the Maps JavaScript widget — the only official+ # Google satellite route for EEA billing accounts (2025-07-08 policy).+ # No tiles: the frontend embeds a real google.maps.Map under Leaflet, so+ # capturable=False (fetch_crop has nothing to stitch — captures are the+ # user's own screenshots, filed with attribution burned in), cacheable is+ # moot, and the meter counts *map loads*, not tiles. eco_max_zoom=0 turns+ # eco off for it: swapping the widget out and back re-instantiates the+ # Google map, and every instantiation is a billed load — eco would cost+ # money here, not save it.+ google_js_key = key_for("google_js")+ if google_js_key:+ providers.append(+ Provider(+ id="google-js",+ label="Google Satellite (Maps JS)",+ url=GOOGLE_JS_LOADER_URL.replace("{key}", google_js_key),+ attribution="Map data © Google",+ max_zoom=21,+ imagery=True,+ capturable=False,+ cacheable=False,+ widget="google-maps-js",+ meter="google_js",+ eco_max_zoom=0,+ )+ )++ # Sentinel-2: open data (attribution only — no capture or cache limit), but+ # a small quota. 512px tiles are what make the tile meter honest: one+ # 512×512 3-band 8-bit tile is exactly 1 processing unit, so counting tiles+ # counts PU. Requests stop at z14 — 10 m/px is Sentinel-2's native ground+ # resolution and anything deeper is Sentinel Hub upsampling we would pay+ # full price for — while the *view* runs to z18 on upscaled native tiles.+ sentinelhub_key = key_for("sentinelhub")+ if sentinelhub_key:+ providers.append(+ Provider(+ id="sentinel2",+ label="Sentinel-2 (Copernicus)",+ url=SENTINELHUB_WMTS_URL.replace("{key}", sentinelhub_key),+ attribution="© Copernicus Sentinel data / Sentinel Hub",+ max_zoom=18,+ max_native_zoom=14,+ imagery=True,+ capturable=True,+ cacheable=True,+ meter="sentinelhub",+ tile_size=512,+ zoom_offset=1, # WMTS names this level 14 where z_shift says 13+ # Its own eco threshold, three levels under its z14 ceiling: at+ # z11 and out a Sentinel-2 pixel is ~40 m of ground and Esri+ # shows the same scene for free, so the quota buys nothing.+ # z12-14 is where the dated mosaic is the reason you're here.+ eco_max_zoom=11,+ )+ )+for entry in settings.get("tile_providers", []):try:url = entry["url"]@@ -185,12 +293,48 @@ def all_providers() -> list[Provider]:def get_provider(provider_id: str) -> Provider:+ """A provider by id, including a Sentinel-2 *variant* id.++ ``sentinel2~SWIR~2026-05-01~2026-05-31`` resolves to the sentinel2 basemap+ rendering that layer over that mosaicking window (engine/sentinel.py). The+ variant is carried on the id rather than passed alongside it so that every+ consumer inherits it for free and none can forget it: the tile proxy and+ fetch_crop only ever hold a Provider, the disk cache keys on ``provider.id``+ (so a window is in the cache key — tiles from two dates can never collide),+ and a capture's provenance records the id it was actually rendered from.+ """+ base_id, sep, spec = provider_id.partition(sentinel.VARIANT_SEP)for provider in all_providers():- if provider.id == provider_id:- return provider+ if provider.id == base_id:+ if not sep:+ return provider+ if provider.id != "sentinel2":+ raise KeyError(f"provider '{base_id}' has no variants")+ try:+ layer, start, end = sentinel.parse_variant(spec)+ except ValueError as exc:+ raise KeyError(str(exc)) from exc+ return replace(+ provider,+ id=provider_id,+ label=f"{provider.label} · {sentinel.variant_label(layer, start, end)}",+ url=sentinel.wmts_url(layer, start, end).replace(+ "{key}", _sentinel_key_from(provider.url)+ ),+ )raise KeyError(f"unknown tile provider '{provider_id}'")+def _sentinel_key_from(url: str) -> str:+ """The instance UUID out of a built Sentinel Hub URL — rebuilding the+ template for a variant needs the credential back, and the resolved provider+ is the only place it exists at this point."""+ match = re.search(r"/ogc/wmts/([^/?]+)", url)+ if not match:+ raise KeyError("Sentinel Hub provider URL carries no instance id")+ return match.group(1)++# -- Web Mercator ------------------------------------------------------------@@ -257,6 +401,18 @@ def resolve_url(provider: Provider) -> str:raise TileFetchError(f"Google session token: {exc}") from exc+def tile_url(url_template: str, z: int, x: int, y: int, zoom_offset: int = 0) -> str:+ """Fill an XYZ template for one tile.++ ``z`` is always a tile-grid level (indices are valid at ``1 << z``);+ ``zoom_offset`` only renames it for providers whose levels are numbered by+ resolution rather than by grid width (Provider.zoom_offset). Every caller+ goes through here so that correction can never be applied in one code path+ and forgotten in another.+ """+ return url_template.format(x=x, y=y, z=z + zoom_offset)++def _default_fetch(client: httpx.Client, url: str) -> Image.Image | None:"""Fetch one tile; None for 'no imagery here' (404 or a known placeholdertile), raise on other errors."""@@ -314,8 +470,17 @@ def fetch_crop(# lower URL z: one 512px tile at z-1 covers four 256px tiles at z.z_shift = int(math.log2(provider.tile_size // TILE_SIZE))zoom = max(min(zoom, provider.max_zoom), z_shift)- tile_z = zoom - z_shift- ts = provider.tile_size+ # Past a provider's native ceiling nothing new exists to fetch (Sentinel-2:+ # native z14, view z18), so the deepest real tiles are fetched and magnified+ # to the requested zoom. `ts` becomes one native tile's *footprint at the+ # view zoom*, which is all the grid math below cares about; the fetched+ # image is still tile_size px and gets resized up to it.+ native_max = provider.max_native_zoom+ native_max = provider.max_zoom if native_max is None else native_max+ upscale = max(0, zoom - max(native_max, z_shift))+ tile_z = zoom - z_shift - upscale+ native_ts = provider.tile_size+ ts = native_ts << upscalewidth, height = min(width, SIZE_MAX), min(height, SIZE_MAX)bearing = bearing % 360.0@@ -355,7 +520,8 @@ def fetch_crop(def grab(tx: int, ty: int) -> tuple[int, int, Image.Image | None]:if not (0 <= tx <= max_index and 0 <= ty <= max_index):return tx, ty, None- return tx, ty, fetch(client, url_template.format(x=tx, y=ty, z=tile_z))+ url = tile_url(url_template, tile_z, tx, ty, provider.zoom_offset)+ return tx, ty, fetch(client, url)with httpx.Client(headers={"User-Agent": USER_AGENT}, timeout=20, follow_redirects=True@@ -384,6 +550,8 @@ def fetch_crop(gaps.append((tx, ty))continueserved += 1+ if upscale:+ tile = tile.resize((ts, ts), Image.Resampling.LANCZOS)canvas.paste(tile, (px, py))# overzoom fallback: fill coverage gaps from parent-level imagery, upscaled —@@ -391,7 +559,10 @@ def fetch_crop(upscaled = 0if gaps:try:- filled, parent_served = _overzoom_fill(resolve_url(provider), gaps, tile_z, ts, fetch)+ filled, parent_served = _overzoom_fill(+ resolve_url(provider), gaps, tile_z, native_ts, fetch,+ provider.zoom_offset, out_size=ts,+ )except TileFetchError:filled, parent_served = {}, 0served += parent_served@@ -434,7 +605,7 @@ def fetch_crop()if provider.attribution_burn:- canvas = _burn_attribution(canvas, attribution)+ canvas = burn_attribution(canvas, attribution)provenance = {"provider": provider.id,@@ -447,10 +618,19 @@ def fetch_crop("center_lat": lat,"center_lon": lon,"zoom": zoom,+ # The zoom the pixels are actually from. Below `zoom` when the view ran+ # past the provider's native ceiling (Sentinel-2 at z18 is magnified z14+ # imagery): the image is real, its resolution is not what the zoom+ # implies, and a reader of this capture has to be able to tell.+ "native_zoom": zoom - upscale,+ "upscaled": bool(upscale),"width": width,"height": height,"bearing": round(bearing, 1),"meters_per_pixel": round(meters_per_pixel(lat, zoom), 3),+ # ground sample distance of the source imagery — unlike meters_per_pixel+ # this doesn't improve by magnifying, so it's the honest resolution+ "native_meters_per_pixel": round(meters_per_pixel(lat, zoom - upscale), 3),"tiles": n_tiles,"tiles_missing": missing,"tiles_upscaled": upscaled,@@ -470,6 +650,8 @@ def _overzoom_fill(tile_z: int,ts: int,fetch: Callable[[httpx.Client, str], Image.Image | None],+ zoom_offset: int = 0,+ out_size: int | None = None,) -> tuple[dict[tuple[int, int], Image.Image], int]:"""Best-effort fill for missing tiles from parent-level imagery.@@ -478,7 +660,12 @@ def _overzoom_fill(child crops + upscales its own quadrant. Returns (filled tiles, number ofparent tiles the provider served — what a billed meter must count).Individual fetch errors just leave tiles unfilled; never raises.++ ``ts`` is the provider's real tile size (the parent's pixels — what the crop+ math measures); ``out_size`` is the footprint the caller pastes at, which is+ larger when the caller is already magnifying past a native ceiling."""+ out_size = ts if out_size is None else out_sizefilled: dict[tuple[int, int], Image.Image] = {}unresolved = list(gaps)served = 0@@ -492,7 +679,7 @@ def _overzoom_fill(def grab(pxy: tuple[int, int]) -> tuple[tuple[int, int], Image.Image | None]:try:- url = url_template.format(x=pxy[0], y=pxy[1], z=tile_z - up)+ url = tile_url(url_template, tile_z - up, pxy[0], pxy[1], zoom_offset)return pxy, fetch(client, url)except Exception:return pxy, None@@ -511,7 +698,7 @@ def _overzoom_fill(continueqx, qy = (tx & mask) * sub, (ty & mask) * subfilled[(tx, ty)] = parent.crop((qx, qy, qx + sub, qy + sub)).resize(- (ts, ts), Image.Resampling.LANCZOS+ (out_size, out_size), Image.Resampling.LANCZOS)unresolved = stillreturn filled, served@@ -597,12 +784,13 @@ def esri_capture_date(ATTRIBUTION_BAND = 20 # px footer appended below the imagery-def _burn_attribution(img: Image.Image, text: str) -> Image.Image:+def burn_attribution(img: Image.Image, text: str) -> Image.Image:"""Append a footer band carrying the attribution line.For providers whose terms make attribution a condition of the allowed use(Google), the capture must never exist without it — burned in, not optional.- The band is added *below* the imagery so nothing is covered.+ The band is added *below* the imagery so nothing is covered. Public: the+ screenshot-capture endpoint stamps user screenshots through the same band."""out = Image.new("RGB", (img.width, img.height + ATTRIBUTION_BAND), (16, 18, 24))out.paste(img, (0, 0))diff --git a/src/azimut/server.py b/src/azimut/server.pyindex 4842ab7..4d6c485 100644--- a/src/azimut/server.py+++ b/src/azimut/server.py@@ -23,7 +23,7 @@ def create_app() -> FastAPI:app = FastAPI(title="Azimut", version=__version__, docs_url="/api/docs")- from .api import cases, drafts, files, inspect, media, proofs, satellite, settings+ from .api import cases, drafts, events, files, ingest, inspect, media, proofs, satellite, settingsapp.include_router(cases.router)app.include_router(media.router)@@ -33,6 +33,10 @@ def create_app() -> FastAPI:app.include_router(drafts.router)app.include_router(files.router)app.include_router(settings.router)+ app.include_router(ingest.router)+ app.include_router(events.router)+ # extension-origin CORS, /api/ingest/* only (see ingest.install_cors)+ ingest.install_cors(app)@app.get("/api/health")def health() -> dict[str, str]:diff --git a/tests/test_events_api.py b/tests/test_events_api.pynew file mode 100644index 0000000..e02c2ac--- /dev/null+++ b/tests/test_events_api.py@@ -0,0 +1,113 @@+"""The SSE nudge channel (api/events.py) and its one producer so far, ingest.++Events are advisory ("case X gained a capture") — the contract that matters is+that an ingest reliably nudges listeners with enough to know whether to+refresh, and that a saturated listener degrades to a missed nudge, never an+error inside the request that produced it.+"""++import asyncio+import io+import json++from PIL import Image++from azimut.api import events+++def _png_bytes():+ buf = io.BytesIO()+ Image.new("RGB", (64, 64), (30, 90, 30)).save(buf, format="PNG")+ return buf.getvalue()+++def test_publish_reaches_every_subscriber_and_unsubscribe_stops_it():+ async def scenario():+ a, b = events.subscribe(), events.subscribe()+ events.publish({"type": "capture", "case_id": "x"})+ assert (await a.get())["case_id"] == "x"+ assert (await b.get())["case_id"] == "x"+ events.unsubscribe(a)+ events.publish({"type": "capture", "case_id": "y"})+ assert (await b.get())["case_id"] == "y"+ assert a.empty() # unsubscribed — no longer receives+ events.unsubscribe(b)++ asyncio.run(scenario())+++def test_a_full_queue_drops_the_nudge_instead_of_failing_the_producer():+ async def scenario():+ q = events.subscribe()+ try:+ for i in range(events._QUEUE_SIZE + 10): # overflow must not raise+ events.publish({"n": i})+ assert q.qsize() == events._QUEUE_SIZE+ finally:+ events.unsubscribe(q)++ asyncio.run(scenario())+++def test_ingest_publishes_a_capture_nudge(client):+ token = client.get("/api/settings").json()["ingest_token"]+ cid = client.post("/api/cases", json={"name": "Live"}).json()["id"]+ q = events.subscribe()+ try:+ r = client.post(+ "/api/ingest/screenshot",+ files={"image": ("shot.png", _png_bytes(), "image/png")},+ data={"url": "https://www.openstreetmap.org/#map=17/48.85/2.29",+ "site": "openstreetmap", "case_id": cid,+ "lat": "48.85", "lon": "2.29", "title": "Test spot"},+ headers={"X-Azimut-Token": token},+ )+ assert r.status_code == 200+ event = q.get_nowait() # the nudge is emitted inside the request+ assert event["type"] == "capture"+ assert event["case_id"] == cid+ assert event["title"] == "Test spot"+ assert event["site"] == "openstreetmap"+ assert event["path"] == r.json()["path"]+ finally:+ events.unsubscribe(q)+++def test_sse_stream_frames_events_and_ends_on_disconnect(monkeypatch):+ # The generator is tested directly: TestClient deadlocks on infinite+ # streams (the disconnect never reaches a generator the response task is+ # itself waiting on), and what matters is ours anyway — framing, the+ # settle/keepalive comments, and that a disconnect unsubscribes the queue.+ monkeypatch.setattr(events, "_PING_SECONDS", 0.01)++ async def scenario():+ q = events.subscribe()+ polls = 0++ async def is_disconnected():+ nonlocal polls+ polls += 1+ return polls > 3 # stay connected long enough to see a ping++ events.publish({"type": "capture", "case_id": "c1"})+ chunks = [chunk async for chunk in events.sse_stream(q, is_disconnected)]+ assert chunks[0] == ": connected\n\n"+ assert 'data: {"type": "capture", "case_id": "c1"}\n\n' in chunks+ assert ": ping\n\n" in chunks # keepalive fired once the queue drained+ # the disconnect cleaned up: no lingering subscriber+ events.publish({"type": "capture", "case_id": "c2"})+ assert q.empty()++ asyncio.run(scenario())+++def test_events_route_is_registered(client):+ # resolves through FastAPI's (lazily included) routers — a plain GET would+ # hang the TestClient on the infinite stream, so prove registration by name+ assert client.app.url_path_for("events") == "/api/events"+++def test_event_payload_is_json_on_the_wire():+ # what the frontend JSON.parses — one data: line per event+ line = f"data: {json.dumps({'type': 'capture', 'case_id': 'c1'})}\n\n"+ assert json.loads(line[len('data: '):].strip()) == {"type": "capture", "case_id": "c1"}diff --git a/tests/test_ingest_api.py b/tests/test_ingest_api.pynew file mode 100644index 0000000..181b98c--- /dev/null+++ b/tests/test_ingest_api.py@@ -0,0 +1,216 @@+"""The capture extension's ingest API (api/ingest.py).++What must hold: nothing files without the pairing token, what files rides the+normal capture pipeline (entity + provenance + burned attribution), and the+CORS opening is exactly extension origins on exactly /api/ingest/* — the token+guards against local callers, CORS against web pages, and each test pins one+of those walls.+"""++import io++from PIL import Image++from azimut.engine import tiles+++def _png_bytes(w=320, h=200, color=(30, 90, 30)):+ buf = io.BytesIO()+ Image.new("RGB", (w, h), color).save(buf, format="PNG")+ return buf.getvalue()+++def _token(client):+ return client.get("/api/settings").json()["ingest_token"]+++def _post(client, token=None, **overrides):+ data = {+ "url": "https://www.google.com/maps/@48.8584,2.2945,17z",+ "lat": "48.8584",+ "lon": "2.2945",+ "zoom": "17",+ }+ files = {"image": ("shot.png", overrides.pop("image", _png_bytes()), "image/png")}+ data.update(overrides)+ data = {k: v for k, v in data.items() if v is not None}+ headers = {"X-Azimut-Token": token} if token else {}+ return client.post("/api/ingest/screenshot", files=files, data=data, headers=headers)+++def test_token_is_minted_once_and_survives_reads(client):+ token = _token(client)+ assert len(token) >= 24+ assert _token(client) == token # stable across reads — pairing must not churn+++def test_rotation_orphans_the_old_token(client):+ old = _token(client)+ new = client.post("/api/settings/ingest-token/rotate").json()["ingest_token"]+ assert new != old+ assert _post(client, token=old).status_code == 401+ assert _post(client, token=new).status_code == 200+++def test_every_ingest_route_requires_the_token(client):+ _token(client) # ensure one is minted — an unminted token must also refuse+ assert _post(client).status_code == 401+ assert _post(client, token="wrong").status_code == 401+ assert client.get("/api/ingest/ping").status_code == 401+ assert client.get("/api/ingest/cases").status_code == 401+ assert client.get("/api/ingest/ping", headers={"X-Azimut-Token": _token(client)}).json()[+ "app"+ ] == "azimut"+++def test_screenshot_files_as_a_capture_with_provenance(client):+ token = _token(client)+ cid = client.post("/api/cases", json={"name": "Ingest"}).json()["id"]+ r = _post(client, token=token, case_id=cid)+ assert r.status_code == 200+ body = r.json()+ assert body["case_id"] == cid+ assert body["method"] == "screenshot"+ assert body["framed"] is False # URL-derived view coords, not a crop frame+ assert body["site"] == "google-maps"+ assert body["source_url"].startswith("https://www.google.com/maps/")+ assert body["attribution"] == "Map data © Google"+ assert body["attribution_burned"] is True+ # the footer band grew the image — attribution is pixels, not metadata+ assert body["height"] == 200 + tiles.ATTRIBUTION_BAND+ # it lists with the case's other captures, coordinates intact+ listed = client.get(f"/api/cases/{cid}/satellite").json()+ assert len(listed) == 1+ assert listed[0]["lat"] == 48.8584+ assert listed[0]["method"] == "screenshot"+++def test_coords_are_optional_but_only_as_a_pair(client):+ token = _token(client)+ cid = client.post("/api/cases", json={"name": "NoCoords"}).json()["id"]+ r = _post(+ client, token=token, case_id=cid,+ url="https://earth.google.com/web/",+ lat=None, lon=None, zoom=None,+ )+ assert r.status_code == 200+ assert r.json()["lat"] is None+ assert r.json()["title"] == "Google Earth" # no coords to name it by+ # half a coordinate is a bug upstream, not a fixable-later entity: the URL+ # here carries no coords to fill the gap, so a lone lat must be refused+ r = _post(client, token=token, case_id=cid,+ url="https://earth.google.com/web/", lon=None, zoom=None)+ assert r.status_code == 422+++def test_the_url_alone_is_enough_metadata(client):+ """The thin-extension contract: a client that sends nothing but the image+ and the URL still gets coordinates, zoom, title, provider and imagery date+ — every format rule lives server-side (engine/mapsites.py), where an app+ update fixes it without touching installed extensions."""+ token = _token(client)+ cid = client.post("/api/cases", json={"name": "UrlOnly"}).json()["id"]+ body = _post(+ client, token=token, case_id=cid,+ url="https://www.google.com/maps/place/Tour+Eiffel/@48.8583701,2.2944813,17z/data=!3m1",+ lat=None, lon=None, zoom=None,+ ).json()+ assert body["lat"] == 48.8583701+ assert body["lon"] == 2.2944813+ assert body["zoom"] == 17+ assert body["title"] == "Tour Eiffel"+ assert body["provider_label"] == "Google Maps"+ # explicit fields are the popup's corrections and win over the URL+ fixed = _post(+ client, token=token, case_id=cid,+ url="https://www.google.com/maps/@48.8584,2.2945,17z",+ lat="48.9", lon="2.4", title="Corrected spot",+ ).json()+ assert (fixed["lat"], fixed["lon"], fixed["title"]) == (48.9, 2.4, "Corrected spot")+++def test_non_map_urls_are_refused(client):+ """Maps only (legal rails) — enforced at the endpoint, not just the popup."""+ token = _token(client)+ for url in ("https://twitter.com/somebody/status/1", "https://maps.example.org/@1,2,3z"):+ assert _post(client, token=token, url=url, lat=None, lon=None, zoom=None+ ).status_code == 422+++def test_empty_case_files_into_a_fresh_scratch_session(client):+ token = _token(client)+ body = _post(client, token=token).json()+ cases = client.get("/api/cases").json()+ match = [c for c in cases if c["id"] == body["case_id"]]+ assert match and match[0]["scratch"] is True+++def test_capture_carries_provider_label_source_link_and_imagery_date(client):+ """An ingested screenshot must read like any other capture in the panels:+ provider chip filled, the source page one click away, and the imagery+ acquisition date shown when the URL carried one — all derived from the URL+ server-side, the extension sends none of it."""+ token = _token(client)+ cid = client.post("/api/cases", json={"name": "Rich"}).json()["id"]+ body = _post(+ client, token=token, case_id=cid,+ url="https://browser.dataspace.copernicus.eu/?zoom=12&lat=45.19&lng=11.77"+ "&fromTime=2024-07-01T00%3A00%3A00.000Z&toTime=2024-07-01T23%3A59%3A59.999Z",+ lat=None, lon=None, zoom=None,+ ).json()+ assert body["provider"] == "copernicus-browser"+ assert body["provider_label"] == "Copernicus Browser"+ assert body["imagery_date"] == "2024-07-01"+ listed = client.get(f"/api/cases/{cid}/satellite").json()+ assert listed[0]["provider_label"] == "Copernicus Browser"+ assert listed[0]["imagery_date"] == "2024-07-01"+ assert listed[0]["source_url"].startswith("https://browser.dataspace.copernicus.eu/")+++def test_malformed_url_and_unknown_case_are_refused(client):+ token = _token(client)+ assert _post(client, token=token, url="not a url").status_code == 422+ assert _post(client, token=token, case_id="nope").status_code == 404+++def test_oversized_payload_is_rejected(client, monkeypatch):+ from azimut.api import ingest++ monkeypatch.setattr(ingest, "MAX_IMAGE_BYTES", 100) # a tiny PNG still beats 100 bytes+ assert _post(client, token=_token(client)).status_code == 413+++def test_cors_opens_exactly_extension_origins_on_exactly_ingest_routes(client):+ ext = {"Origin": "chrome-extension://abcdefghijklmnop"}+ web = {"Origin": "https://evil.example"}+ # preflight from an extension: allowed, echoing the origin+ r = client.options("/api/ingest/screenshot", headers=ext)+ assert r.status_code == 204+ assert r.headers["access-control-allow-origin"] == ext["Origin"]+ assert "X-Azimut-Token" in r.headers["access-control-allow-headers"]+ # a real (401) response still carries the CORS header so the extension can+ # read the verdict instead of a mute network error+ r = client.get("/api/ingest/ping", headers=ext)+ assert r.status_code == 401+ assert r.headers["access-control-allow-origin"] == ext["Origin"]+ # a web page origin gets nothing, token or not — extensions only+ r = client.get("/api/ingest/ping", headers={**web, "X-Azimut-Token": _token(client)})+ assert "access-control-allow-origin" not in r.headers+ # extension origin outside /api/ingest/ gets nothing — the rest of the API+ # keeps the browser's same-origin default+ r = client.get("/api/health", headers=ext)+ assert "access-control-allow-origin" not in r.headers+++def test_extension_zip_serves_the_packaged_runtime_files(client):+ import zipfile as zf++ r = client.get("/api/ingest/extension.zip")+ if r.status_code == 404: # build without the extension bundled+ return+ assert r.headers["content-type"] == "application/zip"+ names = zf.ZipFile(io.BytesIO(r.content)).namelist()+ assert "manifest.json" in names+ # the dev harness must not reach an installed browser+ assert not [n for n in names if "node_modules" in n or n.endswith(".test.js")]+ assert "package.json" not in namesdiff --git a/tests/test_inspect_api.py b/tests/test_inspect_api.pyindex 8f2f898..6f6b7c4 100644--- a/tests/test_inspect_api.py+++ b/tests/test_inspect_api.py@@ -245,6 +245,45 @@ def test_compose_transparent_background_keeps_alpha(client):assert img.getpixel((60, 60))[3] == 255+def test_compose_paints_through_a_remapped_piece_footprint(client):+ """A panorama piece's transparent corners must stay holes, not black wedges.++ The remap projects onto a curve, so the output rectangle overhangs the piece.+ Composited naively that overhang paints over whatever the piece overlaps —+ which, in a panorama, is always its neighbour.+ """+ cid = client.post("/api/cases", json={"name": "RemapCompose"}).json()["id"]+ pngs = _pan_pngs()+ paths = [_upload(client, cid, f"v{i}.png", png)["path"] for i, png in enumerate(pngs)]+ solved = client.post(+ f"/api/cases/{cid}/inspect/auto-stitch",+ json={+ "width": 1600, "height": 800, "mode": "cylindrical",+ "nodes": [{"path": p} for p in paths],+ },+ ).json()+ node = solved["nodes"][0]++ res = client.post(+ f"/api/cases/{cid}/inspect/compose",+ json={+ "width": 1600, "height": 800, "background": None,+ "nodes": [{"src": {"path": paths[0], "ops": [node["op"]]}, "quad": node["quad"]}],+ },+ ).json()++ png = client.get(f"/files/{cid}/{res['item']['path']}").content+ img = Image.open(io.BytesIO(png))+ quad = node["quad"]+ x0, y0 = quad[0]+ x1, y1 = quad[2]+ # Just inside the piece's own top-left corner: on the rectangle, off the curve.+ inset = (round(x0 + 2), round(y0 + 2))+ assert img.getpixel(inset)[3] == 0+ # ...while its middle is painted.+ assert img.getpixel((round((x0 + x1) / 2), round((y0 + y1) / 2)))[3] == 255++def test_compose_node_crop_is_applied_before_warp(client):cid = client.post("/api/cases", json={"name": "CropWarp"}).json()["id"]# left half white, right half black — crop keeps the white half only@@ -359,6 +398,114 @@ def test_auto_stitch_rejects_unrelated_imagery(client):assert "no overlap" in res.json()["detail"]+def _pan_pngs(angles=(-20, 0, 20)):+ """Views of one world through a camera yawed by each angle, as PNG bytes."""+ from test_stitch import _pan++ out = []+ for view in _pan(list(angles)):+ buf = io.BytesIO()+ view.save(buf, "PNG")+ out.append(buf.getvalue())+ return out+++def test_auto_stitch_defaults_to_planar_and_bakes_no_warp(client):+ cid = client.post("/api/cases", json={"name": "StitchPlanar"}).json()["id"]+ left_png, right_png = _overlapping_pair()+ a = _upload(client, cid, "left.png", left_png)+ b = _upload(client, cid, "right.png", right_png)++ body = client.post(+ f"/api/cases/{cid}/inspect/auto-stitch",+ json={"width": 1200, "height": 600, "nodes": [{"path": a["path"]}, {"path": b["path"]}]},+ ).json()++ # Planar's whole bargain: geometry only, so the pieces keep their own pixels+ # and stay hand-warpable.+ assert body["mode"] == "planar"+ assert [n["op"] for n in body["nodes"]] == [None, None]++[email protected]("mode", ["cylindrical", "spherical"])+def test_auto_stitch_panorama_modes_return_a_remap_per_piece(client, mode):+ cid = client.post("/api/cases", json={"name": f"Stitch{mode}"}).json()["id"]+ paths = [+ _upload(client, cid, f"v{i}.png", png)["path"] for i, png in enumerate(_pan_pngs())+ ]+ before = len(client.get(f"/api/cases/{cid}/media").json())++ res = client.post(+ f"/api/cases/{cid}/inspect/auto-stitch",+ json={+ "width": 1600, "height": 800, "mode": mode,+ "nodes": [{"path": p} for p in paths],+ },+ )++ assert res.status_code == 200+ body = res.json()+ assert body["mode"] == mode+ assert body["dropped"] == []+ for node in body["nodes"]:+ assert node["op"]["op"] == "remap"+ assert node["op"]["params"]["warp"] == mode+ assert len(node["op"]["params"]["r"]) == 9+ # Still not a Save gate: a panorama mode re-derives pixels, it does not file any.+ assert len(client.get(f"/api/cases/{cid}/media").json()) == before+++def test_auto_stitch_remap_round_trips_through_the_render_pipeline(client):+ """The op the solver hands back must be one the recipe pipeline can replay.++ This is what carries the warp to the full-res export: nothing stores the+ stitched pixels, only the recipe that reproduces them.+ """+ cid = client.post("/api/cases", json={"name": "StitchReplay"}).json()["id"]+ paths = [+ _upload(client, cid, f"v{i}.png", png)["path"] for i, png in enumerate(_pan_pngs())+ ]+ body = client.post(+ f"/api/cases/{cid}/inspect/auto-stitch",+ json={+ "width": 1600, "height": 800, "mode": "cylindrical",+ "nodes": [{"path": p} for p in paths],+ },+ ).json()+ node = body["nodes"][0]++ res = client.post(+ f"/api/cases/{cid}/inspect/render-preview",+ json={"path": paths[0], "ops": [node["op"]]},+ )++ assert res.status_code == 200+ piece = Image.open(io.BytesIO(res.content))+ # The curved footprint has to survive to the canvas, or the piece would paint+ # black corners over its neighbours.+ assert piece.mode == "RGBA"+ assert piece.getchannel("A").getpixel((0, 0)) == 0+ quad = node["quad"]+ aspect = (quad[1][0] - quad[0][0]) / (quad[3][1] - quad[0][1])+ assert piece.width / piece.height == pytest.approx(aspect, rel=0.01)+++def test_auto_stitch_rejects_an_unknown_mode(client):+ cid = client.post("/api/cases", json={"name": "StitchBadMode"}).json()["id"]+ left_png, right_png = _overlapping_pair()+ a = _upload(client, cid, "left.png", left_png)+ b = _upload(client, cid, "right.png", right_png)++ res = client.post(+ f"/api/cases/{cid}/inspect/auto-stitch",+ json={+ "width": 800, "height": 600, "mode": "toroidal",+ "nodes": [{"path": a["path"]}, {"path": b["path"]}],+ },+ )+ assert res.status_code == 422++def test_auto_stitch_needs_two_pieces(client):cid = client.post("/api/cases", json={"name": "StitchOne"}).json()["id"]a = _upload(client, cid, "a.png")diff --git a/tests/test_mapsites.py b/tests/test_mapsites.pynew file mode 100644index 0000000..019986e--- /dev/null+++ b/tests/test_mapsites.py@@ -0,0 +1,116 @@+"""Map-site URL parsers (engine/mapsites.py).++Server-side on purpose: URL formats race sites that change without notice and+the extension can't be updated remotely — so every rule is here, where an app+update fixes it. The contract: a recognized map site always returns its site+id (coordinates/title/imagery date when the URL carries them, None when it+doesn't), anything else returns None, and nothing ever raises.+"""++import pytest++from azimut.engine.mapsites import parse_map_url++LAT, LON, Z = 45.197652, 11.777344, 6+++# Mirrors frontend/src/lib/maplinks.js exactly: whatever Azimut can send the+# user out to, the backend must be able to read back.+OPEN_IN_LINKS = [+ (f"https://www.google.com/maps/@{LAT},{LON},{Z}z", "google-maps", Z),+ (f"https://www.google.com/maps/@{LAT},{LON},2000m/data=!3m1!1e3", "google-maps", None),+ (f"https://earth.google.com/web/@{LAT},{LON},0a,1000d,35y,0h,0t,0r", "google-earth", None),+ (f"https://maps.apple.com/?ll={LAT},{LON}&z={Z}&t=k", "apple-maps", Z),+ (f"https://www.bing.com/maps?cp={LAT}~{LON}&lvl={Z}&style=h", "bing-maps", Z),+ (f"https://yandex.com/maps/?ll={LON},{LAT}&z={Z}&l=sat", "yandex-maps", Z),+ (f"https://browser.dataspace.copernicus.eu/?zoom={Z}&lat={LAT}&lng={LON}",+ "copernicus-browser", Z),+ (f"https://zoom.earth/#view={LAT},{LON},{Z}z", "zoom-earth", Z),+]++[email protected]("url,site,zoom", OPEN_IN_LINKS)+def test_every_open_in_link_round_trips(url, site, zoom):+ p = parse_map_url(url)+ assert p["site"] == site+ assert p["lat"] == LAT and p["lon"] == LON+ assert p["zoom"] == zoom+++def test_satellites_pro_still_parses():+ # dropped from the app's quick links (its basemaps duplicate the others),+ # but a user browsing there themselves still gets their capture read back+ p = parse_map_url(f"https://satellites.pro/#{LAT},{LON},{Z}")+ assert (p["site"], p["lat"], p["lon"], p["zoom"]) == ("satellites-pro", LAT, LON, Z)+++def test_google_maps_forms():+ p = parse_map_url(+ "https://www.google.com/maps/place/Tour+Eiffel/@48.8583701,2.2944813,17z/data=!3m1!4b1"+ )+ assert (p["site"], p["lat"], p["zoom"], p["title"]) == (+ "google-maps", 48.8583701, 17, "Tour Eiffel")+ # a pinned place without an @ viewport — !3d/!4d+ p = parse_map_url("https://www.google.com/maps/place/x/data=!8m2!3d48.85!4d2.29")+ assert (p["lat"], p["lon"]) == (48.85, 2.29)+ # a share short-link: recognized, no coordinates+ assert parse_map_url("https://maps.app.goo.gl/AbCdEf123")["lat"] is None+ # google search is not a map+ assert parse_map_url("https://www.google.com/search?q=eiffel+tower") is None+++def test_google_earth_heading_and_search_name():+ p = parse_map_url(+ "https://earth.google.com/web/search/Palais%20de%20l%27%C3%89lys%C3%A9e/"+ "@48.8704156,2.3167542,79a,684d,35y,41.12345h,45.18471069t,0r"+ )+ assert p["title"] == "Palais de l'Élysée"+ assert p["bearing"] == pytest.approx(41.12345)+ assert p["zoom"] is None # Earth encodes camera distance, not web zoom++[email protected]("url,title", [+ ("https://www.bing.com/maps?q=tour+eiffel&cp=48.85~2.29&lvl=17", "tour eiffel"),+ ("https://yandex.com/maps/?text=tour%20eiffel&ll=2.29,48.85&z=17", "tour eiffel"),+ ("https://maps.apple.com/?q=Tour+Eiffel&ll=48.85,2.29&z=17", "Tour Eiffel"),+ ("https://www.openstreetmap.org/search?query=tour+eiffel#map=17/48.85/2.29", "tour eiffel"),+ # nothing named in the URL → the app titles by coordinates instead+ ("https://www.google.com/maps/@48.85,2.29,17z", None),+ ("https://satellites.pro/#48.85,2.29,17", None),+])+def test_place_names_become_the_suggested_title(url, title):+ assert parse_map_url(url)["title"] == title+++def test_imagery_dates_only_where_urls_honestly_carry_them():+ p = parse_map_url(+ "https://browser.dataspace.copernicus.eu/?zoom=12&lat=45.19&lng=11.77"+ "&fromTime=2024-07-01T00%3A00%3A00.000Z&toTime=2024-07-01T23%3A59%3A59.999Z"+ )+ assert p["imagery_date"] == "2024-07-01"+ # zoom earth daily date, single-digit parts normalized+ p = parse_map_url("https://zoom.earth/maps/daily/#view=45.19,11.77,8z/date=2025-7-4")+ assert p["imagery_date"] == "2025-07-04"+ # junk dates are dropped, not passed through+ assert parse_map_url("https://zoom.earth/#view=45.19,11.77,8z/date=2025-99-99")[+ "imagery_date"] is None+ # sites whose URLs carry no date — never invented+ assert parse_map_url("https://www.google.com/maps/@48.85,2.29,17z")["imagery_date"] is None+++def test_refusals_and_malformed_input():+ # non-map sites: the extension stays out+ assert parse_map_url("https://twitter.com/somebody/status/1") is None+ assert parse_map_url("https://en.wikipedia.org/wiki/Eiffel_Tower") is None+ # non-web protocols+ assert parse_map_url("chrome://settings") is None+ assert parse_map_url("about:blank") is None+ assert parse_map_url("file:///home/user/map.html") is None+ # garbage never raises+ for junk in ("", "not a url", "https://", "https://www.google.com/maps/@nope",+ "https://www.google.com/maps/place/%E0%A4%A/@48.85,2.29,17z"):+ parse_map_url(junk)+ # out-of-world coordinates are rejected, not filed+ assert parse_map_url("https://www.openstreetmap.org/#map=17/98.0/2.29")["lat"] is None+ # malformed bing cp degrades to "known site, nothing parsed"+ assert parse_map_url("https://www.bing.com/maps?cp=garbage&lvl=9")["lat"] is Nonediff --git a/tests/test_satellite_api.py b/tests/test_satellite_api.pyindex d9be6eb..be6d39d 100644--- a/tests/test_satellite_api.py+++ b/tests/test_satellite_api.py@@ -404,3 +404,124 @@ def test_place_label_follows_the_coordinate_format(client):json={"lat": 48.8583701, "lon": 2.2944813, "zoom": 16, "title": "Rooftop"},).json()assert titled["label"] == "Rooftop"+++def _png_bytes(w=320, h=200, color=(30, 90, 30)):+ import io++ buf = io.BytesIO()+ Image.new("RGB", (w, h), color).save(buf, format="PNG")+ return buf.getvalue()+++def test_widget_usage_endpoint_counts_map_loads(client):+ client.put("/api/settings/keys", json={"google_js": "AIza.js"})+ assert client.post("/api/satellite/usage/google_js").json()["count"] == 1+ assert client.post("/api/satellite/usage/google_js").json()["count"] == 2+ # tile meters are counted by the proxy, never by the browser+ assert client.post("/api/satellite/usage/google").status_code == 404+ assert client.post("/api/satellite/usage/nope").status_code == 404+++def test_screenshot_capture_files_with_burned_attribution(client):+ client.put("/api/settings/keys", json={"google_js": "AIza.js"})+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]++ r = client.post(+ f"/api/cases/{cid}/satellite/screenshot",+ files={"image": ("shot.png", _png_bytes(), "image/png")},+ data={"lat": "48.8584", "lon": "2.2945", "zoom": "18",+ "provider": "google-js", "bearing": "45"},+ )+ assert r.status_code == 200+ body = r.json()+ assert body["method"] == "screenshot"+ assert "Google" in body["attribution"]+ assert body["attribution_burned"] is True+ # the footer band grew the image — attribution is pixels, not metadata+ assert body["height"] == 200 + tiles.ATTRIBUTION_BAND++ listed = client.get(f"/api/cases/{cid}/satellite").json()+ assert len(listed) == 1+ assert listed[0]["method"] == "screenshot"+ assert listed[0]["bearing"] == 45.0+ # nothing said it was framed, so provenance must not imply the coordinates+ # are a crop centre+ assert body["framed"] is False+++def test_screenshot_provenance_distinguishes_a_framed_crop_from_a_pasted_image(client):+ """A screen crop taken through the capture frame is registered — its+ lat/lon *are* the crop centre — while a pasted screenshot's coordinates are+ only the map view at filing time. Provenance has to tell them apart, or a+ reader can't know what the coordinates mean."""+ client.put("/api/settings/keys", json={"google_js": "AIza.js"})+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]++ framed = client.post(+ f"/api/cases/{cid}/satellite/screenshot",+ files={"image": ("shot.png", _png_bytes(), "image/png")},+ data={"lat": "48.8584", "lon": "2.2945", "zoom": "18",+ "provider": "google-js", "framed": "true"},+ ).json()+ assert framed["framed"] is True++ pasted = client.post(+ f"/api/cases/{cid}/satellite/screenshot",+ files={"image": ("shot.png", _png_bytes(), "image/png")},+ data={"lat": "48.8584", "lon": "2.2945", "zoom": "18",+ "provider": "google-js", "framed": "false"},+ ).json()+ assert pasted["framed"] is False+ # both are still screenshots: framing never upgrades the method+ assert framed["method"] == pasted["method"] == "screenshot"++ listed = client.get(f"/api/cases/{cid}/satellite").json()+ assert sorted(c["framed"] for c in listed) == [False, True]+++def test_screenshot_capture_refused_for_tile_providers(client):+ # tile providers have the real, pixel-registered capture path — routing a+ # screenshot around it would only launder away provenance+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]+ r = client.post(+ f"/api/cases/{cid}/satellite/screenshot",+ files={"image": ("shot.png", _png_bytes(), "image/png")},+ data={"lat": "0", "lon": "0", "zoom": "10", "provider": "esri-world-imagery"},+ )+ assert r.status_code == 422+++def test_tile_proxy_benches_google_on_a_persistent_403(client, monkeypatch):+ """A 403 that survives the session re-mint names the key (EEA policy,+ revoked key) — the basemap must stop being offered, with Google's own+ sentence stored as the reason."""+ import httpx++ from azimut.engine import google_tiles++ client.put("/api/settings/keys", json={"google": "AIza.x"})+ monkeypatch.setattr(+ google_tiles, "resolve_template", lambda url, **kw: url.replace("{session}", "tok")+ )+ monkeypatch.setattr(google_tiles, "invalidate", lambda key: None)+ eea = (+ b'{"error": {"code": 403, "status": "PERMISSION_DENIED", "message": '+ b'"Satellite tiles are not available for your account and region."}}'+ )++ def forbidden(url, **kwargs):+ return httpx.Response(+ 403, content=eea, headers={"content-type": "application/json"},+ request=httpx.Request("GET", url),+ )++ monkeypatch.setattr(httpx, "get", forbidden)+ r = client.get("/api/tiles/google-satellite/15/16597/11278")+ assert r.status_code == 403 # passthrough, as before++ status = client.get("/api/settings").json()["provider_status"]["google"]+ assert status["ok"] is False+ assert "not available for your account and region" in status["detail"]+ ids = {p["id"] for p in client.get("/api/satellite/providers").json()}+ assert "google-satellite" not in idsdiff --git a/tests/test_sentinel.py b/tests/test_sentinel.pynew file mode 100644index 0000000..f8dab84--- /dev/null+++ b/tests/test_sentinel.py@@ -0,0 +1,264 @@+"""Sentinel Hub layers, mosaicking windows and date discovery (engine/sentinel.py)."""++from __future__ import annotations++import json++import httpx+import pytest++from azimut.engine import sentinel+++def _response(url, payload=None, text=None, status=200):+ return httpx.Response(+ status,+ content=(text if text is not None else json.dumps(payload)).encode(),+ request=httpx.Request("GET", url),+ )+++# -- the WMTS template ---------------------------------------------------------+++def test_wmts_url_omits_time_by_default():+ url = sentinel.wmts_url()+ assert "LAYER=TRUE_COLOR" in url+ # no TIME = the layer's own default window (most recent), which is the+ # honest answer to "just show me it"+ assert "TIME=" not in url+ assert "{key}" in url and "{z}" in url and "{x}" in url and "{y}" in url+++def test_wmts_url_carries_the_layer_and_the_window():+ url = sentinel.wmts_url("SWIR", "2026-05-01", "2026-05-31")+ assert "LAYER=SWIR" in url+ assert "TIME=2026-05-01/2026-05-31" in url+++def test_wmts_url_ignores_a_half_open_window():+ # a window needs both ends; one date alone would silently mean something+ # other than what the caller thinks+ assert "TIME=" not in sentinel.wmts_url("SWIR", "2026-05-01", None)+++# -- variant ids ---------------------------------------------------------------+++def test_variant_id_of_the_plain_basemap_is_just_the_base_id():+ # the default layer with no window must not get a second name: it would+ # cache twice and read as two providers in provenance+ assert sentinel.variant_id("sentinel2") == "sentinel2"+ assert sentinel.variant_id("sentinel2", "TRUE_COLOR") == "sentinel2"+++def test_variant_id_round_trips_through_parse_variant():+ packed = sentinel.variant_id("sentinel2", "SWIR", "2026-05-01", "2026-05-31")+ assert packed == "sentinel2~SWIR~2026-05-01~2026-05-31"+ base, _, spec = packed.partition("~")+ assert base == "sentinel2"+ assert sentinel.parse_variant(spec) == ("SWIR", "2026-05-01", "2026-05-31")+++def test_variant_id_keeps_a_windowed_default_layer():+ packed = sentinel.variant_id("sentinel2", "TRUE_COLOR", "2026-05-01", "2026-05-01")+ assert packed == "sentinel2~TRUE_COLOR~2026-05-01~2026-05-01"+++def test_parse_variant_takes_a_bare_layer():+ assert sentinel.parse_variant("FALSE_COLOR") == ("FALSE_COLOR", None, None)+++def test_parse_variant_accepts_a_layer_the_catalogue_never_heard_of():+ # an instance serves whatever its configuration says; the catalogue is a+ # default, not a gate (a wrong one comes back as Sentinel Hub's own 400)+ assert sentinel.parse_variant("MY_CUSTOM_SCRIPT") == ("MY_CUSTOM_SCRIPT", None, None)+++ "spec",+ [+ "../../etc/passwd", # the id is a URL path segment *and* a cache directory+ "TRUE COLOR",+ "true_color", # layer names are upper-case; lower would 400 upstream+ "SWIR~2026-05-01", # half a window+ "SWIR~2026-05-01~2026-05-31~extra",+ "SWIR~2026-13-01~2026-05-31", # impossible month+ "SWIR~05/01/2026~2026-05-31", # not ISO+ "SWIR~2026-05-31~2026-05-01", # ends before it starts+ "",+ ],+)+def test_parse_variant_refuses_anything_ill_shaped(spec):+ with pytest.raises(ValueError):+ sentinel.parse_variant(spec)+++def test_variant_label_reads_like_a_human_wrote_it():+ assert sentinel.variant_label("SWIR", None, None).endswith("most recent")+ assert "2026-05-01 → 2026-05-31" in sentinel.variant_label("SWIR", "2026-05-01", "2026-05-31")+ # a single-day window is a day, not a range from a day to itself+ assert sentinel.variant_label("SWIR", "2026-05-01", "2026-05-01").endswith("2026-05-01")+++# -- date discovery ------------------------------------------------------------+++def test_dates_collapses_granules_per_day_newest_first():+ captured = {}++ def get(url, params=None, **kwargs):+ captured["url"] = url+ captured["params"] = params+ return _response(+ url,+ {+ "features": [+ {"properties": {"date": "2026-05-01", "cloudCoverPercentage": 80.0}},+ # same day, second granule covering the point — the clearer+ # one is the one worth reporting+ {"properties": {"date": "2026-05-01", "cloudCoverPercentage": 12.5}},+ {"properties": {"date": "2026-05-11", "cloudCoverPercentage": 3.0}},+ {"properties": {"date": "not-a-date"}}, # never trust the wire+ ]+ },+ )++ found = sentinel.dates("inst-uuid", 48.8584, 2.2945, "2026-05-01", "2026-05-31", get=get)+ assert found == [+ {"date": "2026-05-11", "cloud": 3.0, "granules": 1},+ {"date": "2026-05-01", "cloud": 12.5, "granules": 2},+ ]+ assert "/ogc/wfs/inst-uuid" in captured["url"]+ assert captured["params"]["TYPENAMES"] == "DSS2" # L2A — what the basemap renders+ assert captured["params"]["TIME"] == "2026-05-01/2026-05-31"+++def _square(lat, lon, half=0.5):+ """A granule footprint around a point, GeoJSON order (lon, lat)."""+ return {+ "type": "Polygon",+ "coordinates": [[+ [lon - half, lat - half], [lon + half, lat - half],+ [lon + half, lat + half], [lon - half, lat + half],+ [lon - half, lat - half],+ ]],+ }+++def test_dates_drops_a_granule_whose_imagery_misses_the_point():+ """A granule's *box* can reach the point while its swath doesn't — that day+ renders black. WFS answers on the box, so the footprint has to be checked or+ the date list promises imagery that isn't there."""++ def get(url, params=None, **kwargs):+ return _response(url, {"features": [+ # covers the point+ {"properties": {"date": "2026-05-11", "cloudCoverPercentage": 2},+ "geometry": _square(48.85, 2.29)},+ # box intersects the search area, footprint is a province away+ {"properties": {"date": "2026-05-04", "cloudCoverPercentage": 1},+ "geometry": _square(45.0, 6.0)},+ ]})++ found = sentinel.dates("inst-uuid", 48.8584, 2.2945, "2026-05-01", "2026-05-31", get=get)+ assert [entry["date"] for entry in found] == ["2026-05-11"]+++def test_dates_keeps_a_granule_whatever_axis_order_the_service_used():+ """GeoJSON says lon/lat; an OGC service asked for EPSG:4326 may answer+ lat/lon. Read backwards, every footprint on Earth would be rejected."""+ swapped = {+ "type": "Polygon",+ "coordinates": [[[48.35, 1.79], [49.35, 1.79], [49.35, 2.79], [48.35, 2.79], [48.35, 1.79]]],+ }++ def get(url, params=None, **kwargs):+ return _response(url, {"features": [+ {"properties": {"date": "2026-05-11"}, "geometry": swapped}+ ]})++ found = sentinel.dates("inst-uuid", 48.8584, 2.2945, "2026-05-01", "2026-05-31", get=get)+ assert [entry["date"] for entry in found] == ["2026-05-11"]+++def test_dates_keeps_a_pass_whose_geometry_it_cannot_read():+ """Never drop a real pass over a guess: no geometry means no evidence."""++ def get(url, params=None, **kwargs):+ return _response(url, {"features": [+ {"properties": {"date": "2026-05-11"}},+ {"properties": {"date": "2026-05-08"}, "geometry": {"type": "Point", "coordinates": [2, 48]}},+ ]})++ found = sentinel.dates("inst-uuid", 48.8584, 2.2945, "2026-05-01", "2026-05-31", get=get)+ assert [entry["date"] for entry in found] == ["2026-05-11", "2026-05-08"]+++def test_dates_sends_a_latitude_first_bbox():+ captured = {}++ def get(url, params=None, **kwargs):+ captured.update(params)+ return _response(url, {"features": []})++ sentinel.dates("inst-uuid", 48.0, 2.0, "2026-05-01", "2026-05-31", get=get)+ # EPSG:4326 declares latitude first; lon/lat order would put the box in the+ # Indian Ocean and quietly report "no imagery"+ assert captured["SRSNAME"] == "EPSG:4326"+ lat_min, lon_min, lat_max, lon_max = (float(v) for v in captured["BBOX"].split(","))+ assert lat_min < 48.0 < lat_max+ assert lon_min < 2.0 < lon_max+++def test_dates_reports_a_day_the_service_gave_no_cloud_figure_for():+ def get(url, params=None, **kwargs):+ return _response(url, {"features": [{"properties": {"date": "2026-05-01"}}]})++ found = sentinel.dates("inst-uuid", 48.0, 2.0, "2026-05-01", "2026-05-31", get=get)+ assert found == [{"date": "2026-05-01", "cloud": None, "granules": 1}]+++def test_dates_raises_rather_than_report_an_empty_sky():+ def get(url, params=None, **kwargs):+ return _response(url, {}, status=500)++ # "the lookup failed" and "there are no passes here" are different facts and+ # must never render as the same empty list+ with pytest.raises(httpx.HTTPStatusError):+ sentinel.dates("inst-uuid", 48.0, 2.0, "2026-05-01", "2026-05-31", get=get)+++# -- layer discovery -----------------------------------------------------------++_CAPABILITIES = """<?xml version="1.0"?>+<Capabilities xmlns="http://www.opengis.net/wmts/1.0"+ xmlns:ows="http://www.opengis.net/ows/1.1">+ <Contents>+ <Layer><ows:Identifier>TRUE_COLOR</ows:Identifier><ows:Title>True color</ows:Title></Layer>+ <Layer><ows:Identifier>MY_SHIPS</ows:Identifier><ows:Title>Vessel script</ows:Title></Layer>+ <Layer><ows:Identifier>bad id</ows:Identifier><ows:Title>unusable</ows:Title></Layer>+ </Contents>+</Capabilities>+"""+++def test_capabilities_layers_asks_the_instance_and_keeps_our_hints():+ def get(url, params=None, **kwargs):+ assert params["REQUEST"] == "GetCapabilities"+ return _response(url, text=_CAPABILITIES)++ found = sentinel.capabilities_layers("inst-uuid", get=get)+ assert [entry["id"] for entry in found] == ["TRUE_COLOR", "MY_SHIPS"]+ # a layer we know keeps the reason to pick it; one we don't still gets offered+ assert found[0]["hint"]+ assert found[1] == {"id": "MY_SHIPS", "label": "Vessel script", "hint": ""}+++def test_capabilities_layers_drops_names_that_could_not_be_asked_for():+ def get(url, params=None, **kwargs):+ return _response(url, text=_CAPABILITIES)++ # "bad id" can't survive a variant id (URL path segment + cache directory),+ # so offering it would only produce a broken selection+ assert all(" " not in entry["id"] for entry in sentinel.capabilities_layers("i", get=get))diff --git a/tests/test_settings_api.py b/tests/test_settings_api.pyindex 66ccecd..0247586 100644--- a/tests/test_settings_api.py+++ b/tests/test_settings_api.py@@ -75,6 +75,17 @@ def _upstream(status=200, content=b"JPEGDATA", headers=None):return get+def _png_bytes(size=512, colour=(10, 120, 10)):+ """A real encoded tile — the overzoom path decodes what it magnifies."""+ import io++ from PIL import Image++ buf = io.BytesIO()+ Image.new("RGB", (size, size), colour).save(buf, format="PNG")+ return buf.getvalue()++def test_tile_proxy_serves_and_counts_exactly(client, monkeypatch):client.put("/api/settings/keys", json={"mapbox": "pk.abc"})upstream = _upstream(headers={"cache-control": "max-age=43200"})@@ -316,6 +327,256 @@ def test_test_key_google_mints_a_session(client, monkeypatch):assert minted == ["AIza.x"]+def test_test_key_sentinelhub_reports_the_services_own_words(client, monkeypatch):+ """A bad instance id (or an instance without a TRUE_COLOR layer) comes back+ as a 400 ExceptionReport — the analyst gets Sentinel Hub's sentence, not+ "400 Bad Request"."""+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})++ def ok(url, **kwargs):+ assert "/ogc/wmts/inst-uuid?" in url+ assert "TILEMATRIX=14" in url # the zoom_offset applies here too+ return httpx.Response(200, request=httpx.Request("GET", url))++ monkeypatch.setattr(httpx, "get", ok)+ assert client.post("/api/settings/keys/sentinelhub/test").json()["ok"] is True++ body = (+ "<?xml version='1.0'?><ows:ExceptionReport "+ 'xmlns:ows="http://www.opengis.net/ows/1.1"><ows:Exception>'+ "<ows:ExceptionText>Invalid instance id: inst-uuid</ows:ExceptionText>"+ "</ows:Exception></ows:ExceptionReport>"+ )++ def bad(url, **kwargs):+ return httpx.Response(400, content=body.encode(), request=httpx.Request("GET", url))++ monkeypatch.setattr(httpx, "get", bad)+ result = client.post("/api/settings/keys/sentinelhub/test").json()+ assert result["ok"] is False+ assert result["detail"] == "Invalid instance id: inst-uuid"+++def test_sentinel2_tile_proxy_offsets_the_matrix_and_counts_tiles(client, monkeypatch):+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})+ upstream = _upstream()+ monkeypatch.setattr(httpx, "get", upstream)++ # the frontend asks in grid levels; WMTS wants that level named one higher+ assert client.get("/api/tiles/sentinel2/13/4151/2818").status_code == 200+ assert "TILEMATRIX=14" in upstream.urls[0]+ assert "TILECOL=4151" in upstream.urls[0] and "TILEROW=2818" in upstream.urls[0]+ body = client.get("/api/settings").json()+ assert body["usage"]["sentinelhub"][body["month"]] == 1 # 1 tile == 1 PU+++def test_sentinel2_proxy_never_asks_upstream_past_the_native_ceiling(client, monkeypatch):+ """A grid level deeper than z14 exists only as Sentinel Hub's own upsampling+ of pixels we already have — and every tile of it is billed. Serve the native+ tile magnified instead."""+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})+ upstream = _upstream(content=_png_bytes(), headers={"content-type": "image/png"})+ monkeypatch.setattr(httpx, "get", upstream)++ # grid 17 == view z18 for a 512px provider; native is grid 13 (TILEMATRIX 14)+ r = client.get("/api/tiles/sentinel2/17/66424/45097")+ assert r.status_code == 200+ assert r.headers["x-azimut-overzoom"] == "4" # magnified, not fetched+ assert len(upstream.urls) == 1+ assert "TILEMATRIX=14" in upstream.urls[0] # the native level, nothing deeper+ body = client.get("/api/settings").json()+ assert body["usage"]["sentinelhub"][body["month"]] == 1 # one tile, not sixteen+++def test_sentinel_layers_does_not_touch_the_network_without_check(client, monkeypatch):+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})++ def explode(*a, **k):+ raise AssertionError("opening the layer list must never phone out")++ monkeypatch.setattr(httpx, "get", explode)+ body = client.get("/api/satellite/sentinel/layers").json()+ assert body["source"] == "catalogue"+ ids = [entry["id"] for entry in body["layers"]]+ assert "TRUE_COLOR" in ids and "FALSE_COLOR" in ids and "SWIR" in ids+ assert all(entry["label"] for entry in body["layers"])+++def test_sentinel_layers_check_asks_the_instance(client, monkeypatch):+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})+ xml = (+ '<?xml version="1.0"?><Capabilities xmlns="http://www.opengis.net/wmts/1.0" '+ 'xmlns:ows="http://www.opengis.net/ows/1.1"><Contents>'+ "<Layer><ows:Identifier>TRUE_COLOR</ows:Identifier></Layer>"+ "<Layer><ows:Identifier>VESSELS</ows:Identifier><ows:Title>Vessels</ows:Title></Layer>"+ "</Contents></Capabilities>"+ )++ def get(url, **kwargs):+ return httpx.Response(200, content=xml.encode(), request=httpx.Request("GET", url))++ monkeypatch.setattr(httpx, "get", get)+ body = client.get("/api/satellite/sentinel/layers?check=true").json()+ assert body["source"] == "instance"+ assert [entry["id"] for entry in body["layers"]] == ["TRUE_COLOR", "VESSELS"]+++def test_sentinel_layers_check_falls_back_to_the_catalogue_and_says_why(client, monkeypatch):+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})++ def boom(*a, **k):+ raise httpx.ConnectError("offline")++ monkeypatch.setattr(httpx, "get", boom)+ body = client.get("/api/satellite/sentinel/layers?check=true").json()+ # a failed discovery leaves a usable list rather than an empty dropdown+ assert body["source"] == "catalogue"+ assert "offline" in body["detail"]+++def test_sentinel_dates_lists_passes_and_counts_the_request(client, monkeypatch):+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})+ payload = (+ '{"features": [{"properties": {"date": "2026-05-11", "cloudCoverPercentage": 4}}]}'+ )++ def get(url, **kwargs):+ assert "/ogc/wfs/inst-uuid" in url+ return httpx.Response(200, content=payload.encode(), request=httpx.Request("GET", url))++ monkeypatch.setattr(httpx, "get", get)+ body = client.get(+ "/api/satellite/sentinel/dates"+ "?lat=48.8584&lon=2.2945&start=2026-05-01&end=2026-05-31"+ ).json()+ assert body["dates"] == [{"date": "2026-05-11", "cloud": 4.0, "granules": 1}]+ # a WFS query is ~0.01 PU but one whole request against the request quota —+ # the meter counts what the account is charged for, tile or not+ settings = client.get("/api/settings").json()+ assert settings["usage"]["sentinelhub"][settings["month"]] == 1+++def test_sentinel_dates_without_a_key_is_a_404(client):+ assert client.get(+ "/api/satellite/sentinel/dates?lat=1&lon=1&start=2026-05-01&end=2026-05-31"+ ).status_code == 404+++def test_free_tier_defaults_to_the_provisioned_sentinel_allowance(client):+ body = client.get("/api/settings").json()+ # Copernicus documents 10k but provisions 30k to a General account+ # (observed 2026-07) — the counter measures against what they actually give+ assert body["free_tier"]["sentinelhub"] == 30_000+ assert body["free_tier_default"]["sentinelhub"] == 30_000+++def test_free_tier_override_moves_the_soft_block(client, monkeypatch):+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})+ r = client.put("/api/settings/prefs", json={"free_tiers": {"sentinelhub": 1000, "bogus": 5}})+ assert r.json()["free_tiers"] == {"sentinelhub": 1000} # unknown meters ignored+ assert client.get("/api/settings").json()["free_tier"]["sentinelhub"] == 1000++ # the block now measures against the user's figure, not the shipped default+ config.record_usage("sentinelhub", 900) # 90% of 1000+ monkeypatch.setattr(httpx, "get", _upstream())+ assert client.get("/api/tiles/sentinel2/13/4151/2818").status_code == 429++ # ...and clearing it restores the default, which 900 is nowhere near+ client.put("/api/settings/prefs", json={"free_tiers": {"sentinelhub": None}})+ assert client.get("/api/settings").json()["free_tier"]["sentinelhub"] == 30_000+ assert client.get("/api/tiles/sentinel2/13/4151/2818").status_code == 200+++def test_key_test_records_status_and_benches_the_basemap(client, monkeypatch):+ """A failing key test benches the basemap; saving a different key clears+ the verdict and the basemap comes back."""+ client.put("/api/settings/keys", json={"mapbox": "pk.bad"})++ def unauthorized(url, **kwargs):+ return httpx.Response(401, request=httpx.Request("GET", url))++ monkeypatch.setattr(httpx, "get", unauthorized)+ assert client.post("/api/settings/keys/mapbox/test").json()["ok"] is False++ status = client.get("/api/settings").json()["provider_status"]+ assert status["mapbox"]["ok"] is False+ ids = {p["id"] for p in client.get("/api/satellite/providers").json()}+ assert "mapbox-satellite" not in ids++ # a new key wipes the old key's verdict — the basemap is offered again+ client.put("/api/settings/keys", json={"mapbox": "pk.fresh"})+ assert "mapbox" not in client.get("/api/settings").json()["provider_status"]+ ids = {p["id"] for p in client.get("/api/satellite/providers").json()}+ assert "mapbox-satellite" in ids+++def test_google_key_test_speaks_googles_own_words(client, monkeypatch):+ """The EEA policy block arrives as a 403 with a full explanation in the+ body — the test verdict must carry that sentence, not '403 Forbidden'."""+ client.put("/api/settings/keys", json={"google": "AIza.eea"})+ eea = (+ '{"error": {"code": 403, "status": "PERMISSION_DENIED", "message": '+ '"Your request cannot be served because satellite tiles and 3D tiles '+ 'are not available for your account and region."}}'+ )++ def blocked(url, **kwargs):+ return httpx.Response(+ 403, content=eea.encode(),+ headers={"content-type": "application/json"},+ request=httpx.Request("POST", url),+ )++ monkeypatch.setattr(google_tiles.httpx, "post", blocked)+ result = client.post("/api/settings/keys/google/test").json()+ assert result["ok"] is False+ assert "not available for your account and region" in result["detail"]+ # and the dead basemap is no longer offered+ ids = {p["id"] for p in client.get("/api/satellite/providers").json()}+ assert "google-satellite" not in ids+++def test_google_js_key_is_tested_in_the_browser(client):+ """No server-side probe exists for a Maps JS key — the backend says so,+ and the browser reports its gm_authFailure verdict through /status."""+ client.put("/api/settings/keys", json={"google_js": "AIza.js"})+ assert client.post("/api/settings/keys/google_js/test").json()["ok"] is None++ r = client.post(+ "/api/settings/keys/google_js/status",+ json={"ok": False, "detail": "gm_authFailure: InvalidKeyMapError"},+ )+ assert r.status_code == 200+ ids = {p["id"] for p in client.get("/api/satellite/providers").json()}+ assert "google-js" not in ids # benched by the browser's verdict++ assert client.post(+ "/api/settings/keys/nope/status", json={"ok": True, "detail": ""}+ ).status_code == 404+++def test_per_provider_eco_thresholds(client):+ """Each tile API gets its own eco threshold; the widget is not tunable+ (an eco swap re-bills a map load) and unknown names are ignored."""+ client.put("/api/settings/keys", json={"mapbox": "pk.x", "sentinelhub": "inst", "google_js": "AIza.js"})+ r = client.put(+ "/api/settings/prefs",+ json={"eco_max_zooms": {"mapbox": 12, "sentinelhub": 0, "google_js": 9, "bogus": 3}},+ ).json()+ assert r["eco_max_zooms"] == {"mapbox": 12, "sentinelhub": 0}++ by_id = {p["id"]: p for p in client.get("/api/satellite/providers").json()}+ assert by_id["mapbox-satellite"]["eco_max_zoom"] == 12 # user override+ assert by_id["sentinel2"]["eco_max_zoom"] == 0 # user turned eco off for it+ assert by_id["google-js"]["eco_max_zoom"] == 0 # pinned, not settable++ # None removes the override: sentinel2 falls back to its own default (11)+ r = client.put("/api/settings/prefs", json={"eco_max_zooms": {"sentinelhub": None}}).json()+ assert r["eco_max_zooms"] == {"mapbox": 12}+ by_id = {p["id"]: p for p in client.get("/api/satellite/providers").json()}+ assert by_id["sentinel2"]["eco_max_zoom"] == 11++def test_providers_expose_tile_size(client):client.put("/api/settings/keys", json={"mapbox": "pk.abc", "google": "AIza.x"})providers = {p["id"]: p for p in client.get("/api/satellite/providers").json()}diff --git a/tests/test_stitch.py b/tests/test_stitch.pyindex 40c0336..4d218fc 100644--- a/tests/test_stitch.py+++ b/tests/test_stitch.py@@ -1,10 +1,13 @@-"""Auto-stitch: quad fitting math (pure) and the OpenCV layout solver.+"""Auto-stitch: quad fitting math (pure) and the OpenCV layout solvers.-The solver is exercised against a synthetic scene cut into overlapping crops, so-the right answer is known up front: the crops' offset is what we asked for, and-the solved quads must reproduce it.+The solvers are exercised against synthetic scenes, so the right answer is known+up front. Planar gets a scene cut into overlapping crops: the crops' offset is+what we asked for, and the solved quads must reproduce it. The rotation model gets+views rendered through a camera turned by known angles — built here by direct+sampling, so nothing under test is used to make its own input."""+import mathimport randomimport pytest@@ -13,12 +16,12 @@ from PIL import Image, ImageDrawfrom azimut.engine import stitch-def _scene(width=900, height=500, seed=7) -> Image.Image:+def _scene(width=900, height=500, seed=7, blobs=220) -> Image.Image:"""A richly textured scene — random blobs give the detector real features."""rng = random.Random(seed)img = Image.new("RGB", (width, height), (18, 20, 28))draw = ImageDraw.Draw(img)- for _ in range(220):+ for _ in range(blobs):x, y = rng.randrange(width), rng.randrange(height)r = rng.randrange(6, 34)color = (rng.randrange(40, 255), rng.randrange(40, 255), rng.randrange(40, 255))@@ -29,6 +32,36 @@ def _scene(width=900, height=500, seed=7) -> Image.Image:return img+def _pan(angles, width=520, height=420, focal=520.0, seed=5) -> list[Image.Image]:+ """Views of one world through a pinhole camera yawed by each of ``angles``.++ The world is a 360°-wide cylindrical scene; each view samples it through the+ camera's rays, which is exactly the situation the planar model cannot express+ and the rotation model can.+ """+ import cv2+ import numpy as np++ world = np.asarray(_scene(4000, 900, seed=seed, blobs=3000))+ wh, ww = world.shape[:2]+ world_focal = ww / (2 * math.pi)++ out = []+ ys, xs = np.mgrid[0:height, 0:width].astype(np.float32)+ for deg in angles:+ x = (xs - width / 2) / focal+ y = (ys - height / 2) / focal+ theta = np.arctan2(x, np.ones_like(x)) + math.radians(deg)+ map_x = ((theta * world_focal) % ww).astype(np.float32)+ map_y = ((y / np.sqrt(x**2 + 1)) * world_focal + wh / 2).astype(np.float32)+ out.append(Image.fromarray(cv2.remap(world, map_x, map_y, cv2.INTER_LINEAR)))+ return out+++def _widths(quads):+ return [max(p[0] for p in q) - min(p[0] for p in q) for q in quads]++def _centroid(quad):return (sum(p[0] for p in quad) / 4, sum(p[1] for p in quad) / 4)@@ -127,3 +160,139 @@ def test_solve_layout_raises_when_nothing_overlaps():pieces = [_scene(width=400, height=400, seed=1), _scene(width=400, height=400, seed=2)]with pytest.raises(RuntimeError, match="no overlap"):stitch.solve_layout(pieces, width=800, height=600)+++# --- rotation model --------------------------------------------------------+++def test_rotation_layout_keeps_pieces_even_where_planar_blows_them_up():+ """The reason the panorama modes exist, stated as a test.++ Seven views across a 90° pan. The planar model has to divide each piece by its+ cosine from the anchor, so the end pieces balloon; the cylinder is the surface+ the camera actually swept, so every piece keeps its size.++ How badly planar blows up depends on which piece it anchors to (worst at an+ end, mildest from the middle), so the bar here is only "visibly uneven" — the+ claim under test is the cylinder's evenness, which holds either way.+ """+ views = _pan([-45, -30, -15, 0, 15, 30, 45])++ planar = stitch.solve_layout(views, width=1600, height=800)+ cylindrical = stitch.solve_rotation_layout(views, width=1600, height=800, warp="cylindrical")++ assert cylindrical["dropped"] == []+ assert sorted(cylindrical["quads"]) == list(range(7))+ flat = _widths(planar["quads"].values())+ round_ = _widths(cylindrical["quads"].values())+ assert max(flat) / min(flat) > 2 # the distortion we are fixing+ assert max(round_) / min(round_) == pytest.approx(1.0, abs=0.1)+++def test_rotation_layout_orders_pieces_along_the_pan():+ views = _pan([-30, 0, 30])+ solved = stitch.solve_rotation_layout(views, width=1600, height=800)+ xs = [_centroid(solved["quads"][i])[0] for i in range(3)]+ assert xs[0] < xs[1] < xs[2]+++def test_rotation_layout_places_pieces_inside_the_canvas():+ solved = stitch.solve_rotation_layout(_pan([-20, 0, 20]), width=1000, height=800)+ for quad in solved["quads"].values():+ for x, y in quad:+ assert -1 <= x <= 1001+ assert -1 <= y <= 801+++def test_rotation_layout_returns_a_remap_per_placed_piece():+ solved = stitch.solve_rotation_layout(_pan([-20, 0, 20]), width=1200, height=600, warp="spherical")+ assert sorted(solved["remaps"]) == sorted(solved["quads"])+ for params in solved["remaps"].values():+ assert params["warp"] == "spherical"+ assert len(params["r"]) == 9+ assert params["focal"] > 0 and params["scale"] > 0+++def test_rotation_layout_drops_a_piece_that_matches_nothing():+ views = _pan([-20, 0, 20])+ views.append(_scene(width=520, height=420, seed=999)) # unrelated scene++ solved = stitch.solve_rotation_layout(views, width=1200, height=600)++ # Same promise as the planar solver: the stranger is reported, never guessed at.+ assert solved["dropped"] == [3]+ assert sorted(solved["quads"]) == [0, 1, 2]+ assert 3 not in solved["remaps"]+++def test_rotation_layout_rejects_a_lone_piece():+ with pytest.raises(ValueError, match="at least two"):+ stitch.solve_rotation_layout([_scene(width=200, height=200)], width=400, height=400)+++def test_rotation_layout_raises_when_nothing_overlaps():+ pieces = [_scene(width=400, height=400, seed=1), _scene(width=400, height=400, seed=2)]+ with pytest.raises(RuntimeError, match="no overlap"):+ stitch.solve_rotation_layout(pieces, width=800, height=600)+++def test_rotation_layout_rejects_an_unknown_warp():+ with pytest.raises(ValueError, match="unknown panorama warp"):+ stitch.solve_rotation_layout(_pan([0, 20]), width=800, height=600, warp="planar")+++# --- the remap op ----------------------------------------------------------+++def test_apply_warp_reproduces_the_solved_shape_and_marks_the_footprint():+ views = _pan([-20, 0, 20])+ solved = stitch.solve_rotation_layout(views, width=1200, height=600)+ quad = solved["quads"][0]++ out = stitch.apply_warp(views[0], solved["remaps"][0])++ # The op must hand the compositor the very shape the solver measured, or the+ # piece would not fill the quad it was placed in.+ solved_aspect = (quad[1][0] - quad[0][0]) / (quad[3][1] - quad[0][1])+ assert out.width / out.height == pytest.approx(solved_aspect, rel=0.01)+ # Curved projection: the corners fall outside the piece and must stay clear,+ # or they paint over whatever the piece overlaps.+ assert out.mode == "RGBA"+ alpha = out.getchannel("A")+ assert alpha.getpixel((0, 0)) == 0+ assert alpha.getpixel((out.width // 2, out.height // 2)) == 255+++def test_apply_warp_is_resolution_independent():+ """The params are fractions, so a full-res re-derivation is the same shape."""+ views = _pan([-20, 0, 20])+ solved = stitch.solve_rotation_layout(views, width=1200, height=600)+ params = solved["remaps"][1]++ small = stitch.apply_warp(views[1], params)+ large = stitch.apply_warp(views[1].resize((views[1].width * 3, views[1].height * 3)), params)++ assert large.width / large.height == pytest.approx(small.width / small.height, rel=0.01)+ assert large.width / small.width == pytest.approx(3.0, rel=0.02)+++def test_apply_warp_applies_the_exposure_gain():+ views = _pan([-20, 0, 20])+ params = dict(stitch.solve_rotation_layout(views, width=1200, height=600)["remaps"][0])+ params["gain"] = 0.5++ plain = stitch.apply_warp(views[0], {**params, "gain": 1.0}).convert("RGB")+ dim = stitch.apply_warp(views[0], params).convert("RGB")++ assert _mean(dim) == pytest.approx(_mean(plain) * 0.5, rel=0.02)+++def test_apply_warp_rejects_an_unknown_warp():+ with pytest.raises(ValueError, match="unknown panorama warp"):+ stitch.apply_warp(_scene(width=100, height=100), {"warp": "toroidal"})+++def _mean(img):+ import numpy as np++ return float(np.asarray(img).mean())diff --git a/tests/test_tiles.py b/tests/test_tiles.pyindex 9479f79..d70c3ab 100644--- a/tests/test_tiles.py+++ b/tests/test_tiles.py@@ -221,6 +221,178 @@ def test_all_providers_adds_google_when_keyed(monkeypatch, tmp_path):assert google.tile_size == 1024 # hi-DPI 4x session (1/16th the billed requests)+def test_all_providers_adds_sentinelhub_when_keyed(monkeypatch, tmp_path):+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))+ config.save_settings({**config.DEFAULT_SETTINGS, "api_keys": {"sentinelhub": "inst-uuid"}})+ s2 = next(p for p in tiles.all_providers() if p.id == "sentinel2")+ assert "inst-uuid" in s2.url+ assert "{key}" not in s2.url # the instance id is the whole credential+ assert "TIME=" not in s2.url # omitted: the layer's own default window applies+ assert s2.capturable is True+ assert s2.cacheable is True # open data — no anti-cache clause to respect+ assert s2.attribution_burn is False+ assert s2.session is None+ assert s2.tile_size == 512 # one 512px tile == exactly 1 processing unit+ # 10 m/px native: requests stop at z14 (deeper is upsampling we'd pay for),+ # the view runs to z18 on magnified native tiles — free, since nothing new+ # is fetched+ assert s2.max_native_zoom == 14+ assert s2.max_zoom == 18+ # its own eco threshold: the global z15 sits above its native ceiling, so+ # sharing it would swap Sentinel-2 away at most zooms it can actually serve+ assert s2.eco_max_zoom == 11+++def test_sentinelhub_names_its_zoom_level_by_resolution(monkeypatch, tmp_path):+ """WMTS numbers 512px levels by resolution where Mapbox numbers them by grid+ width: tile indices valid at grid level 13 belong to TILEMATRIX=14."""+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))+ config.save_settings({**config.DEFAULT_SETTINGS, "api_keys": {"sentinelhub": "inst-uuid"}})+ s2 = next(p for p in tiles.all_providers() if p.id == "sentinel2")+ url = tiles.tile_url(s2.url, 13, 4151, 2818, s2.zoom_offset)+ assert "TILEMATRIX=14" in url+ assert "TILECOL=4151" in url and "TILEROW=2818" in url+++def _sentinel(monkeypatch, tmp_path):+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))+ config.save_settings({**config.DEFAULT_SETTINGS, "api_keys": {"sentinelhub": "inst-uuid"}})+ return next(p for p in tiles.all_providers() if p.id == "sentinel2")+++def test_get_provider_resolves_a_sentinel_variant(monkeypatch, tmp_path):+ _sentinel(monkeypatch, tmp_path)+ p = tiles.get_provider("sentinel2~SWIR~2026-05-01~2026-05-31")+ assert "LAYER=SWIR" in p.url+ assert "TIME=2026-05-01/2026-05-31" in p.url+ assert "inst-uuid" in p.url # the credential survives the rebuild+ assert "{key}" not in p.url+ # the id is the variant, so the disk cache keys on it: two windows can never+ # collide in the cache, which is the trap docs/IMAGERY_PROVIDERS.md names+ assert p.id == "sentinel2~SWIR~2026-05-01~2026-05-31"+ assert p.meter == "sentinelhub" # still the same quota+ assert p.max_native_zoom == 14 and p.max_zoom == 18+ assert "SWIR" in p.label and "2026-05-01" in p.label+++def test_get_provider_variant_without_a_window_keeps_the_default_time(monkeypatch, tmp_path):+ _sentinel(monkeypatch, tmp_path)+ p = tiles.get_provider("sentinel2~FALSE_COLOR")+ assert "LAYER=FALSE_COLOR" in p.url+ assert "TIME=" not in p.url+++def test_get_provider_refuses_a_malformed_variant(monkeypatch, tmp_path):+ _sentinel(monkeypatch, tmp_path)+ for bad in ("sentinel2~../etc", "sentinel2~SWIR~2026-99-01~2026-05-31", "sentinel2~a b"):+ with pytest.raises(KeyError):+ tiles.get_provider(bad)+++def test_get_provider_refuses_variants_on_providers_that_have_none(monkeypatch, tmp_path):+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))+ config.save_settings(config.DEFAULT_SETTINGS)+ with pytest.raises(KeyError):+ tiles.get_provider("esri-world-imagery~SWIR")+++def test_fetch_crop_past_native_zoom_magnifies_instead_of_paying(monkeypatch, tmp_path):+ """Sentinel-2 views run to z18 but its pixels stop at z14: the deepest real+ tiles are fetched and magnified. Asking Sentinel Hub for z18 would buy its+ upsampling of the same pixels, 16× the tiles, every one billed."""+ provider = _sentinel(monkeypatch, tmp_path)+ urls = []++ def fetch(client, url):+ urls.append(url)+ return Image.new("RGB", (512, 512), (10, 120, 10))++ img, prov = tiles.fetch_crop(+ 48.8584, 2.2945, 18, 512, 512, provider, marker_style="none", fetch_tile=fetch+ )+ # every request is at the native level (grid 13 → TILEMATRIX 14), none deeper+ assert urls and all("TILEMATRIX=14" in u for u in urls)+ # one native tile now covers 16× the canvas, so a 512px crop needs 1–4 of+ # them — not the 16× more a real z18 grid would have cost+ assert len(urls) <= 4+ assert config.load_settings()["usage"]["sentinelhub"][config.month_key()] == len(urls)+ assert img.size == (512, 512)+ # the canvas is fully covered — the magnified grid must still tile seamlessly+ for xy in ((0, 0), (511, 0), (0, 511), (511, 511), (256, 256)):+ assert img.getpixel(xy) == (10, 120, 10)+ # provenance tells the truth twice: the view is z18, the pixels are z14+ assert prov["zoom"] == 18+ assert prov["native_zoom"] == 14+ assert prov["upscaled"] is True+ assert prov["native_meters_per_pixel"] > prov["meters_per_pixel"]+++def test_fetch_crop_at_native_zoom_is_not_marked_upscaled(monkeypatch, tmp_path):+ provider = _sentinel(monkeypatch, tmp_path)++ def fetch(client, url):+ return Image.new("RGB", (512, 512), (10, 120, 10))++ _, prov = tiles.fetch_crop(+ 48.8584, 2.2945, 14, 512, 512, provider, marker_style="none", fetch_tile=fetch+ )+ assert prov["zoom"] == 14 and prov["native_zoom"] == 14+ assert prov["upscaled"] is False+ assert prov["native_meters_per_pixel"] == prov["meters_per_pixel"]+++def test_fetch_crop_of_a_variant_requests_that_layer_and_window(monkeypatch, tmp_path):+ _sentinel(monkeypatch, tmp_path)+ provider = tiles.get_provider("sentinel2~SWIR~2026-05-01~2026-05-31")+ urls = []++ def fetch(client, url):+ urls.append(url)+ return Image.new("RGB", (512, 512), (10, 120, 10))++ _, prov = tiles.fetch_crop(+ 48.8584, 2.2945, 14, 512, 512, provider, marker_style="none", fetch_tile=fetch+ )+ assert all("LAYER=SWIR" in u and "TIME=2026-05-01/2026-05-31" in u for u in urls)+ # a reader of this capture can tell which layer and which window it is+ assert prov["provider"] == "sentinel2~SWIR~2026-05-01~2026-05-31"+ assert "SWIR" in prov["provider_label"]+++def test_tile_url_leaves_zoom_alone_without_an_offset():+ url = tiles.tile_url("https://x/{z}/{x}/{y}.png", 7, 1, 2)+ assert url == "https://x/7/1/2.png"+++def test_all_providers_adds_google_js_widget_when_keyed(monkeypatch, tmp_path):+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))+ config.save_settings({**config.DEFAULT_SETTINGS, "api_keys": {"google_js": "AIza.js"}})+ widget = next(p for p in tiles.all_providers() if p.id == "google-js")+ assert "AIza.js" in widget.url # the JS loader URL — client-side by design+ assert widget.widget == "google-maps-js"+ assert widget.capturable is False # nothing to stitch — screenshots only+ assert widget.cacheable is False+ assert widget.meter == "google_js" # counts map loads, not tiles+ assert widget.eco_max_zoom == 0 # eco would re-bill a load per swap+++def test_all_providers_benches_a_key_that_failed_auth(monkeypatch, tmp_path):+ """A basemap whose key was last seen failing (EEA block, revoked key) is+ withheld from the selector until the key changes or a test passes."""+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))+ config.save_settings({+ **config.DEFAULT_SETTINGS,+ "api_keys": {"google": "AIza.x", "mapbox": "pk.y"},+ "provider_status": {"google": {"ok": False, "detail": "EEA policy", "at": "now"}},+ })+ ids = {p.id for p in tiles.all_providers()}+ assert "google-satellite" not in ids # benched+ assert "mapbox-satellite" in ids # untouched+ # a passing verdict puts it back+ config.record_provider_status("google", True, "session token created")+ assert "google-satellite" in {p.id for p in tiles.all_providers()}++def test_all_providers_respects_enable_toggles(monkeypatch, tmp_path):monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))config.save_settings({