The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.
JavaScript
v0.1.1: Satellite cost controls, free-layout proofs, collage blocks (#9)
OsintMeThat79f4336067b5
diff --git a/README.md b/README.mdindex 66c1fed..6aed8a1 100644--- a/README.md+++ b/README.md@@ -21,12 +21,27 @@ workbench: fix a direction, fix a location.*| **Media Library** | Import local files or download by URL (X, Telegram, TikTok, YouTube, Instagram… via yt-dlp, with a gallery-dl fallback for image-only posts) → clean local file + metadata + SHA-256. Multi-photo posts open a picker. || **Inspect** | Scratch workspace over any photo/video: frame adjustments, editable crop, sharpest-frame capture, hand-made collage with per-piece warp/scale/rotate — nothing enters the case until you save. || **Satellite** | Coordinates or place name → imagery crop, with select-area capture, map rotation, measurement tools, and reference-image overlays. Esri/OSM by default; add your own Mapbox/Google key for more basemaps (stored locally, never shared). |-| **Proof Composer** | Compose panels side by side, annotate with colored shapes and text (same color = same feature), reorderable legend → export `proof.png` + a re-editable spec. |+| **Proof Composer** | Compose panels in a grid or free layout, annotate with colored shapes and text (same color = same feature), reorderable legend → export `proof.png` + a re-editable spec. || **Post Composer** | Turn a proof into a publishable thread: coordinates in all formats, plus code, attribution, character count, RTL-safe text. Copy-paste ready — Azimut never posts for you. |Every tool works **one-shot** (no setup, scratch session) or inside a **case**— a plain directory holding the whole investigation.+**New in v0.1.1** — a polish pass over the v1 tools:++- **Satellite** — OSM labels overlay, true browser fullscreen, Esri overzoom+ (upscales past World Imagery's last level instead of a "not available" tile),+ and imagery acquisition dates surfaced on the map and in captures.+- **Keyed providers** — a Settings tab for Mapbox/Google keys with per-provider+ toggles, monthly usage counters, a soft block at 90% of the free tier, an eco+ mode that falls back to free imagery when zoomed out, and a disk tile cache.+ Free by default: keys stay optional and local.+- **Proof Composer** — free layout mode (drag panels anywhere, overlap with+ z-order), corner-drag panel resize, and satellite panels that auto-caption+ with provider · coordinates · imagery date.+- **Inspect** — shift-click a block of collage pieces to move, scale and rotate+ them as one.+## Install & run```bashdiff --git a/docs/IMAGERY_PROVIDERS.md b/docs/IMAGERY_PROVIDERS.mdnew file mode 100644index 0000000..abdb981--- /dev/null+++ b/docs/IMAGERY_PROVIDERS.md@@ -0,0 +1,81 @@+# Keyed imagery providers — Mapbox & Google++> Azimut ships two optional user-keyed basemaps alongside the key-less defaults+> (Esri, OSM). 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).+>+> Implemented in [`engine/tiles.py`](../src/azimut/engine/tiles.py),+> [`engine/google_tiles.py`](../src/azimut/engine/google_tiles.py),+> [`engine/tilecache.py`](../src/azimut/engine/tilecache.py) and+> [`api/settings.py`](../src/azimut/api/settings.py).++## Legal rules (decided — do not relax)++| Rule | Why |+|------|-----|+| Keys are **user-supplied**, stored **locally**, **never** bundled into a shared case/zip. | Principle 7; keys are the user's own billing identity. |+| Core features never require a key. Key-less providers (Esri, OSM) stay the default. | Principle 7. |+| **Never** ship/suggest/document unofficial endpoints (`mt1.google.com`, `khms*`, …). Only official APIs. | Legal-only policy. |+| **Google tiles must NOT be cached to disk.** | Google's Map Tiles API forbids pre-fetch/store/cache/offline use of tiles ([policies](https://developers.google.com/maps/documentation/tile/policies)). |+| A Google **capture** is allowed only as a **flattened, attributed screenshot** (single PNG, attribution burned in) — never a store of raw tiles. | Google Geo Guidelines permit screenshots in reports/periodicals ≤5,000 copies **with attribution**; the anti-cache clause forbids tile hoarding. Two different acts. |+| Every capture keeps provider **attribution** (Google/Mapbox + data providers, e.g. Maxar) unmodified. For Google it is **burned into the image footer**. | Attribution is a condition of the allowed use, not a courtesy. |++### Per-provider capability matrix++| Provider | `needs_key` | auth style | `capturable` | `cacheable` (tile disk cache) | attribution source |+|----------|:-----------:|------------|:------------:|:-----------------------------:|--------------------|+| Esri World Imagery | no | — | yes | yes | static string |+| OpenStreetMap | no | — | yes | yes | static string |+| **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 |++¹ Display + static-image capture with attribution is permitted; plan-level+caching/redistribution limits vary, so the cache stays modest (30-day TTL) and+attribution always on.++## Google is not a static `{key}` URL++It needs a session token, minted and refreshed transparently before the rest of the+pipeline sees a normal XYZ template:++1. `POST https://tile.googleapis.com/v1/createSession?key={API_KEY}` →+ `{"session":"<token>","expiry":"<unix>",…}`. Session params (mapType) are part+ of the token identity.+2. Tiles: `GET https://tile.googleapis.com/v1/2dtiles/{z}/{x}/{y}?session={token}&key={API_KEY}`+3. Refresh on expiry or on 401/403.+4. Attribution: `GET https://tile.googleapis.com/tile/v1/viewport?session={token}&key={API_KEY}&zoom={z}&north=&south=&east=&west=`+ → `copyright` (e.g. `"Map data ©2026 Google, Maxar Technologies"`). Never reduced+ to just "Google".++The **token** may be cached; tiles may not.++## Measured findings (2026-07)++**Tile sizes.** Mapbox serves **512px** tiles: it bills 256px tiles 4× vs 512px for+the same ground area at the same m/px. Google serves **1024px hi-DPI** tiles+(`scale=scaleFactor4x, highDpi=true`): it bills per *request* regardless of tile+size, so one request covers sixteen 256px tiles' worth of ground at the same m/px —+verified pixel-identical. Mapbox's `@2x` equivalent is *upsampled* (softer), which+is why Mapbox stays at 512.++**Oversampling.** The live map oversamples Google 2× (1024px tiles in 512px cells,+one zoom deeper) because Google's mid-zoom mosaics are verifiably softer than its+deep ones — net ¼ the cost of plain 256px tiles. The z17 view alone boosts to 4×+(z19 detail): the z18 mosaic it would otherwise show is often an older/hazier+collection than the z19+ aerial. Captures stay 1:1 provider pixels — no resampling+in evidence imagery.++**Billing units.** Both bill **per tile served** — Google's 2D Map Tiles SKU is+"Request that returns a 2D map tile" (session and viewport requests are free);+Mapbox Static Tiles bills per tile request when used with Leaflet. Free tiers:+Google 100k/month then $0.60/1k (plus hard limits of 15k tiles/day and 6k/min per+project), Mapbox 200k/month then $0.50/1k (no hard cap — alerts only). Metered+tiles are proxied through the backend so the counter matches billing exactly;+browser cache hits never re-count.++## Deliberately not basemaps++Street View and Google Photorealistic 3D Tiles are keyed Google products but not+tile providers — a ground-imagery tool and a 3D scene respectively. They live in the+SPEC backlog, not here.diff --git a/docs/KEYED_PROVIDERS.md b/docs/KEYED_PROVIDERS.mddeleted file mode 100644index 15e75d7..0000000--- a/docs/KEYED_PROVIDERS.md+++ /dev/null@@ -1,174 +0,0 @@-# Keyed imagery providers — Mapbox & Google (implementation brief)--> Build spec for a future agent. Goal: let a user add their **own** Mapbox and-> Google Maps Platform API keys in-app, then select **Mapbox Satellite** and-> **Google Satellite** as basemaps in the Satellite tab — with every existing tool-> (rotate, measure, capture, reference windows) working over them exactly like Esri.->-> Read alongside SPEC.md §6 "v1 notes → Tile providers" (legal-only policy) and the-> tile engine [`src/azimut/engine/tiles.py`](../src/azimut/engine/tiles.py).--## 0. Non-negotiable legal rules (decided — do not relax)--These come from Google's and Mapbox's terms; they drive the whole design.--| Rule | Why |-|------|-----|-| Keys are **user-supplied**, stored **locally**, **never** bundled into a shared case/zip. | Principle 7; keys are the user's own billing identity. |-| Core features never require a key. Key-less providers (Esri, OSM) stay the default. | Principle 7. |-| **Never** ship/suggest/document unofficial endpoints (`mt1.google.com`, `khms*`, …). Only official APIs. | Existing legal-only policy. |-| **Google tiles must NOT be cached to disk.** Google's Map Tiles API forbids pre-fetch/store/cache/offline use of tiles. | [Map Tiles API Policies](https://developers.google.com/maps/documentation/tile/policies). |-| A Google **capture** is allowed only as a **flattened, attributed screenshot** (single PNG, attribution burned in). It must never be a store of raw tiles. | Google Geo Guidelines permit screenshots in reports/periodicals ≤5,000 copies **with attribution**; the anti-cache clause forbids tile hoarding. The two are different acts. |-| Every capture keeps provider **attribution** (Google/Mapbox + data providers, e.g. Maxar) unmodified. For Google it is **burned into the image footer** (non-optional). | Attribution is a condition of the allowed use, not a courtesy. |--### Per-provider capability matrix (the model to encode)--| Provider | `needs_key` | auth style | `capturable` | `cacheable` (tile disk cache) | attribution source |-|----------|:-----------:|------------|:------------:|:-----------------------------:|--------------------|-| Esri World Imagery | no | — | yes | yes | static string (current) |-| OpenStreetMap | no | — | yes | yes | static string (current) |-| **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 |--¹ Mapbox: display + static-image capture with attribution is permitted; verify the-user's plan-level caching/redistribution limits before enabling an aggressive-persistent cache. Default to a modest cache, attribution always on.--## 1. Data model — `settings.json`--Extend `DEFAULT_SETTINGS` in [`src/azimut/config.py`](../src/azimut/config.py). `api_keys`-already exists; add first-class keyed providers and usage counters so the user-doesn't hand-write XYZ templates.--```jsonc-{- "api_keys": {- "mapbox": "pk.....", // Mapbox public access token- "google": "AIza...." // Google Maps Platform API key- },- "tile_providers": [ /* still supported for custom/self-hosted XYZ */ ],- "usage": { // per-provider monthly counters (§6)- "google": { "2026-07": 1234 },- "mapbox": { "2026-07": 87 }- }-}-```--Keep back-compat: a user with only `api_keys.mapbox`/`google` set gets the built-in-keyed providers below automatically — no `tile_providers` entry needed.--## 2. Provider model — `tiles.py`--Extend the `Provider` dataclass with the capability flags and an optional-session-token hook:--```python-@dataclass(frozen=True)-class Provider:- # ...existing fields...- capturable: bool = True # may a saved capture be filed from it?- cacheable: bool = True # may its tiles be written to a disk cache?- attribution_burn: bool = False # force attribution stamped into the image- session: str | None = None # provider kind needing a token: "google"-```--`all_providers()` gains the built-in keyed providers when the matching key is-present in `api_keys`:--- **Mapbox Satellite** — `capturable=True, cacheable=True`- URL: `https://api.mapbox.com/styles/v1/mapbox/satellite-v9/tiles/512/{z}/{x}/{y}?access_token={key}`- (`satellite-streets-v12` for a labelled variant; `max_zoom=22`, `imagery=True`).- **512px tiles, not 256**: Mapbox bills 256px tiles 4× vs 512px for the same- ground area at the same m/px (one 512 tile at z-1 = four 256 tiles at z).-- **Google Satellite** — `capturable=True, cacheable=False, attribution_burn=True, session="google"`, `imagery=True`, `max_zoom=22`. URL template resolved at fetch time (needs a live session token, see §3).--`fetch_crop` / the frontend tile layer must:-- refuse to build a saved capture when `provider.capturable is False` (none today, but the flag must gate the code path);-- skip the disk cache entirely when `provider.cacheable is False`;-- stamp attribution into the footer when `attribution_burn is True` (route it into the existing Proof Composer/capture footer, and ensure the Satellite capture PNG itself carries it).--## 3. Google Map Tiles API — session-token adapter--Google is **not** a static `{key}` URL. Add a small adapter (e.g.-`src/azimut/engine/google_tiles.py`) that mints and caches a session token, then-hands the rest of the pipeline a normal XYZ template.--1. **Create session** (once, cache it):- `POST https://tile.googleapis.com/v1/createSession?key={API_KEY}`- body: `{"mapType":"satellite","language":"en-US","region":"US"}`- → `{"session":"<token>","expiry":"<unix>","tileWidth":256,"tileHeight":256,"imageFormat":"jpeg"}`-2. **Tiles** (standard slippy XYZ):- `GET https://tile.googleapis.com/v1/2dtiles/{z}/{x}/{y}?session={token}&key={API_KEY}`-3. **Refresh** the token when `expiry` passes (or on 401/403), transparently.-4. **Attribution**: fetch the viewport copyright string and display/burn it:- `GET https://tile.googleapis.com/tile/v1/viewport?session={token}&key={API_KEY}&zoom={z}&north=&south=&east=&west=`- → `copyright` field (e.g. `"Map data ©2026 Google, Maxar Technologies"`). Do not- reduce it to just "Google".-5. Cache the token in memory (and optionally a short-lived on-disk token file — the- **token**, never tiles). Session params (mapType) are part of the token identity.--Both the live Leaflet layer and backend `fetch_crop` consume the resolved URL from-step 2 — so once the token exists, Google behaves like any XYZ provider and all-tools work unchanged.--## 4. Frontend — API keys settings tab--New settings/options page (SPEC §7 "Settings & secrets"). Minimal:--- Fields: **Mapbox token**, **Google Maps Platform key** — saved to `api_keys`.- Password-style inputs, "how to get one" help links, per-key **test** button- (Mapbox: fetch one tile; Google: `createSession`).-- Keys are app-wide (not per-case). Never written into a case folder or export bundle.-- On save, the keyed providers appear in the Satellite basemap selector automatically.--### Basemap selector behaviour (Satellite tab)--- The bottom-of-map basemap picker lists all `all_providers()`, keyed ones included.-- When the selected provider has `capturable=False`, **disable the capture button**- with a tooltip ("view-only basemap"). (No built-in provider is view-only today,- but wire the gate now.)-- Google + Mapbox render in the live Leaflet map via `L.tileLayer(resolvedUrl)`;- keep the existing rotate/measure/reference-window behaviour untouched.--## 5. Tile disk cache (respect `cacheable`)--If/when a disk tile cache lands (SPEC §9 open question):-- Cache tiles **only** for `cacheable=True` providers (Esri, OSM, Mapbox).-- **Never** cache Google tiles — re-fetch each time; lean on the monthly counter to- stay in free tier. Honour any `Cache-Control` headers Google returns.--## 6. Monthly usage counter--SPEC §7 already promises per-provider monthly counters. Implement here because-keyed providers are billed:--- Increment `usage.<provider>.<YYYY-MM>` per outbound tile request (Google, Mapbox).-- Surface a small readout in the settings tab and near the basemap selector- ("Google: 12,430 tiles this month").-- Optional soft cap: warn / block new fetches when a user-set monthly limit is hit- (protects the free tier; for Google it also limits exposure).-- Counting is local bookkeeping only — no telemetry (principle 1).-- Billing units verified (2026-07): both bill **per tile served** — Google 2D Map- Tiles SKU = "Request that returns a 2D map tile" (sessions are free), Mapbox- Static Tiles = per tile request when used with Leaflet. Free tiers: Google- 100k/month, Mapbox 200k/month. Metered tiles are proxied through the backend- so the counter matches billing exactly (browser cache hits never re-count).--## 7. Tests (required — repo rule)--- `tiles.py`: keyed providers appear in `all_providers()` only when their key is- present; `capturable`/`cacheable` flags parsed and defaulted correctly.-- `google_tiles.py`: session token minted, cached, and refreshed on expiry- (mock the HTTP calls — no real network); viewport copyright parsed.-- Capture path: `capturable=False` blocks a saved capture; `attribution_burn=True`- stamps the footer; `cacheable=False` bypasses the cache.-- Usage counter increments per month key and rolls over correctly.-- Back-compat: existing Esri/OSM capture tests stay green.--## 8. Out of scope (future, separate specs)--- **Street View** (Google Street View Static API) — a distinct ground-imagery tool,- not a basemap; already sketched in SPEC §v2 "Ground Imagery".-- **Google Photorealistic 3D Tiles** — needs a WebGL engine (MapLibre/Cesium), lands- only after the MapLibre migration (SPEC §7); a 3D scene, not a flat capture.-- **Mapillary**\ No newline at end of filediff --git a/docs/SPEC.md b/docs/SPEC.mdindex 4736622..2b92be7 100644--- a/docs/SPEC.md+++ b/docs/SPEC.md@@ -142,6 +142,10 @@ Phasing rule: each version must deliver **one complete workflow people will usedaily**, not a spread of half-tools. The case workspace and entity schema underpinall of them from day one.+Placement rule: where a tool lives on screen is set by the **workspace model**+in [UI.md](UI.md) — new tools land as tabs/modes inside an existing workspace+(Collect / Examine / Map / Compose / Case), never as new rail entries.+### v1 — Proof Studio (media → annotated proof → publishable post)The workflow nothing else provides end-to-end, and the GeoConfirmed daily gesture:@@ -150,9 +154,9 @@ 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, 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. **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 = later. **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**, **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 (↑↓ per panel) so the composite stays near-square instead of a wide bandeau. Each panel can be **resized** (± per panel, 40–250%) — its drawn elements scale with it, and shorter panels bottom-align in their row. 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** except satellite crops). 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** and an **editable footer** (blank = automatic imagery/source attribution). Feature legend (color dot only, numbered in the Annotations tab for reference); export `proof.png` + re-editable JSON spec (`notes`/`legendOrder` per color, panel `row`/`scale`, `coords`/`coordsText`, `source`, `caption/legend/footerSize`, `footer`) saved in `proofs/`. |+| ✅ **Inspect** | A scratch workspace over any photo/video — **nothing enters the case until Save**. **Selection** (video): scrub, step, scan *sharpest* frames, 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 = later. **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** and an **editable footer** (blank = automatic imagery/source attribution). 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`) saved in `proofs/`. || ✅ **Post Composer** | Build a GeoConfirmed-style thread from a proof. Tweet 1 = `Place - Plus code`, description, decimal coordinates (6 digits), `@GeoConfirmed` mention, 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. || ✅ **Case sidebar** | Always visible, three sections. **Case Notes** (`notes.md`). **Saved work** — every artifact, auto-grouped by the tool that produced it (Media Library / Inspect / Satellite / Proof Composer / Post Composer, from `provenance.by`); suggested entities pinned on top to confirm/dismiss; deleting here removes the item **everywhere** (drops its file — danger confirm). **My work** — the analyst's own **nested folders** (`/`-separated, e.g. `Sources/Telegram`), empty until you **drag** items in from Saved work; an item filed here stays in Saved work too (lives in both); deleting here only **unfiles** it (light confirm), and removing a folder cascades its subtree back to Saved work. Styled confirm dialogs, not browser popups. Create/open/promote/**rename**/**delete** cases from the switcher — names must be **unique** (case-insensitive, enforced on create/rename/promote); delete wipes the **whole case folder** and everything in it, gated behind typing `DELETE` in uppercase. |@@ -193,7 +197,7 @@ v1 notes:| Tab | What it does ||-----|--------------|-| **Frame Extractor** | *Shipped early inside **Inspect** (§ v1)* — video scrubber, sharpest-frame suggestions, one-click capture into the case and composer. |+| ✅ **Frame Extractor** | *Shipped early inside **Inspect** (§ v1)* — video scrubber, sharpest-frame suggestions, one-click capture into the case and composer. || **Satellite Compare** | Same coordinates across providers (Esri / Sentinel-2 with date slider / Bing / user-keyed providers), synchronized pan/zoom — imagery history and provider comparison. Builds on the v1 tile abstraction. || **Image Compare** | Overlay two images with opacity/swipe slider + pixel difference — frame vs satellite, or two imagery dates. || **Coordinates** | Convert DMS/decimal/MGRS/plus code/geohash; reverse geocode (Nominatim); quick-open links to Google Maps/Yandex/Bing/OSM. |@@ -233,7 +237,10 @@ 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), OSM context, user-keyed Bing (grows Satellite Compare). ✅ User-keyed **Mapbox & Google** basemaps + API-keys settings tab + monthly usage counters are speced in [KEYED_PROVIDERS.md](KEYED_PROVIDERS.md) (with the per-provider capture/cache legal rules).+- **More satellite basemaps** — Sentinel-2 (date slider), user-keyed Bing (grows Satellite Compare). **OSM context** ✅. 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`).+- **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).- **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.@@ -242,6 +249,7 @@ it stops making sense. One line each.**Toward v3 (investigation layer):**- **Archive-on-download** — optional Wayback push on URL import, archive URL into provenance (early Evidence Locker slice).+- **Extension for saving a web page** — web extension for saving a web page.- **Case bundle export/import** — one-click **.zip** of the whole case a recipient opens in their own workbench; a zip, not a hosted link (principle 1).- **Proof Composer free overlay layer** — **image as a first-class free element** (paste/drop, move/resize, floats or anchors to a panel) — must survive magic tweet-fit; carries the imported-screenshot source field (principle 6).- **Callout / detail inset** — image-as-element wired to a circled feature by a color-matched arrow; optional **smart connector** that reflows when either end moves.@@ -254,6 +262,7 @@ it stops making sense. One line each.**After the MapLibre migration (§7):**- **3D satellite capture** — pitch/terrain + oblique capture, pitch recorded in provenance.+- **Google Photorealistic 3D Tiles** — user-keyed 3D mesh basemap; needs a WebGL engine, and a 3D scene is not a flat capture.**Unscheduled / undecided:**- **Free-form montage editor** — likely unneeded once the free overlay layer lands; only with a crisp boundary vs Proof Composer + Inspect collage (risk = paint-app scope-creep).@@ -291,6 +300,10 @@ it stops making sense. One line each.**monthly usage counters** so a user tracks a keyed quota (Street View, Googleimagery, …) before hitting it. Core features never require a key (principle 7);key-less providers are always the default.+- **UI direction & workspaces**: the rail holds a fixed set of workspaces in+ investigation-pipeline order; tools are tabs/modes inside them; visual+ language is the sober "pro desk" (dense, flat, one accent), not the AI+ dashboard — direction, tables and rollout in [UI.md](UI.md).- **Tool navigation & derivation chain**: cleaner switching between tools, withlinked tools surfacing their **derivation chain** (this proof ← this frame ←this video ← this download) as breadcrumbs — the case's connections made@@ -330,9 +343,10 @@ it stops making sense. One line each.semantics, confidence levels — draft during M0, freeze at v1 release.- Proof spec JSON format: design fresh at M3 (the old compose_proof format is areference, not a constraint).-- Tile providers: which providers ship as presets beyond Esri (Sentinel-2 via a- key-less WMTS? OSM for street context?); tile caching policy (cache under the- case for reproducibility vs a shared cache).+- **Decided: OSM ships for street context, and the tile cache is shared, not+ per-case** ✅ (30-day TTL under the workspace, never Google — see+ [IMAGERY_PROVIDERS.md](IMAGERY_PROVIDERS.md)). Sentinel-2 via a key-less WMTS+ stays open.- One-shot scratch cases: where do they live, when are they cleaned up, what does"promote to case" look like?- Déjà Vu community index: needs infra + moderation; out of scope until v4.diff --git a/docs/UI.md b/docs/UI.mdnew file mode 100644index 0000000..e13c4fc--- /dev/null+++ b/docs/UI.md@@ -0,0 +1,92 @@+# Azimut — UI direction & information architecture++Status: **direction v1** (2026-07-15). Companion to [SPEC.md](SPEC.md) §6–7 — the+spec says *what* tools exist; this doc says *where they live on screen* and *what+they look like*. Nothing here is implemented yet; rollout order at the bottom.++## 1. The two problems++1. **Look & feel**: the current skin is the generic "AI dashboard" — navy-blue+ dark theme, glowing accents, display font, rounded floating cards, marketing+ copy in the chrome. It undermines trust in a tool for evidence work.+2. **Scale**: a flat left rail works at 5 tools. The spec promises ~20 more+ (v2–v4). A flat rail of 25 entries is the GIMP-toolbox failure mode: tools+ mixed together, no visible order, nobody knows where to click next.++## 2. Design direction — the "pro desk" look++Reference points our users already trust: QGIS, Google Earth Pro, DaVinci+Resolve, Lightroom, Obsidian. Dense, flat, sober instruments — not SaaS+landing pages. Everything is tokenized in `frontend/src/app.css`, so this is a+token + shared-primitives pass, not a rewrite.++| Element | Today (AI tell) | Target |+|---|---|---|+| Font | Oxanium display, uppercase, 0.22em tracking | One workhorse UI font everywhere (system stack or Inter); mono for data (coords, hashes — already good, keep) |+| Palette | Blue-tinted navy + amber + glows | Neutral gray dark theme; **one** accent reserved for selection & the primary action only; no glow, ever |+| Shape | 6/10/14px radii, floating cards, pill badges | 2–4px radii, flat panels with visible splitters, rectangular badges |+| Density | Card grids, generous padding | Dense rows, tighter spacing, list + grid toggle where cards exist |+| Type hierarchy | Everything 600, uppercase micro-labels | Few weights; hierarchy by size and placement, not boldness |+| Motion | fade-up, hover lifts | None — instant state changes |+| Copy | Tagline in topbar, instructional italics in panels | No slogans in chrome (tagline → README/About); affordances discoverable, not explained in prose |+| Rail | 76px icon-above-label buttons (mobile pattern) | Compact workspace rail, tooltips (see §3) |++## 3. Information architecture — workspaces, not a tool list++**Principle: the rail holds a fixed, small set of *workspaces* named by+activity, in investigation-pipeline order. Tools ship as tabs/modes *inside*+a workspace — never as new rail entries.** (DaVinci Resolve "pages" model:+few pages in workflow order, media pool persistent across all of them.)++The spec has already been converging on this organically — Frame Extractor and+Panorama folded into Inspect, ELA into its Analyze fold-out, Reverse Search+into Media Library, reference viewers into Satellite. This formalizes it.++| Workspace | Today | Future tools land here as tabs/modes |+|---|---|---|+| **Collect** | Media Library (import, URL download) | Reverse Search launcher, Channel Monitor, Evidence Locker, archive-on-download |+| **Examine** | Inspect (Selection / Frame / Collage / Analyze) | EXIF & Metadata, OCR, Image Compare, Manipulation Hints, Shadow Clock, audio analysis, auto-panorama |+| **Map** | Satellite | **One persistent map, many modes**: Capture, Satellite Compare, Ground Imagery, Coordinates, Measures, Viewshed, OSM Query, Map Board pins/layers |+| **Compose** | Proof Composer, Post Composer | Report Builder, GIF maker |+| **Case** | (sidebar only) | Notes, Case Board / Relations, Timeline, Search Orchestrator |++Rules that keep it sane:++- **Max two levels.** Workspace → tab. Never deeper. Preserves SPEC principle 3+ ("one tool, useful in 30 seconds").+- **One Map.** Eight of the planned tools are "the map + a mode or layer".+ They are modes of a single map workspace (Google Earth model), sharing+ center/zoom/provider state — never separate rail entries.+- **One media viewer.** The Examine analyzers are panels over the currently+ open media, like Analyze already is.+- **Deep links target tabs** (`#map/capture`, `#examine/exif`), extending the+ existing `#satellite`-style scheme.+- **Command palette (Ctrl+K)** — "capture satellite", "open EXIF" — the+ escape hatch that keeps 20+ tools one keystroke away.+- **Navigation follows the object too**: from any media — "Examine", "Locate+ on map", "Add to proof"; the derivation-chain breadcrumb (SPEC §7) is the+ connective tissue. The rail is for starting; objects are for continuing.++## 4. Sidebar consolidation++Today the same items appear in three taxonomies: Media Library facets, Saved+Work grouped by producing tool, and My Work folders. Under the workspace+model, each workspace lists its own artifacts, so the case sidebar slims to:++- **Notes** (unchanged)+- **My Work** — the analyst's folders (the only user-owned taxonomy)+- **Selection details** — provenance / derivation chain / entity editor for+ whatever is selected anywhere in the app++Saved-work-grouped-by-tool disappears as a duplicate view once each workspace+shows its own output.++## 5. Rollout++1. **Token pass** — fonts, radii, density, neutral palette, kill+ tagline/animations. No logic changes.+2. **Workspace shell** — rail → 5 workspaces with tab strips; mostly moving+ existing components (Inspect is already internally tabbed — it's the+ template). Deep links extended.+3. **Sidebar consolidation** (with or after step 2).+4. **Command palette** — once tool count justifies it.diff --git a/frontend/package.json b/frontend/package.jsonindex 5960bce..2a76e7a 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -1,7 +1,7 @@{"name": "azimut-frontend","private": true,- "version": "0.1.0",+ "version": "0.1.1","type": "module","scripts": {"dev": "vite",diff --git a/frontend/src/App.svelte b/frontend/src/App.svelteindex 9509a56..b6025f5 100644--- a/frontend/src/App.svelte+++ b/frontend/src/App.svelte@@ -115,6 +115,10 @@.topbar {height: var(--topbar-h);flex-shrink: 0;+ /* own stacking context above the tool canvas: Leaflet's panes (z-index up+ to 1000) otherwise swallow the case switcher's dropdown */+ position: relative;+ z-index: 1200;display: flex;align-items: center;gap: 16px;diff --git a/frontend/src/app.css b/frontend/src/app.cssindex b60604f..3ab2b37 100644--- a/frontend/src/app.css+++ b/frontend/src/app.css@@ -167,14 +167,17 @@ a:hover {white-space: nowrap;user-select: none;}-.btn:hover:not(:disabled) {+.btn:hover:not(:disabled, .disabled) {background: var(--bg-3);border-color: var(--border-strong);}-.btn:active:not(:disabled) {+.btn:active:not(:disabled, .disabled) {transform: translateY(1px);}-.btn:disabled {+/* an <a class="btn"> can never match :disabled — it opts out with .disabled+ instead (and drops its href, so it doesn't navigate either) */+.btn:disabled,+.btn.disabled {opacity: 0.45;cursor: not-allowed;}@@ -184,7 +187,7 @@ a:hover {border-color: transparent;color: var(--accent-text);}-.btn-primary:hover:not(:disabled) {+.btn-primary:hover:not(:disabled, .disabled) {background: var(--accent-hover);border-color: transparent;}@@ -192,7 +195,7 @@ a:hover {.btn-danger {color: var(--danger);}-.btn-danger:hover:not(:disabled) {+.btn-danger:hover:not(:disabled, .disabled) {background: var(--danger-soft);border-color: var(--danger);}@@ -202,7 +205,7 @@ a:hover {border-color: transparent;color: var(--text-2);}-.btn-ghost:hover:not(:disabled) {+.btn-ghost:hover:not(:disabled, .disabled) {background: var(--bg-2);color: var(--text-1);}diff --git a/frontend/src/components/ConfirmDialog.svelte b/frontend/src/components/ConfirmDialog.svelteindex 0e9c2a9..b6f81d6 100644--- a/frontend/src/components/ConfirmDialog.svelte+++ b/frontend/src/components/ConfirmDialog.svelte@@ -1,5 +1,6 @@<script>import Icon from './Icon.svelte';+ import { portal } from '../lib/fullscreen.js';// A small, styled confirmation dialog — replaces the browser confirm() popup.// Tone drives the accent so a destructive action reads differently from a@@ -28,6 +29,7 @@<divclass="overlay"+ use:portalonclick={(e) => e.target === e.currentTarget && oncancel?.()}role="presentation">diff --git a/frontend/src/components/Icon.svelte b/frontend/src/components/Icon.svelteindex d4cbf5a..420a55e 100644--- a/frontend/src/components/Icon.svelte+++ b/frontend/src/components/Icon.svelte@@ -32,13 +32,15 @@crosshair: 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18Zm0-1v4m0 12v4M2 12h4m12 0h4',user: 'M12 4a4 4 0 1 1 0 8 4 4 0 0 1 0-8Zm-8 17c0-4 3.6-6.5 8-6.5s8 2.5 8 6.5',layers: 'm12 3 9 5-9 5-9-5 9-5Zm-9 9.5 9 5 9-5M3 17l9 5 9-5',+ grid: 'M4 4h7v7H4V4Zm9 0h7v7h-7V4ZM4 13h7v7H4v-7Zm9 0h7v7h-7v-7Z',video: 'M4 6h11a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1Zm12 4 5-3v10l-5-3',image: 'M4 5h16a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1Zm2 12 4-4a1 1 0 0 1 1.4 0l4.6 4M9 9.5h.01',audio: 'M9 18V6l10-2v11.5M9 18a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0Zm10-2.5a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0Z',file: 'M6 3h9l5 5v13a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1Zm8 0v6h6',hash: 'M9 4 7 20M17 4l-2 16M4 9h17M3 15h17',globe: 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18Zm-9 9h18M12 3c2.5 2.5 3.8 5.7 3.8 9S14.5 18.5 12 21c-2.5-2.5-3.8-5.7-3.8-9S9.5 5.5 12 3Z',- settings: 'M12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6Zm8.4 3a8.4 8.4 0 0 0-.1-1.2l2-1.5-2-3.5-2.4 1a8.5 8.5 0 0 0-2-1.2L15.5 3h-4l-.4 2.6a8.5 8.5 0 0 0-2 1.2l-2.4-1-2 3.5 2 1.5a8.6 8.6 0 0 0 0 2.4l-2 1.5 2 3.5 2.4-1a8.5 8.5 0 0 0 2 1.2l.4 2.6h4l.4-2.6a8.5 8.5 0 0 0 2-1.2l2.4 1 2-3.5-2-1.5c.1-.4.1-.8.1-1.2Z',+ leaf: 'M6 21c0-6 2-13 14-15 0 0 1 13-9 14-2.5.3-4-.5-5 1Zm0 0c1.5-5 4-9 9-11',+ settings: 'M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2ZM12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6Z',compass: 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18Zm3.5 5.5-2 5-5 2 2-5 5-2Z',arrowRight: 'M4 12h16m0 0-6-6m6 6-6 6',edit: 'M14 5.5 18.5 10M4 20l1-4.5L16.5 4a2.1 2.1 0 0 1 3 3L8 18.5 4 20Z',diff --git a/frontend/src/components/Modal.svelte b/frontend/src/components/Modal.svelteindex cc2d2c3..9c69a8b 100644--- a/frontend/src/components/Modal.svelte+++ b/frontend/src/components/Modal.svelte@@ -1,5 +1,6 @@<script>import Icon from './Icon.svelte';+ import { portal } from '../lib/fullscreen.js';let { title, onclose, width = '440px', children } = $props();@@ -10,7 +11,12 @@<svelte:window {onkeydown} />-<div class="overlay" onclick={(e) => e.target === e.currentTarget && onclose?.()} role="presentation">+<div+ class="overlay"+ use:portal+ onclick={(e) => e.target === e.currentTarget && onclose?.()}+ role="presentation"+><div class="modal fade-up" style:width role="dialog" aria-label={title}><header><h3>{title}</h3>diff --git a/frontend/src/components/Toasts.svelte b/frontend/src/components/Toasts.svelteindex b19cb38..5007691 100644--- a/frontend/src/components/Toasts.svelte+++ b/frontend/src/components/Toasts.svelte@@ -1,11 +1,12 @@<script>import { uiState } from '../lib/state.svelte.js';import Icon from './Icon.svelte';+ import { portal } from '../lib/fullscreen.js';const icons = { info: 'compass', ok: 'check', danger: 'alert', warn: 'alert' };</script>-<div class="toasts">+<div class="toasts" use:portal>{#each uiState.toasts as t (t.id)}<div class="toast {t.kind} fade-up"><Icon name={icons[t.kind] ?? 'compass'} size={15} />diff --git a/frontend/src/lib/composer.js b/frontend/src/lib/composer.jsindex be7e524..cdaeef3 100644--- a/frontend/src/lib/composer.js+++ b/frontend/src/lib/composer.js@@ -73,16 +73,28 @@ export function panelHeight(p) {/*** Panel layout boxes in doc space: [{x, y, w, h, scale, baseScale, row}] aligned- * with the input `panels`. Panels are grouped by `row` and centred; rows stack- * top→bottom with a caption band + ROW_GAP between them. Each panel is laid out- * at PANEL_H × its own `scale`, so a row's height is its tallest panel and the- * shorter panels are bottom-aligned so their captions share one baseline.+ * with the input `panels`. In the default `grid` layout panels are grouped by+ * `row` and centred; rows stack top→bottom with a caption band + ROW_GAP between+ * them (see layoutPanelsGrid). In the `free` layout each panel sits at its own+ * stored x/y (see layoutPanelsFree) and overlap is allowed — array order is the+ * z-order, front→back (the first panel is the foreground one).** `scale` maps a panel's natural pixels → doc pixels (grows/shrinks with the* user scale); `baseScale` is that mapping at scale 1, used to keep stroke and* arrow-head sizes normalised while still letting them grow with the panel.*/-export function layoutPanels(panels, captionSize = CAPTION_SIZE) {+export function layoutPanels(panels, captionSize = CAPTION_SIZE, layout = 'grid') {+ return layout === 'free'+ ? layoutPanelsFree(panels, captionSize)+ : layoutPanelsGrid(panels, captionSize);+}++/**+ * Grid layout: each panel is laid out at PANEL_H × its own `scale`, so a row's+ * height is its tallest panel and the shorter panels are bottom-aligned so+ * their captions share one baseline.+ */+function layoutPanelsGrid(panels, captionSize = CAPTION_SIZE) {const rows = rowOrder(panels);const band = captionBand(captionSize);// width + height of each row, to centre narrower rows and stack by height@@ -123,6 +135,52 @@ export function layoutPanels(panels, captionSize = CAPTION_SIZE) {});}+/**+ * Free layout: each panel sits at its stored doc-space x/y (its size still+ * derives from PANEL_H × scale, exactly as in the grid). Positions are+ * normalised so the top/left-most panel lands at PAD — stored coordinates can+ * drift while dragging, the document always hugs its content. A panel that has+ * no position yet (just added, or a grid spec toggled to free) falls back to+ * where the grid would have put it, so nothing jumps when entering the mode.+ */+export function layoutPanelsFree(panels, captionSize = CAPTION_SIZE) {+ if (!panels.length) return [];+ const grid = layoutPanelsGrid(panels, captionSize); // fallback positions+ const pos = panels.map((p, i) => ({+ x: p.x ?? grid[i].x,+ y: p.y ?? grid[i].y,+ }));+ const dx = PAD - Math.min(...pos.map((q) => q.x));+ const dy = PAD - Math.min(...pos.map((q) => q.y));+ return panels.map((p, i) => {+ const ph = panelHeight(p);+ const scale = ph / p.natural[1];+ return {+ x: pos[i].x + dx,+ y: pos[i].y + dy,+ w: p.natural[0] * scale,+ h: ph,+ scale,+ baseScale: PANEL_H / p.natural[1],+ row: p.row ?? 0,+ };+ });+}++/**+ * Shift that re-anchors stored free positions at PAD (the normalisation+ * layoutPanelsFree applies on the fly). The caller folds it into every panel's+ * stored x/y after a drag/resize so stored coordinates always equal rendered+ * ones — and can offset the stage by the same amount so nothing jumps on screen.+ */+export function freeNormalizeDelta(panels, captionSize = CAPTION_SIZE) {+ if (!panels.length) return { dx: 0, dy: 0 };+ const grid = layoutPanelsGrid(panels, captionSize);+ const xs = panels.map((p, i) => p.x ?? grid[i].x);+ const ys = panels.map((p, i) => p.y ?? grid[i].y);+ return { dx: PAD - Math.min(...xs), dy: PAD - Math.min(...ys) };+}+/** Height of the stacked panel block (rows + their caption bands), no legend. */export function panelsBlockHeight(panels, captionSize = CAPTION_SIZE) {const rows = rowOrder(panels);@@ -136,6 +194,21 @@ export function panelsBlockHeight(panels, captionSize = CAPTION_SIZE) {return total + (rows.length - 1) * ROW_GAP;}+/**+ * Doc-space y where the panel block ends and the legend may start. Grid: PAD ++ * the stacked block (every row reserves its caption band). Free: the lowest+ * panel bottom, plus a caption band only under panels that actually carry one.+ */+export function panelsBottom(panels, captionSize = CAPTION_SIZE, layout = 'grid') {+ if (!panels.length) return PAD;+ if (layout !== 'free') return PAD + panelsBlockHeight(panels, captionSize);+ const boxes = layoutPanelsFree(panels, captionSize);+ const band = captionBand(captionSize);+ return Math.max(+ ...boxes.map((b, i) => b.y + b.h + (panels[i].caption?.trim() ? band : 0))+ );+}+/*** Distinct colors in order of first use → feature numbering (same color = same* feature). Text labels are excluded — they annotate, they aren't features.@@ -290,11 +363,11 @@ export function legendRowCount(count, columns) {* count and every text band grows with its own font size (all editable per* proof via `text = { captionSize, legendSize, footerSize }`).*/-export function docSize(panels, shapes, notes = {}, text = {}, legendOrder = []) {+export function docSize(panels, shapes, notes = {}, text = {}, legendOrder = [], layout = 'grid') {const {captionSize = CAPTION_SIZE, legendSize = LEGEND_SIZE, footerSize = FOOTER_SIZE,} = text;- const boxes = layoutPanels(panels, captionSize);+ const boxes = layoutPanels(panels, captionSize, layout);const width = boxes.length? Math.max(...boxes.map((b) => b.x + b.w)) + PAD: 640;@@ -303,7 +376,7 @@ export function docSize(panels, shapes, notes = {}, text = {}, legendOrder = [])const cols = legendColumns(contentW, legend.length);const legendRows = legendRowCount(legend.length, cols);const height =- PAD + panelsBlockHeight(panels, captionSize) ++ panelsBottom(panels, captionSize, layout) +(legend.length ? 10 + legendRows * legendLineHeight(legendSize) : 0) +footerBand(footerSize) + PAD;return { width: contentW, height, legend, cols };@@ -321,6 +394,7 @@ export function toSpec(proof) {legendSize: proof.legendSize ?? LEGEND_SIZE,footerSize: proof.footerSize ?? FOOTER_SIZE,footer: proof.footer?.trim() ? proof.footer.trim() : null, // null → default attribution line+ layout: proof.layout ?? 'grid', // 'grid' (rows) | 'free' (per-panel x/y, overlap allowed)notes: { ...(proof.notes ?? {}) },legendOrder: [...(proof.legendOrder ?? [])],panels: proof.panels.map((p) => ({@@ -329,6 +403,8 @@ export function toSpec(proof) {caption: p.caption ?? '',row: p.row ?? 0, // vertical row (0 = top); missing → single-row layoutscale: p.scale ?? 1, // per-panel size multiplier (1 = default PANEL_H)+ x: p.x ?? null, // free-layout doc position; null → grid fallback+ y: p.y ?? null,natural: p.natural,meta: p.meta ?? {},})),@@ -366,6 +442,42 @@ export function offsetShape(shape, d) {return s;}+/**+ * Panel input for a satellite capture. The caption is provider · coordinates,+ * dated with the imagery acquisition date (when the satellite scene was shot,+ * NOT when we fetched the tiles) — the date part is simply omitted when the+ * provider doesn't expose it, never substituted with the fetch date.+ */+export function satPanelInput(s) {+ const parts = [`${s.provider_label} · ${s.lat.toFixed(6)}, ${s.lon.toFixed(6)}`];+ if (s.imagery_date) parts.push(s.imagery_date);+ return {+ src: s.path,+ meta: {+ kind: 'satellite', attribution: s.attribution, lat: s.lat, lon: s.lon,+ zoom: s.zoom, provider: s.provider_label,+ date: s.fetched_at?.slice(0, 10), imagery_date: s.imagery_date ?? null,+ },+ caption: parts.join(' · '),+ };+}++/**+ * Panel input for a media image. Traces the real source link through the+ * derivation chain (a collage/frame carries no URL of its own — follow it back+ * to the downloaded original). A file uploaded from disk has no URL, so it+ * contributes no source.+ */+export function mediaPanelInput(m, mediaList = []) {+ const byPath = new Map(mediaList.map((x) => [x.path, x]));+ const urls = resolveSourceUrls(m, byPath);+ return {+ src: m.path,+ meta: { kind: 'media', source_url: urls[0], source_urls: urls },+ caption: '',+ };+}+/*** True when a media listing item is a satellite capture — mirrors the backend's* `satellite.is_capture`. A capture *is* a media image (one file in `media/`),diff --git a/frontend/src/lib/composer.test.js b/frontend/src/lib/composer.test.jsindex 0e98bca..94281cf 100644--- a/frontend/src/lib/composer.test.js+++ b/frontend/src/lib/composer.test.js@@ -1,11 +1,12 @@import { describe, it, expect } from 'vitest';import {PAD, PANEL_H, GAP, ROW_GAP, FOOTER_H, LEGEND_LINE_H,- layoutPanels, panelsBlockHeight, panelHeight, captionBand, legendLineHeight, footerBand,+ layoutPanels, layoutPanelsFree, freeNormalizeDelta, panelsBottom,+ panelsBlockHeight, panelHeight, captionBand, legendLineHeight, footerBand,docSize, legendColumns, legendRowCount, toSpec, offsetShape, copyShapeSpec, autoLayoutRows, TWEET_GUIDES,autoCoords, formatCoords, resolveSourceUrls, autoSource, autoSourceUrls,proofCoordsText, proofSource, orderedFeatureColors, legendLines,- dedupeBySrc, isSatelliteCapture,+ dedupeBySrc, isSatelliteCapture, satPanelInput, mediaPanelInput,} from './composer.js';// natural is [width, height]; PANEL_H drives the per-row scale.@@ -98,6 +99,93 @@ describe('layoutPanels — per-panel scale', () => {});});+describe('layoutPanels — free mode', () => {+ it('renders panels without a stored position exactly where the grid would', () => {+ const panels = [landscape(1000, 500), landscape(500, 500)];+ expect(layoutPanels(panels, undefined, 'free')).toEqual(layoutPanels(panels));+ });++ it('places panels at their stored x/y, normalised so the top/left-most lands at PAD', () => {+ const panels = [+ landscape(1000, 500, { x: 100, y: 200 }),+ landscape(500, 500, { x: 400, y: 50 }),+ ];+ const boxes = layoutPanelsFree(panels);+ expect(boxes[0].x).toBe(PAD); // min x = 100 → shifted to PAD+ expect(boxes[1].y).toBe(PAD); // min y = 50 → shifted to PAD+ expect(boxes[1].x).toBe(PAD + 300); // relative offsets preserved+ expect(boxes[0].y).toBe(PAD + 150);+ });++ it('allows two panels to overlap and keeps per-panel scale sizing', () => {+ const panels = [+ landscape(1000, 500, { x: PAD, y: PAD, scale: 2 }),+ landscape(1000, 500, { x: PAD, y: PAD }),+ ];+ const boxes = layoutPanelsFree(panels);+ expect(boxes[0]).toMatchObject({ x: PAD, y: PAD, h: PANEL_H * 2 });+ expect(boxes[1]).toMatchObject({ x: PAD, y: PAD, h: PANEL_H });+ expect(boxes[0].w).toBeCloseTo(2880);+ expect(boxes[0].baseScale).toBeCloseTo(PANEL_H / 500);+ });++ it('a null stored position (persisted spec) falls back to the grid too', () => {+ const panels = [landscape(1000, 500, { x: null, y: null })];+ expect(layoutPanelsFree(panels)[0]).toMatchObject({ x: PAD, y: PAD });+ });+});++describe('freeNormalizeDelta — stored positions re-anchor at PAD', () => {+ it('is zero when positions are already anchored', () => {+ const panels = [landscape(1000, 500, { x: PAD, y: PAD })];+ expect(freeNormalizeDelta(panels)).toEqual({ dx: 0, dy: 0 });+ expect(freeNormalizeDelta([])).toEqual({ dx: 0, dy: 0 });+ });++ it('returns the shift needed after a drag past the top/left edge', () => {+ const panels = [+ landscape(1000, 500, { x: -50, y: 120 }),+ landscape(500, 500, { x: 300, y: 40 }),+ ];+ expect(freeNormalizeDelta(panels)).toEqual({ dx: PAD + 50, dy: PAD - 40 });+ });+});++describe('panelsBottom', () => {+ it('matches PAD + panelsBlockHeight in grid mode', () => {+ const panels = [landscape(1000, 500, { row: 0 }), landscape(1000, 500, { row: 1 })];+ expect(panelsBottom(panels)).toBe(PAD + panelsBlockHeight(panels));+ expect(panelsBottom([])).toBe(PAD);+ });++ it('free mode: lowest panel bottom, caption band only under captioned panels', () => {+ const bare = [landscape(1000, 500, { x: PAD, y: PAD })];+ expect(panelsBottom(bare, undefined, 'free')).toBe(PAD + PANEL_H);+ const captioned = [landscape(1000, 500, { x: PAD, y: PAD, caption: 'view' })];+ expect(panelsBottom(captioned, undefined, 'free')).toBe(PAD + PANEL_H + captionBand());+ });++ it('free mode: the lowest panel wins, wherever it sits in the array', () => {+ const panels = [+ landscape(1000, 500, { x: PAD, y: 900 }),+ landscape(500, 500, { x: PAD, y: PAD }),+ ];+ expect(panelsBottom(panels, undefined, 'free')).toBe(900 + PANEL_H);+ });+});++describe('docSize — free layout', () => {+ it('sizes the document to the panel bounding box', () => {+ const panels = [+ landscape(1000, 500, { x: PAD, y: PAD }), // right edge PAD + 1440+ landscape(500, 500, { x: 2000, y: 300 }), // right edge 2720, bottom 1020+ ];+ const { width, height } = docSize(panels, [], {}, {}, [], 'free');+ expect(width).toBe(2720 + PAD);+ expect(height).toBe(1020 + FOOTER_H + PAD);+ });+});+describe('captionBand + panelsBlockHeight', () => {it('grows the caption band with the font size', () => {expect(captionBand(17)).toBe(34);@@ -283,6 +371,71 @@ describe('toSpec — persistence of layout', () => {});});+describe('toSpec — layout mode + free positions', () => {+ it('defaults to the grid layout with null positions', () => {+ const proof = {+ title: 'T', panels: [{ id: 'p1', src: 'a.png', natural: [10, 10] }], shapes: [],+ };+ const spec = toSpec(proof);+ expect(spec.layout).toBe('grid');+ expect(spec.panels[0].x).toBeNull();+ expect(spec.panels[0].y).toBeNull();+ });++ it('persists the free layout and each panel position', () => {+ const proof = {+ title: 'T',+ layout: 'free',+ panels: [{ id: 'p1', src: 'a.png', natural: [10, 10], x: 120, y: 340 }],+ shapes: [],+ };+ const spec = toSpec(proof);+ expect(spec.layout).toBe('free');+ expect(spec.panels[0]).toMatchObject({ x: 120, y: 340 });+ });+});++describe('satPanelInput — satellite caption dates with the imagery date, never the fetch date', () => {+ const capture = {+ path: 'media/sat_1.png',+ attribution: '© Provider',+ lat: 48.85, lon: 2.35, zoom: 17,+ provider_label: 'Esri',+ fetched_at: '2026-07-14T10:00:00Z',+ };++ it('captions provider · coords · imagery acquisition date when known', () => {+ const input = satPanelInput({ ...capture, imagery_date: '2024-03-02' });+ expect(input.caption).toBe('Esri · 48.850000, 2.350000 · 2024-03-02');+ });++ it('omits the date part when the imagery date is unknown (no fetch-date fallback)', () => {+ expect(satPanelInput(capture).caption).toBe('Esri · 48.850000, 2.350000');+ expect(satPanelInput({ ...capture, imagery_date: null }).caption).toBe('Esri · 48.850000, 2.350000');+ });++ it('keeps the full provenance in meta (both dates, provider, coords)', () => {+ const input = satPanelInput({ ...capture, imagery_date: '2024-03-02' });+ expect(input.src).toBe('media/sat_1.png');+ expect(input.meta).toMatchObject({+ kind: 'satellite', provider: 'Esri', lat: 48.85, lon: 2.35, zoom: 17,+ attribution: '© Provider', date: '2026-07-14', imagery_date: '2024-03-02',+ });+ });+});++describe('mediaPanelInput — media panel carries its traced source', () => {+ it('resolves the source link through the derivation chain, no caption', () => {+ const video = { path: 'media/v.mp4', source: { type: 'download', webpage_url: 'https://x.com/a/1' } };+ const frame = { path: 'media/f.png', source: { type: 'inspect', op: 'frame', from: 'media/v.mp4' } };+ const input = mediaPanelInput(frame, [video, frame]);+ expect(input.caption).toBe('');+ expect(input.meta).toMatchObject({+ kind: 'media', source_url: 'https://x.com/a/1', source_urls: ['https://x.com/a/1'],+ });+ });+});+describe('autoLayoutRows — magic tweet fit', () => {const sq = (extra) => landscape(500, 500, extra);diff --git a/frontend/src/lib/fullscreen.js b/frontend/src/lib/fullscreen.jsnew file mode 100644index 0000000..8b44784--- /dev/null+++ b/frontend/src/lib/fullscreen.js@@ -0,0 +1,38 @@+// Fullscreen-aware overlays.+//+// The Fullscreen API paints *only* the fullscreen element's subtree, so an+// overlay parked on <body> (modals, confirms, toasts) is simply invisible while+// a tool is fullscreen — the click lands, nothing shows. Reparenting the+// overlay under the current fullscreen element keeps it on screen, and moving+// it back on exit keeps the non-fullscreen case unchanged.++/** The element a viewport-level overlay must be parented to, to be visible. */+export function overlayHost(doc = document) {+ return doc.fullscreenElement ?? doc.body;+}++/**+ * Svelte action: keep `node` parented to the current overlay host, following+ * the browser in and out of fullscreen for as long as the node lives.+ */+export function portal(node, doc = document) {+ let host = null;++ function place() {+ const next = overlayHost(doc);+ if (next && next !== host) {+ host = next;+ host.appendChild(node);+ }+ }++ place();+ doc.addEventListener('fullscreenchange', place);++ return {+ destroy() {+ doc.removeEventListener('fullscreenchange', place);+ node.remove();+ },+ };+}diff --git a/frontend/src/lib/fullscreen.test.js b/frontend/src/lib/fullscreen.test.jsnew file mode 100644index 0000000..ce3cc7a--- /dev/null+++ b/frontend/src/lib/fullscreen.test.js@@ -0,0 +1,137 @@+import { describe, it, expect } from 'vitest';+import { overlayHost, portal } from './fullscreen.js';++// Minimal DOM stand-ins: the action only ever appends and removes, so a couple+// of objects tracking parentage are enough (no jsdom in this suite).+function makeNode() {+ const node = {+ parent: null,+ remove() {+ if (this.parent) this.parent.children = this.parent.children.filter((c) => c !== this);+ this.parent = null;+ },+ };+ return node;+}++function makeHost(name) {+ return {+ name,+ children: [],+ appendChild(node) {+ node.remove();+ node.parent = this;+ this.children.push(node);+ },+ };+}++function makeDoc(body) {+ return {+ body,+ fullscreenElement: null,+ listeners: [],+ addEventListener(type, fn) {+ if (type === 'fullscreenchange') this.listeners.push(fn);+ },+ removeEventListener(type, fn) {+ this.listeners = this.listeners.filter((l) => l !== fn);+ },+ fire() {+ for (const l of [...this.listeners]) l();+ },+ };+}++describe('overlayHost', () => {+ it('is the body when nothing is fullscreen', () => {+ const body = makeHost('body');+ expect(overlayHost(makeDoc(body))).toBe(body);+ });++ it('is the fullscreen element while a tool owns the screen', () => {+ const body = makeHost('body');+ const tool = makeHost('tool');+ const doc = makeDoc(body);+ doc.fullscreenElement = tool;+ expect(overlayHost(doc)).toBe(tool);+ });+});++describe('portal', () => {+ it('parks the overlay on the body outside fullscreen', () => {+ const body = makeHost('body');+ const doc = makeDoc(body);+ const node = makeNode();++ portal(node, doc);++ expect(node.parent).toBe(body);+ });++ it('moves the overlay into the fullscreen element on entering', () => {+ const body = makeHost('body');+ const tool = makeHost('tool');+ const doc = makeDoc(body);+ const node = makeNode();++ portal(node, doc);+ doc.fullscreenElement = tool;+ doc.fire();++ // this is the bug: an overlay left on <body> is never painted in fullscreen+ expect(node.parent).toBe(tool);+ expect(body.children).toEqual([]);+ });++ it('moves the overlay back to the body on exiting', () => {+ const body = makeHost('body');+ const tool = makeHost('tool');+ const doc = makeDoc(body);+ const node = makeNode();++ doc.fullscreenElement = tool;+ portal(node, doc);+ doc.fullscreenElement = null;+ doc.fire();++ expect(node.parent).toBe(body);+ expect(tool.children).toEqual([]);+ });++ it('opens directly inside the fullscreen element when already fullscreen', () => {+ const body = makeHost('body');+ const tool = makeHost('tool');+ const doc = makeDoc(body);+ doc.fullscreenElement = tool;+ const node = makeNode();++ portal(node, doc);++ expect(node.parent).toBe(tool);+ });++ it('does not re-append when the host is unchanged', () => {+ const body = makeHost('body');+ const doc = makeDoc(body);+ const node = makeNode();++ portal(node, doc);+ doc.fire();+ doc.fire();++ expect(body.children).toEqual([node]);+ });++ it('unhooks and detaches on destroy', () => {+ const body = makeHost('body');+ const doc = makeDoc(body);+ const node = makeNode();++ portal(node, doc).destroy();++ expect(doc.listeners).toEqual([]);+ expect(body.children).toEqual([]);+ expect(node.parent).toBe(null);+ });+});diff --git a/frontend/src/lib/inspect.js b/frontend/src/lib/inspect.jsindex 9040ba7..a5e9f24 100644--- a/frontend/src/lib/inspect.js+++ b/frontend/src/lib/inspect.js@@ -359,6 +359,65 @@ export function rotateQuad(quad, rad, center = null) {});}+// ---------------------------------------------------------------------------+// Group transforms — the multi-select block. Each is the single-quad primitive+// mapped over every quad with one *shared* pivot, which is what makes the block+// move/turn/grow as one rigid unit instead of each piece spinning about its own+// centroid. Callers must pass the quads captured at gesture start and derive the+// pivot once from those: re-deriving it mid-drag would chase the block's own+// bounding box and drift it away under the pointer.+// ---------------------------------------------------------------------------++/**+ * Axis-aligned bounds over several quads, plus their shared centre — the frame+ * drawn around a multi-piece selection and the pivot its rotate/scale turn+ * about. Unrounded, unlike collageBounds (which sizes an export in whole+ * pixels). Returns null for an empty selection.+ */+export function quadsBounds(quads) {+ if (!quads.length) return null;+ const xs = [];+ const ys = [];+ for (const q of quads) for (const [x, y] of q) { xs.push(x); ys.push(y); }+ const minX = Math.min(...xs);+ const minY = Math.min(...ys);+ const maxX = Math.max(...xs);+ const maxY = Math.max(...ys);+ return {+ minX,+ minY,+ maxX,+ maxY,+ width: maxX - minX,+ height: maxY - minY,+ center: [(minX + maxX) / 2, (minY + maxY) / 2],+ };+}++/** Translate a single quad by (dx, dy). */+export function translateQuad(quad, dx, dy) {+ return quad.map(([x, y]) => [x + dx, y + dy]);+}++/** Move a group of quads by (dx, dy). */+export function moveQuads(quads, dx, dy) {+ return quads.map((q) => translateQuad(q, dx, dy));+}++/** Rotate a group of quads around a shared pivot (default: the group centre). */+export function rotateQuads(quads, rad, center = null) {+ const c = center ?? quadsBounds(quads)?.center;+ if (!c) return [];+ return quads.map((q) => rotateQuad(q, rad, c));+}++/** Uniformly scale a group of quads around a shared pivot (default: group centre). */+export function scaleQuads(quads, k, center = null) {+ const c = center ?? quadsBounds(quads)?.center;+ if (!c) return [];+ return quads.map((q) => scaleQuad(q, k, c));+}+/** A sensible starting quad: the image scaled to fit `maxW`, placed at (ox, oy). */export function initialQuad(natW, natH, maxW, ox, oy) {const scale = Math.min(1, maxW / (natW || maxW));diff --git a/frontend/src/lib/inspect.test.js b/frontend/src/lib/inspect.test.jsindex 66b447f..d31bef4 100644--- a/frontend/src/lib/inspect.test.js+++ b/frontend/src/lib/inspect.test.js@@ -2,6 +2,7 @@ import { describe, it, expect } from 'vitest';import {clampCrop, moveCrop, resizeCropByHandle,QUAD_SIDES, quadEdgeMidpoints, moveQuadEdge, quadCentroid,+ quadsBounds, translateQuad, moveQuads, rotateQuads, scaleQuads,} from './inspect.js';const near = (a, b, eps = 1e-6) => Math.abs(a - b) < eps;@@ -124,3 +125,131 @@ describe('quad side resize', () => {expect(near(c0[0], c1[0], 1e-9)).toBe(true);});});++// ---------------------------------------------------------------------------+// Multi-select group transforms: the block moves/turns/grows as one rigid unit+// about a shared pivot, so an off-centre piece is carried around the block's+// centre rather than spinning about its own.+// ---------------------------------------------------------------------------++// two 10x10 squares side by side: group box 0..30 x 0..10, centre [15, 5]+const sqA = [[0, 0], [10, 0], [10, 10], [0, 10]];+const sqB = [[20, 0], [30, 0], [30, 10], [20, 10]];++describe('quadsBounds', () => {+ it('spans every quad of the group and centres between them', () => {+ expect(quadsBounds([sqA, sqB])).toMatchObject({+ minX: 0, minY: 0, maxX: 30, maxY: 10, width: 30, height: 10, center: [15, 5],+ });+ });++ it('is the quad itself for a single-piece selection', () => {+ expect(quadsBounds([sqA])).toMatchObject({ minX: 0, maxX: 10, center: [5, 5] });+ });++ it('covers a rotated/warped quad by its extreme corners', () => {+ const warped = [[10, 5], [110, 0], [120, 90], [0, 85]];+ expect(quadsBounds([warped])).toMatchObject({ minX: 0, minY: 0, maxX: 120, maxY: 90 });+ });++ it('returns null for an empty selection', () => {+ expect(quadsBounds([])).toBe(null);+ });+});++describe('translateQuad + moveQuads', () => {+ it('shifts a single quad by the delta', () => {+ expect(translateQuad(sqA, 5, -3)).toEqual([[5, -3], [15, -3], [15, 7], [5, 7]]);+ });++ it('shifts every quad of the group by the same delta (block keeps its shape)', () => {+ const [a, b] = moveQuads([sqA, sqB], 100, 50);+ expect(a).toEqual([[100, 50], [110, 50], [110, 60], [100, 60]]);+ expect(b).toEqual([[120, 50], [130, 50], [130, 60], [120, 60]]);+ // the gap between the two pieces is untouched+ expect(quadsBounds([a, b]).width).toBe(quadsBounds([sqA, sqB]).width);+ });++ it('does not mutate the input quads', () => {+ moveQuads([sqA], 10, 10);+ expect(sqA).toEqual([[0, 0], [10, 0], [10, 10], [0, 10]]);+ });+});++describe('rotateQuads — the block turns as one', () => {+ it('half-turns the group about its centre, swapping the two pieces over', () => {+ const [a, b] = rotateQuads([sqA, sqB], Math.PI);+ // A lands on B's box and vice versa — proof the pivot is the *group* centre+ expect(quadsBounds([a]).minX).toBeCloseTo(20);+ expect(quadsBounds([a]).maxX).toBeCloseTo(30);+ expect(quadsBounds([b]).minX).toBeCloseTo(0);+ expect(quadsBounds([b]).maxX).toBeCloseTo(10);+ });++ it('carries an off-centre piece around instead of spinning it in place', () => {+ const [a] = rotateQuads([sqA, sqB], Math.PI / 2);+ // a per-piece rotation would have left A's centroid at (5, 5)+ expect(quadCentroid(a)).not.toEqual([5, 5]);+ });++ it('is rigid — the distance between the pieces is preserved', () => {+ const d0 = Math.hypot(...quadCentroid(sqA).map((v, i) => v - quadCentroid(sqB)[i]));+ const [a, b] = rotateQuads([sqA, sqB], 0.7);+ const d1 = Math.hypot(...quadCentroid(a).map((v, i) => v - quadCentroid(b)[i]));+ expect(d1).toBeCloseTo(d0);+ });++ it('leaves the group centre fixed', () => {+ const out = rotateQuads([sqA, sqB], 0.4);+ const c = quadsBounds(out).center;+ expect(c[0]).toBeCloseTo(15);+ expect(c[1]).toBeCloseTo(5);+ });++ it('rotating out and back returns to the start', () => {+ const out = rotateQuads(rotateQuads([sqA, sqB], 0.9, [15, 5]), -0.9, [15, 5]);+ expect(out[0][0][0]).toBeCloseTo(0);+ expect(out[0][0][1]).toBeCloseTo(0);+ expect(out[1][2][0]).toBeCloseTo(30);+ });++ it('honours an explicit pivot over the group centre', () => {+ const [a] = rotateQuads([sqA], Math.PI, [0, 0]); // pivot at A's own corner+ const b = quadsBounds([a]);+ expect(b.minX).toBeCloseTo(-10);+ expect(b.minY).toBeCloseTo(-10);+ expect(b.maxX).toBeCloseTo(0);+ expect(b.maxY).toBeCloseTo(0);+ });++ it('returns an empty array for an empty selection', () => {+ expect(rotateQuads([], 1)).toEqual([]);+ });+});++describe('scaleQuads — the block grows as one', () => {+ it('scales the whole group box about its centre', () => {+ const out = scaleQuads([sqA, sqB], 2);+ const b = quadsBounds(out);+ expect(b.width).toBeCloseTo(60); // 2x the original 30+ expect(b.center[0]).toBeCloseTo(15); // centre pinned+ expect(b.center[1]).toBeCloseTo(5);+ });++ it('pushes the pieces apart, not just enlarges each in place', () => {+ const [a, b] = scaleQuads([sqA, sqB], 2);+ const gap = quadsBounds([b]).minX - quadsBounds([a]).maxX;+ const gap0 = sqB[0][0] - sqA[1][0]; // 10+ expect(gap).toBeCloseTo(gap0 * 2);+ });++ it('shrinking then growing back returns to the start', () => {+ const out = scaleQuads(scaleQuads([sqA, sqB], 0.25, [15, 5]), 4, [15, 5]);+ expect(out[0][0][0]).toBeCloseTo(0);+ expect(out[1][2][0]).toBeCloseTo(30);+ });++ it('returns an empty array for an empty selection', () => {+ expect(scaleQuads([], 2)).toEqual([]);+ });+});diff --git a/frontend/src/lib/usage.js b/frontend/src/lib/usage.jsindex c6d1674..c5a3366 100644--- a/frontend/src/lib/usage.js+++ b/frontend/src/lib/usage.js@@ -1,5 +1,5 @@/**- * Keyed-provider usage bookkeeping (docs/KEYED_PROVIDERS.md §6).+ * Keyed-provider usage bookkeeping (docs/IMAGERY_PROVIDERS.md).** Billed providers (Mapbox, Google) get a per-month tile counter in* settings.json, maintained entirely by the backend: captures count the tiles@@ -10,13 +10,65 @@/*** Documented monthly free allowances, in tile requests — a yardstick for the* counter, not a guarantee (providers change their pricing; verify on their- * pricing pages). Mapbox Static Tiles: 200k/month, then pay-as-you-go per- * extra 1,000 (billed to the card on the account). Google 2D Map Tiles:- * 100k/month, then billed per extra 1,000 against the Cloud project —- * a quota cap set in the Cloud Console makes it stop instead of bill.+ * 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).*/export const FREE_TIER = { mapbox: 200_000, google: 100_000 };+/** Share of the free tier past which the backend pauses a provider. */+export const BLOCK_SHARE = 0.9;++/** Eco mode default: visual zoom at or below which free imagery replaces a+ * billed basemap. The live value is the user's `eco_max_zoom` setting. */+export const ECO_MAX_ZOOM = 15;++/** Where to watch the real counters and set caps, per provider. */+export const USAGE_LINKS = {+ mapbox: 'https://console.mapbox.com/account/statistics/',+ google: 'https://console.cloud.google.com/google/maps-apis/quotas',+};++/** True when a metered provider is paused: past the soft block, no override. */+export function usageBlocked(count, meter, overrides = {}) {+ const free = FREE_TIER[meter];+ if (!free || overrides[meter]) return false;+ return count >= free * BLOCK_SHARE;+}++/**+ * 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)+ * get one extra 2× boost for the z17 view only — the z18 mosaic it would+ * otherwise show is often an older/hazier collection than z19+ (the sharp+ * aerial; measured 2026-07), so that single bracket pays 4× for z19 detail+ * while every other zoom keeps the cheap 2×.+ */+export function layerCell(provider, zoom) {+ const boost = provider.oversample === 2 && zoom === 17 ? 2 : 1;+ return Math.max(256, provider.tile_size / ((provider.oversample || 1) * boost));+}++/**+ * The provider the live map should actually display. Billed basemaps step+ * 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.+ */+export function displayProviderId(+ provider,+ zoom,+ { eco = true, blocked = false, ecoMaxZoom = ECO_MAX_ZOOM } = {}+) {+ if (!provider?.meter) return provider?.id;+ if (blocked) return 'esri-world-imagery';+ if (eco && zoom <= ecoMaxZoom) return 'esri-world-imagery';+ return provider.id;+}+/** The usage bucket for a moment in time: "YYYY-MM" (UTC, matches backend). */export function monthKey(date = new Date()) {return `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, '0')}`;diff --git a/frontend/src/lib/usage.test.js b/frontend/src/lib/usage.test.jsindex add07b7..f64080f 100644--- a/frontend/src/lib/usage.test.js+++ b/frontend/src/lib/usage.test.js@@ -5,7 +5,13 @@ import {tilesShort,tilesOfFree,freeTierShare,+ usageBlocked,+ displayProviderId,+ layerCell,FREE_TIER,+ BLOCK_SHARE,+ ECO_MAX_ZOOM,+ USAGE_LINKS,} from './usage.js';describe('monthKey', () => {@@ -60,3 +66,78 @@ describe('freeTierShare', () => {expect(FREE_TIER.google).toBe(100_000);});});++describe('usageBlocked', () => {+ it('pauses a meter at the block share of its free tier', () => {+ expect(usageBlocked(FREE_TIER.google * BLOCK_SHARE, 'google')).toBe(true);+ expect(usageBlocked(FREE_TIER.google * BLOCK_SHARE - 1, 'google')).toBe(false);+ });++ it('the per-provider override lifts the pause', () => {+ expect(usageBlocked(FREE_TIER.mapbox, 'mapbox', { mapbox: true })).toBe(false);+ expect(usageBlocked(FREE_TIER.mapbox, 'mapbox', { google: true })).toBe(true);+ });++ it('unmetered providers never block', () => {+ expect(usageBlocked(10_000_000, 'bing')).toBe(false);+ });+});++describe('displayProviderId', () => {+ const google = { id: 'google-satellite', meter: 'google' };+ const esri = { id: 'esri-world-imagery', meter: null };++ it('keeps free providers as-is at any zoom', () => {+ expect(displayProviderId(esri, 3)).toBe('esri-world-imagery');+ expect(displayProviderId(esri, 19)).toBe('esri-world-imagery');+ });++ it('eco mode swaps billed basemaps for free imagery when zoomed out', () => {+ expect(displayProviderId(google, ECO_MAX_ZOOM)).toBe('esri-world-imagery');+ expect(displayProviderId(google, ECO_MAX_ZOOM + 1)).toBe('google-satellite');+ expect(displayProviderId(google, ECO_MAX_ZOOM, { eco: false })).toBe('google-satellite');+ });++ it('the eco threshold is configurable (default z15)', () => {+ expect(ECO_MAX_ZOOM).toBe(15);+ expect(displayProviderId(google, 17, { ecoMaxZoom: 17 })).toBe('esri-world-imagery');+ expect(displayProviderId(google, 15, { ecoMaxZoom: 12 })).toBe('google-satellite');+ });++ it('a paused meter always falls back, even zoomed in', () => {+ expect(displayProviderId(google, 19, { blocked: true })).toBe('esri-world-imagery');+ });++ it('handles the pre-load undefined provider', () => {+ expect(displayProviderId(undefined, 10)).toBe(undefined);+ });+});++describe('layerCell', () => {+ const google = { id: 'google-satellite', tile_size: 1024, oversample: 2 };+ const mapbox = { id: 'mapbox-satellite', tile_size: 512, oversample: 1 };+ const esri = { id: 'esri-world-imagery', tile_size: 256, oversample: 1 };++ it('shrinks the cell by the display oversample', () => {+ expect(layerCell(google, 16)).toBe(512); // 1024px tile shown 2× down = z+1 detail+ expect(layerCell(mapbox, 16)).toBe(512); // no oversample — native cell+ expect(layerCell(esri, 16)).toBe(256);+ });++ it('boosts only the z17 bracket for oversampled providers (soft z18 mosaic)', () => {+ expect(layerCell(google, 17)).toBe(256); // z19 detail for the z17 view+ expect(layerCell(google, 18)).toBe(512); // back to the cheap 2×+ expect(layerCell(mapbox, 17)).toBe(512); // non-oversampled providers unaffected+ });++ it('never goes below the 256px minimum cell', () => {+ expect(layerCell({ tile_size: 256, oversample: 2 }, 17)).toBe(256);+ });+});++describe('USAGE_LINKS', () => {+ it('points each billed meter at its provider dashboard', () => {+ expect(Object.keys(USAGE_LINKS).sort()).toEqual(Object.keys(FREE_TIER).sort());+ for (const url of Object.values(USAGE_LINKS)) expect(url).toMatch(/^https:\/\//);+ });+});diff --git a/frontend/src/tools/Inspector.svelte b/frontend/src/tools/Inspector.svelteindex a02553d..d1689fa 100644--- a/frontend/src/tools/Inspector.svelte+++ b/frontend/src/tools/Inspector.svelte@@ -36,7 +36,7 @@let probeInfo = $state(null);let activeTab = $state('selection');- let collageSelectedId = $state(null);+ let collageSelectedIds = $state([]);let cropPieceNode = $state(null);// Real (backend-composited) Save-tab thumbnails, keyed by collage id:// { sig, url } — regenerated only when a collage's layout actually changes.@@ -109,7 +109,7 @@if (!session.collages.some((c) => c.id === session.activeCollageId)) {session.activeCollageId = session.collages[0]?.id ?? null;}- collageSelectedId = null;+ collageSelectedIds = [];// outlast the capture debounce so the restore itself is not re-recordedsetTimeout(() => (collageHistBusy = false), 400);}@@ -289,7 +289,7 @@saveUi.selected = {};saveUi.folder = '';openedSession = null;- collageSelectedId = null;+ collageSelectedIds = [];shared.currentTime = 0;shared.cropMode = false;frameZoom = 1;@@ -431,7 +431,7 @@save: { path: frame.path, time: frame.time ?? null, ops }, quad,};cl.nodes.push(node);- collageSelectedId = node.id;+ collageSelectedIds = [node.id];} catch (e) {toast(e.message, 'danger');}@@ -983,7 +983,7 @@</div>{/if}{:else if activeTab === 'collage'}- <CollageCanvas collage={activeCollage} bind:selectedId={collageSelectedId} {requestCrop} />+ <CollageCanvas collage={activeCollage} bind:selectedIds={collageSelectedIds} {requestCrop} />{:else if activeTab === 'save'}<SaveGallery {savables} {saveUi} />{/if}@@ -995,7 +995,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:selectedId={collageSelectedId} {addToCollage} {requestCrop} />+ <CollageMenu {session} {filters} bind:selectedIds={collageSelectedIds} {addToCollage} {requestCrop} />{:else if activeTab === 'save'}<SaveMenu {savables} {saveUi} {saving} save={saveSelected} />{/if}diff --git a/frontend/src/tools/ProofComposer.svelte b/frontend/src/tools/ProofComposer.svelteindex df77c41..c17a0ad 100644--- a/frontend/src/tools/ProofComposer.svelte+++ b/frontend/src/tools/ProofComposer.svelte@@ -7,20 +7,20 @@import Modal from '../components/Modal.svelte';import ConfirmDialog from '../components/ConfirmDialog.svelte';import {- ANNO_COLORS, PAD, TWEET_GUIDES,+ ANNO_COLORS, PAD, PANEL_H, TWEET_GUIDES,CAPTION_SIZE, LEGEND_SIZE, FOOTER_SIZE,BG, TEXT_MAIN, TEXT_DIM, TEXT_FAINT,- layoutPanels, panelsBlockHeight, legendLineHeight, footerBand,+ layoutPanels, panelsBottom, freeNormalizeDelta, legendLineHeight, footerBand,attributionLine, docSize, offsetShape, autoLayoutRows,- autoCoords, formatCoords, autoSource, resolveSourceUrls,+ autoCoords, formatCoords, autoSource,toSpec, newId, loadImage, orderedFeatureColors, notesFromShapes,- copyShapeSpec, dedupeBySrc, isSatelliteCapture,+ copyShapeSpec, dedupeBySrc, isSatelliteCapture, satPanelInput, mediaPanelInput,} from '../lib/composer.js';import { createHistory } from '../lib/history.js';- const SCALE_MIN = 0.4;+ const SCALE_MIN = 0.25;const SCALE_MAX = 2.5;- const SCALE_STEP = 0.1;+ const SCALE_STEP = 0.05;const DRAW_TOOLS = [{ id: 'select', icon: 'hand', label: 'Select / move' },@@ -39,6 +39,7 @@title: 'Untitled proof', panels: [], shapes: [], notes: {}, legendOrder: [],coordsText: '', source: '', // '' → auto-derived from panels; non-empty → manual overridecaptionSize: CAPTION_SIZE, legendSize: LEGEND_SIZE, footerSize: FOOTER_SIZE, footer: '',+ layout: 'grid', // 'grid' (rows) | 'free' (drag panels anywhere, overlap allowed)});let advancedOpen = $state(false);let collapsed = $state({ panels: false, annotations: false, elements: false });@@ -49,6 +50,7 @@let strokeW = $state(4);let guide = $state(null); // null | '16:9' | '4:5' — tweet centre-crop overlaylet selectedId = $state(null);+ let selectedPanelId = $state(null); // free-layout only: panel picked for move/resizelet picker = $state(false);let pickerItems = $state([]);let openList = $state(null); // list of saved proofs, null = closed@@ -101,6 +103,7 @@proof.legendSize = spec.legendSize ?? LEGEND_SIZE;proof.footerSize = spec.footerSize ?? FOOTER_SIZE;proof.footer = spec.footer ?? '';+ proof.layout = spec.layout ?? 'grid';proof.notes = spec.notes ?? {};proof.panels = spec.panels.map((p) => ({ ...p, img: imgCache.get(p.src) ?? null }));proof.shapes = spec.shapes ?? [];@@ -114,6 +117,7 @@.catch(() => {});}selectedId = null;+ selectedPanelId = null;dirty = true;requestAnimationFrame(fit);// outlast the capture debounce so the restore itself is not re-recorded@@ -134,7 +138,7 @@// ---- konva ------------------------------------------------------------------let containerEl;- let stage, docLayer, uiLayer, transformer, endHandles, guideGroup;+ let stage, docLayer, uiLayer, transformer, endHandles, guideGroup, panelCtrls;let drawing = null; // {panel, node, start, box, kind}let pathDraft = null; // {panel, box, node, points:[]} — multi-click curve in progresslet spacePan = false; // hold-space panning (manual, so it wins over shape drags)@@ -149,7 +153,7 @@transformer = new Konva.Transformer({rotateEnabled: false,flipEnabled: false,- anchorSize: 9,+ anchorSize: 11,anchorCornerRadius: 3,anchorStroke: '#e8a33d',anchorFill: '#161e2e',@@ -162,6 +166,8 @@uiLayer.add(transformer);endHandles = new Konva.Group();uiLayer.add(endHandles);+ panelCtrls = new Konva.Group();+ uiLayer.add(panelCtrls);const resize = new ResizeObserver(() => {stage.width(containerEl.clientWidth);@@ -217,12 +223,14 @@// rebuild canvas whenever the document changes$effect(() => {JSON.stringify([- proof.panels.map((p) => [p.src, p.caption, p.row, p.scale]),+ proof.panels.map((p) => [p.src, p.caption, p.row, p.scale, p.x, p.y]),proof.shapes,proof.notes,proof.legendOrder,proof.captionSize, proof.legendSize, proof.footerSize, proof.footer,+ proof.layout,selectedId,+ selectedPanelId,guide,]);if (stage) rebuild();@@ -235,6 +243,11 @@footerSize: proof.footerSize,});+ // Layout boxes + document measure for the active layout mode.+ const boxesOf = () => layoutPanels(proof.panels, proof.captionSize, proof.layout);+ const measureDoc = () =>+ docSize(proof.panels, proof.shapes, proof.notes, textOpts(), proof.legendOrder, proof.layout);+function resetDoc() {proof.title = 'Untitled proof';proof.panels = [];@@ -247,8 +260,10 @@proof.legendSize = LEGEND_SIZE;proof.footerSize = FOOTER_SIZE;proof.footer = '';+ proof.layout = 'grid';savedName = null;selectedId = null;+ selectedPanelId = null;dirty = false;imgCache.clear();anchorHistory();@@ -261,30 +276,6 @@// ---- panels ------------------------------------------------------------------- function satPanelInput(s) {- return {- src: s.path,- meta: {- kind: 'satellite', attribution: s.attribution, lat: s.lat, lon: s.lon,- zoom: s.zoom, provider: s.provider_label, date: s.fetched_at?.slice(0, 10),- },- caption: `${s.provider_label} · ${s.lat.toFixed(6)}, ${s.lon.toFixed(6)} · ${s.fetched_at?.slice(0, 10) ?? ''}`,- };- }-- function mediaPanelInput(m, mediaList = []) {- // Trace the real source link through the derivation chain (a collage/frame- // carries no URL of its own — follow it back to the downloaded original).- // A file uploaded from disk has no URL, so it contributes no source.- const byPath = new Map(mediaList.map((x) => [x.path, x]));- const urls = resolveSourceUrls(m, byPath);- return {- src: m.path,- meta: { kind: 'media', source_url: urls[0], source_urls: urls },- caption: '',- };- }-async function openPicker() {if (!caseState.current) {toast('Add media first — the composer works on case images', 'info');@@ -326,7 +317,7 @@const row = proof.panels.length? Math.max(...proof.panels.map((p) => p.row ?? 0)): 0;- proof.panels.push({+ const panel = {id: newId('p'),src: item.src,caption: item.caption ?? '',@@ -335,7 +326,10 @@natural: [img.naturalWidth, img.naturalHeight],meta: item.meta ?? {},img,- });+ };+ // grid: append (rightmost / bottom row); free: a new panel lands in front+ if (proof.layout === 'free') proof.panels.unshift(panel);+ else proof.panels.push(panel);dirty = true;requestAnimationFrame(fit);} catch (e) {@@ -402,18 +396,80 @@function scalePanel(index, delta) {const p = proof.panels[index];const cur = p.scale ?? 1;- const next = Math.round(Math.min(SCALE_MAX, Math.max(SCALE_MIN, cur + delta)) * 10) / 10;+ const next = Math.round(Math.min(SCALE_MAX, Math.max(SCALE_MIN, cur + delta)) * 100) / 100;if (next === cur) return;+ if (proof.layout === 'free') materializeFreePositions(); // others must not reflowp.scale = next;dirty = true;requestAnimationFrame(fit);}+ // ---- free layout ------------------------------------------------------------+ // In free mode a panel's stored x/y is its doc position; a panel without one+ // renders at its grid fallback (layoutPanelsFree). Before any mutation that+ // could shift those fallbacks (drag, resize, scale), stored positions are+ // materialised from the rendered layout so panels only move when moved.++ function materializeFreePositions() {+ const boxes = layoutPanels(proof.panels, proof.captionSize, 'free');+ proof.panels.forEach((p, i) => {+ p.x = boxes[i].x;+ p.y = boxes[i].y;+ });+ }++ // Re-anchor stored positions at PAD (dragging past the top/left edge grows+ // the document) and shift the stage by the same amount so nothing jumps.+ function normalizeFree() {+ const { dx, dy } = freeNormalizeDelta(proof.panels, proof.captionSize);+ if (!dx && !dy) return;+ for (const p of proof.panels) {+ p.x += dx;+ p.y += dy;+ }+ stage.position({ x: stage.x() - dx * stage.scaleX(), y: stage.y() - dy * stage.scaleY() });+ }++ // Fold a finished panel drag / corner-resize back into the document.+ function commitPanelNode(panel, node, { resized = false } = {}) {+ materializeFreePositions();+ if (resized) {+ // transformer scales the group; group scale = (PANEL_H·scale)/naturalH+ const next = (node.scaleX() * panel.natural[1]) / PANEL_H;+ panel.scale = Math.round(Math.min(SCALE_MAX, Math.max(SCALE_MIN, next)) * 100) / 100;+ }+ panel.x = node.x();+ panel.y = node.y();+ normalizeFree();+ dirty = true;+ }++ function setLayoutMode(mode) {+ if ((proof.layout ?? 'grid') === mode) return;+ proof.layout = mode;+ selectedPanelId = null;+ dirty = true;+ requestAnimationFrame(fit);+ }++ // Free mode: array order is the z-order, front→back (Z1 = foreground), so+ // "bring forward" swaps toward index 0 and "send backward" toward the end.+ function movePanelZ(index, delta) {+ const target = index + delta;+ if (target < 0 || target >= proof.panels.length) return;+ const [panel] = proof.panels.splice(index, 1);+ proof.panels.splice(target, 0, panel);+ dirty = true;+ }+// "Magic" tweet fit: re-pack panels into rows so the composite lands closest// to the active tweet aspect (the toggled 16:9 / 4:5 guide, else 16:9) and- // reset every panel to its default size.+ // reset every panel to its default size. Row packing is a grid concept, so+ // from free mode this also switches the proof back to the grid layout.function applyMagic() {if (!proof.panels.length) return;+ proof.layout = 'grid';+ selectedPanelId = null;const target = guide ? TWEET_GUIDES[guide] : TWEET_GUIDES['16:9'];const rows = autoLayoutRows(proof.panels, proof.shapes, proof.notes, textOpts(), target);proof.panels.forEach((p, i) => { p.row = rows[i]; p.scale = 1; });@@ -429,6 +485,7 @@proof.panels.splice(index, 1);normalizeRows();selectedId = null;+ selectedPanelId = null;dirty = true;requestAnimationFrame(fit);}@@ -437,7 +494,7 @@function fit() {if (!stage || !containerEl || !containerEl.clientWidth) return;- const { width, height } = docSize(proof.panels, proof.shapes, proof.notes, textOpts());+ const { width, height } = measureDoc();const k = Math.min((containerEl.clientWidth - 24) / width,(containerEl.clientHeight - 24) / height,@@ -463,9 +520,10 @@y: pointer.y - ((pointer.y - stage.y()) / old) * k,});if (guide) {- const { width, height } = docSize(proof.panels, proof.shapes, proof.notes, textOpts());+ const { width, height } = measureDoc();drawGuide(width, height);}+ drawPanelMoveControls(boxesOf()); // keep the arrow bar screen-sizedstage.batchDraw();}@@ -477,7 +535,8 @@}function panelAt(doc) {- const boxes = layoutPanels(proof.panels, proof.captionSize);+ const boxes = boxesOf();+ // array order is front→back, so the first hit is the topmost panelfor (let i = 0; i < boxes.length; i++) {const b = boxes[i];if (doc.x >= b.x && doc.x <= b.x + b.w && doc.y >= b.y && doc.y <= b.y + b.h) {@@ -498,7 +557,10 @@if (tool === 'select') {const onEmpty = e.target === stage || e.target.name() === 'bg';stage.draggable(onEmpty);- if (onEmpty) selectedId = null;+ if (onEmpty) {+ selectedId = null;+ selectedPanelId = null;+ }return;}stage.draggable(false);@@ -661,15 +723,19 @@function rebuild() {docLayer.destroyChildren();- const { width, height, legend, cols } = docSize(proof.panels, proof.shapes, proof.notes, textOpts(), proof.legendOrder);- const boxes = layoutPanels(proof.panels, proof.captionSize);+ const { width, height, legend, cols } = measureDoc();+ const boxes = boxesOf();const capSize = proof.captionSize ?? CAPTION_SIZE;+ const free = proof.layout === 'free';docLayer.add(new Konva.Rect({ name: 'bg', x: 0, y: 0, width, height, fill: BG }));- proof.panels.forEach((panel, i) => {+ // Drawn back→front: array order is front→back, so Z1 (the first panel in+ // the side list) is the foreground panel where free-mode panels overlap.+ for (let i = proof.panels.length - 1; i >= 0; i--) {+ const panel = proof.panels[i];const box = boxes[i];// Outer group is NOT clipped so an element can be dragged across panels;// only the image itself is clipped to the panel box (inner group).@@ -677,7 +743,37 @@id: `pg-${panel.id}`,x: box.x, y: box.y,scaleX: box.scale, scaleY: box.scale,+ draggable: free,+ });+ // Invisible full-panel hit target: the image itself never listens (so+ // drawing tools pass through to the stage), but the panel must catch+ // select-clicks — and, in free mode, drags. Added first so shapes stay+ // on top for hit-testing.+ group.add(new Konva.Rect({+ x: 0, y: 0, width: panel.natural[0], height: panel.natural[1],+ fill: 'transparent', listening: true,+ }));+ group.on('pointerdown', () => {+ // only the select tool touches panels — drawing must pass through+ group.draggable(free && tool === 'select' && !spacePan);+ if (tool === 'select') {+ selectedPanelId = panel.id;+ selectedId = null;+ }});+ if (free) {+ group.on('dragend', () => commitPanelNode(panel, group));+ group.on('transformend', () => commitPanelNode(panel, group, { resized: true }));+ } else {+ // grid: corner-drag only changes the panel's scale — the grid decides+ // where it sits, so the row re-flows around the new size+ group.on('transformend', () => {+ const next = (group.scaleX() * panel.natural[1]) / PANEL_H;+ panel.scale = Math.round(Math.min(SCALE_MAX, Math.max(SCALE_MIN, next)) * 100) / 100;+ dirty = true;+ requestAnimationFrame(fit);+ });+ }if (panel.img) {const imgClip = new Konva.Group({clip: { x: 0, y: 0, width: panel.natural[0], height: panel.natural[1] },@@ -700,14 +796,14 @@fill: TEXT_DIM, ellipsis: true, wrap: 'none', listening: false,}));}- });+ }// legend (colored dots) laid out in `cols` columns, then footer.// Dot + text scale with the legend font size and stay vertically centred.const legendSize = proof.legendSize ?? 17;const lineH = legendLineHeight(legendSize);const r = Math.round(legendSize * 0.62);- const legendTop = PAD + panelsBlockHeight(proof.panels, proof.captionSize) + 8;+ const legendTop = panelsBottom(proof.panels, proof.captionSize, proof.layout) + 8;const colW = (width - PAD * 2 - (cols - 1) * PAD) / cols;legend.filter((l) => l.text).forEach((line, i) => {const col = i % cols;@@ -737,19 +833,37 @@}// selection — keyed on the shape's kind, not the Konva node's class name,- // since a framed/backgrounded text renders as a Group rather than a Text+ // since a framed/backgrounded text renders as a Group rather than a Text.+ // A whole panel can be selected instead (both modes): corner anchors only+ // (aspect locked, elements scale along), never rotated. In grid mode the+ // resize keeps only the scale — the grid re-flows the position.const selectedNode = selectedId ? docLayer.findOne(`#${selectedId}`) : null;- transformer.nodes(selectedNode ? [selectedNode] : []);+ const panelNode = !selectedNode && selectedPanelId+ ? docLayer.findOne(`#pg-${selectedPanelId}`)+ : null;+ // Panels are scale-clamped *during* the gesture: letting the transform run+ // free and clamping on release made the panel visibly snap back whenever+ // the drag overshot the 25–250% range (worst at the bounds, where a resize+ // in the blocked direction just reverted). Shapes stay unconstrained.+ const boundPanel = panelNode ? proof.panels.find((p) => p.id === selectedPanelId) : null;+ transformer.boundBoxFunc((oldBox, newBox) => {+ if (!boundPanel) return newBox;+ const impliedScale =+ (newBox.width / stage.scaleX()) * (boundPanel.natural[1] / (boundPanel.natural[0] * PANEL_H));+ return impliedScale < SCALE_MIN || impliedScale > SCALE_MAX ? oldBox : newBox;+ });+ transformer.nodes(selectedNode ? [selectedNode] : panelNode ? [panelNode] : []);const selKind = selectedShape?.kind;transformer.rotateEnabled(selKind === 'text' || selKind === 'rect' || selKind === 'ellipse');transformer.enabledAnchors(selKind === 'rect' || selKind === 'ellipse'? ['top-left', 'top-right', 'bottom-left', 'bottom-right', 'middle-left', 'middle-right', 'top-center', 'bottom-center']- : selKind === 'text'+ : selKind === 'text' || panelNode? ['top-left', 'top-right', 'bottom-left', 'bottom-right']: []);drawEndHandles(boxes);+ drawPanelMoveControls(boxes);drawGuide(width, height);docLayer.batchDraw();uiLayer.batchDraw();@@ -834,11 +948,59 @@}}+ // Grid-mode panel controls: the selected panel (framed by the transformer)+ // gets a floating arrow bar above it — ← → swap within the row, ↑ ↓ change+ // rows — so panels are moved right where you look instead of via side-list+ // buttons. (Free mode needs no arrows: the panel itself is draggable.)+ // Redrawn on rebuild and on zoom (constant on-screen size).+ function drawPanelMoveControls(boxes) {+ panelCtrls.destroyChildren();+ if (proof.layout === 'free' || tool !== 'select' || !selectedPanelId) return;+ const i = proof.panels.findIndex((p) => p.id === selectedPanelId);+ if (i < 0) return;+ const box = boxes[i];+ const k = stage.scaleX();+ const buttons = [+ { glyph: '←', enabled: canMoveLeft(i), act: () => movePanel(i, -1) },+ { glyph: '→', enabled: canMoveRight(i), act: () => movePanel(i, 1) },+ { glyph: '↑', enabled: (proof.panels[i].row ?? 0) > 0, act: () => movePanelRow(i, -1) },+ { glyph: '↓', enabled: true, act: () => movePanelRow(i, 1) },+ ];+ const s = 30 / k;+ const gap = 6 / k;+ let bx = box.x + box.w / 2 - (buttons.length * s + (buttons.length - 1) * gap) / 2;+ const by = box.y - s - 10 / k; // floats just above the panel+ for (const b of buttons) {+ const g = new Konva.Group({+ x: bx, y: by, opacity: b.enabled ? 1 : 0.35, listening: b.enabled,+ });+ g.add(new Konva.Rect({+ width: s, height: s, cornerRadius: 6 / k,+ fill: '#161e2e', stroke: '#e8a33d', strokeWidth: 1.5 / k,+ }));+ g.add(new Konva.Text({+ width: s, height: s, text: b.glyph, fontSize: 15 / k, fill: TEXT_MAIN,+ align: 'center', verticalAlign: 'middle',+ fontFamily: 'system-ui, sans-serif', listening: false,+ }));+ // swallow the press so the stage doesn't treat it as an empty-deselect+ g.on('pointerdown', (e) => { e.cancelBubble = true; });+ g.on('click tap', (e) => {+ e.cancelBubble = true;+ b.act();+ });+ g.on('pointerenter', () => { containerEl.style.cursor = 'pointer'; });+ g.on('pointerleave', () => { containerEl.style.cursor = ''; });+ panelCtrls.add(g);+ bx += s + gap;+ }+ }+// On drop, re-bind a shape to whichever panel its anchor now sits over and// convert its coordinates into that panel's natural pixel space. Returns the// source/destination layout boxes so the caller can remap x/y or points.function rebindOnDrop(s, node) {- const boxes = layoutPanels(proof.panels, proof.captionSize);+ const boxes = boxesOf();const fromIdx = proof.panels.findIndex((p) => p.id === s.panel);if (fromIdx < 0) return { fromBox: null, toBox: null };const fromBox = boxes[fromIdx];@@ -856,6 +1018,7 @@const dx = fromBox.x + anchor.x * fromBox.scale;const dy = fromBox.y + anchor.y * fromBox.scale;let toIdx = fromIdx;+ // array order is front→back — the topmost panel claims the dropfor (let i = 0; i < boxes.length; i++) {const b = boxes[i];if (dx >= b.x && dx <= b.x + b.w && dy >= b.y && dy <= b.y + b.h) { toIdx = i; break; }@@ -920,6 +1083,7 @@if (tool === 'select') {e.cancelBubble = true;selectedId = s.id;+ selectedPanelId = null;}});node.on('dblclick dbltap', (e) => {@@ -973,6 +1137,7 @@if (tool === 'select') {e.cancelBubble = true;selectedId = s.id;+ selectedPanelId = null;}});node.on('dragstart', () => node.getParent()?.moveToTop());@@ -1017,7 +1182,7 @@// ---- inline text editing (double-click a label on the canvas) ---------------function startTextEdit(s, node) {- const boxes = layoutPanels(proof.panels, proof.captionSize);+ const boxes = boxesOf();const idx = proof.panels.findIndex((p) => p.id === s.panel);const panelScale = idx >= 0 ? boxes[idx].scale : 1;const abs = node.getAbsolutePosition(); // container px, stage transform included@@ -1192,8 +1357,12 @@}if ((e.key === 'Delete' || e.key === 'Backspace') && selectedId) {deleteShape(selectedId);+ } else if ((e.key === 'Delete' || e.key === 'Backspace') && selectedPanelId) {+ const idx = proof.panels.findIndex((p) => p.id === selectedPanelId);+ if (idx >= 0) removePanel(idx);} else if (e.key === 'Escape') {selectedId = null;+ selectedPanelId = null;tool = 'select';} else if (e.key === 'v') tool = 'select';else if (e.key === 'r') tool = 'rect';@@ -1217,7 +1386,7 @@// ---- persistence -------------------------------------------------------------------------function exportPng() {- const { width, height } = docSize(proof.panels, proof.shapes, proof.notes, textOpts());+ const { width, height } = measureDoc();const prevScale = stage.scale();const prevPos = stage.position();const prevSize = { w: stage.width(), h: stage.height() };@@ -1300,6 +1469,7 @@proof.legendSize = spec.legendSize ?? LEGEND_SIZE;proof.footerSize = spec.footerSize ?? FOOTER_SIZE;proof.footer = spec.footer ?? '';+ proof.layout = spec.layout ?? 'grid';for (const p of spec.panels) {try {const img = await loadImage(`/files/${caseState.current.id}/${p.src}`);@@ -1438,6 +1608,23 @@<div class="tb-sep"></div><button class="tb-btn" title="Fit view (f)" onclick={fit}><Icon name="eye" size={18} /></button><div class="tb-sep"></div>+ <button+ class="tb-btn"+ class:active={proof.layout !== 'free'}+ title="Grid layout — panels flow in rows; select one to move it with the on-canvas arrows"+ onclick={() => setLayoutMode('grid')}+ >+ <Icon name="grid" size={18} />+ </button>+ <button+ class="tb-btn"+ class:active={proof.layout === 'free'}+ title="Free layout — drag panels anywhere (overlap allowed), corner handles resize"+ onclick={() => setLayoutMode('free')}+ >+ <Icon name="layers" size={18} />+ </button>+ <div class="tb-sep"></div>{#each Object.keys(TWEET_GUIDES) as g (g)}<buttonclass="tb-btn tb-guide"@@ -1548,41 +1735,55 @@</button>{#if !collapsed.panels}{#each proof.panels as panel, i (panel.id)}- <div class="panel-row card">- <div class="panel-thumb">+ <div class="panel-row card" class:selected={selectedPanelId === panel.id}>+ <button+ class="panel-thumb"+ title="Select this panel on the canvas"+ onclick={() => (selectedPanelId = selectedPanelId === panel.id ? null : panel.id)}+ ><img src={`/files/${caseState.current?.id}/${panel.src}`} alt="" />- <span class="row-badge" title="Row (top→bottom)">R{(panel.row ?? 0) + 1}</span>- </div>+ {#if proof.layout === 'free'}+ <span class="row-badge" title="Stacking order — Z1 is the foreground">Z{i + 1}</span>+ {:else}+ <span class="row-badge" title="Row (top→bottom)">R{(panel.row ?? 0) + 1}</span>+ {/if}+ </button><inputclass="input cap-input"placeholder="Caption…"bind:value={panel.caption}onchange={() => (dirty = true)}/>+ <!-- one compact row: z-order (free only) · size · delete — moving a+ grid panel happens on the canvas (select it, use the arrows) --><div class="panel-actions">- <button class="btn btn-ghost btn-sm" disabled={!canMoveLeft(i)} title="Move left in row" onclick={() => movePanel(i, -1)}>←</button>- <button class="btn btn-ghost btn-sm" disabled={!canMoveRight(i)} title="Move right in row" onclick={() => movePanel(i, 1)}>→</button>- <button class="btn btn-ghost btn-sm" disabled={(panel.row ?? 0) === 0} title="Move up a row" onclick={() => movePanelRow(i, -1)}>↑</button>- <button class="btn btn-ghost btn-sm" title="Move down a row" onclick={() => movePanelRow(i, 1)}>↓</button>+ {#if proof.layout === 'free'}+ <button class="btn btn-ghost btn-sm" disabled={i === 0} title="Bring forward (toward Z1)" onclick={() => movePanelZ(i, -1)}>+ <Icon name="chevronUp" size={13} />+ </button>+ <button class="btn btn-ghost btn-sm" disabled={i === proof.panels.length - 1} title="Send backward" onclick={() => movePanelZ(i, 1)}>+ <Icon name="chevronDown" size={13} />+ </button>+ {/if}+ <div class="panel-scale" title="Panel size — elements scale with it">+ <button+ class="btn btn-ghost btn-sm"+ disabled={(panel.scale ?? 1) <= SCALE_MIN}+ title="Shrink panel"+ onclick={() => scalePanel(i, -SCALE_STEP)}+ >−</button>+ <span class="scale-val">{Math.round((panel.scale ?? 1) * 100)}%</span>+ <button+ class="btn btn-ghost btn-sm"+ disabled={(panel.scale ?? 1) >= SCALE_MAX}+ title="Enlarge panel"+ onclick={() => scalePanel(i, SCALE_STEP)}+ >+</button>+ </div><button class="btn btn-ghost btn-sm" style="margin-left:auto" title="Remove panel" onclick={() => removePanel(i)}><Icon name="trash" size={13} /></button></div>- <div class="panel-scale" title="Panel size — elements scale with it">- <button- class="btn btn-ghost btn-sm"- disabled={(panel.scale ?? 1) <= SCALE_MIN}- title="Shrink panel"- onclick={() => scalePanel(i, -SCALE_STEP)}- >−</button>- <span class="scale-val">{Math.round((panel.scale ?? 1) * 100)}%</span>- <button- class="btn btn-ghost btn-sm"- disabled={(panel.scale ?? 1) >= SCALE_MAX}- title="Enlarge panel"- onclick={() => scalePanel(i, SCALE_STEP)}- >+</button>- </div></div>{/each}{/if}@@ -1975,7 +2176,16 @@flex-direction: column;gap: 6px;}- .panel-thumb { position: relative; }+ .panel-thumb {+ position: relative;+ display: block;+ width: 100%;+ padding: 0;+ border: none;+ background: none;+ cursor: pointer;+ }+ .panel-row.selected { border-color: var(--accent); }.panel-row img {width: 100%;max-height: 90px;@@ -2034,12 +2244,12 @@}.adv-hint { font-size: 11px; color: var(--text-3); margin-top: 5px; }.cap-input { font-size: var(--fs-xs); padding: 5px 8px; }- .panel-actions { display: flex; gap: 2px; }+ .panel-actions { display: flex; align-items: center; gap: 2px; }.panel-scale {display: flex;align-items: center;- justify-content: center;gap: 4px;+ margin: 0 auto; /* centres the size control between z-order and delete */}.scale-val {min-width: 42px;diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelteindex 4770a73..07c6b17 100644--- a/frontend/src/tools/Satellite.svelte+++ b/frontend/src/tools/Satellite.svelte@@ -8,7 +8,13 @@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 { monthCount, tilesShort } from '../lib/usage.js';+ import {+ monthCount,+ tilesShort,+ usageBlocked,+ displayProviderId,+ layerCell,+ } from '../lib/usage.js';import { createViewer, nextZ, restack } from '../lib/refViewers.js';import Icon from '../components/Icon.svelte';import Modal from '../components/Modal.svelte';@@ -51,19 +57,27 @@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 (KEYED_PROVIDERS.md §4) — none built-in today, gate wired anyway+ // button (IMAGERY_PROVIDERS.md) — none built-in today, gate wired anywayconst captureBlocked = $derived(currentProvider?.capturable === false);- // --- keyed-provider usage (KEYED_PROVIDERS.md §6) ---+ // --- keyed-provider usage (IMAGERY_PROVIDERS.md) ---// Metered tiles are proxied through the backend, which counts each one it// actually serves — this readout just mirrors settings.json.let usageTotals = $state({});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 });async function refreshUsage() {try {const s = await api.get('/api/settings');usageTotals = s.usage;usageMonth = s.month;+ usagePrefs = {+ overrides: s.usage_overrides ?? {},+ eco: s.eco_zoom_fallback !== false,+ ecoMaxZoom: s.eco_max_zoom ?? 15,+ };} catch {/* readout only — never blocks the map */}@@ -75,6 +89,32 @@: null);+ // What the map actually shows: a billed basemap steps aside for free imagery+ // when paused (90% soft block) or zoomed out (eco). Captures and the imagery+ // date follow the display, so provenance always matches the pixels.+ const meterBlocked = $derived(+ currentProvider?.meter+ ? usageBlocked(+ monthCount(usageTotals, currentProvider.meter, usageMonth),+ currentProvider.meter,+ usagePrefs.overrides+ )+ : false+ );+ const displayedProviderId = $derived(+ displayProviderId(currentProvider, center.zoom, {+ eco: usagePrefs.eco,+ blocked: meterBlocked,+ ecoMaxZoom: usagePrefs.ecoMaxZoom,+ })+ );+ const displayedProvider = $derived(providers.find((p) => p.id === displayedProviderId));+ // memoized so the layer is only rebuilt when the cell actually changes+ // (i.e. crossing the z17 boost bracket), not on every zoom step+ const displayedCell = $derived(+ displayedProvider ? layerCell(displayedProvider, center.zoom) : 256+ );+// Acquisition date of the imagery under the crosshair — Esri only (item 2).let imageryDate = $state(null); // { supported, date, source } | nulllet dateReqId = 0;@@ -143,6 +183,7 @@}onMount(async () => {+ refreshUsage(); // prefs drive the eco/soft-block fallbacks from the startproviders = await api.get('/api/satellite/providers');// leaflet-rotate patches the global L, so expose it before importing.window.L = L;@@ -195,6 +236,8 @@function onKeydown(e) {if (uiState.tool !== 'satellite' || e.key !== 'Escape') return;+ // a dialog on top owns Escape — it closes itself, the map keeps its state+ if (notesItem || placeModal || refPicker || deleteTarget) return;if (selectArmed) toggleSelect();else if (sizeMenuOpen) sizeMenuOpen = false;else if (measureMode) setMeasureMode(null);@@ -236,7 +279,7 @@try {const r = await api.get(`/api/satellite/imagery-date?lat=${center.lat}&lon=${center.lon}` +- `&zoom=${center.zoom}&provider=${providerId}`+ `&zoom=${center.zoom}&provider=${displayedProviderId}`);if (id === dateReqId) imageryDate = r;} catch {@@ -249,7 +292,7 @@center.lat;center.lon;center.zoom;- providerId;+ displayedProviderId;if (!mapReady) return;clearTimeout(dateTimer);dateTimer = setTimeout(refreshImageryDate, 500);@@ -306,6 +349,13 @@editingBearing = false;}+ // Actions that leave the tool — switching to another tool, opening a browser+ // tab — can't do anything visible while the map owns the whole screen, so+ // they're greyed out rather than silently dropping the user out of it.+ const leavesFullscreen = $derived(+ fullscreen ? 'Exit fullscreen first — this leaves the map' : null+ );+// --- fullscreen (item 5) ---// Prefer the real Fullscreen API — it covers the OS/browser chrome too, unlike// the old fixed-overlay hack. Fall back to a CSS overlay where it's blocked@@ -458,17 +508,34 @@}function setLayer() {- const p = providers.find((x) => x.id === providerId);+ const p = displayedProvider;if (!p || !map) return;- // metered/keyed providers go through the backend tile proxy: the key and- // any session token stay server-side, and every billed tile is counted- // exactly once (browser cache hits never reach the proxy)- const url = p.meter ? `/api/tiles/${p.id}/{z}/{x}/{y}` : p.url;+ // 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 opts = { attribution: p.attribution, maxZoom: p.max_zoom };- if (p.tile_size === 512) {- // 512px tiles: same m/px at z-1, a quarter of the billed requests- opts.tileSize = 512;- opts.zoomOffset = -1;+ // 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+ // mosaics are genuinely softer than its deep ones (verified), so this is+ // what makes the paid imagery actually look paid.+ if (displayedCell !== 256 || p.tile_size > 256) {+ opts.tileSize = displayedCell;+ opts.zoomOffset = -Math.log2(displayedCell / 256);+ opts.minNativeZoom = 0; // never ask for negative URL z at world zooms+ }+ if (p.meter) {+ // billed tiles: skip the throwaway fetches Leaflet makes mid-zoom-animation+ // (intermediate zoom levels that get discarded). Deliberately NOT+ // updateWhenIdle: it delays sharp tiles until the map fully settles,+ // leaving the scaled-up previous zoom (visible blur) on screen — and it+ // saves nothing, since each visible tile is only ever fetched once.+ opts.updateWhenZooming = false;+ opts.keepBuffer = 4;}if (tileLayer) tileLayer.remove();tileLayer = L.tileLayer(url, opts).addTo(map);@@ -481,10 +548,25 @@}$effect(() => {- providerId; // track provider changes+ displayedProviderId; // track provider changes (incl. eco/block fallbacks)+ displayedCell; // and the z17 detail-boost bracketsetLayer();});+ // a basemap disabled in Settings can leave a stale selection — fall back+ $effect(() => {+ if (providers.length && !currentProvider) providerId = 'esri-world-imagery';+ });++ // re-sync providers + prefs when returning to this tab: Settings may have+ // toggled a basemap off (it must vanish from the selector) or changed the+ // eco / override prefs meanwhile (tools stay mounted, so no fresh onMount)+ $effect(() => {+ if (uiState.tool !== 'satellite' || !mapReady) return;+ refreshUsage();+ api.get('/api/satellite/providers').then((r) => (providers = r));+ });+$effect(() => {const id = caseState.current?.id;caseState.rev; // re-fetch when the case is reloaded elsewhere (e.g. sidebar delete)@@ -590,7 +672,7 @@// Output resolution: 1 = view zoom, 2 = one zoom deeper (2×), 'max' = provider max.let resolution = $state(1);- const providerMaxZoom = $derived(providers.find((p) => p.id === providerId)?.max_zoom ?? 19);+ const providerMaxZoom = $derived(displayedProvider?.max_zoom ?? 19);// Single capture button, split-style: the main part re-runs whichever mode// was used last (remembered here); the arrow opens mode + size/ratio/@@ -699,7 +781,8 @@zoom,width,height,- provider: providerId,+ // capture what's on screen: the eco/soft-block fallback, if active+ provider: displayedProviderId,bearing,marker_style: markerStyle,marker_x,@@ -714,8 +797,10 @@toast(result.tiles_missing? `Captured with ${result.tiles_missing} missing tile(s) — no imagery there`- : 'Satellite crop captured & filed',- result.tiles_missing ? 'warn' : 'ok'+ : result.tiles_upscaled+ ? `Captured — ${result.tiles_upscaled} tile(s) upscaled from a lower zoom (recorded in provenance)`+ : 'Satellite crop captured & filed',+ result.tiles_missing || result.tiles_upscaled ? 'warn' : 'ok');} catch (e) {toast(`Capture failed: ${e.message}`, 'danger', 6000);@@ -1255,6 +1340,18 @@title="Tiles requested from this billed provider this month — local counter, see Settings">{usagePill}</span>{/if}+ {#if currentProvider?.meter && displayedProviderId !== providerId}+ <span+ class="fallback-pill"+ class:paused={meterBlocked}+ title={meterBlocked+ ? `${currentProvider.label} passed 90% of its monthly free tier — showing free imagery instead. Override in Settings to keep using it (billed).`+ : `Eco mode: free imagery at low zoom — zoom in to get ${currentProvider.label} detail. Toggle in Settings.`}+ >+ <Icon name={meterBlocked ? 'alert' : 'leaf'} size={11} />+ {meterBlocked ? `${currentProvider.label} paused — free imagery` : 'eco — free imagery'}+ </span>+ {/if}<select class="select" bind:value={markerStyle} title="Marker style"><option value="crosshair">✛ crosshair</option><option value="pin">📍 pin</option>@@ -1447,7 +1544,15 @@{#if linksOpen}<div class="links-grid">{#each externalLinks as l (l.id)}- <a class="ext-link" href={l.url} target="_blank" rel="noreferrer" title={l.url}>+ <a+ class="ext-link"+ class:disabled={fullscreen}+ href={fullscreen ? undefined : l.url}+ target="_blank"+ rel="noreferrer"+ aria-disabled={fullscreen}+ title={leavesFullscreen ?? l.url}+ ><Icon name="globe" size={13} /><span>{l.label}</span><Icon name="external" size={12} />@@ -1537,10 +1642,12 @@<div class="cap card fade-up"><aclass="cap-goto"- href={`/files/${caseState.current.id}/${item.path}`}+ class:disabled={fullscreen}+ href={fullscreen ? undefined : `/files/${caseState.current.id}/${item.path}`}target="_blank"rel="noreferrer"- title="Open the full image"+ aria-disabled={fullscreen}+ title={leavesFullscreen ?? 'Open the full image'}><imgsrc={`/files/${caseState.current.id}/${item.path}`}@@ -1574,17 +1681,20 @@</button><buttonclass="btn btn-ghost btn-sm"- title="Send to Proof Composer"+ disabled={fullscreen}+ title={leavesFullscreen ?? 'Send to Proof Composer'}onclick={() => sendToComposer(item)}><Icon name="proof" size={14} /></button><aclass="btn btn-ghost btn-sm"- href={`/files/${caseState.current.id}/${item.path}`}+ class:disabled={fullscreen}+ href={fullscreen ? undefined : `/files/${caseState.current.id}/${item.path}`}target="_blank"rel="noreferrer"- title="Open"+ aria-disabled={fullscreen}+ title={leavesFullscreen ?? 'Open'}><Icon name="external" size={14} /></a>@@ -1773,6 +1883,10 @@flex: 1;min-width: 0;overflow: hidden;+ /* keep the map's z-index range (Leaflet panes/controls up to 1000, our own+ clusters above them) to itself, so a dialog portalled into the fullscreen+ tool still lands on top of it */+ isolation: isolate;}.map {position: absolute;@@ -2084,7 +2198,7 @@.capture-bar .select {width: auto;}- /* billed-provider tile counter (KEYED_PROVIDERS.md §6) — full readout in Settings */+ /* billed-provider tile counter (IMAGERY_PROVIDERS.md) — full readout in Settings */.usage-pill {font-size: var(--fs-xs);color: var(--text-3);@@ -2100,6 +2214,22 @@background: var(--border);margin: 0 2px;}+ /* eco / soft-block fallback: the billed basemap stepped aside for free imagery */+ .fallback-pill {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ font-size: var(--fs-xs);+ color: var(--ok);+ background: var(--bg-2);+ border: 1px solid var(--border);+ border-radius: 999px;+ padding: 3px 9px;+ white-space: nowrap;+ }+ .fallback-pill.paused {+ color: var(--danger);+ }/* the capture split-button: main action + arrow fused into one pill,mirroring .place-save's main/edit split */.capture-split {@@ -2371,10 +2501,16 @@text-overflow: ellipsis;white-space: nowrap;}- .ext-link:hover {+ .ext-link:hover:not(.disabled) {color: var(--accent);border-color: var(--accent);}+ /* fullscreen: leaving for another tab would drop the map anyway (see+ leavesFullscreen) */+ .ext-link.disabled {+ opacity: 0.45;+ cursor: not-allowed;+ }.ext-link :global(svg:last-child) {color: var(--text-3);flex-shrink: 0;@@ -2456,10 +2592,13 @@object-fit: cover;background: var(--bg-2);}- .cap-goto:hover img {+ .cap-goto.disabled {+ cursor: not-allowed;+ }+ .cap-goto:hover:not(.disabled) img {opacity: 0.9;}- .cap-goto:hover .coords {+ .cap-goto:hover:not(.disabled) .coords {color: var(--accent);}.cap-meta {diff --git a/frontend/src/tools/Settings.svelte b/frontend/src/tools/Settings.svelteindex 8cac517..b832d0d 100644--- a/frontend/src/tools/Settings.svelte+++ b/frontend/src/tools/Settings.svelte@@ -2,10 +2,18 @@import { onMount } from 'svelte';import { api } from '../lib/api.js';import { toast } from '../lib/state.svelte.js';- import { monthCount, tilesOfFree, freeTierShare } from '../lib/usage.js';+ import {+ monthCount,+ tilesOfFree,+ freeTierShare,+ usageBlocked,+ USAGE_LINKS,+ BLOCK_SHARE,+ ECO_MAX_ZOOM,+ } from '../lib/usage.js';import Icon from '../components/Icon.svelte';- // The keyed imagery providers the app knows how to light up (KEYED_PROVIDERS.md).+ // 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.const KEYED = [@@ -15,9 +23,10 @@field: 'Mapbox public access token',placeholder: 'pk.…',help: 'https://account.mapbox.com/access-tokens/',+ usage: USAGE_LINKS.mapbox,unlocks: 'Mapbox Satellite basemap',overage:- 'Beyond the free tier, Mapbox bills extra tiles automatically (pay-as-you-go, per 1,000). Set a spending alert in your Mapbox account.',+ 'Beyond 200k free tiles/month, Mapbox bills extra tiles automatically ($0.50 per 1,000, pay-as-you-go — no hard cap available). Set a spending alert in your Mapbox account.',},{id: 'google',@@ -25,9 +34,10 @@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)',overage:- 'Beyond the free tier, Google bills extra tiles to your Cloud project (per 1,000). A quota cap in the Cloud Console makes it stop serving instead of billing.',+ '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.',},];@@ -38,12 +48,35 @@let saving = $state(false);let testing = $state({ mapbox: false, google: false });let testResult = $state({ mapbox: null, google: 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 eco = $state(true);+ let ecoMaxZoom = $state(ECO_MAX_ZOOM);async function load() {const s = await api.get('/api/settings');keys = { mapbox: s.api_keys.mapbox ?? '', google: s.api_keys.google ?? '' };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 };+ eco = s.eco_zoom_fallback;+ ecoMaxZoom = s.eco_max_zoom ?? ECO_MAX_ZOOM;+ }++ async function savePrefs() {+ try {+ const saved = await api.put('/api/settings/prefs', {+ providers_enabled: enabled,+ usage_overrides: overrides,+ eco_zoom_fallback: eco,+ eco_max_zoom: Number(ecoMaxZoom) || ECO_MAX_ZOOM,+ });+ ecoMaxZoom = saved.eco_max_zoom; // reflect the server's clamping+ } catch (e) {+ toast(`Could not save preferences: ${e.message}`, 'danger');+ }}onMount(() => {@@ -133,6 +166,15 @@</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"+ >+ <input type="checkbox" bind:checked={enabled[k.id]} onchange={savePrefs} />+ 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} />@@ -166,16 +208,34 @@{@const share = freeTierShare(count, k.id)}<div class="usage-row"><div class="usage-line">- <span class="usage-name">{k.label}</span>+ <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><div class="meter-track" aria-hidden="true"><divclass="meter-fill"- class:hot={share >= 0.9}+ class:hot={share >= BLOCK_SHARE}style="width:{Math.min(share * 100, 100)}%"></div></div>+ {#if usageBlocked(count, k.id, overrides)}+ <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={savePrefs} />+ keep serving past {Math.round(BLOCK_SHARE * 100)}% (billed)+ </label>+ {/if}<p class="overage">{k.overage}</p></div>{/if}@@ -184,6 +244,23 @@{:else}<p class="none">No keyed provider configured yet.</p>{/if}+ <label+ class="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={savePrefs} />+ Eco mode: use free imagery when zoomed out, up to z ≤+ <input+ class="input eco-zoom"+ type="number"+ min="1"+ max="21"+ bind:value={ecoMaxZoom}+ onchange={savePrefs}+ disabled={!eco}+ 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>@@ -336,6 +413,50 @@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;+ }+ .toggle {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ font-size: var(--fs-xs);+ color: var(--text-2);+ cursor: pointer;+ user-select: none;+ }+ .toggle input {+ accent-color: var(--accent);+ margin: 0;+ }+ .toggle.override {+ margin-top: 6px;+ color: var(--danger);+ }+ .toggle.eco {+ display: flex;+ margin: 2px 0 10px;+ }+ .eco-zoom {+ width: 58px;+ padding: 2px 6px;+ font-family: var(--font-mono);+ }+ .blocked {+ margin-top: 6px;+ color: var(--danger);+ font-size: var(--fs-xs);+ display: flex;+ align-items: center;+ gap: 5px;+ line-height: 1.4;+ }.none {color: var(--text-3);font-size: var(--fs-sm);diff --git a/frontend/src/tools/inspect/CollageCanvas.svelte b/frontend/src/tools/inspect/CollageCanvas.svelteindex c415b43..d656495 100644--- a/frontend/src/tools/inspect/CollageCanvas.svelte+++ b/frontend/src/tools/inspect/CollageCanvas.svelte@@ -1,5 +1,8 @@<script>- import { quadMatrix3d, quadCentroid, rotateQuad, quadEdgeMidpoints, scaleQuad } from '../../lib/inspect.js';+ import {+ quadMatrix3d, quadCentroid, rotateQuad, quadEdgeMidpoints, scaleQuad,+ quadsBounds, moveQuads, rotateQuads, scaleQuads,+ } from '../../lib/inspect.js';import { uiState } from '../../lib/state.svelte.js';import Icon from '../../components/Icon.svelte';@@ -8,7 +11,11 @@// corner handle to warp — a hand-made panorama. The same quads are sent to the// backend, which renders the full-res warp with PIL (see compose_perspective).// `collage` is the session's *active* collage (a session may hold several).- let { collage, selectedId = $bindable(), requestCrop } = $props();+ //+ // Selection is a *set*: shift-click adds/removes a piece. One piece gets the+ // per-piece handles (warp corners, side resize, rotate, toolbar); several get+ // a single block frame that moves/rotates/scales them as one rigid unit.+ let { collage, selectedIds = $bindable([]), requestCrop } = $props();let wrapEl = $state();let availW = $state(800);@@ -16,7 +23,19 @@let zoom = $state(1); // 1 = fit; wheel zooms toward the pointerlet panX = $state(0);let panY = $state(0);- let movingId = $state(null); // piece being dragged — semi-transparent to align+ let movingIds = $state([]); // pieces being dragged — semi-transparent to align++ const isSel = (id) => selectedIds.includes(id);+ const selectedNodes = $derived(collage.nodes.filter((n) => isSel(n.id)));+ const soloId = $derived(selectedNodes.length === 1 ? selectedNodes[0].id : null);+ // the block frame: only once several pieces are selected+ const groupBox = $derived(+ selectedNodes.length > 1 ? quadsBounds(selectedNodes.map((n) => n.quad)) : null+ );++ function toggleSel(id) {+ selectedIds = isSel(id) ? selectedIds.filter((x) => x !== id) : [...selectedIds, id];+ }const cw = $derived(collage.width);const ch = $derived(collage.height);@@ -56,7 +75,7 @@// Drag on the empty background pans the view (a plain click still deselects).function startPan(e) {- selectedId = null;+ selectedIds = [];const sx = e.clientX;const sy = e.clientY;const ox = panX;@@ -73,21 +92,63 @@window.addEventListener('pointerup', up);}+ // Shift-click adds/removes a piece from the block without moving anything.+ // Otherwise: pressing a piece *outside* the block selects just it; pressing one+ // already *inside* the block keeps the whole selection, so the drag carries every+ // piece — and, if the pointer never really moved, collapses to that single piece+ // on release (a plain click still means "just this one").function startMove(e, node) {e.preventDefault();- selectedId = node.id;- movingId = node.id;- let [px, py] = toCanvas(e);+ if (e.shiftKey) {+ toggleSel(node.id);+ return;+ }+ const group = isSel(node.id) ? collage.nodes.filter((n) => isSel(n.id)) : [node];+ if (!isSel(node.id)) selectedIds = [node.id];+ const base = group.map((n) => n.quad.map(([x, y]) => [x, y]));+ const [px, py] = toCanvas(e);+ let moved = false;const move = (ev) => {const [nx, ny] = toCanvas(ev);- const dx = nx - px;- const dy = ny - py;- node.quad = node.quad.map(([x, y]) => [x + dx, y + dy]);- px = nx;- py = ny;+ if (!moved) {+ // ignore the sub-pixel jitter of a click, so it can still collapse the block+ if (Math.hypot(nx - px, ny - py) * scale < 3) return;+ moved = true;+ movingIds = group.map((n) => n.id); // once, not on every move+ }+ // always re-derive from the quads captured at press: accumulating deltas+ // would drift the piece away from the pointer over a long drag+ const out = moveQuads(base, nx - px, ny - py);+ group.forEach((n, i) => (n.quad = out[i]));+ };+ const up = () => {+ if (!moved && group.length > 1) selectedIds = [node.id];+ movingIds = [];+ window.removeEventListener('pointermove', move);+ window.removeEventListener('pointerup', up);+ };+ window.addEventListener('pointermove', move);+ window.addEventListener('pointerup', up);+ }++ // Block rotate / resize share one shape: snapshot the selected quads and the+ // pivot *once* at press, then map a pure group transform over them until+ // release. Re-deriving the pivot mid-drag would chase the block's own bounding+ // box and walk it away under the pointer.+ function dragGroup(e, transform) {+ e.preventDefault();+ e.stopPropagation();+ const group = collage.nodes.filter((n) => isSel(n.id));+ const base = group.map((n) => n.quad.map(([x, y]) => [x, y]));+ const bounds = quadsBounds(base);+ if (!bounds) return;+ const c = bounds.center;+ const start = toCanvas(e);+ const move = (ev) => {+ const out = transform(base, c, toCanvas(ev), start);+ group.forEach((n, i) => (n.quad = out[i]));};const up = () => {- movingId = null;window.removeEventListener('pointermove', move);window.removeEventListener('pointerup', up);};@@ -95,10 +156,25 @@window.addEventListener('pointerup', up);}+ // Angle the pointer has swept around the block's centre since the press.+ const startGroupRotate = (e) =>+ dragGroup(e, (base, c, [mx, my], [sx, sy]) =>+ rotateQuads(base, Math.atan2(my - c[1], mx - c[0]) - Math.atan2(sy - c[1], sx - c[0]), c));++ // Uniform scale about the block's centre, tracking the handle's distance from+ // it — the block grows as one, so the pieces spread apart instead of each+ // swelling in place (matches the per-piece side handles' feel).+ const startGroupResize = (e) =>+ dragGroup(e, (base, c, [mx, my], [sx, sy]) => {+ const d0 = Math.hypot(sx - c[0], sy - c[1]) || 1;+ const k = Math.min(20, Math.max(0.05, Math.hypot(mx - c[0], my - c[1]) / d0));+ return scaleQuads(base, k, c);+ });+function startWarp(e, node, corner) {e.preventDefault();e.stopPropagation();- selectedId = node.id;+ selectedIds = [node.id];const move = (ev) => {node.quad[corner] = toCanvas(ev);node.quad = [...node.quad];@@ -118,7 +194,7 @@function startEdgeResize(e, node, side) {e.preventDefault();e.stopPropagation();- selectedId = node.id;+ selectedIds = [node.id];const c = quadCentroid(node.quad);const base = node.quad.map(([x, y]) => [x, y]);const mid = quadEdgeMidpoints(base)[side];@@ -152,19 +228,19 @@collage.nodes = [...nodes];}- // Delete / Backspace removes the selected piece. The Inspect tool stays+ // Delete / Backspace removes every selected piece. The Inspect tool stays// mounted when another tab is shown, so bail unless it is the visible tool —// and when typing in a field or when a modal (e.g. the crop editor) is open.function onKey(e) {if (uiState.tool !== 'inspect') return;- if (selectedId == null) return;+ if (!selectedIds.length) return;if (e.key !== 'Delete' && e.key !== 'Backspace') return;const t = e.target;if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return;if (document.querySelector('.overlay')) return;e.preventDefault();- collage.nodes = collage.nodes.filter((n) => n.id !== selectedId);- selectedId = null;+ collage.nodes = collage.nodes.filter((n) => !isSel(n.id));+ selectedIds = [];}// Rotate the piece around its centroid by dragging the rotate handle around@@ -172,7 +248,7 @@function startRotate(e, node) {e.preventDefault();e.stopPropagation();- selectedId = node.id;+ selectedIds = [node.id];const c = quadCentroid(node.quad);const base = node.quad.map(([x, y]) => [x, y]);const [sx, sy] = toCanvas(e);@@ -214,8 +290,8 @@{@const box = boxOf(node)}<imgclass="node"- class:selected={node.id === selectedId}- class:ghost={node.ghost || node.id === movingId}+ class:selected={isSel(node.id)}+ class:ghost={node.ghost || movingIds.includes(node.id)}src={box.url}alt="collage piece"style:width={`${box.w}px`}@@ -223,9 +299,9 @@style:transform={quadMatrix3d(box.w, box.h, node.quad)}draggable="false"onpointerdown={(e) => (e.stopPropagation(), startMove(e, node))}- ondblclick={() => { selectedId = node.id; requestCrop?.(node); }}+ ondblclick={() => { selectedIds = [node.id]; requestCrop?.(node); }}/>- {#if node.id === selectedId}+ {#if node.id === soloId}<!-- round corner handles: free perspective warp -->{#each node.quad as pt, i (i)}<button@@ -333,6 +409,54 @@</div>{/if}{/each}++ <!-- Block frame for a multi-piece selection: one axis-aligned box around the+ lot, with corner handles that scale it and a knob that turns it — all+ about the box's centre, so the pieces hold their relative places. The+ box itself never listens, so the pieces under it stay clickable. -->+ {#if groupBox}+ <div+ class="group-box"+ style:left={`${groupBox.minX}px`}+ style:top={`${groupBox.minY}px`}+ style:width={`${groupBox.width}px`}+ style:height={`${groupBox.height}px`}+ style:border-width={`${1.5 / scale}px`}+ ></div>+ {#each [[groupBox.minX, groupBox.minY], [groupBox.maxX, groupBox.minY], [groupBox.maxX, groupBox.maxY], [groupBox.minX, groupBox.maxY]] as corner, i (i)}+ <button+ class="side-handle"+ style:left={`${corner[0]}px`}+ style:top={`${corner[1]}px`}+ style:width={`${14 / scale}px`}+ style:height={`${14 / scale}px`}+ onpointerdown={startGroupResize}+ aria-label="Resize the selected block"+ title="Drag to resize the whole selection"+ ></button>+ {/each}+ <!-- rotate knob on a stem off the block's right edge (mirrors the per-piece one) -->+ <div+ class="rot-stem"+ style:left={`${groupBox.maxX}px`}+ style:top={`${groupBox.center[1]}px`}+ style:width={`${24 / scale}px`}+ style:height={`${1.5 / scale}px`}+ style:transform={`translateY(${-0.75 / scale}px)`}+ ></div>+ <button+ class="rot-handle"+ style:left={`${groupBox.maxX + 24 / scale}px`}+ style:top={`${groupBox.center[1]}px`}+ style:width={`${20 / scale}px`}+ style:height={`${20 / scale}px`}+ onpointerdown={startGroupRotate}+ aria-label="Rotate the selected block"+ title="Drag to rotate the whole selection"+ >+ <Icon name="reset" size={13 / scale} />+ </button>+ {/if}</div><div class="view-ctl">@@ -342,7 +466,7 @@<Icon name="eye" size={14} /> Fit</button>{:else}- <span class="zoom-hint">scroll to zoom · drag background to pan</span>+ <span class="zoom-hint">scroll to zoom · drag background to pan · shift-click to select several</span>{/if}</div>@@ -399,6 +523,14 @@.node.ghost {opacity: 0.55;}+ /* Frame around a multi-piece selection. Never listens — the pieces it spans+ (and their own handles) must stay clickable through it. */+ .group-box {+ position: absolute;+ border-style: dashed;+ border-color: var(--accent);+ pointer-events: none;+ }.tbtn.on {background: var(--accent-soft);}diff --git a/frontend/src/tools/inspect/CollageMenu.svelte b/frontend/src/tools/inspect/CollageMenu.svelteindex dd78caf..002c625 100644--- a/frontend/src/tools/inspect/CollageMenu.svelte+++ b/frontend/src/tools/inspect/CollageMenu.svelte@@ -1,23 +1,30 @@<script>- import { previewStyle, scaleQuad, rotateQuad, quadCentroid, cropImgStyle, styleText, uid } from '../../lib/inspect.js';+ import {+ previewStyle, scaleQuad, rotateQuad, quadCentroid, cropImgStyle, styleText, uid,+ rotateQuads, scaleQuads,+ } from '../../lib/inspect.js';import Icon from '../../components/Icon.svelte';// Right-panel menu for the Collage tab: switch/create collages, add tray frames// 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, selectedId = $bindable(), addToCollage, requestCrop } = $props();+ let { session, filters, selectedIds = $bindable([]), addToCollage, requestCrop } = $props();const active = $derived(session.collages.find((c) => c.id === session.activeCollageId) ?? session.collages[0]);const onCanvas = (id) => active?.nodes.some((n) => n.frameId === id);- const selected = $derived(active?.nodes.find((n) => n.id === selectedId) ?? null);+ // These controls act on one piece; a multi-piece block is transformed as a+ // whole on the canvas, so the section simply steps aside for it.+ const selected = $derived(+ selectedIds.length === 1 ? (active?.nodes.find((n) => n.id === selectedIds[0]) ?? null) : null+ );function switchCollage(id) {session.activeCollageId = id;- selectedId = null;+ selectedIds = [];}function addCollage() {@@ -26,19 +33,19 @@const c = { id: uid('cl'), name: `Collage ${next}`, width: 1600, height: 800, background: '#12141c', transparent: true, nodes: [] };session.collages.push(c);session.activeCollageId = c.id;- selectedId = null;+ selectedIds = [];}function removeCollage(id) {if (session.collages.length <= 1) return; // always keep at least onesession.collages = session.collages.filter((c) => c.id !== id);if (session.activeCollageId === id) session.activeCollageId = session.collages[0].id;- selectedId = null;+ selectedIds = [];}function removeNode(id) {active.nodes = active.nodes.filter((n) => n.id !== id);- if (selectedId === id) selectedId = null;+ selectedIds = selectedIds.filter((x) => x !== id);}function bringFront(id) {@@ -72,6 +79,27 @@function rotateByDeg(node, deg) {node.quad = rotateQuad(node.quad, (deg * Math.PI) / 180, quadCentroid(node.quad));}++ // ---- multi-piece block ----------------------------------------------------+ // Same precise steps as the single-piece section, but about the block's shared+ // centre — the exact counterpart of the on-canvas block handles.+ const selectedGroup = $derived(+ selectedIds.length > 1 ? (active?.nodes.filter((n) => selectedIds.includes(n.id)) ?? []) : []+ );++ function applyToGroup(out) {+ selectedGroup.forEach((n, i) => (n.quad = out[i]));+ }++ const scaleGroupBy = (k) => applyToGroup(scaleQuads(selectedGroup.map((n) => n.quad), k));++ const rotateGroupByDeg = (deg) =>+ applyToGroup(rotateQuads(selectedGroup.map((n) => n.quad), (deg * Math.PI) / 180));++ function removeGroup() {+ active.nodes = active.nodes.filter((n) => !selectedIds.includes(n.id));+ selectedIds = [];+ }</script><div class="module">@@ -92,7 +120,7 @@</div></div>- <p class="hint">Pieces are the frames you captured. Add them, drag to arrange, pull corners to warp into a panorama.</p>+ <p class="hint">Pieces are the frames you captured. Add them, drag to arrange, pull corners to warp into a panorama. Shift-click to select several and move them as one block.</p><div class="section"><div class="section-head"><span>Frames</span></div>@@ -145,6 +173,30 @@</div>{/if}+ {#if selectedGroup.length > 1}+ <div class="section">+ <div class="section-head"><span>Selected block <span class="count">{selectedGroup.length}</span></span></div>+ <p class="hint">Scales and turns as one, about the block's centre. Shift-click a piece to add or drop it.</p>+ <div class="scale-row">+ <span class="lbl">Scale</span>+ <button class="btn btn-sm sq" onclick={() => scaleGroupBy(1 / 1.1)} aria-label="Shrink block">−</button>+ <button class="btn btn-sm sq" onclick={() => scaleGroupBy(1.1)} aria-label="Enlarge block">+</button>+ <span class="sub">or drag a block corner</span>+ </div>+ <div class="scale-row">+ <span class="lbl">Rotate</span>+ <button class="btn btn-sm sq" onclick={() => rotateGroupByDeg(-15)} aria-label="Rotate block left">↺</button>+ <button class="btn btn-sm sq" onclick={() => rotateGroupByDeg(15)} aria-label="Rotate block right">↻</button>+ <span class="sub">or drag the ↻ knob</span>+ </div>+ <div class="actions">+ <button class="btn btn-sm danger" onclick={removeGroup} title="or press Delete">+ <Icon name="trash" size={13} /> Remove {selectedGroup.length}+ </button>+ </div>+ </div>+ {/if}+<button class="btn btn-sm w-full" disabled title="Automatic stitching is coming soon"><Icon name="hash" size={14} /> Auto panorama (coming soon)</button>diff --git a/src/azimut/__init__.py b/src/azimut/__init__.pyindex 03dd29f..43bec69 100644--- a/src/azimut/__init__.py+++ b/src/azimut/__init__.py@@ -1,3 +1,3 @@"""Azimut — the OSINT investigator's workbench."""-__version__ = "0.1.0"+__version__ = "0.1.1"diff --git a/src/azimut/api/satellite.py b/src/azimut/api/satellite.pyindex 6783cd7..5e417b1 100644--- a/src/azimut/api/satellite.py+++ b/src/azimut/api/satellite.py@@ -8,10 +8,18 @@ from typing import Anyimport httpxfrom fastapi import APIRouter, HTTPExceptionfrom fastapi.responses import Response+from PIL import Imagefrom pydantic import BaseModel, Fieldfrom .. import config-from ..engine import geo, google_tiles, media as media_engine, satellite as satellite_engine, tiles+from ..engine import (+ geo,+ google_tiles,+ media as media_engine,+ satellite as satellite_engine,+ tilecache,+ tiles,+)from ..workspace import CaseErrorfrom .cases import get_case@@ -72,25 +80,26 @@ def providers() -> list[dict[str, Any]]:"session": p.session,"meter": p.meter,"tile_size": p.tile_size,+ "oversample": p.oversample,}for p in tiles.all_providers()][email protected]("/tiles/{provider_id}/{z}/{x}/{y}")-def tile_proxy(provider_id: str, z: int, x: int, y: int) -> Response:- """Live-map tiles for keyed providers, proxied through the app.+def _serve_tile(+ provider: tiles.Provider, z: int, x: int, y: int+) -> tuple[bytes, str, dict[str, str]] | Response | None:+ """One tile: disk cache first (cacheable providers), then upstream.- Two reasons (docs/KEYED_PROVIDERS.md §3/§6): the API key and Google session- token never reach the browser, and the meter counts *exactly* what the- provider bills — one bump per tile actually served; a browser cache hit- never reaches this endpoint, so it never over-counts. Nothing is stored- server-side: the provider's own Cache-Control is passed through untouched.+ Returns ``(content, media_type, headers)`` for a served tile, ``None`` when+ the provider has no imagery there (404 or a known placeholder tile), or a+ passthrough ``Response`` for any other upstream error. The meter counts+ exactly what the provider billed: every upstream 2xx/3xx, never a cache hit."""- try:- provider = tiles.get_provider(provider_id)- except KeyError as exc:- raise HTTPException(status_code=404, detail=str(exc)) from exc+ if provider.cacheable:+ cached = tilecache.get(provider.id, z, x, y)+ if cached:+ return cached[0], cached[1], {"Cache-Control": "private, max-age=86400"}upstream: httpx.Response | None = Nonefor attempt in (1, 2):@@ -111,17 +120,83 @@ def tile_proxy(provider_id: str, z: int, x: int, y: int) -> Response:continuebreak- if provider.meter and upstream.status_code < 400:+ if upstream.status_code == 404:+ return None+ if upstream.status_code >= 400:+ return Response(+ content=upstream.content,+ status_code=upstream.status_code,+ media_type=upstream.headers.get("content-type", "image/png"),+ )+ if provider.meter:config.record_usage(provider.meter, 1)+ if tiles.is_placeholder_tile(upstream.content):+ return None # billed above (the provider did serve it), but not imagery+ media_type = upstream.headers.get("content-type", "image/png")+ if provider.cacheable:+ tilecache.put(provider.id, z, x, y, upstream.content, media_type)headers = {}if upstream.headers.get("cache-control"):headers["Cache-Control"] = upstream.headers["cache-control"]- return Response(- content=upstream.content,- status_code=upstream.status_code,- media_type=upstream.headers.get("content-type", "image/png"),- headers=headers,- )+ return upstream.content, media_type, headers++[email protected]("/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.++ Why a proxy (docs/IMAGERY_PROVIDERS.md): API keys and the Google+ session token never reach the browser; the meter counts *exactly* what a+ billed provider serves (a browser cache hit never reaches this endpoint);+ cacheable providers get the shared disk tile cache; and coverage gaps+ (404s / "not yet available" placeholders) are overzoomed — the parent+ tile's quadrant upscaled — instead of breaking the map.+ """+ try:+ provider = tiles.get_provider(provider_id)+ except KeyError as exc:+ raise HTTPException(status_code=404, detail=str(exc)) from exc+ if provider.meter and config.usage_blocked(provider.meter):+ raise HTTPException(+ status_code=429,+ detail=f"{provider.label} is paused: {int(config.BLOCK_SHARE * 100)}% of the "+ "monthly free tier is used — enable the override in Settings to keep going",+ )++ served = _serve_tile(provider, z, x, y)+ if isinstance(served, Response):+ return served+ if served is not None:+ content, media_type, headers = served+ return Response(content=content, media_type=media_type, headers=headers)++ # no imagery at this zoom — climb parents and upscale the matching quadrant+ import io++ for up in range(1, tiles.OVERZOOM_LEVELS + 1):+ if z - up < 0:+ break+ parent = _serve_tile(provider, z - up, x >> up, y >> up)+ if parent is None or isinstance(parent, Response):+ continue+ image = Image.open(io.BytesIO(parent[0])).convert("RGB")+ sub = image.width >> up+ if sub < 1:+ break+ mask = (1 << up) - 1+ qx, qy = (x & mask) * sub, (y & mask) * sub+ tile = image.crop((qx, qy, qx + sub, qy + sub)).resize(+ (image.width, image.width), Image.Resampling.LANCZOS+ )+ buf = io.BytesIO()+ tile.save(buf, format="PNG")+ return Response(+ content=buf.getvalue(),+ media_type="image/png",+ # derived, cheap to rebuild from the cached parent — short-lived+ headers={"Cache-Control": "private, max-age=3600", "X-Azimut-Overzoom": str(up)},+ )+ raise HTTPException(status_code=404, detail="no imagery at this location/zoom")@router.get("/satellite/imagery-date")diff --git a/src/azimut/api/settings.py b/src/azimut/api/settings.pyindex dca2ff7..4513ba5 100644--- a/src/azimut/api/settings.py+++ b/src/azimut/api/settings.py@@ -1,6 +1,6 @@"""REST API for app-wide settings: API keys and per-provider usage counters.-Keys are the user's own billing identity (docs/KEYED_PROVIDERS.md §0): stored+Keys are the user's own billing identity (docs/IMAGERY_PROVIDERS.md): storedlocally in settings.json, app-wide (never per-case), never written into a casefolder or export bundle. Usage counters are local bookkeeping only."""@@ -29,6 +29,18 @@ class KeysIn(BaseModel):google: str | None = None+class PrefsIn(BaseModel):+ """Keyed-provider preferences — None leaves a field untouched."""++ # {"mapbox": bool, "google": bool}: basemap on/off without touching the key+ providers_enabled: dict[str, bool] | None = None+ # {"mapbox": bool, ...}: keep serving past the 90% soft block (billed)+ usage_overrides: dict[str, bool] | None = None+ # swap billed basemaps for free imagery at low zoom (≤ eco_max_zoom)+ eco_zoom_fallback: bool | None = None+ eco_max_zoom: int | None = None # clamped to a sane zoom range++@router.get("/settings")def get_settings() -> dict[str, Any]:settings = config.load_settings()@@ -36,6 +48,37 @@ def get_settings() -> dict[str, Any]:"api_keys": settings.get("api_keys", {}),"usage": settings.get("usage", {}),"month": config.month_key(),+ "providers_enabled": settings.get("providers_enabled", {}),+ "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)),+ # server-side constants the UI mirrors+ "free_tier": config.FREE_TIER,+ "block_share": config.BLOCK_SHARE,+ }++[email protected]("/settings/prefs")+def put_prefs(body: PrefsIn) -> dict[str, Any]:+ settings = config.load_settings()+ if body.providers_enabled is not None:+ merged = dict(settings.get("providers_enabled", {}))+ merged.update({k: bool(v) for k, v in body.providers_enabled.items() if k in KEYED_PROVIDERS})+ settings["providers_enabled"] = merged+ if body.usage_overrides is not None:+ merged = dict(settings.get("usage_overrides", {}))+ merged.update({k: bool(v) for k, v in body.usage_overrides.items() if k in KEYED_PROVIDERS})+ settings["usage_overrides"] = merged+ if body.eco_zoom_fallback is not None:+ 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)))+ config.save_settings(settings)+ return {+ "providers_enabled": settings.get("providers_enabled", {}),+ "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)),}diff --git a/src/azimut/config.py b/src/azimut/config.pyindex b6c8556..70dbfe1 100644--- a/src/azimut/config.py+++ b/src/azimut/config.py@@ -13,6 +13,7 @@ No database server — plain files only (spec §4).from __future__ import annotations+import copyimport jsonimport osimport threading@@ -31,8 +32,31 @@ DEFAULT_SETTINGS: dict[str, Any] = {# Per-provider monthly tile-request counters: {"<provider_id>": {"YYYY-MM": count}}.# Local bookkeeping only, for billed keyed providers (Mapbox, Google)."usage": {},+ # Keyed-provider preferences (docs/IMAGERY_PROVIDERS.md):+ # - providers_enabled: {"mapbox": bool, "google": bool} — absent means enabled;+ # a saved key can be kept while the basemap is hidden from the selector.+ # - usage_overrides: {"mapbox": bool, ...} — serve past the 90% soft block,+ # accepting the provider's billing. Off by default.+ # - eco_zoom_fallback: at low zoom (≤ eco_max_zoom) the live map swaps a+ # billed basemap for free imagery; paid detail only matters zoomed in.+ "providers_enabled": {},+ "usage_overrides": {},+ "eco_zoom_fallback": True,+ "eco_max_zoom": 15,}+# Documented monthly free allowances per meter, in tile 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}+# 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+# Eco mode default: visual zoom at or below which free imagery replaces a+# billed basemap. The live value is the user's settings.json `eco_max_zoom`.+ECO_MAX_ZOOM = 15+def workspace_root() -> Path:root = Path(os.environ.get("AZIMUT_HOME", "~/Azimut")).expanduser()@@ -60,11 +84,13 @@ def ensure_workspace() -> None:def load_settings() -> dict[str, Any]:+ # deep copies: callers mutate nested dicts (usage counters, prefs), and a+ # shallow copy would let that leak into DEFAULT_SETTINGS itselftry:data = json.loads(settings_path().read_text(encoding="utf-8"))except (OSError, json.JSONDecodeError):- return dict(DEFAULT_SETTINGS)- merged = dict(DEFAULT_SETTINGS)+ return copy.deepcopy(DEFAULT_SETTINGS)+ merged = copy.deepcopy(DEFAULT_SETTINGS)merged.update(data)return merged@@ -87,7 +113,7 @@ _usage_lock = threading.Lock() # tile proxy bumps the counter from many threadsdef record_usage(meter: str, count: int = 1, when: datetime | None = None) -> int:"""Bump a provider's tile counter for the month; returns the new total.- Local bookkeeping only (docs/KEYED_PROVIDERS.md §6): billed keyed providers+ Local bookkeeping only (docs/IMAGERY_PROVIDERS.md): billed keyed providers(Mapbox, Google) get a per-month tally so the user can watch their quota.No telemetry — the counter never leaves settings.json."""@@ -98,3 +124,21 @@ def record_usage(meter: str, count: int = 1, when: datetime | None = None) -> inper_month[bucket] = int(per_month.get(bucket, 0)) + int(count)save_settings(settings)return per_month[bucket]+++def month_usage(meter: str, settings: dict[str, Any] | None = None) -> int:+ """This month's tile tally for a meter."""+ settings = settings or load_settings()+ return int((settings.get("usage", {}).get(meter) or {}).get(month_key(), 0))+++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 the+ user hasn't opted into overage billing for it (docs/IMAGERY_PROVIDERS.md)."""+ free = FREE_TIER.get(meter)+ if not free:+ return False+ settings = settings or load_settings()+ if settings.get("usage_overrides", {}).get(meter):+ return False+ return month_usage(meter, settings) >= free * BLOCK_SHAREdiff --git a/src/azimut/engine/google_tiles.py b/src/azimut/engine/google_tiles.pyindex f81d437..5175627 100644--- a/src/azimut/engine/google_tiles.py+++ b/src/azimut/engine/google_tiles.py@@ -1,4 +1,4 @@-"""Google Map Tiles API session-token adapter (docs/KEYED_PROVIDERS.md §3).+"""Google Map Tiles API session-token adapter (docs/IMAGERY_PROVIDERS.md).Google satellite tiles are not a static XYZ URL: a client first mints ashort-lived *session token* (createSession), then requests standard slippy@@ -25,7 +25,17 @@ CREATE_SESSION_URL = "https://tile.googleapis.com/v1/createSession"VIEWPORT_URL = "https://tile.googleapis.com/tile/v1/viewport"# mapType is part of the token's identity — a satellite session only serves# satellite tiles. Only this one kind is minted today.-SESSION_BODY = {"mapType": "satellite", "language": "en-US", "region": "US"}+# scale+highDpi make each tile 1024×1024 px instead of 256: one request covers+# what sixteen would, and Google bills per request regardless of tile size.+# Verified live (2026-07): the 4x hi-DPI imagery is pixel-identical to the+# same area fetched as 256px tiles two zoom levels deeper.+SESSION_BODY = {+ "mapType": "satellite",+ "language": "en-US",+ "region": "US",+ "scale": "scaleFactor4x",+ "highDpi": True,+}EXPIRY_SLACK = 60 # refresh this many seconds before the reported expiry_lock = threading.Lock()diff --git a/src/azimut/engine/tilecache.py b/src/azimut/engine/tilecache.pynew file mode 100644index 0000000..e10b1a0--- /dev/null+++ b/src/azimut/engine/tilecache.py@@ -0,0 +1,57 @@+"""Disk tile cache for providers whose terms allow it (docs/IMAGERY_PROVIDERS.md).++Layout: ``<workspace>/tile-cache/<provider_id>/<z>/<x>_<y>.<ext>`` — plain+files, rebuildable, safe to delete wholesale. Only providers with+``cacheable=True`` land here: Google is excluded by its Map Tiles API terms+(encoded as ``cacheable=False`` on the provider, enforced by the callers).+Entries expire after ``TTL_DAYS``: this is a transient performance/cost cache,+never a permanent offline imagery store.+"""++from __future__ import annotations++import time+from pathlib import Path++from .. import config++TTL_DAYS = 30+# content-type ↔ file extension; anything else (HTML error pages, exotic+# formats) is simply not cached+_EXT = {"image/jpeg": "jpg", "image/png": "png", "image/webp": "webp"}+_TYPE = {ext: media for media, ext in _EXT.items()}+++def _tile_dir(provider_id: str, z: int) -> Path:+ return config.workspace_root() / "tile-cache" / provider_id / str(int(z))+++def get(provider_id: str, z: int, x: int, y: int) -> tuple[bytes, str] | None:+ """Cached ``(content, media_type)`` if present and fresh; stale entries are+ dropped on sight. Never raises — a broken cache reads as a miss."""+ base = _tile_dir(provider_id, z)+ for ext, media_type in _TYPE.items():+ path = base / f"{int(x)}_{int(y)}.{ext}"+ try:+ if not path.is_file():+ continue+ if time.time() - path.stat().st_mtime > TTL_DAYS * 86400:+ path.unlink(missing_ok=True)+ return None+ return path.read_bytes(), media_type+ except OSError:+ return None+ return None+++def put(provider_id: str, z: int, x: int, y: int, content: bytes, media_type: str) -> None:+ """Store one served tile. Never raises — the cache is an optimization."""+ ext = _EXT.get((media_type or "").split(";")[0].strip())+ if not ext or not content:+ return+ try:+ base = _tile_dir(provider_id, z)+ base.mkdir(parents=True, exist_ok=True)+ (base / f"{int(x)}_{int(y)}.{ext}").write_bytes(content)+ except OSError:+ passdiff --git a/src/azimut/engine/tiles.py b/src/azimut/engine/tiles.pyindex 0d778bd..769e80f 100644--- a/src/azimut/engine/tiles.py+++ b/src/azimut/engine/tiles.py@@ -9,6 +9,7 @@ services.from __future__ import annotations+import hashlibimport mathfrom concurrent.futures import ThreadPoolExecutorfrom dataclasses import dataclass, field@@ -47,19 +48,28 @@ class Provider:cacheable: bool = True # may its tiles be written to a disk cache?attribution_burn: bool = False # force attribution stamped into the imagesession: str | None = None # provider kind needing a live token, e.g. "google"- # usage-counter bucket in settings.json (docs/KEYED_PROVIDERS.md §6);+ # usage-counter bucket in settings.json (docs/IMAGERY_PROVIDERS.md);# None = unmetered. Billed keyed providers count every tile request.meter: str | None = None- # px per tile edge. Mapbox bills 256px tiles 4× vs 512px ones (same imagery- # resolution: one 512 tile at z-1 = four 256 tiles at z), so keyed Mapbox- # uses 512. The visual zoom stays the caller's; the URL z is offset down.+ # px per tile edge. Providers billing per request regardless of tile size+ # get the biggest tile that keeps full imagery detail: Mapbox 512 (its @2x+ # 1024 variant is upsampled — verified softer, not used), Google 1024+ # (hi-DPI 4x, verified pixel-identical). The visual zoom stays the+ # caller's; the URL z is offset down (512 → z-1, 1024 → z-2).tile_size: int = 256+ # Live-map display oversampling: 2 = the map shows tiles from one zoom+ # deeper, downscaled 2× in CSS. Google's mid-zoom mosaics are genuinely+ # softer than its deep ones (verified 2026-07: z18-detail downscaled to a+ # z16 footprint beats the native z16 tile), so the layer trades 4× the+ # requests (still ¼ of plain 256px tiles) for crisp imagery. Captures are+ # unaffected: they stay 1:1 provider pixels for evidential integrity.+ oversample: int = 1-# Built-in keyed providers (docs/KEYED_PROVIDERS.md §2): only surfaced from+# Built-in keyed providers (docs/IMAGERY_PROVIDERS.md): only surfaced from# all_providers() once the matching api_keys entry is set. Mapbox's token is a# static credential baked straight into the URL; Google needs a live session-# token minted per docs/KEYED_PROVIDERS.md §3, so {session} stays unresolved+# token minted per docs/IMAGERY_PROVIDERS.md, so {session} stays unresolved# here and is substituted at fetch time (engine/google_tiles.py).MAPBOX_SATELLITE_URL = ("https://api.mapbox.com/styles/v1/mapbox/satellite-v9/tiles/512/{z}/{x}/{y}?access_token={key}"@@ -89,8 +99,10 @@ def all_providers() -> list[Provider]:providers = list(BUILTIN_PROVIDERS)settings = config.load_settings()keys = settings.get("api_keys", {})+ # a keyed basemap can be switched off in Settings without deleting the key+ enabled = settings.get("providers_enabled", {})- mapbox_key = keys.get("mapbox")+ mapbox_key = keys.get("mapbox") if enabled.get("mapbox", True) else Noneif mapbox_key:providers.append(Provider(@@ -107,7 +119,7 @@ def all_providers() -> list[Provider]:))- google_key = keys.get("google")+ google_key = keys.get("google") if enabled.get("google", True) else Noneif google_key:providers.append(Provider(@@ -124,6 +136,8 @@ def all_providers() -> list[Provider]:attribution_burn=True,session="google",meter="google",+ tile_size=1024, # hi-DPI 4x session (engine/google_tiles.py)+ oversample=2, # mid-zoom mosaics are soft — show z+1 detail))@@ -194,6 +208,24 @@ class TileFetchError(Exception):pass+# Some providers answer in-coverage-gap requests with a real HTTP-200 tile that+# just says "no imagery": Esri World Imagery's constant "Map data not yet+# available" JPEG (byte-identical everywhere, verified 2026-07). Matching by+# content hash turns those into missing tiles, so the overzoom fallback can+# fill them from the parent level instead of showing the gray placard.+PLACEHOLDER_TILE_SHA256 = frozenset(+ {"9eafd300d61393184a4abc1d458564cfd1cd9b6f9c4e9c74687045c0a0e5b858"} # Esri+)+# How many parent zoom levels the overzoom fallback may climb. Three levels+# means an 8× upscale at worst — soft, but it keeps the map usable where a+# provider's coverage ends a level or two short.+OVERZOOM_LEVELS = 3+++def is_placeholder_tile(content: bytes) -> bool:+ return hashlib.sha256(content).hexdigest() in PLACEHOLDER_TILE_SHA256++def resolve_url(provider: Provider) -> str:"""The provider's live XYZ template — session token substituted if needed."""if provider.session != "google":@@ -205,11 +237,14 @@ def resolve_url(provider: Provider) -> str:def _default_fetch(client: httpx.Client, url: str) -> Image.Image | None:- """Fetch one tile; None for 'no imagery here' (404), raise on other errors."""+ """Fetch one tile; None for 'no imagery here' (404 or a known placeholder+ tile), raise on other errors."""response = client.get(url)if response.status_code == 404:return Noneresponse.raise_for_status()+ if is_placeholder_tile(response.content):+ return Noneimport ioreturn Image.open(io.BytesIO(response.content)).convert("RGB")@@ -249,6 +284,11 @@ def fetch_crop(raise TileFetchError(f"provider '{provider.id}' requires an API key (settings.json)")if not provider.capturable:raise TileFetchError(f"provider '{provider.id}' is view-only and cannot be captured")+ if provider.meter and config.usage_blocked(provider.meter):+ raise TileFetchError(+ f"{provider.label} is paused: {int(config.BLOCK_SHARE * 100)}% of the monthly "+ "free tier is used — enable the override in Settings to keep going (billed)"+ )# Bigger tiles keep the caller's visual zoom (same m/px) but request a# 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))@@ -314,13 +354,30 @@ def fetch_crop(raiseserved = 0 # tiles the provider actually returned — what a billed meter counts+ gaps: list[tuple[int, int]] = [] # in-range tiles the provider had nothing forfor tx, ty, tile in results:px, py = int(tx * ts - left), int(ty * ts - top)if tile is None:missing += 1+ if 0 <= tx <= max_index and 0 <= ty <= max_index:+ gaps.append((tx, ty))continueserved += 1canvas.paste(tile, (px, py))++ # overzoom fallback: fill coverage gaps from parent-level imagery, upscaled —+ # soft beats a gray placeholder, and provenance records how many were faked up+ upscaled = 0+ if gaps:+ try:+ filled, parent_served = _overzoom_fill(resolve_url(provider), gaps, tile_z, ts, fetch)+ except TileFetchError:+ filled, parent_served = {}, 0+ served += parent_served+ for (tx, ty), tile in filled.items():+ canvas.paste(tile, (int(tx * ts - left), int(ty * ts - top)))+ upscaled = len(filled)+ missing -= upscaledif provider.meter and served:config.record_usage(provider.meter, served)@@ -375,6 +432,7 @@ def fetch_crop("meters_per_pixel": round(meters_per_pixel(lat, zoom), 3),"tiles": n_tiles,"tiles_missing": missing,+ "tiles_upscaled": upscaled,"fetched_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),"marker_style": marker_style,"marker_x": int(marker_x),@@ -385,6 +443,59 @@ def fetch_crop(return canvas, provenance+def _overzoom_fill(+ url_template: str,+ gaps: list[tuple[int, int]],+ tile_z: int,+ ts: int,+ fetch: Callable[[httpx.Client, str], Image.Image | None],+) -> tuple[dict[tuple[int, int], Image.Image], int]:+ """Best-effort fill for missing tiles from parent-level imagery.++ Climbs up to OVERZOOM_LEVELS levels; each needed parent is fetched exactly+ once (adjacent gaps share parents — one billed request, not four) and every+ child crops + upscales its own quadrant. Returns (filled tiles, number of+ parent tiles the provider served — what a billed meter must count).+ Individual fetch errors just leave tiles unfilled; never raises.+ """+ filled: dict[tuple[int, int], Image.Image] = {}+ unresolved = list(gaps)+ served = 0+ with httpx.Client(+ headers={"User-Agent": USER_AGENT}, timeout=20, follow_redirects=True+ ) as client:+ for up in range(1, OVERZOOM_LEVELS + 1):+ sub = ts >> up # the child's footprint inside its parent, in px+ if not unresolved or tile_z - up < 0 or sub < 1:+ break++ 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)+ return pxy, fetch(client, url)+ except Exception:+ return pxy, None++ wanted = list({(tx >> up, ty >> up) for tx, ty in unresolved})+ with ThreadPoolExecutor(max_workers=6) as pool:+ parents = dict(pool.map(grab, wanted))+ served += sum(1 for img in parents.values() if img is not None)++ still: list[tuple[int, int]] = []+ mask = (1 << up) - 1+ for tx, ty in unresolved:+ parent = parents.get((tx >> up, ty >> up))+ if parent is None:+ still.append((tx, ty))+ continue+ qx, qy = (tx & mask) * sub, (ty & mask) * sub+ filled[(tx, ty)] = parent.crop((qx, qy, qx + sub, qy + sub)).resize(+ (ts, ts), Image.Resampling.LANCZOS+ )+ unresolved = still+ return filled, served++# -- Esri imagery capture date (best-effort) ----------------------------------# Esri publishes per-scene acquisition metadata for World Imagery through thediff --git a/tests/test_config.py b/tests/test_config.pyindex 6e5a08e..f115b06 100644--- a/tests/test_config.py+++ b/tests/test_config.py@@ -1,4 +1,4 @@-"""Settings persistence and back-compat merging (spec: docs/KEYED_PROVIDERS.md §1)."""+"""Settings persistence and back-compat merging (spec: docs/IMAGERY_PROVIDERS.md)."""import jsondiff --git a/tests/test_settings_api.py b/tests/test_settings_api.pyindex 254cf9e..991f7c7 100644--- a/tests/test_settings_api.py+++ b/tests/test_settings_api.py@@ -132,6 +132,153 @@ def test_tile_proxy_google_remints_session_on_403(client, monkeypatch):assert body["usage"]["google"][body["month"]] == 1 # the retry isn't double-counted+def test_get_settings_exposes_prefs_and_free_tier(client):+ body = client.get("/api/settings").json()+ assert body["free_tier"] == config.FREE_TIER+ assert body["block_share"] == config.BLOCK_SHARE+ assert body["eco_max_zoom"] == config.ECO_MAX_ZOOM+ assert body["eco_zoom_fallback"] is True+ assert body["providers_enabled"] == {}+ assert body["usage_overrides"] == {}+++def test_put_prefs_roundtrips_and_filters_unknown_providers(client):+ saved = client.put(+ "/api/settings/prefs",+ json={+ "providers_enabled": {"mapbox": False, "bogus": False},+ "usage_overrides": {"google": True},+ "eco_zoom_fallback": False,+ },+ ).json()+ assert saved["providers_enabled"] == {"mapbox": False} # unknown ids dropped+ assert saved["usage_overrides"] == {"google": True}+ assert saved["eco_zoom_fallback"] is False+ # partial PUT leaves other prefs untouched+ saved = client.put("/api/settings/prefs", json={"eco_zoom_fallback": True}).json()+ assert saved["providers_enabled"] == {"mapbox": False}+ assert saved["eco_zoom_fallback"] is True+++def test_disabled_provider_hidden_but_key_kept(client):+ client.put("/api/settings/keys", json={"mapbox": "pk.abc"})+ client.put("/api/settings/prefs", json={"providers_enabled": {"mapbox": False}})+ ids = {p["id"] for p in client.get("/api/satellite/providers").json()}+ assert "mapbox-satellite" not in ids+ assert client.get("/api/settings").json()["api_keys"] == {"mapbox": "pk.abc"}+ client.put("/api/settings/prefs", json={"providers_enabled": {"mapbox": True}})+ ids = {p["id"] for p in client.get("/api/satellite/providers").json()}+ assert "mapbox-satellite" in ids+++def test_tile_proxy_blocks_at_soft_limit_and_override_lifts(client, monkeypatch):+ client.put("/api/settings/keys", json={"mapbox": "pk.abc"})+ monkeypatch.setattr(httpx, "get", _upstream())+ config.record_usage("mapbox", int(config.FREE_TIER["mapbox"] * config.BLOCK_SHARE))++ r = client.get("/api/tiles/mapbox-satellite/14/8298/5639")+ assert r.status_code == 429+ assert "Settings" in r.json()["detail"]++ client.put("/api/settings/prefs", json={"usage_overrides": {"mapbox": True}})+ assert client.get("/api/tiles/mapbox-satellite/14/8298/5639").status_code == 200+++def test_tile_proxy_disk_cache_serves_repeats_without_rebilling(client, monkeypatch):+ client.put("/api/settings/keys", json={"mapbox": "pk.abc"})+ upstream = _upstream()+ monkeypatch.setattr(httpx, "get", upstream)++ assert client.get("/api/tiles/mapbox-satellite/14/8298/5639").status_code == 200+ r = client.get("/api/tiles/mapbox-satellite/14/8298/5639")+ assert r.status_code == 200+ assert r.content == b"JPEGDATA"+ assert len(upstream.urls) == 1 # second hit came from the disk cache+ body = client.get("/api/settings").json()+ assert body["usage"]["mapbox"][body["month"]] == 1 # cache hits aren't billed+++def test_tile_proxy_never_caches_google(client, monkeypatch):+ client.put("/api/settings/keys", json={"google": "AIza.x"})+ monkeypatch.setattr(+ google_tiles, "resolve_template", lambda url, **kw: url.replace("{session}", "tok")+ )+ upstream = _upstream()+ monkeypatch.setattr(httpx, "get", upstream)++ client.get("/api/tiles/google-satellite/15/16597/11278")+ client.get("/api/tiles/google-satellite/15/16597/11278")+ assert len(upstream.urls) == 2 # terms forbid a disk cache — always upstream+ assert not (config.workspace_root() / "tile-cache" / "google-satellite").exists()+ body = client.get("/api/settings").json()+ assert body["usage"]["google"][body["month"]] == 2+++def _png_tile(size=256, colour=(30, 90, 200)):+ 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_overzoom_fills_coverage_gaps(client, monkeypatch):+ parent_png = _png_tile()++ def get(url, **kwargs):+ get.urls.append(url)+ # imagery ends at z18: deeper levels 404, the parent level serves+ if "/tile/19/" in url:+ return httpx.Response(404, content=b"", request=httpx.Request("GET", url))+ return httpx.Response(+ 200, content=parent_png, headers={"content-type": "image/png"},+ request=httpx.Request("GET", url),+ )++ get.urls = []+ monkeypatch.setattr(httpx, "get", get)++ r = client.get("/api/tiles/esri-world-imagery/19/155000/400000")+ assert r.status_code == 200+ assert r.headers["x-azimut-overzoom"] == "1"+ assert r.headers["content-type"] == "image/png"+ # served tile is a full-size upscale of the parent quadrant+ import io++ from PIL import Image++ img = Image.open(io.BytesIO(r.content))+ assert img.size == (256, 256)+++def test_tile_proxy_placeholder_tile_triggers_overzoom(client, monkeypatch):+ import hashlib++ from azimut.engine import tiles++ placeholder = b"esri-map-data-not-yet-available"+ monkeypatch.setattr(+ tiles, "PLACEHOLDER_TILE_SHA256", frozenset({hashlib.sha256(placeholder).hexdigest()})+ )+ parent_png = _png_tile(colour=(120, 40, 40))++ def get(url, **kwargs):+ body, ctype = (+ (placeholder, "image/jpeg") if "/tile/19/" in url else (parent_png, "image/png")+ )+ return httpx.Response(+ 200, content=body, headers={"content-type": ctype},+ request=httpx.Request("GET", url),+ )++ monkeypatch.setattr(httpx, "get", get)+ r = client.get("/api/tiles/esri-world-imagery/19/155000/400000")+ assert r.status_code == 200+ assert r.headers["x-azimut-overzoom"] == "1"++def test_test_key_without_saved_key_is_404(client):assert client.post("/api/settings/keys/mapbox/test").status_code == 404assert client.post("/api/settings/keys/unknown/test").status_code == 404@@ -170,7 +317,20 @@ def test_test_key_google_mints_a_session(client, monkeypatch):def test_providers_expose_tile_size(client):- client.put("/api/settings/keys", json={"mapbox": "pk.abc"})+ 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()}assert providers["esri-world-imagery"]["tile_size"] == 256+ assert providers["esri-world-imagery"]["oversample"] == 1assert providers["mapbox-satellite"]["tile_size"] == 512 # 4× cheaper, same m/px+ assert providers["mapbox-satellite"]["oversample"] == 1 # its @2x is upsampled — no gain+ assert providers["google-satellite"]["tile_size"] == 1024 # hi-DPI 4x session+ # the live map shows Google one zoom deeper (mid-zoom mosaics are soft)+ assert providers["google-satellite"]["oversample"] == 2+++def test_put_prefs_eco_max_zoom_clamped(client):+ saved = client.put("/api/settings/prefs", json={"eco_max_zoom": 15}).json()+ assert saved["eco_max_zoom"] == 15+ assert client.get("/api/settings").json()["eco_max_zoom"] == 15+ assert client.put("/api/settings/prefs", json={"eco_max_zoom": 99}).json()["eco_max_zoom"] == 21+ assert client.put("/api/settings/prefs", json={"eco_max_zoom": -3}).json()["eco_max_zoom"] == 1diff --git a/tests/test_tiles.py b/tests/test_tiles.pyindex e6a4e70..96479d3 100644--- a/tests/test_tiles.py+++ b/tests/test_tiles.py@@ -180,6 +180,41 @@ def test_all_providers_adds_google_when_keyed(monkeypatch, tmp_path):assert google.cacheable is Falseassert google.attribution_burn is Trueassert google.session == "google"+ assert google.tile_size == 1024 # hi-DPI 4x session (1/16th the billed requests)+++def test_all_providers_respects_enable_toggles(monkeypatch, tmp_path):+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))+ config.save_settings({+ **config.DEFAULT_SETTINGS,+ "api_keys": {"mapbox": "pk.test", "google": "AIza.test"},+ "providers_enabled": {"mapbox": False},+ })+ ids = {p.id for p in tiles.all_providers()}+ # mapbox switched off (key kept), google untouched by an absent entry+ assert "mapbox-satellite" not in ids+ assert "google-satellite" in ids+++def test_fetch_crop_blocked_at_soft_limit(monkeypatch, tmp_path):+ provider = _keyed_provider(monkeypatch, tmp_path, "mapbox", "pk.test")+ config.record_usage("mapbox", int(config.FREE_TIER["mapbox"] * config.BLOCK_SHARE))+ with pytest.raises(tiles.TileFetchError, match="free tier"):+ tiles.fetch_crop(48.8584, 2.2945, 15, 512, 512, provider, fetch_tile=_green_tile)+++def test_fetch_crop_override_lifts_the_block(monkeypatch, tmp_path):+ provider = _keyed_provider(monkeypatch, tmp_path, "mapbox", "pk.test")+ config.record_usage("mapbox", config.FREE_TIER["mapbox"]) # 100% used+ settings = config.load_settings()+ settings["usage_overrides"] = {"mapbox": True}+ config.save_settings(settings)++ def fetch(client, url):+ return Image.new("RGB", (512, 512), (10, 120, 10))++ img, prov = tiles.fetch_crop(48.8584, 2.2945, 15, 512, 512, provider, fetch_tile=fetch)+ assert prov["tiles_missing"] == 0def test_fetch_crop_rejects_non_capturable_provider():@@ -240,16 +275,59 @@ def test_fetch_crop_missing_tiles_are_not_billed(monkeypatch, tmp_path):calls = {"n": 0}def fetch(client, url):+ if "/tiles/512/14/" not in url:+ return None # overzoom parents: nothing there eithercalls["n"] += 1return None if calls["n"] == 1 else Image.new("RGB", (512, 512), (10, 120, 10))img, prov = tiles.fetch_crop(48.8584, 2.2945, 15, 900, 900, provider, fetch_tile=fetch)assert prov["tiles_missing"] == 1+ assert prov["tiles_upscaled"] == 0# only tiles the provider actually served count toward the meterusage = config.load_settings()["usage"]["mapbox"][config.month_key()]assert usage == prov["tiles"] - 1+def test_fetch_crop_overzoom_fills_gaps_from_parent(monkeypatch, tmp_path):+ provider = _keyed_provider(monkeypatch, tmp_path, "mapbox", "pk.test")+ calls = {"n": 0, "parents": []}++ def fetch(client, url):+ if "/tiles/512/14/" in url: # the crop's own zoom level+ calls["n"] += 1+ return None if calls["n"] == 1 else Image.new("RGB", (512, 512), (10, 120, 10))+ calls["parents"].append(url) # one level up: imagery exists+ return Image.new("RGB", (512, 512), (200, 50, 50))++ img, prov = tiles.fetch_crop(+ 48.8584, 2.2945, 15, 900, 900, provider, marker_style="none", fetch_tile=fetch+ )+ # the gap was filled from the parent level, once, and recorded as upscaled+ assert prov["tiles_missing"] == 0+ assert prov["tiles_upscaled"] == 1+ assert len(calls["parents"]) == 1+ assert "/tiles/512/13/" in calls["parents"][0]+ # the parent tile the provider served is billed alongside the direct ones+ usage = config.load_settings()["usage"]["mapbox"][config.month_key()]+ assert usage == (prov["tiles"] - 1) + 1+++def test_default_fetch_treats_placeholder_tile_as_missing(monkeypatch):+ import hashlib++ body = b"esri-not-yet-available"+ monkeypatch.setattr(+ tiles, "PLACEHOLDER_TILE_SHA256", frozenset({hashlib.sha256(body).hexdigest()})+ )++ class FakeClient:+ def get(self, url):+ return httpx.Response(200, content=body, request=httpx.Request("GET", url))++ assert tiles._default_fetch(FakeClient(), "http://tiles.example/1/2/3") is None+ assert tiles.is_placeholder_tile(b"real imagery") is False++def test_fetch_crop_unmetered_provider_records_nothing(monkeypatch, tmp_path):monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))tiles.fetch_crop(@@ -274,10 +352,13 @@ def test_fetch_crop_google_resolves_session_and_burns_attribution(monkeypatch, tdef fetch(client, url):urls.append(url)- return _green_tile(client, url)+ return Image.new("RGB", (1024, 1024), (10, 120, 10))img, prov = tiles.fetch_crop(48.8584, 2.2945, 15, 512, 512, provider, fetch_tile=fetch)assert all("session=tok-live" in u and "key=AIza.test" in u for u in urls)+ # 1024px hi-DPI tiles: same m/px, requested two zooms lower — 16× fewer requests+ assert all("/2dtiles/13/" in u for u in urls)+ assert prov["zoom"] == 15 # provenance keeps the visual zoom# dynamic viewport copyright recorded, not just "Google"assert prov["attribution"] == "Map data ©2026 Google, Maxar Technologies"assert prov["attribution_burned"] is True@@ -307,7 +388,7 @@ def test_fetch_crop_google_remints_session_on_403(monkeypatch, tmp_path):"expired", request=request, response=httpx.Response(403, request=request))assert "session=tok-fresh" in url- return _green_tile(client, url)+ return Image.new("RGB", (1024, 1024), (10, 120, 10))img, prov = tiles.fetch_crop(48.8584, 2.2945, 15, 512, 512, provider, fetch_tile=fetch)assert invalidated == ["AIza.test"]