The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.
JavaScript
Compare Detect: seven detectors on the bands, one cloud mask, three map positions (#81)
OsintMeThat3622ed76967c
diff --git a/docs/ASSIST_HANDOVER.md b/docs/ASSIST_HANDOVER.mdindex a34411d..57e3dcc 100644--- a/docs/ASSIST_HANDOVER.md+++ b/docs/ASSIST_HANDOVER.md@@ -13,23 +13,34 @@ the work lands in a release. What is *done* is described inis the only switch. `lib/map/compare.js` carries the grouping.- **No machine-learning model, and not as a fallback.** At Sentinel-2's 10 m apixel a 30 m vessel is three pixels: there is no shape to recognise, and a- detector trained on shapes would do worse than the physics. So the two new- Copernicus methods read reflectance:- - `vessels` — CFAR on B08. Water absorbs near-infrared almost completely, so a- hull is an outlier against the sea *around it*; the background comes from a- ring with its middle punched out (`analyzers.local_contrast`), which is what- makes one threshold work on a calm lagoon and a sunlit swell alike.- - `hotspots` — the published short-wave test: B12 above an absolute floor and- high against B11 and B08. Cloud is bright in B12 too but bright in its- neighbours as well, so its ratios sit at one, and that is what rejects it.- Both ride on `sentinel.band_frame`, which already existed for spectral- indices. No new dependency: numpy and opencv-python-headless were already in.-- **Preset names state what is measured, never what it means.** "Vessels on- water" is a claim about infrared contrast; "Boats" would have claimed- recognition. `signal_score` is signal strength and `confidence` stays null.+ detector trained on shapes would do worse than the physics. Every method reads+ a band product (`sentinel.DETECT_PRODUCTS`) and says what it measured.+- **Detect is Copernicus-only.** Every method measures reflectance, which Wayback+ pictures have already stretched away. Recipes and watches saved against Wayback+ or a picture method still load: `colour`, `brightness` and `smoke` map to+ `surface`, `water_objects` to `vessels`, and a Wayback source comes back undated.+- **Thresholds come from real scenes.** Calibrated on Bab-el-Mandeb (glint, rough+ sea), Singapore Strait (dense anchorage, cumulus), Gibraltar, Dover Strait+ (empty sea), Rumaila flares, California and Cerrado wildfires, Jebel Ali roofs,+ Egypt's new capital (seven months), Rondônia (dry season) and irrigated desert.+ What each taught is next to the constant it set, in `engine/analyzers.py`:+ - `vessels` needs near *and* short-wave infrared contrast against its own ring+ of sea. Wave crests match hulls in B08 and not in B11. Non-water over 5 ha is+ land. Sen2Cor calls hulls cloud, so classified cloud under 5 ha is ignored.+ - `hotspots` is Murphy et al. 2016 on B8A, which shares B12's grid.+ - `structure` is every band moving the same way with NDVI held; `spots` is a+ change whose wider neighbourhood mostly held, measured against a ring with a+ hole punched in it (`SPOT_GUARD`, `SPOT_RING`) — a median box the size of the+ target read a 90 m mark in the Yemeni desert at 3.5% where it had moved 7%;+ burn scars must end dark, because dry soil also has a negative NBR.+ - The global shift between dates is removed but capped at 3%, or a burn+ covering most of a tile erases itself.+- **Names say what an analyst looks for.** A candidate carries `margin` (how far+ past its threshold), a `strength` word and a `measure` in units; the catalogue+ words each method's reading. `signal_score` and `confidence` are gone.- **Disk follows findings, not area.** `prune_frames` drops the frames of tilesthat produced no candidate, which is what let `MAX_TILES` go from 256 to 4096- (313 km a side on Sentinel, 4.9 km on Wayback). The trade is stated in the+ (313 km a side). The trade is stated in thepanel and in UI.md: an offline rerun now covers what the tile cache stillholds, not the whole of a past sweep.- **Detect leads the maps.** Inside the mode the A/B source cards are hidden and@@ -50,23 +61,57 @@ the work lands in a release. What is *done* is described in- **Detect's drawing stays in Detect.** Areas and candidate layers render onlyin the mode that explains them. A kept candidate is a pin and shows wherevercase work shows, which is the honest way for a result to outlive the mode.+- **Difference reads the same sky as Detect.** `skyMask` in+ `lib/map/changeDetect.js` is the browser's copy of `analyzers.sky`: the same+ cloud classes, the same 5 ha floor, the same unsure edge and the same cast+ away from the sun, turned by the map's bearing because a view can be. Both+ sides of that port were calibrated on cumulus over the Beauce and over the+ Kakhovka reservoir bed, which is what turned up the water rule below. The+ browser gets the bytes from `change-*` frames whose alpha must stay the data+ mask, because a canvas premultiplies it.+- **A band frame is fetched by an act, then held.** Run and the cloud switch are+ the two acts; a pan is not. Each frame is asked for with 20% of the view as+ margin and kept in `changeCapture`, so a reading that follows the camera keeps+ working inside that margin and reports `needsFetch` past it, leaving the last+ reading up and marked out of date. The switch itself runs the reading: leaving+ an unfiltered mask on screen under an "on" switch is how the first version of+ this read as broken. There is no live/manual switch any more — the reading+ always follows the camera, and the only question left is whether a request is+ spent, which only Run and the cloud switch ever do.+- **Water is only water when both dates say so.** Sen2Cor reads a deep cloud+ shadow as water — a fifth of the Ukrainian scene — and a cast that spares+ water found 0.3% of the shadow instead of 13.7%. Where a second pass exists,+ `sky(…, other)` asks it; a single-date method (`vessels`) still spares water,+ which is the sea it works on.+- **Matching tones is off on Sentinel-2.** The default is `auto`: nothing on+ Sentinel-2, a histogram on Esri releases. Two L2A passes are corrected and+ rendered by one formula, so a match can only eat real change — it erased the+ Cerrado burn, 74% of a tile, leaving 0.3% highlighted where 71% had been. Esri+ releases carry two renderings and a median tone shift of 15 levels between+ them, a quarter of the pairs past 25, so there a match still earns its place.+ Cloud is left out of the estimate either way.+- **A spectral index is thresholded, not split.** Otsu always finds a line, and+ after the cloud came out it found one in the noise: 19% of a clear Amazon week+ highlighted at the floor. Both modes now draw the line at a stated index+ change, 0.25 at the default sensitivity.+- **The picture cloud guess is gone.** "Bright and colourless, near-black"+ marked 94% of Gibraltar and 100% of Dover as shadow — sea and forest — and+ caught a fifth of the real cloud in Amazonia. The filter now appears on a+ Sentinel-2 pair only, where a classification exists.- **"Watch" is the UI word for a follow-up.** The entity type id stays`analysis-follow-up`; renaming storage for a word nobody reads is not worth amigration.## Still open-1. **No tile halo.** `detect` runs per tile with no overlap; components crossing- a seam are merged afterwards by their boxes (`merge`), which can overmerge and- can split a target whose halves each fall under `min_area`. Needs boundary- tests before multi-tile results can be called robust.-2. **Promotion saves one evidence part.** `promote` calls `preview_bytes(...)`- with the default `part=0`, so a candidate spanning several tiles promotes only- its first before/after. The promoted place also carries `evidence` as an- attribute rather than a formal link to the filed media.- `PREVIEW_EDGE`/`PREVIEW_MARGIN` decide how far the crop is enlarged; the zoom- is a whole number and nearest-neighbour on purpose, and that is worth keeping- whatever else changes there.+1. **The tile halo is 32 px.** Products are read with `PAD` pixels of the+ neighbours, enough for the vessel ring and a coastline, and a candidate+ crossing a seam is merged and previewed as one stitched picture. Clouds more+ than 306 m past the edge still cast no shadow into the tile.+2. **The promoted place carries `evidence` as an attribute** rather than a+ formal link to the filed media. `PREVIEW_EDGE`/`PREVIEW_MARGIN` decide how far+ the crop is enlarged; the zoom is a whole number and nearest-neighbour on+ purpose, and that is worth keeping whatever else changes there.3. **Preserved frames are trusted by filename.** `frame` reuses any`runs-*.assets/<key>.png` it finds without checking the recorded `sha256`against the bytes. The key is derived from the source and tile, not the@@ -79,21 +124,32 @@ the work lands in a release. What is *done* is described inpercent and `FULL_COVER = 0.98` is what counts as whole. It answers about thegranule footprints, which is where imagery exists — not about cloud insidethem, for which the scene's own figure is the only number on offer and it- covers a 110 km granule, not the area drawn. Wayback release dates are- publication dates, not acquisition dates. Both distinctions are in the UI- copy — keep them.-6. **The picture cloud test is a guess and must stay opt-in.** Bright and- colourless is equally a cloud, a white roof, a gravel pad and fresh snow, and- nothing in a rendered image separates them. That is why it lives in its own- `guess_clouds` rather than riding on `ignore_clouds`, which means Sentinel-2's- scene classification and is on by default. Wiring the two together would- silently change what every saved colour recipe finds.-7. **No measured benchmark.** Sequential bounded tiles are an argument about- memory, not a measurement, and no accuracy check against real imagery exists.- The detector tests use synthetic frames: they prove the method does what it- claims on a controlled input, not that it finds ships in the Bosphorus.+ covers a 110 km granule, not the area drawn. The distinction is in the UI+ copy; keep it.+6. **`CLP`/`CLM` are not read.** On Copernicus Data Space they were zeros for+ some acquisitions, a thick cloud included. If they become reliable they would+ help thin cloud edges, but over desert they also flagged dark fields.+7. **Calibration is visual, not a benchmark.** The scenes above were reviewed by+ eye in true colour and SWIR, with no AIS or fire perimeter as ground truth.+ Small boats and whitecaps stay hard to part at the Small size, and seasonal+ urban shadows read as construction between February and September.+8. **A size band drops what it finds, silently.** A candidate outside+ `min_area`/`max_area` is found and then filtered, so a mark between two bands+ reads as "nothing found". The bands are now written under the buttons and+ **All** sets neither bound; what is still missing is a count of what the band+ dropped, which would turn "nothing" into "three, all larger than Small".+9. **Thin veils the classification misses still highlight.** A haze that neither+ Sen2Cor nor its unsure class calls cloud leaves change around it. The+ published multitemporal test (MAJA: blue reflectance rising against the other+ date) was tried and dropped: on the Amazon pair it grew the mask from 33% to+ 48% of the scene for no drop in what was highlighted, and it would cost a+ band and split the two modes' masks apart.+10. **A cloud smaller than 5 ha in a zoomed-in view is not masked.** The floor is+ ground area, so a small cumulus crossing a close view is ignored the same way+ a white roof is. Detect has the same floor on a fixed grid, where it is the+ right call; here the view can be anything.-## Verification at handover+## Verification at handover (Detect)- Backend: `2813 passed` (`pytest -q tests/ -p no:randomly`, 17 min).One caveat: under `pytest-randomly`'s default ordering a single unrelated test,diff --git a/docs/IMAGERY_PROVIDERS.md b/docs/IMAGERY_PROVIDERS.mdindex 54d3704..5b7c031 100644--- a/docs/IMAGERY_PROVIDERS.md+++ b/docs/IMAGERY_PROVIDERS.md@@ -168,9 +168,10 @@ z14 ceiling. The JS widget is excluded because replacing it bills another load.## Sentinel-2 is a dated mosaic, not a basemap-Use the OGC WMTS endpoint. Catalog provides STAC metadata but no pixels. The-Process API requires POST and evalscript, so band math remains deferred with-Satellite Compare.+Use the OGC WMTS endpoint for pictures. Catalog provides STAC metadata but no+pixels. Band math goes through WMS GetMap with an `EVALSCRIPT` parameter rather+than the Process API, which wants a POST and a separate token; see "Detect reads+band products" below.```https://sh.dataspace.copernicus.eu/ogc/wmts/{key}?SERVICE=WMTS&REQUEST=GetTile@@ -281,6 +282,38 @@ detail. The swap is limited to those low-detail views.PU scales with **area**, so tile size is cost-neutral (1024 → 4 PU, 256 → 0.25 PU):Google's big-tile trick buys nothing here. 512 wins on the requests/min limit alone.+### Detect reads band products, not pictures++A Detect sweep fetches, for each tile and date, the WMTS picture the analyst+reviews and one WMS band product the detector measures (`sentinel.DETECT_PRODUCTS`:+`vessel`, `fire`, `surface`, `index-*`). Each product is four bytes a pixel, so one+metered request carries everything a detector reads:++- **The box is padded by 32 px** (`analyzers.PAD`, 306 m) on every side, so a ship's+ background ring, a coastline and a cloud's edge do not stop at the tile border.+ Checked against raw bands, the padded frame lands on the tile's grid exactly.+- **Reflectance is stretched by a gain of 2** (1.6 for short-wave infrared in+ `surface`). Glint puts open sea near 9% in the near-infrared; the old gain of 8+ saturated at 12.5%, where hulls and wave crests read the same.+- **The fourth byte is the sky**: the scene class in the low four bits and a flag+ for near-infrared under 15%, which is what the engine casts cloud shadows onto.+- **`CLP`/`CLM` are not used.** On Copernicus Data Space they come back as zeros for+ some acquisitions, a thick cloud included, and over bright desert they flag dark+ irrigated fields as cloud when they are there.+- **Input bands cost processing units**, output bands do not: each product asks for+ only the bands its detector reads, plus `SCL`.++Products are cached beside their picture under `<variant>~<product>~v<N>`+(`analyzers.product_cache_id`), so a rerun over the same dates spends nothing,+and `PRODUCT_VERSION` keeps a frame from an older layout from being decoded as a+newer one.++Difference asks for the same bands over the view on screen (`sentinel.CHANGE_PRODUCTS`:+`change-<index>`, and `change-sky` for the sky alone). Those frames are decoded in+the browser, which draws them into a canvas, so alpha has to stay the data mask —+a canvas premultiplies it — and the sky byte rides in green instead. Nothing is+cached: the view is whatever the camera is on.+### The view goes deeper than the pixels`max_native_zoom` (14) and `max_zoom` (18) are different questions: where thediff --git a/docs/SPEC.md b/docs/SPEC.mdindex 5a893e7..7e60427 100644--- a/docs/SPEC.md+++ b/docs/SPEC.md@@ -168,15 +168,15 @@ proof for publication.| ✅ **Point menu** | Right-clicking the ground copies that point in every format, looks it up, saves, measures, reads the sky or opens its imagery history from it, and links it out. || ✅ **Map windows** | Opens the map in several tabs with the view in the URL, links map tabs and extension panels on other sites to one camera, and syncs saved points, grids and sweeps live to every tab and extension panel. || ✅ **Map layers** | Stacks key-less overlays (borders, roads, railways, power lines, sea marks, GPS traces), NASA FIRMS fires and VIIRS night lights for a chosen day, and filters drawn pins by kind and folder. |-| ✅ **Media on the map** | Draws the case's located photos and videos where a relation, a GPS reading or a proof puts them, and plays the stack in the panel beside the imagery. |+| ✅ **Media on the map** | Draws the case's located photos and videos where a relation, a GPS reading or a proof puts them, opens the Map panel, the home map and the extension on them, and plays the stack in the panel beside the imagery. || ✅ **Imagery Wayback** | Browses every Esri World Imagery release, narrowed to the ones that changed the point, and dates the pixels apart from the release. || ✅ **Satellite Compare** | Aligns and annotates two dated views, assists matched-product change reading, saves editable sessions and files or exports attributed PNG/GIF outputs. |-| ✅ **Compare Detect** | Sweeps drawn areas at native resolution for changes, vessels on water and short-wave hotspots; candidates are reviewed one at a time and only a kept one becomes a case pin, and a saved watch reruns on demand. |+| ✅ **Compare Detect** | Sweeps drawn areas of Copernicus Sentinel-2 at native resolution for vessels, fires and flares, construction, small spots, burn scars, vegetation loss and new water, at a small, medium or large target size; candidates come strongest first, one at a time, and only a kept one becomes a case pin. || ✅ **Passes over an area** | Picks Detect's Copernicus dates from the passes the drawn areas really have, each with the share of them its swath reached, and reports what a finished run actually swept. |-| ✅ **Cloud & shadow filter** | One click in Difference and Detect, on Sentinel-2's scene classification where there is one and a stated guess from the picture where there is not, with a margin that takes the fringe both masks leave. |+| ✅ **Cloud & shadow filter** | One click in Difference and Detect, both on Sentinel-2's scene classification: unsure edges taken, classified "clouds" too small to be one dropped, and shadows cast away from the sun, including the ones the classification read as water. || ✅ **Capture scale & north** | Adds a scale bar and true-north needle to app and extension captures when resolution and heading are known. || ✅ **Footprint tracing** | Traces a place's uncertainty as a polygon around its pin, in place of the radius. |-| ✅ **Extension map tools** | Draws measure, media pins, sun and moon, search grids and case media over third-party maps, calibrated per site by a replayable command. |+| ✅ **Extension map tools** | Draws measure, the case's points one position at a time, sun and moon, search grids and case media over third-party maps, calibrated per site by a replayable command. || ✅ **Extension updates** | Updates the unpacked extension in one click, installs a signed self-updating Firefox add-on, and flags a copy out of step with the app. || ✅ **Site hand-offs** | Fills the X or Bluesky composer with a prepared thread and uploads a case picture straight into Lens, Yandex, Bing or TinEye. || ✅ **Home & Guide** | Opens on a case dashboard or a front door when no case is open, and `?` opens the Guide on the current tab. |@@ -371,8 +371,9 @@ stops making sense.restarts the extension is only reachable from the app's own localhost page,names the install it means, and its worst outcome is an extension thatrestarts. The map tools widen that island by five read routes and two writes,- each trimmed to what a panel draws — saved points without their thumbnails or- link tallies, a sweep's own spec, a case's images and videos by name — and the panel+ each trimmed to what a panel draws — one position's points without their+ thumbnails or link tallies, a sweep's own spec, a case's images and videos by+ name — and the panelitself reaches them only through the worker's own allowlist, since a contentscript's fetch would carry the map site's origin and be refused. Keeping thosepanels in step adds one more, and it is the narrowest of them: a read-onlydiff --git a/docs/UI.md b/docs/UI.mdindex 4eb182c..025fd55 100644--- a/docs/UI.md+++ b/docs/UI.md@@ -82,22 +82,23 @@ before; **Guide** is for somebody who has not.- **The recent rows carry the case's own pictures.** The catalog already attaches athumbnail to the rows that have one (`thumb`), so six frames of an afternoon's workare shown rather than six filenames.-- **The points are on a real map, and it is only a reading.** The saved index is drawn+- **The points are on a real map, and it is only a reading.** The case's located+ footage (`GET /satellite/media`, the Map panel's own first position) is drawnas dots on the same engine the Map tool uses (`overview/PlaceMap.svelte`), framed onthe case, capped at 200 points, and the wheel and the drag are all it answers: nocapture, no basemap picker, nothing that writes. Hovering a dot names it. Thebasemap is the keyless, unmetered imagery and nothing else, so opening the pagecannot spend a quota. Coming back to the tab re-reads the case, and points thatdid not change leave the camera where it was put. The foot says how many points the- case holds, how many are drawn when that is fewer, and opens the Map tool. With- nothing placed there is no map, and the figures take the shoulder instead of leaving- a hole.+ case holds, how many are drawn when that is fewer, and opens the Map tool. A place+ nobody filmed is a pin, and pins are read in the Map tool: with no footage placed+ there is no map here, and the figures take the shoulder instead of leaving a hole.- **The case by family is drawn in the Graph's own eight hues** (`--graph-<family>`),each bar measured against the biggest family rather than against the total. Onereading of one case cannot be two palettes.- **The dashboard reads only the open case.** Five bounded summary reads supply thecatalog summary, one timeline page, the newest rows, a count of the last seven days,- and the compact saved index the Satellite panel already opens on. A separate read+ and the located media the Map panel opens on. A separate readloads the case checklists. Nothing opens asecond case to count it, and the only thing that reaches the network is the map ofthe case, fetching the imagery under its points.@@ -1206,37 +1207,56 @@ the mode closes the column.**Difference** checks that the sources can be compared before it runs.Colour, structure and brightness methods read captured pixels in a worker.-Sentinel-2 also offers NDVI, NDWI, NBR and NDBI from the actual spectral bands.-Index frames are fetched only by **Read this view**, one metered request per-side; reopening a session or moving the camera does not fetch them. A changed-view must be run again before export. Pixel methods refresh after movement when-live updates are enabled; disabling them keeps the last mask anchored to the ground.+Sentinel-2 also offers six spectral indices — NDVI, NDWI, MNDWI, NBR, NDBI and+BSI, the ones Detect measures — from the actual bands. Band frames are fetched by+an explicit act only — **Read this view**, or switching the cloud filter on —+one metered request per side; reopening a session or moving the camera never+fetches. Each frame is kept with a margin of ground around the view, so the+reading keeps its bands while the camera stays inside that margin, and past it+the last reading stays up, marked in the footer as an earlier read, until Run. A changed view must be run again before+export. A reading recomputes by itself after every move, on the+frames it holds; what it never does on a pan is spend a request.These viewport captures depend on display resolution and zoom. Use **Detect**for a fixed analysis grid across camera changes.**Highlights over** sits above the tabs and says what the reading is laid on: Aalone, B alone, or both images side by side with the same mask on each — the one-arrangement that shows what a change went *from* and *to* at the same time.+arrangement that shows what a change went *from* and *to* at the same time. The+eye beside the title hides the overlay, and **Blink** flashes it on and off,+because a thin highlight over busy imagery is easier to catch moving than still.**Clouds & shadows** sits beside it, one click, because cloud is the first thing-that goes wrong in a reading and hunting for the switch that fixes it is the-wrong first minute. It says which answer it is giving: Sentinel-2's own scene-classification under a spectral index, and a guess from the picture — bright and-colourless, or near-black — under the pixel methods. The Filters tab splits cloud-from shadow and sets the mask margin, which grows the mask past the soft edge-both tests leave behind.+that goes wrong in a reading. It gives Detect's answer, not a guess: Sentinel-2's+scene classification, grown into the unsure pixels around a real cloud, with+classified "clouds" too small to be one ignored and each cloud cast away from the+sun to find the shadows the classification missed — including the ones it read as+water, which the other date settles. It is offered on a Sentinel-2 pair only,+because that is where a classification exists; over a picture method it reads one+small frame a side, fetched by the switch itself so that the highlights on screen+are always the ones the switch describes.+The Filters tab splits cloud from shadow and sets the mask margin in ground+metres, which grows the mask past the soft edge the classification leaves.Detection, Display and Filters tabs separate the rest of the settings, with hover descriptions.The settings panel offers automatic/manual thresholds, tone matching, alignment,smoothing, cleanup, minimum area, class filters, palettes and heat/class/outline-displays. Coverage, highlighted-area and selectable change zones describe the result. These are candidate pixel+displays. A spectral index skips the automatic threshold: it is highlighted past+a stated index change, the line Detect draws, so panning cannot move it. Tone+matching defaults to automatic, which means none on Sentinel-2 — two passes+already corrected to surface reflectance have no exposure left to match, and+matching them would erase a burn that covers most of the view — and a histogram+on Esri releases, which carry two renderings. Coverage, highlighted+area and selectable change zones describe the result, each zone carrying the same+strength word a Detect candidate does: how far past the line it got. These are candidate pixelchanges for inspection, not confirmed changes to objects.-**Detect** sweeps a drawn area at native resolution and keeps what it found, for-Wayback and Copernicus Sentinel-2. Setup reads as three numbered steps, in the-order the work happens: an area, the imagery, then what to look for.+**Detect** sweeps a drawn area of Copernicus Sentinel-2 at native resolution and+keeps what it found. Every detector measures reflectance bands, which a rendered+picture has already stretched away, so Wayback has nothing to give it. Setup reads+as three numbered steps, in the order the work happens: an area, the imagery, then+what to look for.Step 1 draws rectangles, polygons or circles, or takes the current view as a-rectangle in one click, and prices the result before anything is fetched — ground-area, native tiles, frames to fetch and roughly how long. A named area set can be+rectangle in one click, and prices the result before anything is fetched: ground+area, native tiles, Copernicus requests and roughly how long. Each date costs two+requests a tile, the picture reviewed and the bands measured. A named area set can besaved for this case and reused. An area is grabbed by its edge: dragging insideone pans the map as it would anywhere else, a click on the edge shows its cornerhandles, and a press that does not travel selects without nudging the geometry.@@ -1246,7 +1266,7 @@ pan, a zoom or a turn.Step 2 and the stage share one imagery between them, so what is on screen is whata run would sweep. On arrival the maps lead, because what is above the stage isusually what you came to analyze. From the first change made here — or straight-away when the maps show something this cannot read — the direction reverses and+away when the maps show anything but Sentinel-2 — the direction reverses andthe maps follow this step; the A/B source cards step aside while Detect is on, sothere is one place to choose imagery rather than two. An analyzer that reads onedate shows one map, because there is no pair to compare. The run is blocked, with@@ -1263,20 +1283,35 @@ than after it. A finished run reports the share it really read, so "nothingfound" and "never looked" stay different answers. The lookup is billed as oneCopernicus request and never runs on its own.-Step 3 picks the analyzer. Four ship built in: large surface change, vessels on-water, new structures or ground disturbance, and active fire or hotspot. The last-two of those read Copernicus bands rather than the rendered picture — vessels from-near-infrared contrast against the water around them, hotspots from the published-short-wave infrared ratios — so they are Sentinel-2 only and fetch band frames-beside the picture, all of them metered. The same **Clouds & shadows** switch sits-under the analyzer, on for the methods that read Sentinel-2's classification and-off for the ones that can only guess from the picture — a guess that cannot tell-cloud from a white roof is never made on anyone's behalf. Methods whose subject-is itself bright and colourless (smoke, bright shapes on water) or that already-reject cloud by their band ratios (hotspots) offer no switch at all. Thresholds-and the analyzer itself open from links rather than sitting in the way; any-analyzer can be duplicated under a name of its own and is then shared by every-case.+Step 3 picks the analyzer. Eight ship built in, for big things and small ones:+vessels, fires and gas flares, construction and earthworks, small spots (impacts,+burn marks, vehicles), any surface change, burn scars, vegetation loss, and+flooding or new water. Each reads its own band product, and each was tuned on real+scenes rather than synthetic ones: rough sea under glint, a dense anchorage under+cumulus, oil fires and wildfires, bright roofs, a construction site across seven+months, dry-season pastures. Vessels stand out from their own patch of sea in near+*and* short-wave infrared, which a breaking wave does not, and a candidate joined to+bulk land is a coast. Fires take the published short-wave ratios on B8A, which+shares B12's grid. Construction is ground that moved the same way in every band+while its vegetation held; a small spot changed while the ring of ground around it+did not, that ring read with a hole in its middle so the spot cannot sit in its own+background; a burn has to end dark, which a dried pasture does not.++**Small**, **Medium**, **Large** and **All** under the analyzer set the target+size as a whole: floor and ceiling area, cleanup and grouping together, since a+small target needs no cleanup that would erase it. What the chosen one accepts is+written under the buttons in ground terms — a mark outside that band is found and+then dropped, which reads as "nothing found" unless it is said. **All** sets no+floor and no ceiling, for the mark that falls between two bands. Tuning any of+those by hand leaves no size selected. The **Clouds & shadows** switch reads Sentinel-2's classification, grows a+real cloud into the unsure pixels touching it, ignores classified "clouds" too small+to be one (white hulls and roofs), and casts each cloud away from the sun to find the+shadows the classification missed. The fire detector offers no switch: its band+ratios reject cloud already. Thresholds and the analyzer itself open from links+rather than sitting in the way. The **+** beside the analyzer starts one of your+own, either as a copy of the one in hand or from scratch; a built-in can be read+and copied but never written over, and an analyzer of your own can be saved,+renamed or removed from there. The library is shared by every case.A **watch** keeps an analyzer, its areas and a date rule together, and**Run again** in Saved launches a fresh pass — a weekly harbour review is that@@ -1292,8 +1327,12 @@ candidate evidence and review state. A finished run keeps the frames of the tilethat produced a candidate and drops the rest, so a case grows with what was foundrather than with how much was swept.-What a sweep produces is a list of candidates, and nothing else reaches the case-on its own. Review them one at a time: **Keep as a pin** files that one candidate,+What a sweep produces is a list of candidates, strongest first, and nothing else+reaches the case on its own. Each says how strong it is in a word (weak, clear or+strong: how far past its threshold it got) and what was measured in units a reader+can check, such as "6.2× brighter than the water around it" or "NBR 0.61 → −0.28".+A candidate that crosses a tile edge is one candidate with one picture, stitched+from the tiles it touches. Review them one at a time: **Keep as a pin** files that one candidate,with its own copy of the evidence and its provenance, and is the single act thatwrites to the case; **Dismiss** takes it off the map. Either verdict moves to thenext candidate still waiting, and a running tally says how many are left. Keeping@@ -1308,7 +1347,21 @@ Annotations store longitude/latitude points and stay on their ground through panzoom and rotation. Notes, arrows, boxes, ellipses, lines, freehand strokes, distancemeasures and polygons can belong to A, B or both. Polygon drawing ends with adouble-click or Enter; Escape cancels. Select a mark to move it or edit its style,-double-click a note to edit its text, and use Undo/Redo for annotation changes.+double-click a note to edit its text, and use Undo/Redo for annotation changes. A+selected mark shows its corner handles, so its geometry is corrected where it was+drawn rather than deleted and redrawn; a note is dragged whole and has none.+Every mark carries a wide invisible band along its outline, because a four-pixel+arrow is a target nobody hits twice. Clicking the ground beside a mark lets it go;+dragging the map is a pan and keeps it. The tool rail packs into two columns, like+Proof Maker's, so it stays short enough to fit a laptop window. Its colour, width+and fill panels close on Escape, on their own button, on a press anywhere else,+and with the button behind them when the selection is dropped.++**Right-click the ground** here too, on either map, for the acts Compare can+honour: copy the point in every coordinate format, ask what is there, save a+place there, or start a distance measure from it — the annotation of the same+name, anchored on the point and closed by the next click. The rows Satellite+offers for its own rails are left out rather than shown dead.**Save comparison** writes the editable version-2 session under `.compare/` andupdates its rendered media preview in My work (PNG, or GIF for blink). A preview@@ -1335,22 +1388,15 @@ bearing. Picks are remembered locally and offered back when the bar is empty.Saved work — places, captures and screenshots filed by the extension — lives inone right-hand **Saved** panel, grouped by geography rather than by date. Thetree's depth follows the case: one country opens straight on its regions, a-worldwide case opens on continents. A filter and an-`All / Places / Captures | Proofs · Media` switch stay pinned above it; a screenshot-counts as a capture. The first three positions filter, and `All` shows-everything: a proof usually stands on the capture it composes, so that capture-wears a dot rather than carrying a second mark. The two past the rule are-**modes** — each swaps the panel to its own index and hides the rest, so nothing-stacks two marks on one spot. **Proofs** reads `GET /proofs/index`, and **Media**-`GET /satellite/media`; both are read the first time that position is opened,-never on case open. The panel opens on **Media**, which is what a map is read-for: where the case's footage stands.-A proof is placed by the coordinates written in its own spec — the composer's-coordinate field first, then the point its panels gave it — and only failing-that by every capture it composes, which is why deleting a capture does not-unpin the proofs built on it. A proof is filed in My work like any other-artifact, so the folder grouping works there too; **Locate** does not appear,-since a proof states or borrows its point and the pass has nothing to look up.+worldwide case opens on continents. A filter and a `Media / Places / Captures`+switch stay pinned above it; a screenshot counts as a capture. The panel opens on+**Media**, which is what a map is read for: where the case's footage stands. That+position is a **mode** — it reads its own index (`GET /satellite/media`, the first+time it is opened, never on case open) — while Places and Captures filter the one+compact index the case opens with. One position is drawn at a time, so nothing+stacks two marks on one spot. Proofs are not a position of their own: a proof+stands on the point it argues, which is a place the switch already draws, and+that place wears a dot and a count instead.**Media** lists the case's located images and videos, one row per point. A filecarries no coordinates of its own, so the position is read off the graph, bydiff --git a/extension/README.md b/extension/README.mdindex c99cee8..33c3bcb 100644--- a/extension/README.md+++ b/extension/README.md@@ -105,7 +105,7 @@ on. Press it again to close it. Six tools share it:| Tool | What it does ||---|---|| Measure | Distance along a clicked path, or the area it encloses. Same formulas and same wording as the app. |-| Points | Draws the case's saved work on the map, and files a new point. |+| Points | Draws one of the case's three positions — its located media, its places, its captures — on the map, and files a new point. || Sun & moon | Plants a point and draws the day's sun and moon arcs around it, with a date and an hour slider. || Grid | Drags a box or clicks out a shape, cuts it into metric cells, and marks each cleared or flagged. The grid is saved into the case and opens in the app's own Grid Search. || Refs | Floats an image or a video from the case over the map, to compare against the imagery while you pan. |@@ -224,6 +224,13 @@ which is the honest thing for a tool whose output ends up in a case file.to keep it open. Points at the same spot merge into one counted mark, the way theapp's own Saved layer merges them.+**One position is drawn at a time**, the same three the app's Saved panel offers+and in the same order: the located media the case collected, the places dropped+by hand, the captures taken of them. The panel opens on the media, and switching+position reads that position — a file carries no coordinates of its own and is+not in the index the other two come from. Filing a point goes to Places, so the+point just filed is drawn rather than swallowed.+**The case stays in step, in every window onto it.** Save a point in the app andit appears here; mark a cell here and it appears in the app's own Grid Search andin any other map you have the panel open on. Nothing needs reloading and nothing@@ -276,7 +283,7 @@ measured places the drawing again without asking.The token allows this extension to file captures through the local Azimutserver, to read back the media and proofs a thread attaches, and — for the map-tools — the saved points, search grids, images and videos of the case you pick. Rotate it in+tools — the points, search grids, images and videos of the case you pick. Rotate it inSettings to revoke existing pairings.## Fill the composerdiff --git a/extension/mapoverlay.js b/extension/mapoverlay.jsindex 6595f83..83a4643 100644--- a/extension/mapoverlay.js+++ b/extension/mapoverlay.js@@ -1300,8 +1300,15 @@async function loadPins() {if (!state.caseId) return;+ const wanted = tools.pins.kind;try {- tools.pins.load(await call("GET", "/api/ingest/saved", { query: { case_id: state.caseId } }));+ const rows = await call("GET", "/api/ingest/saved", {+ query: { case_id: state.caseId, kind: wanted },+ });+ // the switch moved again while this was in flight: those rows belong to a+ // position nobody is looking at+ if (tools.pins.kind !== wanted) return;+ tools.pins.load(rows);tools.pins.atZoom(state.view?.zoom);render();} catch (e) {@@ -1331,6 +1338,9 @@tools.pins.clearDraft();state.pinTitle = "";state.note = "";+ // a point filed while the footage is drawn would land on a position that+ // cannot show it: go to the one it belongs to rather than swallowing it+ tools.pins.setKind("places");await loadPins();} catch (e) {state.note = e.message;@@ -2051,6 +2061,13 @@const draft = tool.draft;return `${button("pin-drop", "pin", tool.dropping ? "Click the map" : "Place a point", tool.dropping)}+ <div class="row wrap">+ ${tool.kinds+ .map((entry) =>+ button("pin-kind", "", entry.label, tool.kind === entry.id, ` data-kind="${esc(entry.id)}"`)+ )+ .join("")}+ </div><div class="readout small">${esc(readout)}</div>${draft ? `<input data-act="pin-title" placeholder="Name this point" value="${esc(state.pinTitle)}">@@ -2300,6 +2317,12 @@syncArmed();return render();}+ if (act === "pin-kind") {+ if (!tools.pins.setKind(target.dataset.kind)) return;+ redraw();+ render();+ return loadPins();+ }if (act === "pin-save") return placePin();if (act === "pin-cancel") {tools.pins.clearDraft();diff --git a/extension/maptheme.js b/extension/maptheme.jsindex c6645a3..ea20e3b 100644--- a/extension/maptheme.js+++ b/extension/maptheme.js@@ -106,7 +106,7 @@/** Which glyph a saved row is drawn with — `SavedOverlay.svelte`'s own map.* A stack holding more than one kind falls back to the place glyph. */- const SAVED_GLYPH = { place: "pin", capture: "satellite", screenshot: "screen", proof: "proof" };+ const SAVED_GLYPH = { place: "pin", capture: "satellite", screenshot: "screen" };window.AzimutMapTheme = {TOKENS,diff --git a/extension/maptools.js b/extension/maptools.jsindex 93213ac..f481bbf 100644--- a/extension/maptools.js+++ b/extension/maptools.js@@ -241,9 +241,23 @@* Points at the same spot merge into one counted mark, exactly as the app's* Saved layer merges them, and the name belongs to the mark under the pointer* or the one held open by a click.+ *+ * **One position at a time**, the same three the app's panel offers: the+ * located footage first, then the points dropped by hand, then the captured+ * imagery. Each is its own read — the panel calls back for the rows rather+ * than filtering a set it holds, because media never was in the saved index.*/+ /** What the points tool can draw, in the order a case is read. Mirrors the+ * app's own switch (`lib/geoTree.KINDS`) and the `kind` the saved route takes. */+ const PIN_KINDS = [+ { id: "media", label: "Media" },+ { id: "places", label: "Places" },+ { id: "captures", label: "Captures" },+ ];+function createPins() {let rows = [];+ let kind = PIN_KINDS[0].id;let zoom = null;let marks = [];let dropping = false;@@ -272,6 +286,20 @@get marks() {return marks;},+ kinds: PIN_KINDS,+ get kind() {+ return kind;+ },+ /** Switch position. The rows belong to the position that asked for them,+ * so they go with it rather than being drawn under the new label until+ * the panel's own read lands. */+ setKind(next) {+ if (!PIN_KINDS.some((entry) => entry.id === next) || next === kind) return false;+ kind = next;+ rows = [];+ regroup();+ return true;+ },get dropping() {return dropping;},@@ -284,7 +312,7 @@get held() {return held;},- /** The case's saved index, filtered to what can actually be drawn. */+ /** The rows of the open position, filtered to what can actually be drawn. */load(index) {rows = (index ?? []).filter((row) => Number.isFinite(row.lat) && Number.isFinite(row.lon)@@ -361,10 +389,18 @@const out = marks.map((mark) => {const only = mark.kinds.length === 1 ? mark.kinds[0] : "place";const shown = mark.key === hovered || mark.key === held;+ // a stack of files draws as footage only when all of it is footage,+ // the way the app's own layer glyphs one (`SavedOverlay.svelte`)+ const glyph =+ only === "media"+ ? mark.items.every((row) => row.media_kind === "video")+ ? "video"+ : "image"+ : (THEME.SAVED_GLYPH[only] ?? "pin");return {kind: "mark",at: { lat: mark.lat, lon: mark.lon },- glyph: THEME.SAVED_GLYPH[only] ?? "pin",+ glyph,// a bare place carries no imagery: the app outlines it rather than// filling it, so a stack of captures never hides behind oneplace: only === "place",@@ -393,7 +429,10 @@: "Filing the point you clicked";}if (dropping) return "Click the map to place a point";- if (!rows.length) return "Nothing placed in this case yet";+ if (!rows.length) {+ const label = PIN_KINDS.find((entry) => entry.id === kind)?.label.toLowerCase();+ return `No ${label} in this case yet`;+ }const merged = rows.length - marks.length;return merged > 0 ? `${rows.length} here, in ${marks.length} marks` : `${rows.length} on this map`;},diff --git a/frontend/e2e/app.fixture.js b/frontend/e2e/app.fixture.jsindex 0c44d7b..ce2d485 100644--- a/frontend/e2e/app.fixture.js+++ b/frontend/e2e/app.fixture.js@@ -692,7 +692,6 @@ export async function installAppFixture(page, options = {}) {const placeWrites = [];const proofSaves = [];const fixtureSavedIndex = options.savedIndex ?? savedIndex;- const fixtureProofIndex = options.proofIndex ?? [];// Located files as the Media position reads them (GET /satellite/media).const fixtureMediaIndex = options.mediaIndex ?? [];const fixtureMedia = (options.media ?? media).map((item) => ({ ...item }));@@ -700,10 +699,8 @@ export async function installAppFixture(page, options = {}) {const fixtureProviders = options.widget ? [...providers, WIDGET_PROVIDER] : providers;const widgetLoads = [];const fixtureSavedIndexes = options.savedIndexes ?? { [CASE_ID]: fixtureSavedIndex };- const fixtureProofIndexes = options.proofIndexes ?? { [CASE_ID]: fixtureProofIndex };const fixtureMediaIndexes = options.mediaIndexes ?? { [CASE_ID]: fixtureMediaIndex };const savedIndexDelays = options.savedIndexDelays ?? {};- const proofIndexDelays = options.proofIndexDelays ?? {};const caseDelays = options.caseDelays ?? {};const graphDelays = options.graphDelays ?? {};const fixtureDrafts = options.drafts ?? {};@@ -1334,12 +1331,6 @@ export async function installAppFixture(page, options = {}) {if (caseId && path === `/api/cases/${caseId}/satellite/media`) {return json(route, fixtureMediaIndexes[caseId] ?? []);}- if (caseId && path === `/api/cases/${caseId}/proofs/index`) {- if (proofIndexDelays[caseId]) {- await new Promise((resolve) => setTimeout(resolve, proofIndexDelays[caseId]));- }- return json(route, fixtureProofIndexes[caseId] ?? []);- }// The case as the catalog answers for it: a spec's own list, or the drawn case so// the fixture stands for one case rather than two — the graph's search reads the// catalog, and it has to be able to find an entity the drawing left out.@@ -2006,10 +1997,10 @@ export async function installAppFixture(page, options = {}) {/*** Put the Saved panel, and the layer drawing from it, on one position.*- * The panel opens on **Media**, so a spec about places, captures or proofs asks- * for its own position rather than assuming the one it used to open on.+ * The panel opens on **Media**, so a spec about places or captures asks for its+ * own position rather than assuming the one it used to open on.*/-export async function showSaved(page, kind = 'All') {+export async function showSaved(page, kind) {await page.getByRole('group', { name: 'What this panel lists' }).getByRole('button', { name: kind, exact: true })diff --git a/frontend/e2e/compare.spec.js b/frontend/e2e/compare.spec.jsindex eb1d3a1..3574843 100644--- a/frontend/e2e/compare.spec.js+++ b/frontend/e2e/compare.spec.js@@ -38,14 +38,17 @@ test('linked maps keep annotations on the ground through pan, modes and save', aawait page.mouse.move(box.x + box.width / 2 + 60, box.y + box.height / 2 + 40, { steps: 5 });await page.mouse.up();await expect(page.locator('.annotation-canvas .mark')).toHaveCount(2);- const before = await canvas.locator('path').getAttribute('d');+ // The drawn outline, not the transparent band laid over it to be grabbed:+ // both carry the same `d`, so a bare `path` matches two and settles nothing.+ const outline = canvas.locator('.mark > path:not(.edge)');+ const before = await outline.getAttribute('d');await page.mouse.move(box.x + 100, box.y + 100);await page.mouse.down();await page.mouse.move(box.x + 180, box.y + 140, { steps: 8 });await page.mouse.up();- await expect(canvas.locator('path')).not.toHaveAttribute('d', before);+ await expect(outline).not.toHaveAttribute('d', before);await expect.poll(async () => {- const paths = await page.locator('.annotation-canvas .mark path').evaluateAll((nodes) => nodes.map((node) => node.getAttribute('d')));+ const paths = await page.locator('.annotation-canvas .mark > path:not(.edge)').evaluateAll((nodes) => nodes.map((node) => node.getAttribute('d')));const numbers = paths.map((path) => path.match(/-?\d+(?:\.\d+)?/g).map(Number));return Math.max(...numbers[0].map((n, i) => Math.abs(n - numbers[1][i])));}).toBeLessThan(1);@@ -86,7 +89,7 @@ test('spectral frames are requested only by Run, including after reopening and mtitle: 'Spectral', spec: { version: 2, camera: { lat: 48.8584, lon: 2.2945, zoom: 16, bearing: 35 },mode: 'change', change_assist: { method: 'index' }, a: side('2026-08-01'), b: side('2026-09-01') },} }));- await page.route('**/api/compare/sentinel-index', async (route) => {+ await page.route('**/api/compare/sentinel-frame', async (route) => {const body = route.request().postDataJSON();requests.push(body);const png = await page.evaluate(({ width, height }) => {@@ -117,9 +120,16 @@ test('spectral frames are requested only by Run, including after reopening and mawait page.mouse.move(box.x + 180, box.y + 130, { steps: 8 });await page.mouse.up();await expect(page.locator('.secondary .change-map')).not.toHaveCSS('transform', 'none');- await expect(page.getByLabel('Difference', { exact: true })).toContainText('Run again to match it');+ await expect(page.getByLabel('Difference', { exact: true })).toContainText('Run again to match this view');await expect(page.getByRole('button', { name: 'Read this view', exact: true })).toBeEnabled();expect(requests).toHaveLength(2);+ // The cloud filter reads Sentinel-2's own classification, so switching it on+ // over a picture method asks for the sky then and there, rather than leaving+ // an unfiltered reading up behind an "on" switch.+ await page.getByLabel('Method', { exact: true }).selectOption('colour');+ await page.getByRole('button', { name: /Clouds & shadows/ }).click();+ await expect.poll(() => requests.length).toBe(4);+ expect(requests.slice(2).map((request) => request.product)).toEqual(['sky', 'sky']);expect(errors).toEqual([]);});@@ -133,6 +143,12 @@ test('changes run in the worker and export a composed PNG', async ({ page }) =>await page.getByRole('button', { name: 'Difference', exact: true }).click();await expect(page.locator('.secondary .change-map')).toBeVisible({ timeout: 20000 });await expect(page.getByLabel('Difference', { exact: true })).toContainText('highlighted');+ // Highlights that come and go are easier to catch over busy imagery.+ await page.getByRole('button', { name: 'Blink the highlights', exact: true }).click();+ await expect(page.locator('.secondary .change-map')).toBeHidden();+ await expect(page.locator('.secondary .change-map')).toBeVisible();+ await page.getByRole('button', { name: 'Stop blinking the highlights', exact: true }).click();+ await expect(page.locator('.secondary .change-map')).toBeVisible();await page.getByLabel('Method', { exact: true }).selectOption('structure');await expect(page.getByLabel('Difference', { exact: true })).toContainText('coverage');await page.getByRole('button', { name: 'Export', exact: true }).click();@@ -145,16 +161,23 @@ test('changes run in the worker and export a composed PNG', async ({ page }) =>test('analyzer areas run explicitly, and candidates are reviewed one at a time', async ({ page }) => {const { errors } = await openCompare(page, 'Esri Wayback');const requests = [];- const recipe = { id: 'large-change', name: 'Large surface change', description: 'Pixel changes to review',- phenomenon: 'Surface change', method: 'colour', providers: ['esri-wayback', 'sentinel2'], zones: [],- colour: '#f6a81a', style: 'both', parameters: { sensitivity: 55, min_area: 20, min_score: 0,- cleanup: 1, smoothing: 0, normalize: false, index: 'ndvi', direction: 'both',- ignore_clouds: true, ignore_shadows: true, merge_metres: 0 } };+ const sizes = {+ small: { min_area: 300, max_area: 0, cleanup: 0, smoothing: 0, merge_metres: 0 },+ medium: { min_area: 2000, max_area: 0, cleanup: 1, smoothing: 0, merge_metres: 30 },+ large: { min_area: 20000, max_area: 0, cleanup: 1, smoothing: 1, merge_metres: 100 },+ };+ const recipe = { id: 'large-change', name: 'Any surface change', description: 'Reflectance that moved',+ phenomenon: 'Surface change', method: 'surface', zones: [], colour: '#f6a81a', style: 'both',+ parameters: { sensitivity: 67, ...sizes.medium, index: 'ndvi', direction: 'both',+ ignore_clouds: true, ignore_shadows: true, cloud_margin: 5 } };await page.route('**/api/compare/analyzers', (route) => route.fulfill({ json: {- builtins: [recipe], custom: [], max_tiles: 256, max_results: 2000,- methods: [{ id: 'colour', label: 'Colour', single: false, sentinel_only: false, classes: false }],- grids: { sentinel2: [13, 512], 'esri-wayback': [19, 256] },+ builtins: [recipe], custom: [], max_tiles: 4096, max_results: 2000, grid: [13, 512],+ methods: [{ id: 'surface', label: 'Any reflectance change', single: false, clouds: true, sizes,+ measure: 'Reflectance moved by {value}%' }],} }));+ await page.route('**/api/satellite/sentinel/acquisitions', (route) => route.fulfill({ json: {+ dates: [{ date: '2026-05-11', cloud: 2, granules: 1, coverage: 1 },+ { date: '2026-05-04', cloud: 4, granules: 1, coverage: 1 }], truncated: false } }));let saved;await page.route('**/api/cases/*/analysis/**', async (route) => {const path = new URL(route.request().url()).pathname;@@ -163,10 +186,10 @@ test('analyzer areas run explicitly, and candidates are reviewed one at a time',const [[w, n], [e, s]] = input.zones[0].points;const row = { id: '0-1', coordinates: [(w + e) / 2, (n + s) / 2],bbox: [Math.min(w, e), Math.min(n, s), Math.max(w, e), Math.max(n, s)],- area: 90, width: 15, height: 6, signal_score: 0.8, confidence: null,+ area: 90, width: 15, height: 6, margin: 3.4, strength: 'strong', measure: { value: 18.2 },phenomenon: 'Surface change', review: 'new', parts: [{ frames: ['a', 'b'], box: [0, 0, 1, 1] }] };saved = { id: '123456789abc', title: input.title, input, status: 'ready', progress: 1, total: 1,- count: 1, results: [row], engine_version: 1, created_at: '2026-09-16T00:00:00Z' };+ count: 1, results: [row], engine_version: 2, created_at: '2026-09-16T00:00:00Z' };await route.fulfill({ json: { ...saved, status: 'queued', results: [], count: 0 } });} else if (route.request().method() === 'PATCH' && path.includes('/results/')) {saved.results[0].review = route.request().postDataJSON().review;@@ -188,14 +211,19 @@ test('analyzer areas run explicitly, and candidates are reviewed one at a time',await page.mouse.move(box.x + 80, box.y + 100);await page.mouse.down(); await page.mouse.move(box.x + 190, box.y + 190, { steps: 6 }); await page.mouse.up();await expect(page.getByLabel('Area name', { exact: true })).toHaveCount(1);- await expect(page.getByLabel('Detect', { exact: true })).toContainText('tiles of 256px');- await page.getByRole('button', { name: 'Change imagery, dates or the rule…' }).click();- await page.getByLabel('Release A', { exact: true }).selectOption('1');- await page.getByLabel('Release B', { exact: true }).selectOption('2');+ await expect(page.getByLabel('Detect', { exact: true })).toContainText('1 tile');+ // Wayback on the maps is nothing Detect can read, so it asks for Sentinel-2 dates.+ await expect(page.getByLabel('Detect', { exact: true })).toContainText('Detect reads Sentinel-2');+ await page.getByRole('button', { name: 'Change dates or the rule…' }).click();+ await page.getByRole('button', { name: 'Find passes', exact: true }).click();+ await page.getByLabel('Use 2026-05-04').getByRole('button', { name: 'A', exact: true }).click();+ await page.getByLabel('Use 2026-05-11').getByRole('button', { name: 'B', exact: true }).click();await page.getByLabel('Analysis name', { exact: true }).fill('Harbour sweep');+ await page.getByRole('group', { name: 'Target size' }).scrollIntoViewIfNeeded();+ await page.screenshot({ path: test.info().outputPath('analyzers-setup.png') });expect(requests).toHaveLength(0);await page.getByRole('button', { name: 'Run on 1 area', exact: true }).click();- await expect(page.getByText('Signal score 80% · not a calibrated confidence', { exact: true })).toBeVisible();+ await expect(page.getByText('Strong · Reflectance moved by 18.2%', { exact: true })).toBeVisible();expect(requests).toHaveLength(1);expect(requests[0].zones).toHaveLength(1);const pins = page.locator('.analysis-overlay [role="button"]');@@ -219,8 +247,10 @@ test('analyzer areas run explicitly, and candidates are reviewed one at a time',await page.getByRole('button', { name: 'Detect', exact: true }).click();await page.getByRole('button', { name: 'Saved', exact: true }).click();await page.locator('.cmp-dock .link').filter({ hasText: 'Harbour sweep' }).first().click();- await expect(page.getByText('Signal score 80% · not a calibrated confidence', { exact: true })).toBeVisible();+ await expect(page.getByText('Strong · Reflectance moved by 18.2%', { exact: true })).toBeVisible();expect(requests).toHaveLength(1);+ expect(requests[0].a).toMatchObject({ provider: 'sentinel2', date: '2026-05-04' });+ expect(requests[0].b).toMatchObject({ provider: 'sentinel2', date: '2026-05-11' });await page.screenshot({ path: test.info().outputPath('analyzers.png') });expect(errors).toEqual([]);});diff --git a/frontend/e2e/home-guide.spec.js b/frontend/e2e/home-guide.spec.jsindex c6b0612..fa8b307 100644--- a/frontend/e2e/home-guide.spec.js+++ b/frontend/e2e/home-guide.spec.js@@ -23,10 +23,11 @@ const summary = {countable: 0,};-// Two points a few hundred metres apart, one north-west of the other.-const savedIndex = [- { id: 'p1', key: 'p1', kind: 'place', title: 'North gate', lat: 49.9951, lon: 36.2304 },- { id: 'p2', key: 'p2', kind: 'capture', title: 'Depot roof', lat: 49.9889, lon: 36.2401 },+// Two located files a few hundred metres apart, one north-west of the other:+// the home map draws the case's footage, which is what it is built on.+const mediaIndex = [+ { id: 'm1', key: '[email protected],36.2304', kind: 'media', media_kind: 'image', title: 'North gate', lat: 49.9951, lon: 36.2304 },+ { id: 'm2', key: '[email protected],36.2401', kind: 'media', media_kind: 'video', title: 'Depot roof', lat: 49.9889, lon: 36.2401 },];test('draws the case on the free imagery, and presses through to the map', async ({ page }) => {@@ -35,7 +36,7 @@ test('draws the case on the free imagery, and presses through to the map', asyncconst { pathname } = new URL(request.url());if (pathname.startsWith('/api/tiles/')) tiles.push(pathname);});- await installAppFixture(page, { savedIndex, summary });+ await installAppFixture(page, { mediaIndex, summary });await page.goto('/#overview');await awaitMapReady(page);@@ -51,7 +52,7 @@ test('draws the case on the free imagery, and presses through to the map', async});test('the ? reaches the section written about the tab it was pressed from', async ({ page }) => {- await installAppFixture(page, { savedIndex, summary });+ await installAppFixture(page, { mediaIndex, summary });await page.goto('/#satellite');await page.locator('.topbar button[title="Guide: Satellite"]').click();@@ -62,7 +63,7 @@ test('the ? reaches the section written about the tab it was pressed from', asyn});test('a recipe step opens the tab it names', async ({ page }) => {- await installAppFixture(page, { savedIndex, summary });+ await installAppFixture(page, { mediaIndex, summary });await page.goto('/#guide');await page.locator('.contents .jump', { hasText: 'Worked examples' }).click();diff --git a/frontend/e2e/place-precision.spec.js b/frontend/e2e/place-precision.spec.jsindex 46e68a3..460f01e 100644--- a/frontend/e2e/place-precision.spec.js+++ b/frontend/e2e/place-precision.spec.js@@ -55,7 +55,7 @@ async function openCard(page) {});await page.goto('/#satellite');await awaitMapReady(page);- await showSaved(page); // the layer is on, on the Media position+ await showSaved(page, 'Places'); // the panel opens on Media; these are pinsawait page.locator('.saved-mark').click();return fixture;}diff --git a/frontend/e2e/saved-case-switch.spec.js b/frontend/e2e/saved-case-switch.spec.jsnew file mode 100644index 0000000..d3fc8f8--- /dev/null+++ b/frontend/e2e/saved-case-switch.spec.js@@ -0,0 +1,43 @@+import { test, expect } from '@playwright/test';+import { CASE_ID, awaitMapReady, installAppFixture, showSaved } from './app.fixture.js';++// Opening a second case must not leave the first one's rows on screen while the+// new index is still on its way — the panel would be reading one case under the+// name of another.++const point = {+ lat: 48.8584,+ lon: 2.2945,+ geo: { state: 'ok', country_code: 'fr', country: 'France' },+ continent: 'Europe',+ country_en: 'France',+};++test('clears capture rows before a different case index arrives', async ({ page }) => {+ const secondId = 'browser-test-b';+ const fixture = await installAppFixture(page, {+ cases: [+ { id: CASE_ID, name: 'Case A', scratch: false, folders: [] },+ { id: secondId, name: 'Case B', scratch: false, folders: [] },+ ],+ savedIndexes: {+ [CASE_ID]: [{ id: 'capture-a', key: 'capture-a', kind: 'capture', title: 'Capture A', ...point }],+ [secondId]: [{ id: 'capture-b', key: 'capture-b', kind: 'capture', title: 'Capture B', ...point }],+ },+ savedIndexDelays: { [secondId]: 1200 },+ });++ await page.goto('/#satellite');+ await awaitMapReady(page); // the rows are read beside a map, and one mark is on it+ const savedPanel = page.locator('.captures');+ await showSaved(page, 'Captures');+ await expect(savedPanel.getByText('Capture A', { exact: true })).toBeVisible();+ await expect(page.locator('.saved-mark-capture')).toHaveCount(1);+ await page.getByTitle('Switch case').click();+ await page.locator('.menu .item').filter({ hasText: 'Case B' }).click();++ await expect(savedPanel.getByText('Capture A', { exact: true })).toBeHidden({ timeout: 500 });+ await expect(page.locator('.saved-mark-capture')).toBeHidden({ timeout: 500 });+ await expect(savedPanel.getByText('Capture B', { exact: true })).toBeVisible();+ fixture.expectNoUnexpectedRequests();+});diff --git a/frontend/e2e/saved-linked-posts.spec.js b/frontend/e2e/saved-linked-posts.spec.jsdeleted file mode 100644index f08ee58..0000000--- a/frontend/e2e/saved-linked-posts.spec.js+++ /dev/null@@ -1,128 +0,0 @@-import { test, expect } from '@playwright/test';-import { CASE_ID, awaitMapReady, installAppFixture, showSaved } from './app.fixture.js';--// The third one names a target this build dropped, which is what a draft saved-// before that looks like: it is listed, and it opens (on X, by normalizePostTarget).-const linkedPosts = [- { id: 'post-1', name: 'panorama-publication', title: 'Panorama publication', target: 'x' },- { id: 'post-2', name: 'source-follow-up', title: 'Follow-up with sources', target: 'bluesky' },- { id: 'post-3', name: 'later-note', title: 'Later note', target: 'mastodon' },-];--const point = {- lat: 48.8584,- lon: 2.2945,- geo: { state: 'ok', country_code: 'fr', country: 'France' },- continent: 'Europe',- country_en: 'France',-};--test('shows every linked post from a proof popup and opens the selected draft', async ({ page }) => {- const fixture = await installAppFixture(page, {- savedIndex: [{- id: 'capture-1',- key: 'capture-1',- kind: 'capture',- title: 'Source capture',- path: 'media/source.png',- fetched_at: '2026-07-24T08:00:00Z',- proofs: 1,- ...point,- }],- proofIndex: [{- id: 'proof-1',- key: '[email protected],2.2945',- kind: 'proof',- name: 'panorama-proof',- title: 'Panorama autostitch test',- path: 'proofs/panorama-proof.png',- fetched_at: '2026-07-24T09:00:00Z',- posts: linkedPosts.length,- linked_posts: linkedPosts,- ...point,- }],- drafts: {- 'later-note': {- title: 'Later note',- updated_at: '2026-07-24T10:00:00Z',- state: { target: 'mastodon', tweet1: 'Later context' },- },- },- });-- await page.goto('/#satellite');- await awaitMapReady(page);- await showSaved(page, 'Proofs');- await expect(page.getByText('Panorama autostitch test')).toBeVisible();-- await page.locator('.saved-mark-proof').click();-- const popup = page.locator('.saved-popup');- await expect(popup.getByText('Linked posts · 3')).toBeVisible();- await expect(popup.getByText('Panorama publication')).toBeVisible();- await expect(popup.getByText('Follow-up with sources')).toBeVisible();- await expect(popup.getByText('Later note')).toHaveCount(0);-- await popup.getByRole('button', { name: '+ 1 more' }).click();- await expect(popup.getByText('Later note')).toBeVisible();- await popup.getByRole('button', { name: /Later note/ }).click();-- await expect(page.getByRole('button', { name: 'Geo Report', exact: true })).toHaveClass(/active/);- await expect(page.getByLabel('Post name')).toHaveValue('Later note');- fixture.expectNoUnexpectedRequests();-});--test('clears capture rows before a different case index arrives', async ({ page }) => {- const secondId = 'browser-test-b';- const fixture = await installAppFixture(page, {- cases: [- { id: CASE_ID, name: 'Case A', scratch: false, folders: [] },- { id: secondId, name: 'Case B', scratch: false, folders: [] },- ],- savedIndexes: {- [CASE_ID]: [{ id: 'capture-a', key: 'capture-a', kind: 'capture', title: 'Capture A', ...point }],- [secondId]: [{ id: 'capture-b', key: 'capture-b', kind: 'capture', title: 'Capture B', ...point }],- },- savedIndexDelays: { [secondId]: 1200 },- });-- await page.goto('/#satellite');- await awaitMapReady(page); // the rows are read beside a map, and one mark is on it- const savedPanel = page.locator('.captures');- await showSaved(page);- await expect(savedPanel.getByText('Capture A', { exact: true })).toBeVisible();- await expect(page.locator('.saved-mark-capture')).toHaveCount(1);- await page.getByTitle('Switch case').click();- await page.locator('.menu .item').filter({ hasText: 'Case B' }).click();-- await expect(savedPanel.getByText('Capture A', { exact: true })).toBeHidden({ timeout: 500 });- await expect(page.locator('.saved-mark-capture')).toBeHidden({ timeout: 500 });- await expect(savedPanel.getByText('Capture B', { exact: true })).toBeVisible();- fixture.expectNoUnexpectedRequests();-});--test('clears proof rows before a different case proof index arrives', async ({ page }) => {- const secondId = 'browser-test-b';- const fixture = await installAppFixture(page, {- cases: [- { id: CASE_ID, name: 'Case A', scratch: false, folders: [] },- { id: secondId, name: 'Case B', scratch: false, folders: [] },- ],- proofIndexes: {- [CASE_ID]: [{ id: 'proof-a', key: 'proof-a', kind: 'proof', name: 'proof-a', title: 'Proof A', ...point }],- [secondId]: [{ id: 'proof-b', key: 'proof-b', kind: 'proof', name: 'proof-b', title: 'Proof B', ...point }],- },- proofIndexDelays: { [secondId]: 1200 },- });-- await page.goto('/#satellite');- await awaitMapReady(page); // the panel is the map tool's, and it opens with it- await showSaved(page, 'Proofs');- await expect(page.getByText('Proof A')).toBeVisible();- await page.getByTitle('Switch case').click();- await page.locator('.menu .item').filter({ hasText: 'Case B' }).click();-- await expect(page.getByText('Proof A')).toBeHidden({ timeout: 500 });- await expect(page.getByText('Proof B')).toBeVisible();- fixture.expectNoUnexpectedRequests();-});diff --git a/frontend/e2e/saved-relations.spec.js b/frontend/e2e/saved-relations.spec.jsindex 92692f1..12d5c18 100644--- a/frontend/e2e/saved-relations.spec.js+++ b/frontend/e2e/saved-relations.spec.js@@ -73,7 +73,7 @@ test('opens a stacked row’s relations without closing the card', async ({ pageawait page.goto('/#satellite');await awaitMapReady(page);- await showSaved(page); // the layer is on, on the Media position+ await showSaved(page, 'Places'); // the panel opens on Media; these are pinsawait page.locator('.saved-mark').click();const popup = page.locator('.saved-popup');@@ -98,7 +98,7 @@ test('corrects the reading of a relation in place, and takes one back', async ({await page.goto('/#satellite');await awaitMapReady(page);- await showSaved(page); // the layer is on, on the Media position+ await showSaved(page, 'Places'); // the panel opens on Media; these are pinsawait page.locator('.saved-mark').click();const popup = page.locator('.saved-popup');@@ -125,7 +125,7 @@ test('settles a suggested relation from the card, which survives the click', asyawait page.goto('/#satellite');await awaitMapReady(page);- await showSaved(page); // the layer is on, on the Media position+ await showSaved(page, 'Places'); // the panel opens on Media; these are pinsawait page.locator('.saved-mark').click();const popup = page.locator('.saved-popup');@@ -169,7 +169,7 @@ test('shows the findings on the card and leaves the pointers out', async ({ pageawait page.goto('/#satellite');await awaitMapReady(page);- await showSaved(page); // the layer is on, on the Media position+ await showSaved(page, 'Places'); // the panel opens on Media; these are pinsawait page.locator('.saved-mark').click();const popup = page.locator('.saved-popup');diff --git a/frontend/src/lib/extensionMapSync.test.js b/frontend/src/lib/extensionMapSync.test.jsindex 8361348..a34441b 100644--- a/frontend/src/lib/extensionMapSync.test.js+++ b/frontend/src/lib/extensionMapSync.test.js@@ -156,6 +156,18 @@ function open({ answers } = {}) {for (const cb of ports.at(-1).disconnects) cb();},pick: (id) => root().querySelector(`[data-tab="${id}"]`).click(),+ /** Press one of the open tool's own controls. */+ press: (act, data = {}) => {+ const where = Object.entries(data)+ .map(([key, value]) => `[data-${key}="${value}"]`)+ .join('');+ root().querySelector(`[data-act="${act}"]${where}`).click();+ },+ /** A click on the map itself, which is the drawing surface over it. */+ clickMap: (at = { x: 120, y: 90 }) =>+ root()+ .querySelector('canvas')+ .dispatchEvent(new window.PointerEvent('pointerdown', { clientX: at.x, clientY: at.y })),/** Open a saved sweep the way the picker does. */openSweep: (name = 'sweep') => {const select = root().querySelector('[data-act="grid-open"]');@@ -223,7 +235,7 @@ describe('the case’s points', () => {panel.app['/api/ingest/saved'] = [POINT, { ...POINT, id: 'p2', title: 'The bridge' }];panel.nudge({ type: 'place', case_id: CASE, title: 'The bridge' });await vi.waitFor(() => expect(panel.tools.pins.rows).toHaveLength(2));- expect(panel.queries('/api/ingest/saved').at(-1)).toEqual({ case_id: CASE });+ expect(panel.queries('/api/ingest/saved').at(-1)).toEqual({ case_id: CASE, kind: 'media' });});it('re-reads them when the app moves its own saved work', async () => {@@ -243,6 +255,34 @@ describe('the case’s points', () => {await settle(50);expect(panel.asks()).not.toContain('/api/ingest/saved');});++ it('reads one position at a time, the footage first', async () => {+ // media has an index of its own on the app's side, so switching position is+ // another read rather than a filter over rows the panel already holds+ panel = open();+ await settle();+ panel.pick('pins');+ panel.forget();+ panel.app['/api/ingest/saved'] = [{ ...POINT, id: 'c1', kind: 'capture', title: 'Roof' }];+ panel.press('pin-kind', { kind: 'captures' });+ await vi.waitFor(() => expect(panel.tools.pins.rows).toHaveLength(1));+ expect(panel.queries('/api/ingest/saved').at(-1)).toEqual({ case_id: CASE, kind: 'captures' });+ expect(panel.tools.pins.kind).toBe('captures');+ });++ it('goes to the position a point it just filed is on', async () => {+ // filing one while the footage is drawn would land it on a position that+ // cannot show it+ panel = open();+ await settle();+ panel.pick('pins');+ panel.press('pin-drop');+ panel.clickMap();+ panel.forget();+ panel.press('pin-save');+ await vi.waitFor(() => expect(panel.tools.pins.kind).toBe('places'));+ expect(panel.queries('/api/ingest/saved').at(-1)).toEqual({ case_id: CASE, kind: 'places' });+ });});describe('an open sweep', () => {diff --git a/frontend/src/lib/extensionMapTools.test.js b/frontend/src/lib/extensionMapTools.test.jsindex 6479bb7..cf96084 100644--- a/frontend/src/lib/extensionMapTools.test.js+++ b/frontend/src/lib/extensionMapTools.test.js@@ -475,6 +475,42 @@ describe('saved points', () => {expect(tool.draft).toBe(null);});+ it('draws footage with its own glyph, a stack of it only when all of it is', () => {+ const tool = ext.createPins();+ tool.load([+ { id: 'v', key: 'v', kind: 'media', media_kind: 'video', title: 'Clip', lat: 40, lon: 3 },+ { id: 'p', key: 'p', kind: 'media', media_kind: 'image', title: 'Photo', lat: 41, lon: 3 },+ ]);+ tool.atZoom(18);+ expect(tool.shapes().map((shape) => shape.glyph)).toEqual(['video', 'image']);++ // one photograph in the stack and the mark is no longer footage of one kind+ tool.load([+ { id: 'v', key: 'v', kind: 'media', media_kind: 'video', title: 'Clip', lat: 40, lon: 3 },+ { id: 'p', key: 'p', kind: 'media', media_kind: 'image', title: 'Photo', lat: 40, lon: 3 },+ ]);+ tool.atZoom(18);+ expect(tool.shapes()[0].glyph).toBe('image');+ });++ it('opens on the footage, and drops the rows with the position it left', () => {+ // media is not in the saved index: the rows belong to the position that+ // asked for them, and the panel reads again rather than filtering+ const tool = loaded();+ expect(tool.kind).toBe('media');+ expect(tool.kinds.map((entry) => entry.id)).toEqual(['media', 'places', 'captures']);++ expect(tool.setKind('captures')).toBe(true);+ expect(tool.rows).toEqual([]);+ expect(tool.marks).toEqual([]);+ expect(tool.readout()).toBe('No captures in this case yet');++ // the position it is already on, and one that does not exist, change nothing+ expect(tool.setKind('captures')).toBe(false);+ expect(tool.setKind('proofs')).toBe(false);+ expect(tool.kind).toBe('captures');+ });+it('works on a view without geometry', () => {expect(ext.createPins().needsGeometry).toBe(false);});diff --git a/frontend/src/lib/geoTree.js b/frontend/src/lib/geoTree.jsindex 65059d7..6e1c0fd 100644--- a/frontend/src/lib/geoTree.js+++ b/frontend/src/lib/geoTree.js@@ -13,23 +13,31 @@import { matchesTerms } from './folderBrowse.js';import { haversine } from './measure.js';-/** The switch's five positions. The first three filter the saved rows — a+/** The switch's three positions, in the order a case is read: the footage+ * first, then the points dropped on it, then the imagery captured of it.+ *+ * **Media** is a mode, not a filter — a file carries no point of its own and+ * stands where the graph puts it, so it has an index of its own and swaps the+ * rows the panel reads. Places and captures filter the one saved index; a* screenshot is a capture with a different origin, not a thing to choose- * between. The last two are *modes*: a proof and a photo carry no point of- * their own and stand where the graph puts them, so drawing them with the- * places they borrow from would stack two marks on one spot. Each swaps the- * rows the panel reads instead. */+ * between. */export const KINDS = [+ { id: 'media', label: 'Media' },+ { id: 'places', label: 'Places' },+ { id: 'captures', label: 'Captures' },+];++/** The kinds a list reading the saved index alone can offer, where `all` is+ * honestly all of it — media is not in that index (`PointPicker.svelte`). */+export const SAVED_KINDS = [{ id: 'all', label: 'All' },{ id: 'places', label: 'Places' },{ id: 'captures', label: 'Captures' },- { id: 'proofs', label: 'Proofs', mode: true },- { id: 'media', label: 'Media', mode: true },];/** True when this position swaps the row source rather than filtering it. */export function isMode(kind) {- return KINDS.some((k) => k.id === kind && k.mode);+ return kind === 'media';}/** Where an item with no country goes, and what that bucket is called. */@@ -89,8 +97,6 @@ function savedText(row) {: `${row.lat}, ${row.lon}\n${Number(row.lat).toFixed(4)}, ${Number(row.lon).toFixed(4)}`;return [row.title,- // what the analyst called this point, when a proof states several- row.label,row.notes,row.provider,row.site,@@ -106,9 +112,9 @@ function savedText(row) {.join('\n');}-/** One row per entity, keeping the first. A proof that composes captures in two- * cities is two marks on the map — the map is about places — but one line in a- * flat list, which is about things. */+/** One row per entity, keeping the first. A file recorded in one city and+ * showing another is two marks on the map — the map is about places — but one+ * line in a flat list, which is about things. */export function oneEach(rows) {const seen = new Set();return (rows ?? []).filter((row) => !seen.has(row.id) && seen.add(row.id));diff --git a/frontend/src/lib/geoTree.test.js b/frontend/src/lib/geoTree.test.jsindex 27920f1..9b07ef8 100644--- a/frontend/src/lib/geoTree.test.js+++ b/frontend/src/lib/geoTree.test.js@@ -9,6 +9,7 @@ import {KINDS,oneEach,pendingLocate,+ SAVED_KINDS,savedFolders,} from './geoTree.js';@@ -144,34 +145,34 @@ describe('buildGeoTree filtering', () => {expect(filterSaved(rows, { kind: 'all' })).toHaveLength(3);});- it('switches to proofs rather than mixing them into the saved rows', () => {- // A proof sits on the capture it composes, so drawing both at once would- // stack two marks on one point. The fourth position swaps the source- // instead: `isMode` tells the panel to fetch, not to filter.- expect(KINDS.map((k) => k.id)).toEqual(['all', 'places', 'captures', 'proofs', 'media']);- expect(isMode('proofs')).toBe(true);- expect(isMode('all')).toBe(false);-- // and the filter itself never has to know about proofs- expect(filterSaved(rows, { kind: 'proofs' })).toHaveLength(3);+ it('offers three positions, the footage first', () => {+ // what a case is built on comes before the pins dropped on it, and a proof+ // is not a position at all: it stands on a place this list already draws+ expect(KINDS.map((k) => k.id)).toEqual(['media', 'places', 'captures']);+ // the picker, which reads the saved index alone, is where `all` is honest+ expect(SAVED_KINDS.map((k) => k.id)).toEqual(['all', 'places', 'captures']);});- it('switches to located media the same way', () => {- // a photo stands where a place, a proof or a capture puts it, so it is a- // source of its own rather than a filter over the places it borrows from+ it('switches to located media rather than filtering for it', () => {+ // a file stands where a place or a capture puts it, so it is a source of+ // its own rather than a filter over the points it borrows from: `isMode`+ // tells the panel to fetch, not to filterexpect(isMode('media')).toBe(true);+ expect(isMode('places')).toBe(false);+ expect(isMode('captures')).toBe(false);+ // and the filter itself never has to know about mediaexpect(filterSaved(rows, { kind: 'media' })).toHaveLength(3);});- it('lists a two-place proof once, however many marks it draws', () => {+ it('lists a file standing twice once, however many marks it draws', () => {// the map is about places, a flat list is about thingsconst twice = [- { ...rows[0], id: 'pr1', key: 'pr1@50,30', kind: 'proof', title: 'Two cities' },- { ...rows[0], id: 'pr1', key: 'pr1@48,2', kind: 'proof', title: 'Two cities' },+ { ...rows[0], id: 'm1', key: 'm1@50,30', kind: 'media', title: 'Two cities' },+ { ...rows[0], id: 'm1', key: 'm1@48,2', kind: 'media', title: 'Two cities' },{ ...rows[1] },];- expect(oneEach(twice).map((r) => r.key ?? r.id)).toEqual(['pr1@50,30', 'bb']);+ expect(oneEach(twice).map((r) => r.key ?? r.id)).toEqual(['m1@50,30', 'bb']);});it('searches title, notes, provider, site and geography', () => {@@ -310,18 +311,6 @@ describe('addressing a row in the tree', () => {});});-describe('a proof of several points', () => {- it('finds a row by the name its point was given', () => {- // three rows under one title: the label is what tells them apart- const rows = [- { id: 'p', kind: 'proof', title: 'Harbour strike', label: 'impact 2', geo: {} },- { id: 'p', kind: 'proof', title: 'Harbour strike', label: 'caméra', geo: {} },- ];- expect(filterSaved(rows, { query: 'caméra' })).toHaveLength(1);- expect(filterSaved(rows, { query: 'harbour' })).toHaveLength(2);- });-});-describe('showing only the folders wanted on the map', () => {const rows = [UA('a', 'Donetsk Oblast', { kind: 'place', folder: 'Bridges' }),diff --git a/frontend/src/lib/guide.js b/frontend/src/lib/guide.jsindex e81a929..0652200 100644--- a/frontend/src/lib/guide.js+++ b/frontend/src/lib/guide.js@@ -216,7 +216,7 @@ export const GUIDE = [},{label: 'Compare keeps the ground fixed',- text: 'Read two locked views side by side, by swipe, opacity or blink. Matched products also get Change assist; notes and shapes stay editable in the saved comparison and appear in its outputs.',+ text: 'Read two locked views side by side, by swipe, opacity or blink. Matched products also get Difference and Detect; notes and shapes stay editable in the saved comparison and appear in its outputs.',},{label: 'Coords & Sky keeps calculations separate',diff --git a/frontend/src/lib/map/analyzers.js b/frontend/src/lib/map/analyzers.jsindex 0725050..2aa9827 100644--- a/frontend/src/lib/map/analyzers.js+++ b/frontend/src/lib/map/analyzers.js@@ -13,11 +13,11 @@ export function marksToZones(marks, previous = []) {}));}+/** Detect reads Sentinel-2 bands, so a map showing anything else has nothing to give it. */export function mapSource(side) {- if (!side || !['esri-wayback', 'sentinel2'].includes(side.provider)) return null;- return { provider: side.provider, date: side.sentinel?.date || '',- release: side.wayback_release ?? null, layer: side.sentinel?.layer || 'TRUE_COLOR',- maxcc: side.sentinel?.maxcc ?? 30 };+ if (side?.provider !== 'sentinel2') return null;+ return { provider: 'sentinel2', date: side.sentinel?.date || '',+ layer: side.sentinel?.layer || 'TRUE_COLOR', maxcc: side.sentinel?.maxcc ?? 30 };}/** Display clustering changes only marker layout; persisted candidates stay intact. */@@ -33,10 +33,62 @@ export function displayGroups(rows, project, radius = 24) {return groups;}+/** A source as a date; runs saved before Detect went Copernicus-only name their release. */export function sourceLabel(source) {- return source.provider === 'sentinel2'- ? `Sentinel-2 · ${source.date} · ${source.layer}`- : `Wayback · release ${source.release}`;+ if (source.provider === 'esri-wayback') return `Wayback release ${source.release}`;+ return source.date || 'no date yet';+}++/**+ * A candidate's reading in words. The catalogue words each method's reading+ * (`METHODS[].measure`), so this only fills the blanks and never needs to know+ * which method it is looking at.+ */+export function describeMeasure(template, measure, index = '') {+ if (!template || !measure) return '';+ const signed = (value) => `${value > 0 ? '+' : value < 0 ? '−' : ''}${Math.abs(Math.round(value))}`;+ const blanks = {+ value: () => Number(measure.value).toFixed(1),+ signed: () => signed(measure.signed),+ before: () => Number(measure.before).toFixed(2),+ after: () => Number(measure.after).toFixed(2),+ index: () => index.toUpperCase(),+ };+ let missing = false;+ const text = template.replace(/\{(\w+)\}/g, (_, name) => {+ const value = name === 'index' ? index : measure[name];+ if (!blanks[name] || value === undefined || value === null) { missing = true; return ''; }+ return blanks[name]();+ });+ return missing ? '' : text;+}++export const STRENGTHS = { weak: 'Weak', clear: 'Clear', strong: 'Strong' };++/** Which of Small, Medium and Large the parameters are, or '' once tuned by hand. */+export function sizeOf(parameters, sizes) {+ for (const [name, values] of Object.entries(sizes ?? {})) {+ if (Object.entries(values).every(([key, value]) => Number(parameters?.[key]) === value)) return name;+ }+ return '';+}++/**+ * What a size preset actually accepts, in ground terms.+ *+ * The buttons read as "how sensitive", which is not what they set: they set the+ * floor and ceiling on a candidate's area. A mark that falls outside the band is+ * dropped after being found, so the band is worth stating rather than implying.+ */+export function sizeBand(values) {+ const min = Number(values?.min_area) || 0;+ const max = Number(values?.max_area) || 0;+ const across = (area) => `${Math.round(Math.sqrt(area))} m`;+ const area = (value) => (value >= 10_000 ? `${Math.round(value / 10_000)} ha` : `${Math.round(value)} m²`);+ if (!min && !max) return 'Any size: nothing is dropped for being too big or too small.';+ if (!min) return `Up to ${area(max)}, about ${across(max)} across.`;+ if (!max) return `From ${area(min)} up, about ${across(min)} across.`;+ return `${area(min)} to ${area(max)}, about ${across(min)} to ${across(max)} across.`;}/** A zone's outline, the way the engine reads it: `Zone.ring()` in JavaScript. */@@ -109,10 +161,9 @@ export function coverage(zones, grid) {*/export const SECONDS_PER_FRAME = 0.35;-/** Frames fetched per tile: the picture reviewed, plus any bands measured. */-export function framesPerTile({ single = false, bands = false } = {}) {- const pictures = single ? 1 : 2;- return bands ? pictures * 2 : pictures;+/** Frames fetched per tile: for each date, the picture reviewed and the bands measured. */+export function framesPerTile({ single = false } = {}) {+ return single ? 2 : 4;}export function readableDuration(seconds) {diff --git a/frontend/src/lib/map/analyzers.test.js b/frontend/src/lib/map/analyzers.test.jsindex c992a56..c2c73e9 100644--- a/frontend/src/lib/map/analyzers.test.js+++ b/frontend/src/lib/map/analyzers.test.js@@ -1,11 +1,15 @@import { describe, expect, it } from 'vitest';import {coverage,+ describeMeasure,displayGroups,framesPerTile,mapSource,readableDuration,marksToZones,+ sizeBand,+ sizeOf,+ sourceLabel,viewZone,zoneMarks,zoneRing,@@ -18,10 +22,14 @@ describe('saved analysis geometry', () => {expect(marksToZones(marks, zones)).toEqual(zones);expect(marksToZones([{ ...marks[0], points: [[2, 2], [3, 2], [3, 3]] }], zones)[0].name).toBe('Port');});- it('restricts sources without silently converting another provider', () => {+ it('takes only Sentinel-2 from the maps, because Detect reads its bands', () => {expect(mapSource({ provider: 'google' })).toBeNull();- expect(mapSource({ provider: 'esri-world-imagery' })).toBeNull();- expect(mapSource({ provider: 'esri-wayback', wayback_release: 123 })).toMatchObject({ release: 123 });+ expect(mapSource({ provider: 'esri-wayback', wayback_release: 123 })).toBeNull();+ expect(mapSource({ provider: 'sentinel2', sentinel: { date: '2026-05-11', layer: 'SWIR', maxcc: 20 } }))+ .toEqual({ provider: 'sentinel2', date: '2026-05-11', layer: 'SWIR', maxcc: 20 });+ expect(sourceLabel({ provider: 'sentinel2', date: '2026-05-11' })).toBe('2026-05-11');+ // runs saved before still say what they read+ expect(sourceLabel({ provider: 'esri-wayback', release: 7 })).toBe('Wayback release 7');});it('changes screen clustering without changing saved detection geometry', () => {const rows = [{ id: 1, coordinates: [1, 1] }, { id: 2, coordinates: [2, 1] }];@@ -52,7 +60,7 @@ describe('what a run will cost before it starts', () => {});it('counts native tiles per grid, and never promises less work than the run', () => {- // Sentinel's 512px level-13 tiles are 4.9 km across; Wayback's are 76 m.+ // Sentinel's 512px level-13 tiles are 4.9 km across; a finer grid counts more.expect(coverage(kmSquare(0.01), [13, 512]).tiles).toBe(1);expect(coverage(kmSquare(0.01), [19, 256]).tiles).toBe(225);// Overlapping areas are the same tiles, counted once.@@ -65,11 +73,9 @@ describe('what a run will cost before it starts', () => {});it('counts the requests a sweep makes, and says how long that is', () => {- expect(framesPerTile({ single: false })).toBe(2);- expect(framesPerTile({ single: true })).toBe(1);- // A band detector fetches the picture reviewed and the bands measured.- expect(framesPerTile({ single: true, bands: true })).toBe(2);- expect(framesPerTile({ single: false, bands: true })).toBe(4);+ // Every date fetches the picture reviewed and the bands measured.+ expect(framesPerTile({ single: true })).toBe(2);+ expect(framesPerTile({ single: false })).toBe(4);expect(readableDuration(20)).toBe('20 s');expect(readableDuration(600)).toBe('10 min');expect(readableDuration(7200)).toBe('2.0 h');@@ -82,3 +88,37 @@ describe('what a run will cost before it starts', () => {expect(zone.id).toMatch(/^[a-z0-9-]{8,48}$/);});});++describe('what a candidate says about itself', () => {+ it('fills the words its method gives with its own reading', () => {+ expect(describeMeasure('{value}× brighter than the water around it', { value: 6.24 }))+ .toBe('6.2× brighter than the water around it');+ expect(describeMeasure('Reflectance {signed}% in every band', { signed: -12.4 }))+ .toBe('Reflectance −12% in every band');+ expect(describeMeasure('{index} {before} → {after}', { before: 0.612, after: 0.104 }, 'nbr'))+ .toBe('NBR 0.61 → 0.10');+ });++ it('says nothing rather than half a sentence', () => {+ expect(describeMeasure('{value}× brighter', undefined)).toBe('');+ expect(describeMeasure('{index} {before} → {after}', { before: 0.5 }, 'ndvi')).toBe('');+ expect(describeMeasure('', { value: 1 })).toBe('');+ });++ it('knows which size a recipe is at, and when it was tuned by hand', () => {+ const sizes = { small: { min_area: 0, cleanup: 0 }, medium: { min_area: 250, cleanup: 0 } };+ expect(sizeOf({ min_area: 250.0, cleanup: 0, sensitivity: 70 }, sizes)).toBe('medium');+ expect(sizeOf({ min_area: 300, cleanup: 0 }, sizes)).toBe('');+ expect(sizeOf({ min_area: 0 }, undefined)).toBe('');+ });++ it('says what a size actually accepts, in ground terms', () => {+ // The buttons read as "how sensitive"; what they set is a floor and a+ // ceiling on area, and a mark outside the band is found and then dropped.+ expect(sizeBand({ min_area: 0, max_area: 800 })).toContain('Up to 800 m²');+ expect(sizeBand({ min_area: 0, max_area: 800 })).toContain('28 m across');+ expect(sizeBand({ min_area: 20_000, max_area: 0 })).toContain('From 2 ha up');+ expect(sizeBand({ min_area: 400, max_area: 8000 })).toContain('400 m² to 8000 m²');+ expect(sizeBand({ min_area: 0, max_area: 0 })).toContain('Any size');+ });+});diff --git a/frontend/src/lib/map/changeAssist.js b/frontend/src/lib/map/changeAssist.jsindex 34ac094..3fa2cc5 100644--- a/frontend/src/lib/map/changeAssist.js+++ b/frontend/src/lib/map/changeAssist.js@@ -1,12 +1,14 @@/**- * What Change assist is allowed to read, and the settings it reads with.+ * What Difference is allowed to read, and the settings it reads with.** A pixel difference is only worth showing when both pictures come from one* rendering chain: a highlighted provider or style difference would otherwise* pass for a change on the ground. `changeCompatibility` answers that before* anything is computed, and grades a fair pair as `matched` (one product, one* render) or `indicative` (one chain, but something the analyst should keep in- * mind). `api/compare.py` refuses the same pairs on save.+ * mind). It also names the `family` behind the pair, which decides two things a+ * picture cannot answer on its own: whether Sentinel-2's sky classification can+ * be fetched for the cloud filter, and whether matching tones is honest.** The detection itself lives in `changeDetect.js` and runs in a worker.*/@@ -20,13 +22,25 @@ export const CHANGE_METHODS = Object.freeze([{ id: 'index', label: 'Spectral index', hint: 'Real Sentinel-2 bands for both dates, fetched on demand.' },]);+// The same six indices Detect measures, so a reading here and a sweep there+// speak of one quantity.export const CHANGE_INDICES = Object.freeze([{ id: 'ndvi', label: 'NDVI', hint: 'Vegetation', gain: 'Greener', loss: 'Vegetation lost' },{ id: 'ndwi', label: 'NDWI', hint: 'Water', gain: 'Wetter', loss: 'Water receded' },+ { id: 'mndwi', label: 'MNDWI', hint: 'Water, past built-up land', gain: 'Wetter', loss: 'Water receded' },{ id: 'nbr', label: 'NBR', hint: 'Burn scars', gain: 'Recovered', loss: 'Burnt' },{ id: 'ndbi', label: 'NDBI', hint: 'Built-up', gain: 'Built or cleared', loss: 'Less built-up' },+ { id: 'bsi', label: 'BSI', hint: 'Bare soil', gain: 'Barer', loss: 'Covered' },]);+// How far an index has to move to count, at the sensitivity either end. The+// published marks sit mid-scale: 0.27 for a burn ratio, 0.25 for vegetation+// lost. Detect scales the same way, so both modes draw one line.+export const INDEX_CHANGE = Object.freeze({ loosest: 0.05, strictest: 0.5 });++export const indexThreshold = (sensitivity) =>+ INDEX_CHANGE.loosest + (INDEX_CHANGE.strictest - INDEX_CHANGE.loosest) * (1 - sensitivity / 100);+export const CHANGE_DISPLAYS = Object.freeze([{ id: 'classes', label: 'Classes' },{ id: 'heat', label: 'Heat' },@@ -73,17 +87,18 @@ export const CHANGE_DEFAULTS = Object.freeze({index: 'ndvi',threshold: 'auto',sensitivity: 55,- normalize: 'histogram',+ normalize: 'auto',smoothing: 1,alignment: 4,cleanup: 1,min_area: 0,ignore_clouds: false,ignore_shadows: false,- // A cloud fades out at its edges and its shadow has no edge at all, so both- // masks stop short of where a reader would put the cloud. Growing them takes+ // A cloud fades out at its edges and its shadow has no edge at all, so the+ // mask stops short of where a reader would put the cloud. Growing it takes// the fringe that otherwise survives as a ring of highlights around the mask.- cloud_margin: 2,+ // In ground metres, because this reading follows the camera.+ cloud_margin: 50,classes: ['gain', 'loss', 'changed'],display: 'classes',palette: 'directional',@@ -91,7 +106,7 @@ export const CHANGE_DEFAULTS = Object.freeze({opacity: 70,base: 'b',visible: true,- live: true,+ blink: false,});const pick = (value, allowed, fallback) => (allowed.includes(value) ? value : fallback);@@ -112,14 +127,14 @@ export function changeSettings(raw = {}) {index: pick(value.index, CHANGE_INDICES.map((entry) => entry.id), CHANGE_DEFAULTS.index),threshold: pick(value.threshold, ['auto', 'manual'], CHANGE_DEFAULTS.threshold),sensitivity: whole(value.sensitivity, 0, 100, CHANGE_DEFAULTS.sensitivity),- normalize: pick(value.normalize, ['none', 'mean', 'histogram'], CHANGE_DEFAULTS.normalize),+ normalize: pick(value.normalize, ['auto', 'none', 'mean', 'histogram'], CHANGE_DEFAULTS.normalize),smoothing: whole(value.smoothing, 0, 4, CHANGE_DEFAULTS.smoothing),alignment: whole(value.alignment, 0, 8, CHANGE_DEFAULTS.alignment),cleanup: whole(value.cleanup, 0, 3, CHANGE_DEFAULTS.cleanup),min_area: Number.isFinite(area) ? Math.min(1_000_000, Math.max(0, area)) : 0,ignore_clouds: value.ignore_clouds ?? CHANGE_DEFAULTS.ignore_clouds,ignore_shadows: value.ignore_shadows ?? CHANGE_DEFAULTS.ignore_shadows,- cloud_margin: whole(value.cloud_margin, 0, 10, CHANGE_DEFAULTS.cloud_margin),+ cloud_margin: whole(value.cloud_margin, 0, 200, CHANGE_DEFAULTS.cloud_margin),classes,display: pick(value.display, CHANGE_DISPLAYS.map((entry) => entry.id), CHANGE_DEFAULTS.display),palette: pick(value.palette, Object.keys(CHANGE_PALETTES), CHANGE_DEFAULTS.palette),@@ -127,7 +142,7 @@ export function changeSettings(raw = {}) {opacity: whole(value.opacity, 0, 100, CHANGE_DEFAULTS.opacity),base: pick(value.base, CHANGE_BASES.map((entry) => entry.id), CHANGE_DEFAULTS.base),visible: value.visible !== false,- live: value.live !== false,+ blink: value.blink === true,};}@@ -141,7 +156,7 @@ function layerReading(side, skipped) {});}-const refuse = (reason) => ({ ok: false, reason, methods: [] });+const refuse = (reason) => ({ ok: false, reason, methods: [], clouds: false });const PIXEL_METHODS = ['colour', 'structure', 'brightness'];const ESRI = new Set(['esri-world-imagery', 'esri-wayback']);@@ -154,7 +169,7 @@ const ESRI = new Set(['esri-world-imagery', 'esri-wayback']);export function changeCompatibility(a, b) {if (!a?.present || !b?.present) return refuse('Add imagery A and B first.');if (a.widget || b.widget) {- return refuse('Change assist needs app-rendered pixels, not a web map widget.');+ return refuse('Difference needs app-rendered pixels, not a web map widget.');}if (a.provider === 'sentinel2' && b.provider === 'sentinel2') {@@ -175,6 +190,10 @@ export function changeCompatibility(a, b) {}return {ok: true,+ family: 'sentinel2',+ // Sentinel-2 carries its own scene classification, so cloud and shadow+ // are read rather than guessed — the one family where the filter is offered.+ clouds: true,grade: notes.length ? 'indicative' : 'matched',label: `Sentinel-2 · ${String(a.sentinel.layer).replace(/_/g, ' ')}`,from: dateA,@@ -196,6 +215,8 @@ export function changeCompatibility(a, b) {const mixed = a.provider !== b.provider;return {ok: true,+ family: 'esri',+ clouds: false,grade: mixed ? 'indicative' : 'matched',label: mixed ? 'Esri World Imagery and Wayback' : 'Esri Wayback',from: releaseA == null ? 'latest' : String(releaseA),@@ -231,6 +252,8 @@ export function changeCompatibility(a, b) {}return {ok: true,+ family: 'viirs',+ clouds: false,grade: 'matched',label: `VIIRS · ${a.nightlights.source === 'noaa20' ? 'NOAA-20' : 'Suomi NPP'}`,from: a.nightlights.day,@@ -240,5 +263,19 @@ export function changeCompatibility(a, b) {};}- return refuse('Change assist reads Sentinel-2 passes, Esri releases or VIIRS night lights.');+ return refuse('Difference reads Sentinel-2 passes, Esri releases or VIIRS night lights.');+}++/**+ * Whether a reading needs Sentinel-2 bands, which are fetched and metered.+ *+ * A spectral index is nothing but bands. The cloud filter over the picture+ * methods needs the scene classification behind them, which is one small frame+ * a side. The reading still follows the camera on the frames already held; what+ * it will not do is spend a request on a pan.+ */+export function changeNeedsFrames(settings, status) {+ if (settings.method === 'index') return 'index';+ const filtered = settings.ignore_clouds || settings.ignore_shadows;+ return status?.clouds && filtered ? 'sky' : '';}diff --git a/frontend/src/lib/map/changeAssist.test.js b/frontend/src/lib/map/changeAssist.test.jsindex 3fbadc1..d057ddd 100644--- a/frontend/src/lib/map/changeAssist.test.js+++ b/frontend/src/lib/map/changeAssist.test.js@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest';-import { CHANGE_DEFAULTS, changeCompatibility, changeSettings } from './changeAssist.js';+import { CHANGE_DEFAULTS, changeCompatibility, changeNeedsFrames, changeSettings } from './changeAssist.js';const side = (patch = {}) => ({present: true,@@ -17,11 +17,15 @@ const sentinel = (date, patch = {}) =>sentinel: { layer: 'TRUE_COLOR', effectiveDate: date, maxcc: 40, ...patch },});-describe('which pairs Change assist reads', () => {+describe('which pairs Difference reads', () => {it('reads two Wayback releases as matched when unrelated layers agree', () => {expect(changeCompatibility(side(), side({ waybackRelease: 2 }))).toMatchObject({ok: true,grade: 'matched',+ family: 'esri',+ // A picture carries no scene classification, so there is no honest cloud+ // filter over it and the switch is not offered.+ clouds: false,methods: ['colour', 'structure', 'brightness'],});expect(@@ -40,6 +44,8 @@ describe('which pairs Change assist reads', () => {expect(changeCompatibility(sentinel('2026-08-01'), sentinel('2026-09-01'))).toMatchObject({ok: true,grade: 'matched',+ family: 'sentinel2',+ clouds: true,methods: ['colour', 'structure', 'brightness', 'index'],});const acrossLayers = changeCompatibility(@@ -77,10 +83,27 @@ describe('which pairs Change assist reads', () => {});});-describe('Change assist settings', () => {+describe('what a reading has to fetch', () => {+ const status = (clouds) => ({ ok: true, clouds, methods: [] });++ it('asks for bands for an index, and for the sky when the cloud filter is on', () => {+ expect(changeNeedsFrames(changeSettings({ method: 'index' }), status(true))).toBe('index');+ expect(changeNeedsFrames(changeSettings({ ignore_clouds: true }), status(true))).toBe('sky');+ expect(changeNeedsFrames(changeSettings({ ignore_shadows: true }), status(true))).toBe('sky');+ });++ it('asks for nothing where a picture is all there is, so the reading stays live', () => {+ expect(changeNeedsFrames(changeSettings({}), status(true))).toBe('');+ expect(changeNeedsFrames(changeSettings({ ignore_clouds: true }), status(false))).toBe('');+ });+});++describe('Difference settings', () => {it('fills a missing or older session with the defaults', () => {expect(changeSettings({})).toEqual({ ...CHANGE_DEFAULTS, classes: ['gain', 'loss', 'changed'] });- expect(changeSettings({ normalize: true, noise: 3 })).toMatchObject({ normalize: 'histogram' });+ expect(changeSettings({ normalize: true, noise: 3 })).toMatchObject({ normalize: 'auto' });+ // a session that chose histogram keeps it; only the default moved+ expect(changeSettings({ normalize: 'histogram' })).toMatchObject({ normalize: 'histogram' });});it('keeps every value inside its range', () => {diff --git a/frontend/src/lib/map/changeCapture.js b/frontend/src/lib/map/changeCapture.jsindex 302d089..f1a83b3 100644--- a/frontend/src/lib/map/changeCapture.js+++ b/frontend/src/lib/map/changeCapture.js@@ -1,26 +1,104 @@-/** Capture-sized change detection, with on-demand spectral frames. */+/**+ * Capture-sized change detection, with Sentinel-2 band frames fetched once and+ * then reused.+ *+ * A band frame is a metered request, so it is asked for by an explicit act —+ * Run, or switching the cloud filter on — and never by a pan. To keep the+ * filter working while the analyst moves around, each frame is fetched with a+ * margin of ground around the view and held: a later reading whose view still+ * falls inside it, at a similar resolution, is served from that copy. A move+ * past the margin, a zoom, or another date leaves the reading waiting for Run+ * rather than quietly spending a request.+ */+import { changeNeedsFrames } from './changeAssist.js';import { runChangeDetection } from './changeRunner.js';import { compose, frameBox, groundPerPixel, imageToMercator, invert, scale, screenToMercator } from './groundFrame.js';-export async function spectralPixels(frame, width, height, side, index) {- const box = frameBox(frame);- const response = await fetch('/api/compare/sentinel-index', {+/** Ground kept around the view, as a share of it on each side. */+const MARGIN = 0.2;+/** What the backend will render, one side at a time. */+const MAX_EDGE = 2048;+/** How far the held copy's resolution may drift from what a reading wants. */+const SCALE_RANGE = [0.6, 2.5];++const held = new Map();++const grow = (box, share) => {+ const width = (box.east - box.west) * share;+ const height = (box.north - box.south) * share;+ return { west: box.west - width, east: box.east + width,+ south: box.south - height, north: box.north + height };+};++const covers = (outer, inner) => outer.west <= inner.west && outer.east >= inner.east+ && outer.south <= inner.south && outer.north >= inner.north;++/** Only for tests and for a case being closed: the held frames are per session. */+export function forgetBandFrames() {+ held.clear();+}++function frameKey(side, product) {+ const sentinel = side?.sentinel ?? {};+ return [product, sentinel.effectiveDate || sentinel.date || '', sentinel.layer ?? '',+ sentinel.maxcc ?? ''].join('|');+}++/**+ * The bytes of one band frame over `box`, from the held copy or from the network.+ *+ * @returns {Promise<{blob: Blob, box: object, width: number, height: number}|null>}+ * null when a fetch was needed and `fetchAllowed` said no.+ */+async function frameBytes(side, product, box, metresPerPixel, fetchAllowed) {+ const key = frameKey(side, product);+ const copy = held.get(key);+ const drift = copy ? copy.metresPerPixel / metresPerPixel : 0;+ if (copy && covers(copy.box, box) && drift >= SCALE_RANGE[0] && drift <= SCALE_RANGE[1]) {+ return copy;+ }+ if (!fetchAllowed) return null;+ const wanted = grow(box, MARGIN);+ const width = Math.min(MAX_EDGE, Math.max(1, Math.round((wanted.east - wanted.west) / metresPerPixel)));+ const height = Math.min(MAX_EDGE, Math.max(1, Math.round((wanted.north - wanted.south) / metresPerPixel)));+ const response = await fetch('/api/compare/sentinel-frame', {method: 'POST',headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ ...box, width, height, day: side.sentinel.effectiveDate || side.sentinel.date,- maxcc: side.sentinel.maxcc, layer: side.sentinel.layer, index }),+ body: JSON.stringify({ ...wanted, width, height, day: side.sentinel.effectiveDate || side.sentinel.date,+ maxcc: side.sentinel.maxcc, layer: side.sentinel.layer, product }),});if (!response.ok) {const body = await response.json().catch(() => ({}));- throw new Error(typeof body.detail === 'string' ? body.detail : `Spectral request failed (${response.status})`);+ throw new Error(typeof body.detail === 'string' ? body.detail : `Band request failed (${response.status})`);}- const bitmap = await createImageBitmap(await response.blob());+ const fetched = { blob: await response.blob(), box: wanted, width, height,+ metresPerPixel: (wanted.east - wanted.west) / width };+ held.set(key, fetched);+ return fetched;+}++/**+ * One Sentinel-2 band frame projected onto the compared view.+ *+ * `product` is a spectral index, or `sky` for the scene classification alone —+ * the cloud filter's answer over the picture methods.+ */+export async function bandFrame(frame, width, height, side, product, fetchAllowed = true) {+ const box = frameBox(frame);+ const metres = groundPerPixel(frame) * frame.width / width;+ const source = await frameBytes(side, product, box, metres, fetchAllowed);+ if (!source) return null;+ // No colour management and no premultiplied alpha: these bytes are a+ // measurement and a scene class, not a picture.+ const bitmap = await createImageBitmap(source.blob,+ { premultiplyAlpha: 'none', colorSpaceConversion: 'none' });try {const canvas = document.createElement('canvas');canvas.width = width;canvas.height = height;const ctx = canvas.getContext('2d');- const matrix = compose(scale(width / frame.width), compose(invert(screenToMercator(frame)), imageToMercator(box, width, height)));+ const matrix = compose(scale(width / frame.width), compose(invert(screenToMercator(frame)),+ imageToMercator(source.box, source.width, source.height)));ctx.imageSmoothingEnabled = false;ctx.setTransform(matrix.a, matrix.b, matrix.c, matrix.d, matrix.e, matrix.f);ctx.drawImage(bitmap, 0, 0);@@ -30,7 +108,14 @@ export async function spectralPixels(frame, width, height, side, index) {}}-export async function detectCaptures(sources, settings, sides) {+/**+ * Read the two captured views.+ *+ * `fetchAllowed` is false for a reading that follows the camera on its own: it+ * then runs on held frames, or reports `needsFetch` so the caller can leave the+ * last reading up and wait for Run.+ */+export async function detectCaptures(sources, settings, sides, status = null, fetchAllowed = true) {const frame = sources.a.frame;const ratio = Math.min(1, 1536 / Math.max(sources.a.canvas.width, sources.a.canvas.height));const width = Math.max(1, Math.round(sources.a.canvas.width * ratio));@@ -43,13 +128,23 @@ export async function detectCaptures(sources, settings, sides) {context.drawImage(source.canvas, 0, 0, width, height);return context.getImageData(0, 0, width, height).data;};- let index = null;- if (settings.method === 'index') {- const [a, b] = await Promise.all(sides.map((side) => spectralPixels(frame, width, height, side, settings.index)));- index = { a, b };+ const needed = changeNeedsFrames(settings, status);+ let frames = null;+ if (needed) {+ const product = needed === 'index' ? settings.index : 'sky';+ const [a, b] = await Promise.all(+ sides.map((side) => bandFrame(frame, width, height, side, product, fetchAllowed)));+ if (!a || !b) return { needsFetch: true };+ frames = { a, b };}const result = await runChangeDetection({ a: pixels(sources.a), b: pixels(sources.b), width, height,- settings, index, metresPerPixel: groundPerPixel(frame) * frame.width / width });+ settings, frames, family: status?.family ?? '',+ ground: {+ lat: frame.lat,+ bearing: frame.bearing ?? 0,+ days: sides.map((side) => side?.sentinel?.effectiveDate || side?.sentinel?.date || ''),+ },+ metresPerPixel: groundPerPixel(frame) * frame.width / width });const canvas = document.createElement('canvas');canvas.width = width;canvas.height = height;diff --git a/frontend/src/lib/map/changeCapture.test.js b/frontend/src/lib/map/changeCapture.test.jsindex c48b016..9c81ade 100644--- a/frontend/src/lib/map/changeCapture.test.js+++ b/frontend/src/lib/map/changeCapture.test.js@@ -6,12 +6,13 @@ const runChangeDetection = vi.fn(async ({ width, height }) => ({pixels: new Uint8ClampedArray(width * height * 4), width, height, counts: {},}));vi.mock('./changeRunner.js', () => ({ runChangeDetection }));-const { detectCaptures, spectralPixels } = await import('./changeCapture.js');+const { detectCaptures, bandFrame, forgetBandFrames } = await import('./changeCapture.js');const frame = { lng: 2.3, lat: 48.8, zoom: 15, bearing: 35, width: 800, height: 600 };const contexts = [];beforeEach(() => {vi.clearAllMocks();+ forgetBandFrames();contexts.length = 0;vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(function () {const context = {@@ -37,32 +38,76 @@ describe('captured change frames', () => {expect(result.canvas.width).toBe(1536);expect(result.canvas.height).toBe(1152);expect(runChangeDetection).toHaveBeenCalledWith(expect.objectContaining({- width: 1536, height: 1152, index: null, metresPerPixel: expect.any(Number),+ width: 1536, height: 1152, frames: null, metresPerPixel: expect.any(Number),+ ground: expect.objectContaining({ lat: frame.lat, bearing: frame.bearing }),}));expect(fetch).not.toHaveBeenCalled();});- it('requests the named pass and projects its index pixels onto a rotated frame', async () => {+ it('requests the named pass with a margin, and projects it onto a rotated frame', async () => {const bitmap = { close: vi.fn() };vi.stubGlobal('createImageBitmap', vi.fn(async () => bitmap));fetch.mockResolvedValue({ ok: true, blob: async () => new Blob() });- const data = await spectralPixels(frame, 80, 60, {- sentinel: { date: '2026-09-01', layer: 'TRUE_COLOR', maxcc: 30 },- }, 'ndvi');+ const side = { sentinel: { date: '2026-09-01', layer: 'TRUE_COLOR', maxcc: 30 } };+ const data = await bandFrame(frame, 80, 60, side, 'ndvi');expect(data.length).toBe(80 * 60 * 4);const [url, request] = fetch.mock.calls[0];- expect(url).toBe('/api/compare/sentinel-index');+ expect(url).toBe('/api/compare/sentinel-frame');expect(request.method).toBe('POST');- expect(JSON.parse(request.body)).toMatchObject({ day: '2026-09-01', index: 'ndvi', maxcc: 30, width: 80, height: 60 });+ const asked = JSON.parse(request.body);+ expect(asked).toMatchObject({ day: '2026-09-01', product: 'ndvi', maxcc: 30 });+ // Ground is kept around the view, at the resolution the reading works at.+ expect(asked.width).toBeGreaterThan(80);+ expect(asked.height).toBeGreaterThan(60);const matrix = contexts[0].setTransform.mock.calls[0];expect(matrix.every(Number.isFinite)).toBe(true);expect(matrix[1]).not.toBe(0);expect(bitmap.close).toHaveBeenCalledOnce();});+ it('serves a pan inside the margin from the frame it holds, and refuses to fetch on its own', async () => {+ vi.stubGlobal('createImageBitmap', vi.fn(async () => ({ close: vi.fn() })));+ fetch.mockResolvedValue({ ok: true, blob: async () => new Blob() });+ const side = { sentinel: { date: '2026-09-01', layer: 'TRUE_COLOR', maxcc: 30 } };+ await bandFrame(frame, 80, 60, side, 'ndvi');+ expect(fetch).toHaveBeenCalledTimes(1);+ // a nudge of the camera: the held frame still reaches, so nothing is spent+ const nudged = { ...frame, lng: frame.lng + 0.0005 };+ expect(await bandFrame(nudged, 80, 60, side, 'ndvi')).not.toBeNull();+ expect(fetch).toHaveBeenCalledTimes(1);+ // a move past the margin, with no leave to fetch: the caller is told, not billed+ const away = { ...frame, lng: frame.lng + 0.2 };+ expect(await bandFrame(away, 80, 60, side, 'ndvi', false)).toBeNull();+ expect(fetch).toHaveBeenCalledTimes(1);+ expect(await bandFrame(away, 80, 60, side, 'ndvi')).not.toBeNull();+ expect(fetch).toHaveBeenCalledTimes(2);+ });++ it('fetches the sky alone when the cloud filter is on over the picture methods', async () => {+ const bitmap = { close: vi.fn() };+ vi.stubGlobal('createImageBitmap', vi.fn(async () => bitmap));+ fetch.mockResolvedValue({ ok: true, blob: async () => new Blob() });+ const capture = { canvas: { width: 400, height: 300 }, frame };+ const sides = [{ sentinel: { date: '2026-08-01' } }, { sentinel: { date: '2026-09-01' } }];+ await detectCaptures({ a: capture, b: capture }, changeSettings({ ignore_clouds: true }), sides,+ { ok: true, clouds: true, family: 'sentinel2' });+ expect(fetch.mock.calls.map(([, request]) => JSON.parse(request.body).product)).toEqual(['sky', 'sky']);+ // A reading that follows the camera may use what is held, never the network.+ forgetBandFrames();+ fetch.mockClear();+ const held = await detectCaptures({ a: capture, b: capture },+ changeSettings({ ignore_clouds: true }), sides, { ok: true, clouds: true, family: 'sentinel2' }, false);+ expect(held).toEqual({ needsFetch: true });+ expect(fetch).not.toHaveBeenCalled();+ expect(runChangeDetection).toHaveBeenCalledWith(expect.objectContaining({+ family: 'sentinel2',+ ground: expect.objectContaining({ days: ['2026-08-01', '2026-09-01'] }),+ }));+ });+it('reports a quota refusal without decoding or computing a mask', async () => {fetch.mockResolvedValue({ ok: false, status: 429, json: async () => ({ detail: 'Sentinel Hub is paused' }) });- await expect(spectralPixels(frame, 80, 60, { sentinel: { date: '2026-09-01' } }, 'ndvi'))+ await expect(bandFrame(frame, 80, 60, { sentinel: { date: '2026-09-01' } }, 'ndvi')).rejects.toThrow('Sentinel Hub is paused');expect(runChangeDetection).not.toHaveBeenCalled();});diff --git a/frontend/src/lib/map/changeDetect.js b/frontend/src/lib/map/changeDetect.jsindex fcf1197..26bef7f 100644--- a/frontend/src/lib/map/changeDetect.js+++ b/frontend/src/lib/map/changeDetect.js@@ -8,10 +8,14 @@* 1. **Register.** A small integer shift that best lays B over A absorbs the* sub-tile offsets two renders can carry.* 2. **Match tone.** B's channels are moved onto A's, by mean or by histogram,- * so a hazier or brighter day is not read as change everywhere.+ * so a hazier or brighter day is not read as change everywhere. Cloud is+ * left out of that estimate, and Sentinel-2 skips it: two L2A passes are+ * already corrected, so matching them can only erase real change.* 3. **Measure.** One signed difference per pixel: perceptual colour distance,* lightness, edge strength, or a real spectral index when both are given.- * 4. **Mask.** Pixels without data, and optionally cloud and shadow, drop out.+ * 4. **Mask.** Pixels without data, and optionally cloud and its shadow, drop+ * out. The sky is read from Sentinel-2's scene classification, exactly as+ * Detect reads it (`skyMask`), never guessed from the picture.* 5. **Threshold.** Otsu's split of the difference histogram, or the analyst's* own level, over a floor that keeps rendering noise out.* 6. **Clean.** A morphological opening removes speckle, a closing fills pinholes.@@ -21,7 +25,7 @@* alpha carries the strength.*/-import { CHANGE_PALETTES, changeSettings } from './changeAssist.js';+import { CHANGE_PALETTES, changeSettings, indexThreshold } from './changeAssist.js';const clamp = (value, min, max) => Math.min(max, Math.max(min, value));@@ -105,8 +109,13 @@ function shifted(right, width, height, offset) {return out;}-/** B's three channels moved onto A's, by their means or by their whole histograms. */-export function matchTone(left, right, mode = 'histogram') {+/**+ * B's three channels moved onto A's, by their means or by their whole histograms.+ *+ * `keep` leaves cloud out of the estimate: a third of a scene under cumulus+ * would otherwise drag the whole ground of the other date after it.+ */+export function matchTone(left, right, mode = 'histogram', keep = null) {if (mode !== 'mean' && mode !== 'histogram') return right;const out = new Uint8ClampedArray(right);for (let channel = 0; channel < 3; channel += 1) {@@ -115,6 +124,7 @@ export function matchTone(left, right, mode = 'histogram') {let count = 0;for (let index = 0; index < left.length; index += 4) {if (left[index + 3] < 200 || right[index + 3] < 200) continue;+ if (keep && !keep[index / 4]) continue;histA[left[index + channel]] += 1;histB[right[index + channel]] += 1;count += 1;@@ -169,33 +179,213 @@ function sobel(lightness, width, height) {return out;}-/** Decode an index frame (`engine/sentinel.py`): R = index, G = scene class, A = data. */-export function decodeIndex(pixels) {+/**+ * Decode a Difference frame (`engine/sentinel.py`): R = index, G = the sky byte+ * Detect's products carry (scene class in the low four bits, a dark flag above+ * it), A = the data mask. `change-sky` frames carry the sky alone.+ */+export function decodeFrame(pixels) {const count = pixels.length / 4;const value = new Float32Array(count);const scene = new Uint8Array(count);+ const dark = new Uint8Array(count);const valid = new Uint8Array(count);for (let pixel = 0; pixel < count; pixel += 1) {const index = pixel * 4;value[pixel] = pixels[index] / 127.5 - 1;- scene[pixel] = pixels[index + 1];+ scene[pixel] = pixels[index + 1] & 15;+ dark[pixel] = (pixels[index + 1] & 16) > 0 ? 1 : 0;valid[pixel] = pixels[index + 3] > 127 ? 1 : 0;}- return { value, scene, valid };+ return { value, scene, dark, valid };+}++// Sentinel-2 L2A scene classes, and what Detect made of them on real scenes+// (`engine/analyzers.py` holds the same constants and the same reasoning).+const SCL_DEFECTIVE = 1;+const SCL_SHADOW = 3;+const SCL_WATER = 6;+const SCL_SNOW = 11;+const CLOUD_CORE = [8, 9, 10];+// "Unclassified or low-probability cloud": too timid to trust alone, but next+// to a real cloud it is that cloud's thin edge.+const CLOUD_EDGE = [7, 8, 9, 10];+// Sen2Cor calls white hulls and bright roofs cloud; no cumulus is under 5 ha.+const MIN_CLOUD_M2 = 50_000;+// A shadow sits under its cloud's outline, moved away from the sun by the+// cloud's height times the tangent of the sun's zenith.+const CLOUD_HEIGHTS = [200, 5000];+const MAX_SHADOW_M = 4000;+const MAX_MARGIN_PX = 60;++/** Connected regions (8-way) of a flag array, with each one's pixel count. */+export function label(flags, width, height) {+ const labels = new Int32Array(flags.length);+ const sizes = [0];+ const stack = [];+ for (let start = 0; start < flags.length; start += 1) {+ if (!flags[start] || labels[start]) continue;+ const id = sizes.length;+ let size = 0;+ labels[start] = id;+ stack.push(start);+ while (stack.length) {+ const pixel = stack.pop();+ size += 1;+ const x = pixel % width;+ const y = (pixel - x) / width;+ for (let dy = -1; dy <= 1; dy += 1) {+ const ny = y + dy;+ if (ny < 0 || ny >= height) continue;+ for (let dx = -1; dx <= 1; dx += 1) {+ const nx = x + dx;+ if (nx < 0 || nx >= width) continue;+ const near = ny * width + nx;+ if (flags[near] && !labels[near]) {+ labels[near] = id;+ stack.push(near);+ }+ }+ }+ }+ sizes.push(size);+ }+ return { labels, sizes };+}++/** Solar azimuth and zenith in degrees when Sentinel-2 flies over, from `analyzers.py`. */+export function sunPosition(day, lat) {+ const local = 10.5 + lat / 72;+ const when = new Date(`${day}T00:00:00Z`);+ const start = Date.UTC(when.getUTCFullYear(), 0, 1);+ const yearDay = Math.floor((when.getTime() - start) / 86_400_000);+ const g = ((2 * Math.PI) / 365) * (yearDay + (local - 12) / 24);+ const declination = 0.006918 - 0.399912 * Math.cos(g) + 0.070257 * Math.sin(g)+ - 0.006758 * Math.cos(2 * g) + 0.000907 * Math.sin(2 * g)+ - 0.002697 * Math.cos(3 * g) + 0.00148 * Math.sin(3 * g);+ const minutes = 229.18 * (0.000075 + 0.001868 * Math.cos(g) - 0.032077 * Math.sin(g)+ - 0.014615 * Math.cos(2 * g) - 0.040849 * Math.sin(2 * g));+ const hour = (((local * 60 + minutes) / 4 - 180) * Math.PI) / 180;+ const phi = (lat * Math.PI) / 180;+ const cosine = Math.sin(phi) * Math.sin(declination)+ + Math.cos(phi) * Math.cos(declination) * Math.cos(hour);+ const zenith = (Math.acos(Math.max(-1, Math.min(1, cosine))) * 180) / Math.PI;+ const azimuth = (Math.atan2(+ Math.sin(hour),+ Math.cos(hour) * Math.sin(phi) - Math.tan(declination) * Math.cos(phi),+ ) * 180) / Math.PI + 180;+ return { azimuth: ((azimuth % 360) + 360) % 360, zenith };+}++/** The mask moved by (dx, dy) × distance, leaving empty where it came from off-frame. */+function shift(mask, width, height, dx, dy) {+ const out = new Uint8Array(mask.length);+ const ox = Math.round(dx);+ const oy = Math.round(dy);+ if (!ox && !oy) return mask.slice();+ for (let y = 0; y < height; y += 1) {+ const sy = y - oy;+ if (sy < 0 || sy >= height) continue;+ for (let x = 0; x < width; x += 1) {+ const sx = x - ox;+ if (sx < 0 || sx >= width) continue;+ if (mask[sy * width + sx]) out[y * width + x] = 1;+ }+ }+ return out;+}++/**+ * The mask laid down at every distance from `start` to `start + length` along+ * (dx, dy). Doubling: each pass ORs what is covered with itself moved by as+ * much again, so a reach of 400 pixels costs nine shifts rather than 400.+ */+export function smear(mask, width, height, dx, dy, start, length) {+ if (length <= 0) return new Uint8Array(mask.length);+ let covered = shift(mask, width, height, dx * start, dy * start);+ let span = 1;+ while (span < length) {+ const step = Math.min(span, length - span);+ const moved = shift(covered, width, height, dx * step, dy * step);+ for (let pixel = 0; pixel < covered.length; pixel += 1) {+ if (moved[pixel]) covered[pixel] = 1;+ }+ span += step;+ }+ return covered;}-// Sentinel-2 L2A scene classes: 3 cloud shadow, 8–10 cloud and cirrus, 11 snow.-const SHADOW_CLASSES = new Set([3]);-const CLOUD_CLASSES = new Set([8, 9, 10]);+/**+ * Cloud and cloud shadow in one Sentinel-2 frame, as Detect reads them.+ *+ * Cloud starts from the classification's cloud classes, drops what is too small+ * to be one, and takes every unsure pixel touching what is left. Shadow is the+ * classified shadow plus the cloud's outline cast away from the sun, wherever+ * the ground under it is dark and not water — and dark water is only water when+ * the other date says so too, because Sen2Cor reads a deep shadow as water.+ *+ * @param {ReturnType<typeof decodeFrame>} frame+ * @param {ReturnType<typeof decodeFrame>|null} other the pass on the other side+ * @param {{width: number, height: number, metresPerPixel: number, lat: number,+ * bearing: number, day: string}} ground+ */+export function skyMask(frame, other, ground) {+ const { width, height, metresPerPixel, lat, bearing, day } = ground;+ const count = width * height;+ const core = new Uint8Array(count);+ const edge = new Uint8Array(count);+ for (let pixel = 0; pixel < count; pixel += 1) {+ if (!frame.valid[pixel]) continue;+ if (CLOUD_CORE.includes(frame.scene[pixel])) core[pixel] = 1;+ if (CLOUD_EDGE.includes(frame.scene[pixel])) edge[pixel] = 1;+ }+ const area = metresPerPixel > 0 ? metresPerPixel * metresPerPixel : 0;+ const cores = label(core, width, height);+ const seeded = new Uint8Array(count);+ for (let pixel = 0; pixel < count; pixel += 1) {+ const id = cores.labels[pixel];+ if (id && (!area || cores.sizes[id] * area >= MIN_CLOUD_M2)) seeded[pixel] = 1;+ }+ const edges = label(edge, width, height);+ const grown = new Uint8Array(edges.sizes.length);+ for (let pixel = 0; pixel < count; pixel += 1) {+ if (seeded[pixel]) grown[edges.labels[pixel]] = 1;+ }+ const cloud = new Uint8Array(count);+ const shadow = new Uint8Array(count);+ let clouded = false;+ for (let pixel = 0; pixel < count; pixel += 1) {+ const scene = frame.scene[pixel];+ if ((edges.labels[pixel] && grown[edges.labels[pixel]])+ || scene === SCL_DEFECTIVE || scene === SCL_SNOW) {+ cloud[pixel] = 1;+ clouded = true;+ }+ if (scene === SCL_SHADOW) shadow[pixel] = 1;+ }+ if (!clouded || !metresPerPixel || !day) return { cloud, shadow };+ const { azimuth, zenith } = sunPosition(day, lat);+ const tangent = Math.tan((zenith * Math.PI) / 180);+ const start = Math.round((CLOUD_HEIGHTS[0] * tangent) / metresPerPixel);+ const length = Math.round(+ Math.min(CLOUD_HEIGHTS[1] * tangent, MAX_SHADOW_M) / metresPerPixel,+ ) - start;+ // The map may be turned, so the sun's compass angle is read in screen terms;+ // rows then run away from the top of the view rather than north.+ const turned = ((azimuth - (bearing || 0)) * Math.PI) / 180;+ const cast = smear(cloud, width, height, -Math.sin(turned), Math.cos(turned), start, length);+ for (let pixel = 0; pixel < count; pixel += 1) {+ if (!cast[pixel] || cloud[pixel] || !frame.dark[pixel]) continue;+ const water = frame.scene[pixel] === SCL_WATER+ && (!other || other.scene[pixel] === SCL_WATER);+ if (!water) shadow[pixel] = 1;+ }+ return { cloud, shadow };+}/*** Grow a flag array by `radius`, separably: a horizontal pass then a vertical* one, which is the same result as a square dilation for a fraction of the work.- *- * Both cloud masks stop short of where a reader would put the cloud's edge —- * a classification calls the soft rim ground, and a brightness test loses the- * rim where it fades. That rim is where the ring of highlights around every- * mask comes from, so the mask is grown rather than trusted as drawn.*/export function growMask(flags, width, height, radius) {if (!radius) return flags;@@ -221,38 +411,50 @@ export function growMask(flags, width, height, radius) {return grown;}+/** Cloud and shadow on either date, as the settings ask for them, grown by the margin. */+export function weatherMask(frames, ground, settings) {+ const count = ground.width * ground.height;+ const blocked = new Uint8Array(count);+ if (!frames || !(settings.ignore_clouds || settings.ignore_shadows)) return blocked;+ const sides = [frames.a, frames.b];+ sides.forEach((frame, side) => {+ const other = sides[1 - side] ?? null;+ const { cloud, shadow } = skyMask(frame, other, { ...ground, day: ground.days[side] });+ for (let pixel = 0; pixel < count; pixel += 1) {+ if ((settings.ignore_clouds && cloud[pixel]) || (settings.ignore_shadows && shadow[pixel])) {+ blocked[pixel] = 1;+ }+ }+ });+ const radius = Math.min(+ MAX_MARGIN_PX,+ Math.round(settings.cloud_margin / Math.max(ground.metresPerPixel, 0.01)),+ );+ return growMask(blocked, ground.width, ground.height, radius);+}+/*** One signed difference per pixel and the pixels it is valid for.* `magnitude` is on a 0…255 scale for every method, so one threshold rule fits.+ *+ * @param {Uint8ClampedArray} left picture A+ * @param {Uint8ClampedArray} right picture B, registered and toned+ * @param {{a: object, b: object}|null} frames decoded band frames, for the index+ * @param {Uint8Array|null} blocked cloud and shadow, already grown by the margin*/-export function measure(left, right, width, height, settings, index = null) {+export function measure(left, right, width, height, settings, frames = null, blocked = null) {const count = width * height;const magnitude = new Float32Array(count);const direction = new Int8Array(count);const chroma = new Uint8Array(count);const valid = new Uint8Array(count);- const masking = settings.ignore_clouds || settings.ignore_shadows;-- if (settings.method === 'index' && index) {- const a = decodeIndex(index.a);- const b = decodeIndex(index.b);- // Cloud on either date invalidates the pixel: a difference is a measurement- // only when both sides of it are ground.- let blocked = new Uint8Array(count);- if (masking) {- for (let pixel = 0; pixel < count; pixel += 1) {- const clouded = CLOUD_CLASSES.has(a.scene[pixel]) || CLOUD_CLASSES.has(b.scene[pixel]);- const shaded = SHADOW_CLASSES.has(a.scene[pixel]) || SHADOW_CLASSES.has(b.scene[pixel]);- if ((settings.ignore_clouds && clouded) || (settings.ignore_shadows && shaded)) {- blocked[pixel] = 1;- }- }- blocked = growMask(blocked, width, height, settings.cloud_margin);- }+ if (settings.method === 'index' && frames) {for (let pixel = 0; pixel < count; pixel += 1) {- if (!a.valid[pixel] || !b.valid[pixel] || blocked[pixel]) continue;- const delta = b.value[pixel] - a.value[pixel];+ // Cloud on either date invalidates the pixel: a difference is a+ // measurement only when both sides of it are ground.+ if (!frames.a.valid[pixel] || !frames.b.valid[pixel] || blocked?.[pixel]) continue;+ const delta = frames.b.value[pixel] - frames.a.value[pixel];valid[pixel] = 1;// a full index swing of 1.0 reads as 255magnitude[pixel] = Math.min(255, Math.abs(delta) * 255);@@ -267,13 +469,6 @@ export function measure(left, right, width, height, settings, index = null) {const labB = new Float32Array(count * 2);const labOfA = [0, 0, 0];const labOfB = [0, 0, 0];- // Cloud reads as near-white with no colour, shadow as near-black. There is no- // scene classification behind a rendered picture, so this is a guess — it is- // offered as an option, and the panel says as much, for exactly that reason.- const cloudy = (lab) => lab[0] > 86 && Math.hypot(lab[1], lab[2]) < 12;- const shaded = (lab) => lab[0] < 10;- let blocked = new Uint8Array(count);- const inFrame = new Uint8Array(count);for (let pixel = 0; pixel < count; pixel += 1) {const i = pixel * 4;if (left[i + 3] < 200 || right[i + 3] < 200) continue;@@ -285,13 +480,7 @@ export function measure(left, right, width, height, settings, index = null) {labA[pixel * 2 + 1] = labOfA[2];labB[pixel * 2] = labOfB[1];labB[pixel * 2 + 1] = labOfB[2];- inFrame[pixel] = 1;- if (settings.ignore_clouds && (cloudy(labOfA) || cloudy(labOfB))) blocked[pixel] = 1;- else if (settings.ignore_shadows && (shaded(labOfA) || shaded(labOfB))) blocked[pixel] = 1;- }- if (masking) blocked = growMask(blocked, width, height, settings.cloud_margin);- for (let pixel = 0; pixel < count; pixel += 1) {- if (inFrame[pixel] && !blocked[pixel]) valid[pixel] = 1;+ if (!blocked?.[pixel]) valid[pixel] = 1;}if (settings.method === 'structure') {@@ -407,9 +596,13 @@ export function otsu(field, valid) {}/** The level below which nothing counts: what a re-render of the same pixels leaves. */-const FLOORS = { colour: 18, brightness: 16, structure: 22, index: 38 };+const FLOORS = { colour: 18, brightness: 16, structure: 22 };export function thresholdFor(field, valid, settings) {+ // An index is a measured quantity, so its line is a stated index change and+ // not a split of whatever this view happens to hold: the same line Detect+ // draws, so panning cannot move it.+ if (settings.method === 'index') return indexThreshold(settings.sensitivity) * 255;const floor = FLOORS[settings.method] ?? 18;const lean = (settings.sensitivity - 50) / 50; // -1 … 1if (settings.threshold === 'manual') {@@ -458,12 +651,16 @@ export function cleanMask(mask, width, height, radius) {// -- zones ------------------------------------------------------------------------+/** How far past its line a zone got, in the words Detect uses for a candidate. */+export const strengthOf = (margin) => (margin >= 3 ? 'strong' : margin >= 1.5 ? 'clear' : 'weak');+/**- * Connected regions of the mask, each with its extent, its area on the ground- * and its dominant direction. Returned in frame fractions so a caller can place- * them on whichever map they belong to.+ * Connected regions of the mask, each with its extent, its area on the ground,+ * its dominant direction and how far past the threshold it got. Returned in+ * frame fractions so a caller can place them on whichever map they belong to.*/-export function findZones(mask, classes, strength, width, height, metresPerPixel, minimumArea = 0) {+export function findZones(mask, classes, strength, width, height, metresPerPixel,+ minimumArea = 0, threshold = 0) {const labels = new Int32Array(mask.length);const zones = [];const stack = [];@@ -520,13 +717,17 @@ export function findZones(mask, classes, strength, width, height, metresPerPixelconst kind = zone.gain >= zone.loss && zone.gain >= zone.changed? 'gain': zone.loss >= zone.changed ? 'loss' : 'changed';- const intensity = zone.strength / zone.pixels / 255;+ const average = zone.strength / zone.pixels;+ const intensity = average / 255;+ const margin = threshold > 0 ? average / threshold : 0;out.push({id: zone.id,kind,pixels: zone.pixels,area,intensity: Math.round(intensity * 100) / 100,+ margin: Math.round(margin * 100) / 100,+ strength: strengthOf(margin),score: zone.pixels * intensity,box: {x1: zone.minX / width,@@ -572,14 +773,19 @@ const CLASS_CODE = { gain: 1, loss: 2, changed: 3 };* @param {number} input.height* @param {object} input.settings see `changeSettings`* @param {number} [input.metresPerPixel] ground size of one working pixel- * @param {{a: Uint8ClampedArray, b: Uint8ClampedArray}} [input.index] index frames+ * @param {{a: Uint8ClampedArray, b: Uint8ClampedArray}} [input.frames] band frames+ * @param {{lat: number, bearing: number, days: string[]}} [input.ground] where and when+ * @param {string} [input.family] sentinel2, esri or viirs*/-export function detectChange({ a, b, width, height, settings: raw, metresPerPixel = 0, index = null }) {+export function detectChange({+ a, b, width, height, settings: raw, metresPerPixel = 0, frames = null,+ ground = null, family = '',+}) {if (!a || !b || a.length !== b.length || a.length !== width * height * 4) {throw new Error('change frames must have the same pixel geometry');}const settings = changeSettings(raw);- if (settings.method === 'index' && (!index?.a || !index?.b)) {+ if (settings.method === 'index' && (!frames?.a || !frames?.b)) {throw new Error('the spectral index frames are missing');}const count = width * height;@@ -588,8 +794,22 @@ export function detectChange({ a, b, width, height, settings: raw, metresPerPixe? estimateAlignment(a, b, width, height, settings.alignment): { x: 0, y: 0, score: 0 };const registered = usesPixels ? shifted(b, width, height, offset) : b;- const toned = usesPixels ? matchTone(a, registered, settings.normalize) : registered;- const measured = measure(a, toned, width, height, settings, index);+ const decoded = frames?.a && frames?.b+ ? { a: decodeFrame(frames.a), b: decodeFrame(shifted(frames.b, width, height, offset)) }+ : null;+ const place = { width, height, metresPerPixel, lat: ground?.lat ?? 0,+ bearing: ground?.bearing ?? 0, days: ground?.days ?? ['', ''] };+ const blocked = decoded ? weatherMask(decoded, place, settings) : null;+ // Two Sentinel-2 passes are already corrected to surface reflectance and+ // rendered by one formula, so there is no exposure left to match — only real+ // change, which a match would eat: a burn over most of a view moves the+ // histogram, and matching it puts the view back the way it was.+ const tone = settings.normalize !== 'auto'+ ? settings.normalize+ : (family === 'sentinel2' ? 'none' : 'histogram');+ const keep = blocked ? blocked.map((flag) => (flag ? 0 : 1)) : null;+ const toned = usesPixels ? matchTone(a, registered, tone, keep) : registered;+ const measured = measure(a, toned, width, height, settings, decoded, blocked);const field = boxBlur(measured.magnitude, width, height, settings.smoothing, measured.valid);const threshold = thresholdFor(field, measured.valid, settings);@@ -617,7 +837,7 @@ export function detectChange({ a, b, width, height, settings: raw, metresPerPixe}const { zones, labels, kept } = findZones(- mask, classes, field, width, height, metresPerPixel, settings.min_area+ mask, classes, field, width, height, metresPerPixel, settings.min_area, threshold);const palette = CHANGE_PALETTES[settings.palette] ?? CHANGE_PALETTES.directional;diff --git a/frontend/src/lib/map/changeDetect.test.js b/frontend/src/lib/map/changeDetect.test.jsindex 4608e8c..aa377f9 100644--- a/frontend/src/lib/map/changeDetect.test.js+++ b/frontend/src/lib/map/changeDetect.test.js@@ -2,12 +2,14 @@ import { describe, expect, it } from 'vitest';import {boxBlur,cleanMask,- decodeIndex,+ decodeFrame,detectChange,estimateAlignment,findZones,matchTone,otsu,+ skyMask,+ sunPosition,toLab,} from './changeDetect.js';@@ -94,6 +96,17 @@ describe('thresholds and filters', () => {});describe('zones', () => {+ it('says how far past the line each zone got, in the words Detect uses', () => {+ const mask = new Uint8Array(36);+ const classes = new Uint8Array(36);+ const strength = new Float32Array(36);+ for (const pixel of [7, 8, 13, 14]) { mask[pixel] = 1; classes[pixel] = 1; strength[pixel] = 200; }+ for (const pixel of [22, 23, 28, 29]) { mask[pixel] = 1; classes[pixel] = 2; strength[pixel] = 60; }+ const { zones } = findZones(mask, classes, strength, 6, 6, 10, 0, 50);+ expect(zones.map((zone) => zone.strength)).toEqual(['strong', 'weak']);+ expect(zones[0].margin).toBe(4);+ });+it('groups connected pixels with their area on the ground and dominant direction', () => {const width = 10;const mask = new Uint8Array(100);@@ -174,69 +187,118 @@ describe('detecting change', () => {expect(result.pixels[(20 * 40 + 20) * 4 + 3]).toBe(0);});- /** Index frames with a cloud class from column `cloudFrom` rightwards. */- const indexFrame = (width, value, cloudFrom = 99) => {- const pixels = new Uint8ClampedArray(width * width * 4);- for (let pixel = 0; pixel < width * width; pixel += 1) {+ /** A band frame: R the index, G the sky byte, A the data mask. */+ const bandFrame = (width, height, at) => {+ const pixels = new Uint8ClampedArray(width * height * 4);+ for (let pixel = 0; pixel < width * height; pixel += 1) {const x = pixel % width;- pixels.set([Math.round((value(x) + 1) * 127.5), x >= cloudFrom ? 9 : 4, 0, 255], pixel * 4);+ const y = (pixel - x) / width;+ const { value = 0, scene = 4, dark = false, data = true } = at(x, y) ?? {};+ pixels.set([Math.round((value + 1) * 127.5), scene + (dark ? 16 : 0), 0, data ? 255 : 0], pixel * 4);}return pixels;};+ /** Index frames with a cloud class from column `cloudFrom` rightwards. */+ const indexFrame = (width, value, cloudFrom = 99) =>+ bandFrame(width, width, (x) => ({ value: value(x), scene: x >= cloudFrom ? 9 : 4 }));+it('reads a real spectral index, masking clouded pixels', () => {- const width = 20;+ const width = 40;const before = indexFrame(width, () => 0.7);- const after = indexFrame(width, (x) => (x < 10 ? 0.7 : -0.1), 16);+ const after = indexFrame(width, (x) => (x < 20 ? 0.7 : -0.1), 32);const blank = new Uint8ClampedArray(width * width * 4);const result = detectChange({- a: blank, b: blank, width, height: width,+ a: blank, b: blank, width, height: width, metresPerPixel: 20,settings: settings({ method: 'index', ignore_clouds: true, cloud_margin: 0 }),- index: { a: before, b: after },+ frames: { a: before, b: after },});- expect(result.counts.lost).toBe(6 * width);- expect(result.coverage).toBeCloseTo(16 / 20);- expect(decodeIndex(after).value[0]).toBeCloseTo(0.7, 1);+ expect(result.counts.lost).toBe(12 * width);+ expect(result.coverage).toBeCloseTo(32 / 40);+ expect(decodeFrame(after).value[0]).toBeCloseTo(0.7, 1);expect(() => detectChange({a: blank, b: blank, width, height: width, settings: settings({ method: 'index' }),})).toThrow('index frames');});- it('grows the cloud mask by the margin, taking the edge it left behind', () => {+ it('measures an index against a stated change, not against this view', () => {+ // Detect draws the same line, so a sweep and a reading agree, and panning+ // cannot move it the way a split of the view's own histogram would.+ const width = 40;+ const before = indexFrame(width, () => 0.6);+ const after = indexFrame(width, (x) => (x < 20 ? 0.45 : 0.1));+ const blank = new Uint8ClampedArray(width * width * 4);+ const read = (sensitivity) => detectChange({+ a: blank, b: blank, width, height: width, metresPerPixel: 20,+ settings: settings({ method: 'index', sensitivity }), frames: { a: before, b: after },+ });+ // 0.25 at the default: the 0.15 side is left alone, the 0.5 side is not+ expect(read(55).counts.lost).toBe(20 * width);+ expect(read(95).counts.lost).toBe(40 * width);+ });++ it('grows the cloud mask by a margin in ground metres', () => {// A classification calls a cloud's soft rim ground, and that rim is where// the ring of highlights around every mask comes from.- const width = 20;+ const width = 40;const before = indexFrame(width, () => 0.7);- const after = indexFrame(width, (x) => (x < 10 ? 0.7 : -0.1), 16);+ const after = indexFrame(width, (x) => (x < 20 ? 0.7 : -0.1), 32);const blank = new Uint8ClampedArray(width * width * 4);const read = (cloud_margin) => detectChange({- a: blank, b: blank, width, height: width,+ a: blank, b: blank, width, height: width, metresPerPixel: 20,settings: settings({ method: 'index', ignore_clouds: true, cloud_margin }),- index: { a: before, b: after },+ frames: { a: before, b: after },});- // columns 10…15 changed and 16… are cloud; a 2px margin eats 14 and 15 too- expect(read(2).counts.lost).toBe(4 * width);- expect(read(2).coverage).toBeCloseTo(14 / 20);+ // columns 20…31 changed and 32… are cloud; 40 m of margin eats 30 and 31 too+ expect(read(40).counts.lost).toBe(10 * width);+ expect(read(40).coverage).toBeCloseTo(30 / 40);// and the margin only ever costs what it says: off, the edge is exact- expect(read(0).counts.lost).toBe(6 * width);+ expect(read(0).counts.lost).toBe(12 * width);});it('leaves every pixel alone when nothing is being masked', () => {// The margin must not eat anything on its own: it grows a mask, and with// both switches off there is no mask to grow.- const width = 20;+ const width = 40;const before = indexFrame(width, () => 0.7);- const after = indexFrame(width, (x) => (x < 10 ? 0.7 : -0.1), 16);+ const after = indexFrame(width, (x) => (x < 20 ? 0.7 : -0.1), 32);const blank = new Uint8ClampedArray(width * width * 4);const result = detectChange({- a: blank, b: blank, width, height: width,- settings: settings({ method: 'index', cloud_margin: 4 }),- index: { a: before, b: after },+ a: blank, b: blank, width, height: width, metresPerPixel: 20,+ settings: settings({ method: 'index', cloud_margin: 80 }),+ frames: { a: before, b: after },});- expect(result.counts.lost).toBe(10 * width);+ expect(result.counts.lost).toBe(20 * width);expect(result.coverage).toBeCloseTo(1);});+ it('keeps cloud out of the tone match, and skips it on Sentinel-2 altogether', () => {+ // A third of the view under cumulus would otherwise drag the ground of the+ // other date after it; and two corrected passes have nothing to match.+ const width = 40;+ const a = frame(width, width, [90, 100, 80]);+ const b = frame(width, width, [90, 100, 80]).paint(0, 0, 14, width, [245, 245, 245]);+ const clear = bandFrame(width, width, () => ({}));+ const clouded = bandFrame(width, width, (x) => ({ scene: x < 14 ? 9 : 4 }));+ const read = (patch, family) => detectChange({+ a: a.pixels, b: b.pixels, width, height: width, metresPerPixel: 20, family,+ frames: { a: clear, b: clouded },+ settings: settings({ ignore_clouds: true, cloud_margin: 0, ...patch }),+ });+ // masked cloud and a matched histogram: the ground under it must stay quiet+ expect(read({ normalize: 'histogram' }, 'esri').share).toBe(0);+ expect(read({ normalize: 'auto' }, 'esri').settings.normalize).toBe('auto');+ expect(read({ normalize: 'auto' }, 'sentinel2').share).toBe(0);+ // a burn covering most of a view is real change, and matching would eat it+ const dark = frame(width, width, [40, 42, 34]);+ const burnt = detectChange({ a: a.pixels, b: dark.pixels, width, height: width,+ settings: settings({ normalize: 'auto' }), family: 'sentinel2' });+ const matched = detectChange({ a: a.pixels, b: dark.pixels, width, height: width,+ settings: settings({ normalize: 'auto' }), family: 'esri' });+ expect(burnt.share).toBeGreaterThan(0.9);+ expect(matched.share).toBe(0);+ });+it('draws outlines and a heat ramp from the same zones', () => {const a = frame(30, 30);const b = frame(30, 30).paint(5, 5, 20, 20, [240, 240, 240]);@@ -253,3 +315,73 @@ describe('detecting change', () => {})).toThrow('same pixel geometry');});});++describe('the sky over a Sentinel-2 pair', () => {+ const sky = (width, height, at) => {+ const pixels = new Uint8ClampedArray(width * height * 4);+ for (let pixel = 0; pixel < width * height; pixel += 1) {+ const x = pixel % width;+ const y = (pixel - x) / width;+ const { scene = 4, dark = false } = at(x, y) ?? {};+ pixels.set([0, scene + (dark ? 16 : 0), 0, 255], pixel * 4);+ }+ return decodeFrame(pixels);+ };+ const ground = (patch = {}) => ({+ width: 60, height: 60, metresPerPixel: 20, lat: 48, bearing: 0, day: '2026-06-21', ...patch,+ });+ const inside = (mask, x, y, width = 60) => Boolean(mask[y * width + x]);++ it('ignores a classified cloud too small to be one, and takes the veil around a real one', () => {+ // Sen2Cor calls white hulls and bright roofs cloud; no cumulus is under 5 ha.+ const frame = sky(60, 60, (x, y) => {+ if (x >= 4 && x < 8 && y >= 4 && y < 8) return { scene: 9 }; // 0.6 ha: a roof+ if (x >= 20 && x < 40 && y >= 20 && y < 40) return { scene: 9 }; // 16 ha: a cloud+ if (x >= 18 && x < 20 && y >= 20 && y < 40) return { scene: 7 }; // its veil+ if (x >= 50 && x < 54 && y >= 4 && y < 8) return { scene: 7 }; // unsure, alone+ return {};+ });+ const { cloud } = skyMask(frame, null, ground());+ expect(inside(cloud, 6, 6)).toBe(false);+ expect(inside(cloud, 30, 30)).toBe(true);+ expect(inside(cloud, 19, 30)).toBe(true);+ expect(inside(cloud, 52, 6)).toBe(false);+ });++ it('casts a cloud away from the sun, onto dark ground only, and turns with the map', () => {+ const { azimuth } = sunPosition('2026-06-21', 48);+ expect(azimuth).toBeGreaterThan(120); // late morning at 48°N: the sun is south-east+ expect(azimuth).toBeLessThan(200);+ const frame = sky(60, 60, (x, y) => {+ if (x >= 24 && x < 36 && y >= 34 && y < 46) return { scene: 9 };+ if (y < 34 && x >= 24) return { dark: true }; // dark ground north of the cloud+ if (y >= 34 && x < 24) return { dark: true }; // and dark ground west of it+ return {};+ });+ const north = skyMask(frame, null, ground()).shadow;+ expect(inside(north, 30, 28)).toBe(true);+ expect(inside(north, 30, 52)).toBe(false); // never towards the sun+ expect(inside(north, 16, 44)).toBe(false);+ // Turned so that east is up, the same cast lands on the ground that is west.+ const turned = skyMask(frame, null, ground({ bearing: 90 })).shadow;+ expect(inside(turned, 16, 44)).toBe(true);+ expect(inside(turned, 30, 28)).toBe(false);+ });++ it('believes dark water only when the other date sees water too', () => {+ // Sen2Cor reads a deep cloud shadow as water, so a cast shadow that spares+ // water finds none of it; a lake, which is water on both dates, is spared.+ const frame = sky(60, 60, (x, y) => {+ if (x >= 24 && x < 36 && y >= 34 && y < 46) return { scene: 9 };+ if (y < 34 && x < 30) return { scene: 6, dark: true }; // called water under the cloud+ if (y < 34) return { scene: 6, dark: true }; // a real lake+ return {};+ });+ const other = sky(60, 60, (x, y) => (y < 34 && x >= 30 ? { scene: 6 } : {}));+ const { shadow } = skyMask(frame, other, ground());+ expect(inside(shadow, 28, 28)).toBe(true);+ expect(inside(shadow, 32, 28)).toBe(false);+ // with no second date to ask, water is water and the shadow is missed+ expect(inside(skyMask(frame, null, ground()).shadow, 28, 28)).toBe(false);+ });+});diff --git a/frontend/src/lib/map/changeRunner.js b/frontend/src/lib/map/changeRunner.jsindex 85909bc..4c4fc86 100644--- a/frontend/src/lib/map/changeRunner.js+++ b/frontend/src/lib/map/changeRunner.js@@ -1,7 +1,7 @@/*** Hand a change detection to the worker, or run it here where there is none.*- * One worker, started on first use and kept: Change assist reruns on every+ * One worker, started on first use and kept: Difference reruns on every* settled camera, and a worker's start-up would cost more than the work. A* newer request does not cancel an older one in the worker (a computation* cannot be interrupted), so callers compare their own request number.diff --git a/frontend/src/lib/map/compare.js b/frontend/src/lib/map/compare.jsindex 3a4ac47..e3ff160 100644--- a/frontend/src/lib/map/compare.js+++ b/frontend/src/lib/map/compare.js@@ -43,7 +43,7 @@ export const COMPARE_LAYERS = Object.freeze([{ id: 'gpstraces', label: 'GPS traces', hint: 'Raw GPS tracks from OpenStreetMap', group: 'reference' },{ id: 'firms', label: 'Active fires', hint: 'Thermal detections from NASA FIRMS', group: 'events' },{ id: 'nightlights', label: 'Night lights', hint: 'The ground at night from NASA VIIRS', group: 'events' },- { id: 'saved', label: 'Saved work', hint: 'Places, captures and proofs in this case', group: 'case' },+ { id: 'saved', label: 'Saved work', hint: 'Places and captures in this case', group: 'case' },]);export const LAYER_GROUPS = Object.freeze([diff --git a/frontend/src/lib/map/compareExport.js b/frontend/src/lib/map/compareExport.jsindex c717181..356760b 100644--- a/frontend/src/lib/map/compareExport.js+++ b/frontend/src/lib/map/compareExport.js@@ -4,7 +4,7 @@* This composes pixels, not the Compare DOM: provider menus, zoom buttons and* the swipe handle are controls. The picture is the two aligned images plus* what explains them: which source and date each side is, where the camera- * was, a scale bar and north arrow, the Change assist legend, the credits, and+ * was, a scale bar and north arrow, the Difference legend, the credits, and* the annotations projected onto the ground they were pinned to.** Everything is placed from each side's camera frame (`groundFrame.js`), sodiff --git a/frontend/src/lib/map/contextMenu.js b/frontend/src/lib/map/contextMenu.jsindex d26953b..d0f6b8d 100644--- a/frontend/src/lib/map/contextMenu.js+++ b/frontend/src/lib/map/contextMenu.js@@ -42,6 +42,18 @@ export const ACTIONS = [{ id: 'centre', label: 'Centre the map here', icon: 'crosshair' },];+/**+ * The acts a tool can actually perform, in the order above.+ *+ * Satellite offers all of them; Compare has no sun panel and no measure rail,+ * so it asks for the subset it can honour rather than showing rows that do+ * nothing. The order stays the list's, not the caller's, so the menu reads the+ * same wherever it opens.+ */+export function actionsFor(ids) {+ return ACTIONS.filter((action) => ids.includes(action.id));+}+/** The external maps, opened on the clicked point at the current zoom. */export function openRows(lat, lon, zoom) {const round = (value) => Number(value.toFixed(6));diff --git a/frontend/src/lib/map/contextMenu.test.js b/frontend/src/lib/map/contextMenu.test.jsindex 086df2c..7da1039 100644--- a/frontend/src/lib/map/contextMenu.test.js+++ b/frontend/src/lib/map/contextMenu.test.js@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest';-import { ACTIONS, copyRows, nextFocus, openRows, placeMenu } from './contextMenu.js';+import { ACTIONS, actionsFor, copyRows, nextFocus, openRows, placeMenu } from './contextMenu.js';describe('copying the point', () => {it('offers every format the app writes, the analyst’s own first', () => {@@ -35,6 +35,13 @@ describe('what the menu offers', () => {}});+ it('gives a tool the subset it can honour, in the menu’s own order', () => {+ expect(actionsFor(['measure', 'lookup', 'place']).map((action) => action.id))+ .toEqual(['lookup', 'place', 'measure']);+ expect(actionsFor([])).toEqual([]);+ expect(actionsFor(['nothing-here'])).toEqual([]);+ });+it('opens the external maps on the clicked point, at the current zoom', () => {const links = openRows(48.85837123456, 2.29448123456, 18);const google = links.find((link) => link.id === 'google');diff --git a/frontend/src/lib/overview.js b/frontend/src/lib/overview.jsindex 9c159cf..72168fc 100644--- a/frontend/src/lib/overview.js+++ b/frontend/src/lib/overview.js@@ -130,7 +130,7 @@ export function familyBars(summary, familyOf = () => null) {/** How many points the home map draws before it stops. Higher than the plate that* drew them without a map could take: a dense patch there was one smear, and here* it is something to zoom into. The cap is what keeps a case with thousands of- * saved points from paying for all of them on a page nobody came to read them on. */+ * located files from paying for all of them on a page nobody came to read them on. */export const MAP_PINS = 200;/**@@ -144,7 +144,7 @@ function coordinate(value) {}/**- * The case's saved points, as the home map takes them.+ * The case's located media, as the home map takes them.** Coordinates and nothing else: the map projects, frames and draws them* (`tools/overview/PlaceMap.svelte`), so this only decides which rows can be drawn@@ -164,7 +164,6 @@ export function mapPins(rows, { limit = MAP_PINS } = {}) {if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue;points.push({id: String(row.key ?? row.id ?? `${lat},${lon}`),- kind: row.kind ?? 'place',title: row.title ?? '',lat,lon,diff --git a/frontend/src/lib/overview.test.js b/frontend/src/lib/overview.test.jsindex 23c50cf..73e2d2d 100644--- a/frontend/src/lib/overview.test.js+++ b/frontend/src/lib/overview.test.js@@ -137,14 +137,14 @@ describe('the bars the figures are drawn as', () => {});describe('the case as points on the map', () => {- const row = (over) => ({ key: 'k', kind: 'place', title: 'Quai sud', ...over });+ const row = (over) => ({ key: 'k', kind: 'media', title: 'Quai sud', ...over });- it('hands the map the position, the kind and the title it draws them with', () => {+ it('hands the map the position and the title it draws them with', () => {const { pins, total } = mapPins([row({ lat: 49.98, lon: 36.25 })]);expect(total).toBe(1);+ // one colour for every point, so what a row is never crosses overexpect(pins[0]).toEqual({id: 'k',- kind: 'place',title: 'Quai sud',lat: 49.98,lon: 36.25,@@ -159,8 +159,6 @@ describe('the case as points on the map', () => {it('names a row that carries no key of its own, since a dot is drawn by id', () => {const { pins } = mapPins([{ id: 'e7', lat: 50, lon: 4 }, { lat: 12, lon: 77 }]);expect(pins.map((pin) => pin.id)).toEqual(['e7', '12,77']);- // and a row that says nothing about what it is is still a place- expect(pins[1].kind).toBe('place');});it('leaves out what has nowhere to be drawn', () => {@@ -182,7 +180,7 @@ describe('the case as points on the map', () => {expect(total).toBe(MAP_PINS + 20);});- it('is empty on a case that saved nothing', () => {+ it('is empty on a case that has nothing placed', () => {expect(mapPins([])).toEqual({ pins: [], total: 0 });expect(mapPins(null)).toEqual({ pins: [], total: 0 });});diff --git a/frontend/src/tools/Compare.render.test.js b/frontend/src/tools/Compare.render.test.jsindex 275b0ec..2b77bad 100644--- a/frontend/src/tools/Compare.render.test.js+++ b/frontend/src/tools/Compare.render.test.js@@ -39,24 +39,27 @@ const SESSION = {},};+const SIZES = {+ small: { min_area: 0, max_area: 0, cleanup: 0, smoothing: 0, merge_metres: 0 },+ medium: { min_area: 2000, max_area: 0, cleanup: 1, smoothing: 0, merge_metres: 30 },+ large: { min_area: 20000, max_area: 0, cleanup: 1, smoothing: 1, merge_metres: 100 },+};const RECIPE = {- id: 'pair', name: 'Large surface change', description: 'Changes to review',- phenomenon: 'Change', method: 'colour', providers: ['esri-wayback', 'sentinel2'], zones: [],- colour: '#f6a81a', style: 'both',- parameters: { sensitivity: 55, min_area: 20, min_score: 0, cleanup: 1, smoothing: 0,- normalize: false, index: 'ndvi', direction: 'both', ignore_clouds: true,- ignore_shadows: true, merge_metres: 0 },+ id: 'pair', name: 'Any surface change', description: 'Reflectance that moved',+ phenomenon: 'Change', method: 'surface', zones: [], colour: '#f6a81a', style: 'both',+ parameters: { sensitivity: 67, ...SIZES.medium, index: 'ndvi', direction: 'both',+ ignore_clouds: true, ignore_shadows: true, cloud_margin: 5 },};const ANALYZERS = {- builtins: [RECIPE, { ...RECIPE, id: 'solo', name: 'Vessels on water', method: 'vessels',- providers: ['sentinel2'] }],+ builtins: [RECIPE, { ...RECIPE, id: 'solo', name: 'Vessels', method: 'vessels' }],custom: [],methods: [- { id: 'colour', label: 'Colour change', single: false, sentinel_only: false, classes: false },- { id: 'vessels', label: 'Infrared contrast over water', single: true, sentinel_only: true, classes: true },+ { id: 'surface', label: 'Any reflectance change', single: false, clouds: true, sizes: SIZES,+ measure: 'Reflectance moved by {value}%' },+ { id: 'vessels', label: 'Vessels', single: true, clouds: true, sizes: SIZES,+ measure: '{value}× brighter than the water around it' },],- max_tiles: 4096, max_results: 2000,- grids: { sentinel2: [13, 512], 'esri-wayback': [19, 256] },+ max_tiles: 4096, max_results: 2000, grid: [13, 512],};const get = vi.fn(async (path) => {@@ -99,6 +102,7 @@ const caseState = { current: { id: 'case-a' } };vi.mock('../lib/state.svelte.js', () => ({caseState,ensureCase,+ fmtCoords: (lat, lon) => `${lat.toFixed(5)}, ${lon.toFixed(5)}`,prefs: { homeView: { lat: 48.8566, lon: 2.3522, zoom: 16 }, units: 'metric' },prefsReady: Promise.resolve(),reloadCase,@@ -488,6 +492,59 @@ describe('Compare', () => {);});+ it('acts on the right-clicked point, offering only what Compare can honour', async () => {+ await open();+ await add('A');+ await add('B');+ engines[0].handlers.contextmenu({ lat: 43.3, lon: 5.4, x: 120, y: 90 });+ flushSync();++ const menu = target.querySelector('[role="menu"]');+ expect(menu.textContent).toContain('What is here?');+ expect(menu.textContent).toContain('Save place here…');+ expect(menu.textContent).toContain('Measure from here');+ expect(menu.textContent).not.toContain('Sun and moon from here');+ expect(menu.textContent).not.toContain('Imagery history here');+ // It belongs to the surface it opened on, and travels with it.+ expect(target.querySelector('.surface-shell.primary [role="menu"]')).not.toBeNull();++ button('Measure from here', menu).click();+ await settle();+ expect(target.querySelector('[role="menu"]')).toBeNull();+ expect(target.querySelector('button[title^="Measure"]').getAttribute('aria-pressed')).toBe('true');++ // The first end is the point that was clicked; the next click takes the other.+ const canvas = target.querySelector('[aria-label="Annotations on imagery A"]');+ canvas.getBoundingClientRect = () => ({ left: 0, top: 0, width: 1000, height: 600 });+ canvas.dispatchEvent(new MouseEvent('pointermove', { bubbles: true, clientX: 200, clientY: 90 }));+ canvas.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true, clientX: 200, clientY: 90 }));+ flushSync();+ const drawn = [...target.querySelectorAll('.surface-shell.primary .mark path')];+ expect(drawn.some((path) => path.getAttribute('stroke-dasharray') === '8 6')).toBe(true);+ });++ it('saves a place on the right-clicked point without leaving the comparison', async () => {+ await open();+ await add('A');+ await add('B');+ engines[1].handlers.contextmenu({ lat: 43.3, lon: 5.4, x: 40, y: 40 });+ flushSync();+ expect(target.querySelector('.surface-shell.secondary [role="menu"]')).not.toBeNull();++ button('Save place here…', target.querySelector('[role="menu"]')).click();+ await settle();+ const dialog = document.querySelector('[role="dialog"]');+ expect(dialog.textContent).toContain('Save place');+ dialog.querySelector('#place-title').value = 'New quay';+ dialog.querySelector('#place-title').dispatchEvent(new Event('input', { bubbles: true }));+ button('Save', dialog).click();+ await settle();+ expect(post).toHaveBeenCalledWith(+ '/api/cases/case-a/satellite/place',+ expect.objectContaining({ lat: 43.3, lon: 5.4, title: 'New quay' })+ );+ });+it('saves a reopenable session and restores sources, layers, mode and camera', async () => {await open();await add('A');@@ -534,10 +591,10 @@ describe('Compare', () => {const dock = () => target.querySelector('.cmp-dock');const stage = () => target.querySelector('.compare-stage');expect(stage().classList.contains('solo')).toBe(false);- // Inside it, one place to choose imagery, and the maps follow it: world- // imagery on A and Wayback on B is no pair, so the step takes the wheel.+ // Inside it, one place to choose imagery, and the maps follow it: Detect+ // reads Sentinel-2 bands, so world imagery and Wayback hand over the wheel.expect(target.querySelector('.source-bar')).toBeNull();- expect(dock().textContent).toContain('so they now show the one below');+ expect(dock().textContent).toContain('Detect reads Sentinel-2, so the maps now show it.');expect(target.querySelectorAll('.surface-shell .map')).toHaveLength(2);const picker = target.querySelector('select[aria-label="Analyzer"]');diff --git a/frontend/src/tools/Compare.svelte b/frontend/src/tools/Compare.svelteindex 61bc4e7..9c7a3d9 100644--- a/frontend/src/tools/Compare.svelte+++ b/frontend/src/tools/Compare.svelte@@ -12,12 +12,15 @@import {caseState,ensureCase,+ fmtCoords,prefs,prefsReady,reloadCase,toast,uiState,} from '../lib/state.svelte.js';+ import { saveRelation } from '../lib/relations.svelte.js';+ import { actionsFor } from '../lib/map/contextMenu.js';import {COMPARE_LAYERS,COMPARE_MODES,@@ -38,6 +41,7 @@} from '../lib/map/compareExport.js';import {changeCompatibility,+ changeNeedsFrames,changeSettings,} from '../lib/map/changeAssist.js';import {@@ -83,6 +87,8 @@import { detectCaptures } from '../lib/map/changeCapture.js';import { apply, cssMatrix, frameToFrame, fromMercator, screenToMercator } from '../lib/map/groundFrame.js';import MapSurface from './satellite/MapSurface.svelte';+ import MapContextMenu from './satellite/MapContextMenu.svelte';+ import PlaceDialog from './satellite/PlaceDialog.svelte';import SavedOverlay from './satellite/SavedOverlay.svelte';import LayerPane from './compare/LayerPane.svelte';import AnnotationCanvas from './compare/AnnotationCanvas.svelte';@@ -176,28 +182,27 @@* The source cards step aside while it is on, and this is how what is drawn* on stays what is measured.*/+ /** Said once per absence: every date picked pushes sources again. */+ let sentinelMissingSaid = false;function applyAnalysisSources(next) {- let missing = null;- for (const [letter, target, sentinel, wayback] of [['a', a, s2a, wba], ['b', b, s2b, wbb]]) {+ let missing = false;+ for (const [letter, target, sentinel] of [['a', a, s2a], ['b', b, s2b]]) {const source = next?.[letter];if (!source) continue;if (!imagery.find(source.provider)) {- missing = source.provider;+ missing = true;continue;}target.providerId = source.provider;target.present = true;- if (source.provider === 'sentinel2') {- sentinel.layer = source.layer || sentinel.layer;- sentinel.date = source.date || '';- sentinel.setMaxcc(source.maxcc ?? 100);- } else {- wayback.pick(source.release ?? null);- }+ sentinel.layer = source.layer || sentinel.layer;+ sentinel.date = source.date || '';+ sentinel.setMaxcc(source.maxcc ?? 100);}- if (missing) {- toast(`${missing === 'sentinel2' ? 'Copernicus Sentinel-2' : missing} is not configured, so the maps still show the previous imagery`, 'warn', 6000);+ if (missing && !sentinelMissingSaid) {+ toast('Copernicus Sentinel-2 is not configured, so the maps still show the previous imagery', 'warn', 6000);}+ sentinelMissingSaid = missing;invalidateChangeAssist();}@@ -236,7 +241,8 @@let changeUrl = $state('');/** One transform per surface: the mask is ground, and each map frames it. */let changeTransform = $state({ a: '', b: '' });- const changeVisible = $derived(changeOptions.visible);+ let changeBlinkOn = $state(true);+ const changeVisible = $derived(changeOptions.visible && (!changeOptions.blink || changeBlinkOn));const changeBase = $derived(changeOptions.base);const changeOpacity = $derived(changeOptions.opacity);const changePalette = $derived(changeOptions.palette);@@ -440,6 +446,21 @@}/** Where the computed mask lands on each surface as it is framed right now. */+ // Highlights over busy imagery are easier to catch when they come and go, so+ // the overlay can blink in place rather than the analyst toggling the eye.+ const CHANGE_BLINK_MS = 620;+ $effect(() => {+ if (!(mode === 'change' && changeOptions.blink && changeOptions.visible && changeUrl)) {+ changeBlinkOn = true;+ return;+ }+ const timer = setInterval(() => (changeBlinkOn = !changeBlinkOn), CHANGE_BLINK_MS);+ return () => {+ clearInterval(timer);+ changeBlinkOn = true;+ };+ });+function placeChangeMap() {if (!changeResult) return;changeTransform = {@@ -718,7 +739,7 @@if (next === 'change') {changeOptions.visible = true;if (!changeStatus.methods.includes(changeOptions.method)) changeOptions.method = changeStatus.methods[0];- if (changeOptions.method !== 'index' && changeOptions.live) void refreshChangeAssist();+ void refreshChangeAssist({ fetch: false });}}@@ -761,7 +782,7 @@nightlights: { ...target.night },sentinel: {layer: sentinel.layer,- // Change assist is only honest over named acquisitions. Freeze a live+ // A difference is only honest over named acquisitions. Freeze a live// "latest" pass to the date it meant when this workspace is saved.date: mode === 'change' ? sentinel.date || sentinel.latest : sentinel.date,maxcc: sentinel.maxcc,@@ -911,7 +932,7 @@a.engine?.resize();b.engine?.resize();savedSignature = sessionSignature();- if (mode === 'change' && changeOptions.method !== 'index' && changeOptions.live) void refreshChangeAssist();+ if (mode === 'change') void refreshChangeAssist({ fetch: false });toast(`Opened ${sessionName}`, 'ok');} catch (error) {toast(`Could not open the comparison: ${error.message}`, 'danger');@@ -1048,8 +1069,10 @@let changeRenderedKey = $state('');const detectionKey = $derived(changeKey());+ const changeFrames = $derived(changeNeedsFrames(changeSettings(changeOptions), changeStatus));+function changeKey() {- const { opacity, base, visible, zones, live, ...analysis } = changeSettings(changeOptions);+ const { opacity, base, visible, blink, zones, ...analysis } = changeSettings(changeOptions);return JSON.stringify([changeSide(a, s2a, wba, shownA),changeSide(b, s2b, wbb, shownB),@@ -1061,12 +1084,14 @@function invalidateChangeAssist() {changeRenderedKey = '';- if (mode !== 'change' || changeOptions.method === 'index' || !changeOptions.live) return;+ if (mode !== 'change') return;+ // A reading that follows the camera never spends a request: it runs on the+ // band frames already held, and waits for Run when they no longer reach.clearTimeout(changeTimer);- changeTimer = setTimeout(() => void refreshChangeAssist(), 180);+ changeTimer = setTimeout(() => void refreshChangeAssist({ fetch: false }), 180);}- async function refreshChangeAssist() {+ async function refreshChangeAssist({ fetch = true } = {}) {if (mode !== 'change' || !changeStatus.ok) return;if (!changeStatus.methods.includes(changeOptions.method)) { changeError = 'Choose a compatible method'; return; }const key = changeKey();@@ -1082,8 +1107,11 @@if (request !== changeRequest || key !== changeKey()) return;const sources = await sourceCanvases();if (request !== changeRequest || key !== changeKey()) return;- const result = await detectCaptures(sources, settings, sides);+ const result = await detectCaptures(sources, settings, sides, changeStatus, fetch);if (request !== changeRequest || mode !== 'change' || key !== changeKey()) return;+ // Nothing held reaches this view: the last reading stays up, marked out+ // of date, until the analyst asks for the frames.+ if (result.needsFetch) return;changeResult = result;placeChangeMap();changeUrl = result.canvas.toDataURL('image/png');@@ -1111,9 +1139,8 @@detectionKey;changeRequest++;changeBusy = false;- if (changeOptions.method === 'index' || !changeOptions.live) return;clearTimeout(changeTimer);- changeTimer = setTimeout(() => void refreshChangeAssist(), 180);+ changeTimer = setTimeout(() => void refreshChangeAssist({ fetch: false }), 180);return () => clearTimeout(changeTimer);});@@ -1229,6 +1256,135 @@return () => document.removeEventListener('keydown', onKey);});+ // --- the right-click menu: acts on the point under the cursor -------------+ //+ // Satellite's menu, cut down to what Compare can honour. There is no measure+ // rail and no sun panel here, so those acts are left out rather than shown+ // dead; the measure is the annotation of the same name, started on the point+ // instead of on a drag that would have to begin somewhere else. The camera is+ // shared, so the menu belongs to the side it was opened on and nothing else.+ let pointMenu = $state(null); // { side, lat, lon, x, y, frame, lookup }+ let pointLookupSeq = 0;+ let canvasA = $state(null);+ let canvasB = $state(null);+ const pointActions = $derived(+ actionsFor(both && !detecting ? ['lookup', 'place', 'measure'] : ['lookup', 'place'])+ );++ function onMapContextMenu(side, at) {+ pointLookupSeq += 1;+ const element = (side === 'a' ? a : b).element;+ pointMenu = {+ ...at,+ side,+ frame: { width: element?.clientWidth ?? 0, height: element?.clientHeight ?? 0 },+ lookup: null,+ };+ }++ function closePointMenu() {+ pointLookupSeq += 1;+ pointMenu = null;+ }++ async function onPointMenu(id, value) {+ if (!pointMenu) return;+ const point = { lat: pointMenu.lat, lon: pointMenu.lon };+ if (id === 'lookup') return lookUpPoint(point);+ const { side } = pointMenu;+ closePointMenu();+ if (id === 'copy') {+ try {+ await navigator.clipboard.writeText(value);+ toast('Coordinates copied', 'ok', 1600);+ } catch {+ toast('The browser refused the clipboard', 'warn');+ }+ } else if (id === 'place') {+ openNewPlaceAt(point);+ } else if (id === 'measure') {+ annotationTool = 'measure';+ await tick();+ (side === 'a' ? canvasA : canvasB)?.startFrom([point.lon, point.lat]);+ toast('Click the far end of the measure', 'info', 4000);+ }+ }++ /** "What is here?": the geocoder's name for the point, shown in the menu itself. */+ async function lookUpPoint(point) {+ const mine = ++pointLookupSeq;+ pointMenu = { ...pointMenu, lookup: { busy: true } };+ try {+ const answer = await api.get(`/api/geo/reverse?lat=${point.lat}&lon=${point.lon}`);+ if (mine !== pointLookupSeq || !pointMenu) return;+ pointMenu = {+ ...pointMenu,+ lookup: { text: answer.display_name || 'No name for this point' },+ };+ } catch (error) {+ if (mine !== pointLookupSeq || !pointMenu) return;+ pointMenu = { ...pointMenu, lookup: { error: `Lookup failed: ${error.message}` } };+ }+ }++ // The menu is pinned to a screen point, so a zoom or a pan leaves it pointing+ // at somewhere else. A drag already closes it by pressing outside; the wheel+ // does not, so the settled view does.+ $effect(() => {+ if (!pointMenu) return;+ return (pointMenu.side === 'a' ? a.engine : b.engine)?.on('view-settled', closePointMenu);+ });++ // --- saving a place from the menu ----------------------------------------+ let placeModal = $state(null);+ let placeSaving = $state(false);++ /** The same dialog Satellite opens, on the point that was right-clicked. */+ function openNewPlaceAt({ lat, lon }) {+ placeModal = {+ id: null,+ title: '',+ notes: '',+ folder: '',+ lat,+ lon,+ zoom: Math.round(view.zoom),+ bearing,+ relation: null, // collected by the dialog, filed once the place exists+ };+ }++ const placeCoordsLabel = (mark) => fmtCoords(mark.lat, mark.lon);++ async function savePlaceModal() {+ if (!placeModal || placeSaving) return;+ placeSaving = true;+ try {+ const draft = placeModal;+ const owner = await ensureCase();+ const entity = await api.post(`/api/cases/${owner.id}/satellite/place`, {+ lat: draft.lat,+ lon: draft.lon,+ zoom: draft.zoom,+ bearing: draft.bearing,+ title: draft.title,+ notes: draft.notes,+ folder: draft.folder,+ });+ // The relation is filed last: it needs a place that exists, and saving the+ // point is worth keeping even if the edge is refused.+ if (draft.relation && entity?.id) await saveRelation(owner.id, entity.id, draft.relation);+ placeModal = null;+ await reloadCase();+ await savedWork.load(owner.id);+ toast('Place saved', 'ok', 1600);+ } catch (error) {+ toast(`Could not save place: ${error.message}`, 'danger', 6000);+ } finally {+ placeSaving = false;+ }+ }+function changeShare(counts) {if (!counts) return 0;const changed = counts.gained + counts.lost + counts.changed;@@ -1340,13 +1496,13 @@async function comparisonBlob() {if (mode === 'change' && !changeStatus.ok) throw new Error(changeStatus.reason);- if (mode === 'change' && changeOptions.method !== 'index' && changeOptions.live && (changeRenderedKey !== changeKey() || !changeResult)) {+ if (mode === 'change' && (changeRenderedKey !== changeKey() || !changeResult)) {clearTimeout(changeTimer);- await refreshChangeAssist();+ await refreshChangeAssist({ fetch: changeFrames !== '' });}const sources = await sourceCanvases();if (mode === 'change' && (changeRenderedKey !== changeKey() || !changeResult)) {- throw new Error('Run Change assist for this view before exporting');+ throw new Error('Run Difference for this view before exporting');}const renderChangeMap = mode === 'change' ? changeResult : null;return canvasBlob(compose(sources, { renderChangeMap }));@@ -1629,16 +1785,28 @@onwidgetfailed={(provider, error) => onWidgetFailed('a', provider, error)}onviewsettled={(next) => onSurfaceSettled('a', next)}onbearingchange={(next) => onSurfaceBearing('a', next)}+ oncontextmenu={(at) => onMapContextMenu('a', at)}>+ {#if pointMenu?.side === 'a'}+ <MapContextMenu+ at={pointMenu}+ frame={pointMenu.frame}+ zoom={view.zoom}+ format={prefs.coordFormat}+ actions={pointActions}+ lookup={pointMenu.lookup}+ onpick={onPointMenu}+ onclose={closePointMenu}+ />+ {/if}{#if a.overlays.includes('saved')}<SavedOverlayengine={a.engine}- items={savedWork.shown}+ items={savedWork.rows}caseId={caseState.current?.id}coords={savedCoords}onopen={openSaved}onedit={openSaved}- onshowproofs={() => toast('Open Satellite to browse proofs', 'info')}onrefresh={reloadCase}/>{/if}@@ -1651,10 +1819,10 @@style:transform={changeTransform.a} />{/if}{#if both && !grabbing && !detecting}- <AnnotationCanvas {annotations} engine={a.engine} letter="a" units={prefs.units}+ <AnnotationCanvas bind:this={canvasA} {annotations} engine={a.engine} letter="a" units={prefs.units}active={uiState.tool === 'compare'} bind:tool={annotationTool} bind:selectedId={selectedAnnotationId}colour={annotationColour} strokeWidth={annotationStroke} fillOpacity={annotationFill}- {annotationSide} onchange={setAnnotations} />+ editVertices={true} {annotationSide} onchange={setAnnotations} />{/if}<!-- Detect's own drawing stays in Detect: areas and candidates belongto the column that explains them, and the reading modes stay clean@@ -1664,7 +1832,7 @@onpick={(run, result) => analyzerPanel?.pick(run, result)} />{/if}{#if detecting && !grabbing && analyzerAreasVisible}- <AnnotationCanvas annotations={analyzerMarks} engine={a.engine} letter="a" editVertices={true}+ <AnnotationCanvas annotations={analyzerMarks} engine={a.engine} letter="a" editVertices={true} edgeOnly={true}bind:tool={analyzerDrawing} bind:selectedId={analyzerSelectedZone} colour="#38bdf8"fillOpacity={0.08} onchange={setAnalyzerMarks} />{/if}@@ -1714,16 +1882,28 @@onwidgetfailed={(provider, error) => onWidgetFailed('b', provider, error)}onviewsettled={(next) => onSurfaceSettled('b', next)}onbearingchange={(next) => onSurfaceBearing('b', next)}+ oncontextmenu={(at) => onMapContextMenu('b', at)}>+ {#if pointMenu?.side === 'b'}+ <MapContextMenu+ at={pointMenu}+ frame={pointMenu.frame}+ zoom={view.zoom}+ format={prefs.coordFormat}+ actions={pointActions}+ lookup={pointMenu.lookup}+ onpick={onPointMenu}+ onclose={closePointMenu}+ />+ {/if}{#if b.overlays.includes('saved')}<SavedOverlayengine={b.engine}- items={savedWork.shown}+ items={savedWork.rows}caseId={caseState.current?.id}coords={savedCoords}onopen={openSaved}onedit={openSaved}- onshowproofs={() => toast('Open Satellite to browse proofs', 'info')}onrefresh={reloadCase}/>{/if}@@ -1734,17 +1914,17 @@style:transform={changeTransform.b} />{/if}{#if both && !grabbing && !detecting}- <AnnotationCanvas {annotations} engine={b.engine} letter="b" units={prefs.units}+ <AnnotationCanvas bind:this={canvasB} {annotations} engine={b.engine} letter="b" units={prefs.units}active={uiState.tool === 'compare'} bind:tool={annotationTool} bind:selectedId={selectedAnnotationId}colour={annotationColour} strokeWidth={annotationStroke} fillOpacity={annotationFill}- {annotationSide} onchange={setAnnotations} />+ editVertices={true} {annotationSide} onchange={setAnnotations} />{/if}{#if detecting && !grabbing && analyzerLayers.some((layer) => layer.visible)}<AnalysisOverlay engine={b.engine} layers={analyzerLayers} selected={analyzerResult}onpick={(run, result) => analyzerPanel?.pick(run, result)} />{/if}{#if detecting && !grabbing && analyzerAreasVisible}- <AnnotationCanvas annotations={analyzerMarks} engine={b.engine} letter="b" editVertices={true}+ <AnnotationCanvas annotations={analyzerMarks} engine={b.engine} letter="b" editVertices={true} edgeOnly={true}bind:tool={analyzerDrawing} bind:selectedId={analyzerSelectedZone} colour="#38bdf8"fillOpacity={0.08} onchange={setAnalyzerMarks} />{/if}@@ -1780,7 +1960,7 @@{/if}{#if both && mode === 'change'}- <div class="change-legend" class:colourblind={changePalette === 'colourblind'} class:hidden={!changeVisible}>+ <div class="change-legend" class:colourblind={changePalette === 'colourblind'} class:hidden={!changeOptions.visible}><span><i class="gain"></i> Appeared / stronger in B</span><span><i class="loss"></i> Disappeared / weaker from A</span><span><i class="changed"></i> Other evolution</span>@@ -1797,13 +1977,11 @@<ChangePanel bind:settings={changeOptions} status={changeStatus} result={changeResult}busy={changeBusy} error={changeError}stale={!!changeResult && changeRenderedKey !== detectionKey}- onrun={refreshChangeAssist} onzone={visitZone} onclose={() => setMode('side')} />+ onrun={() => refreshChangeAssist()} onzone={visitZone} onclose={() => setMode('side')} />{/if}{#if both && detecting}<AnalyzerPanel bind:this={analyzerPanel} caseId={caseState.current?.id}- sources={{ a: { ...sideSpec(a, s2a, wba), wayback_release: wba.release ?? wba.releases[0]?.release },- b: { ...sideSpec(b, s2b, wbb), wayback_release: wbb.release ?? wbb.releases[0]?.release } }}- releases={wba.releases.length ? wba.releases : wbb.releases}+ sources={{ a: sideSpec(a, s2a, wba), b: sideSpec(b, s2b, wbb) }}bind:zones={analyzerZones} bind:drawing={analyzerDrawing} bind:selectedZone={analyzerSelectedZone}bind:layers={analyzerLayers} bind:showZones={analyzerAreasVisible}bind:singleImage={analyzerSingle} bind:selectedResult={analyzerResult}@@ -2008,6 +2186,18 @@/>{/if}+{#if placeModal}+ <PlaceDialog+ bind:draft={placeModal}+ caseId={caseState.current?.id}+ folders={caseState.current?.folders ?? []}+ saving={placeSaving}+ coords={placeCoordsLabel}+ onsave={savePlaceModal}+ onclose={() => (placeModal = null)}+ />+{/if}+<style>.tool { position: relative; }.spacer { flex: 1; }diff --git a/frontend/src/tools/Overview.render.test.js b/frontend/src/tools/Overview.render.test.jsindex 4c170c9..19d5549 100644--- a/frontend/src/tools/Overview.render.test.js+++ b/frontend/src/tools/Overview.render.test.js@@ -34,9 +34,9 @@ const RECENT = [{ id: 'e2', type: 'place', label: 'Quai sud', attrs: {}, provenance: { at: '2026-09-09T09:00:00Z' } },];-const SAVED = [- { id: 'p1', key: 'p1', kind: 'place', title: 'Quai sud', lat: 49.98, lon: 36.25 },- { id: 'p2', key: 'p2', kind: 'capture', title: 'Depot', lat: 49.99, lon: 36.3 },+const LOCATED = [+ { id: 'm1', key: '[email protected],36.25', kind: 'media', title: 'Quai sud', lat: 49.98, lon: 36.25 },+ { id: 'm2', key: '[email protected],36.3', kind: 'media', title: 'Depot', lat: 49.99, lon: 36.3 },];const PROVIDERS = [@@ -63,7 +63,7 @@ const answers = async (url) => {if (url === '/api/satellite/providers') return PROVIDERS;if (url.includes('/catalog/summary')) return SUMMARY;if (url.includes('/timeline')) return { items: [], undated: 3, unplaced: 0, total: 9 };- if (url.includes('/satellite/index')) return SAVED;+ if (url.includes('/satellite/media')) return LOCATED;if (url.includes('since=')) return { items: [], total: 5, next_cursor: null };if (url.includes('/catalog/entities')) return { items: RECENT, total: 30, next_cursor: null };return {};@@ -182,8 +182,8 @@ describe('with a case open', () => {const paths = asked.filter((url) => url.startsWith('/api/cases/'));expect(paths).toHaveLength(6);expect(paths).toContain('/api/cases/case-a/todos');- // every one of them capped, counting, or the compact index the map panel already- // opens on — never a whole-graph read+ // every one of them capped, counting, or the located-media index the map panel+ // opens its own first position on — never a whole-graph readexpect(paths.filter((url) => url.includes('limit=')).length).toBe(3);expect(paths.every((url) => url.startsWith('/api/cases/case-a/'))).toBe(true);// and the one read that is not the case's own: which basemap the map of the@@ -214,7 +214,7 @@ describe('with a case open', () => {return { ...SUMMARY, total: 18, by_status: {}, by_folder: { work: 18 }, unlinked: 0 };}if (url.includes('/timeline')) return { undated: 0 };- if (url.includes('/satellite/index')) return [];+ if (url.includes('/satellite/media')) return [];return { items: [], total: 0, next_cursor: null };});await open();@@ -228,7 +228,7 @@ describe('with a case open', () => {get.mockImplementation(async (url) => {if (url.includes('/catalog/summary')) return { ...SUMMARY, total: 0, by_type: {}, by_status: {}, by_folder: {}, unlinked: 0 };if (url.includes('/timeline')) return { undated: 0 };- if (url.includes('/satellite/index')) return [];+ if (url.includes('/satellite/media')) return [];return { items: [], total: 0, next_cursor: null };});await open();@@ -261,7 +261,7 @@ describe('with a case open', () => {it('leaves the map out, and the shoulder filled, when nothing is placed', async () => {get.mockImplementation(async (url) => {- if (url.includes('/satellite/index')) return [];+ if (url.includes('/satellite/media')) return [];return answers(url);});await open();diff --git a/frontend/src/tools/Overview.svelte b/frontend/src/tools/Overview.svelteindex a645c39..114881a 100644--- a/frontend/src/tools/Overview.svelte+++ b/frontend/src/tools/Overview.svelte@@ -1,8 +1,8 @@<script>/** Case dashboard, or a workspace entry page when no case is open.* Five bounded reads supply the dashboard; CaseTodos owns its metadata read.- * The map uses imagery for the saved points. Release notices reuse the startup- * check, and do not initiate another network request.+ * The map uses imagery for the case's located footage. Release notices reuse the+ * startup check, and do not initiate another network request.*/import { api } from '../lib/api.js';import {@@ -67,7 +67,7 @@let summary = $state(null); // catalog counts, or null until the first read landslet timeline = $state(null); // one timeline page, read for its undated countlet recent = $state([]); // the newest rows the case filed- let saved = $state([]); // the case's saved points, for the plate+ let located = $state([]); // the case's located media, for the platelet week = $state(0); // how many landed in the last seven dayslet naming = $state(''); // the first case being named, on the front doorlet creating = $state(false);@@ -79,7 +79,7 @@* so it is offered the three ways material gets in instead. */const empty = $derived(Boolean(summary) && Number(summary.total ?? 0) === 0);const bars = $derived(familyBars(summary, entityFamily));- const plate = $derived(mapPins(saved));+ const plate = $derived(mapPins(located));const touched = $derived(lastTouched(caseState.current, caseState.list));const badges = $derived(updateBadges(updatesState, prefs.updateDismissedVersion));const notes = $derived(markdownHtml(updatesState.app?.notes ?? ''));@@ -99,14 +99,14 @@api.get(`/api/cases/${id}/timeline?limit=1`),api.get(buildCatalogQuery(id, { limit: RECENT, order: '-created' })),api.get(buildCatalogQuery(id, { limit: 1, since: weekAgo() })),- api.get(`/api/cases/${id}/satellite/index`),+ api.get(`/api/cases/${id}/satellite/media`),]);if (caseState.current?.id !== id) return;if (counts.status === 'fulfilled') summary = counts.value;if (dates.status === 'fulfilled') timeline = dates.value;if (newest.status === 'fulfilled') recent = newest.value?.items ?? [];if (lately.status === 'fulfilled') week = Number(lately.value?.total ?? 0);- if (points.status === 'fulfilled') saved = Array.isArray(points.value) ? points.value : [];+ if (points.status === 'fulfilled') located = Array.isArray(points.value) ? points.value : [];}// Re-read when the case changes, when a write reloads it, and when the analyst@@ -120,7 +120,7 @@summary = null;timeline = null;recent = [];- saved = [];+ located = [];week = 0;return;}diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelteindex 69069e3..f33847b 100644--- a/frontend/src/tools/Satellite.svelte+++ b/frontend/src/tools/Satellite.svelte@@ -970,6 +970,10 @@let railHeight = $state(0);const railBottom = $derived(RAIL_TOP + railHeight + 8);+ /** Whether the case has anything the saved layer could draw, on any of its+ * three positions — media reads its own index, so one length is not enough. */+ const savedAnything = $derived(savedWork.rows.length > 0 || savedWork.media.length > 0);+/*** The saved layer's own two questions, asked where the layer is listed.*@@ -1105,16 +1109,19 @@id: 'saved',label: 'Saved work',on: savedOverlay,- disabled: !savedWork.rows.length,+ // Either index is enough to have something to draw: a case whose footage+ // is placed but which nobody has dropped a pin in is exactly the case the+ // panel opens on Media for.+ disabled: !savedAnything,detail: savedWork.shown.length ? String(savedWork.shown.length) : '',- title: savedWork.rows.length+ title: savedAnything? "This case's saved work, or its located photos and videos"- : 'Nothing is saved in this case yet',+ : 'Nothing is saved or placed in this case yet',toggle: () => (savedOverlay = !savedOverlay),// Which of them are drawn. The same two answers the Saved panel is asking// — what kind, and which folder — so a map read here and a panel read// beside it can never disagree about what is on the case.- controls: savedOverlay && savedWork.rows.length ? savedFilters : null,+ controls: savedOverlay && savedAnything ? savedFilters : null,},...(sheetPoints? [@@ -1262,7 +1269,7 @@return savedWork.load(id);});- // The proofs and media indexes, each read the first time its position is opened.+ // The media index, read the first time that position is opened.$effect(() => savedWork.loadMode(caseState.current?.id, caseState.rev));// A reloaded media index re-reads the stack being played: a file deleted or@@ -1281,8 +1288,8 @@mediaView = { items, index: Math.max(0, items.findIndex((row) => row.key === current)) };});- // another workspace asked to show one capture: clear whatever filter is on so- // it can't be hidden, then let the tree open its branch and scroll to it+ // another workspace asked to show one capture: put the panel on the position+ // that lists it, then let the tree open its branch and scroll to it$effect(() => {const path = uiState.focusCapture;if (!path) return;@@ -1290,7 +1297,7 @@if (!row) return;uiState.focusCapture = null;capturesCollapsed = false;- savedWork.kind = 'all';+ savedWork.kind = 'captures';savedWork.query = '';revealSavedId = row.id;});@@ -1733,29 +1740,19 @@return fmtCoords(item.lat, item.lon);}- // One action, two directions: a capture goes *into* a new proof, a proof row- // opens the proof it already is.+ /** A capture or a place, queued for the composer to build a proof on. */function sendToComposer(item) {- if (item.kind === 'proof') {- uiState.openProof = item.name;- } else if (!uiState.composeQueue.includes(item.path)) {- uiState.composeQueue.push(item.path);- }+ if (!uiState.composeQueue.includes(item.path)) uiState.composeQueue.push(item.path);uiState.tool = 'proof';}+ /** A proof already built on the file being played: open it where it lives. */function openProofByName(proof) {if (!proof?.name) return;uiState.openProof = proof.name;uiState.tool = 'proof';}- function openLinkedPost(post) {- if (!post.name) return;- uiState.openDraft = post.name;- uiState.tool = 'post';- }-// the HUD readout and everything copied out of it follow the user's// coordinate format (Settings → General); captures keep decimal degreesconst readout = $derived(fmtCoords(displayCoords.lat, displayCoords.lon));@@ -2045,9 +2042,6 @@activeKey={mediaView ? mediaView.items[mediaView.index]?.key : null}onopen={openSaved}onedit={editSaved}- onproof={sendToComposer}- onpost={openLinkedPost}- onshowproofs={() => (savedWork.kind = 'proofs')}onrefresh={reloadCase}ontrace={startTrace}onmedia={openMedia}diff --git a/frontend/src/tools/Satellite.test.js b/frontend/src/tools/Satellite.test.jsindex 30fefa7..34d5a04 100644--- a/frontend/src/tools/Satellite.test.js+++ b/frontend/src/tools/Satellite.test.js@@ -99,19 +99,19 @@ describe('Satellite saved work', () => {expect((source.match(/bind:hoveredId=\{hoveredSavedId\}/g) ?? []).length).toBe(3);});- it('opens a proof rather than queueing it as a panel of a new one', () => {- expect(source).toContain("if (item.kind === 'proof') {");- expect(source).toContain('uiState.openProof = item.name');+ it('queues a saved row as a panel of a new proof', () => {+ expect(source).toContain('function sendToComposer(item)');+ expect(source).toContain('uiState.composeQueue.push(item.path)');});- it('opens a linked post in the existing Post Composer draft flow', () => {- expect(source).toContain('function openLinkedPost(post)');- expect(source).toContain('uiState.openDraft = post.name');- expect(source).toContain('onpost={openLinkedPost}');+ it('opens a proof already built on the file being played', () => {+ expect(source).toContain('function openProofByName(proof)');+ expect(source).toContain('uiState.openProof = proof.name');+ expect(source).toContain('onproof={openProofByName}');});- it('reveals a capture the case sidebar points at, whatever the filter was', () => {- expect(source).toContain("savedWork.kind = 'all'");+ it('reveals a capture the case sidebar points at, on the position that lists it', () => {+ expect(source).toContain("savedWork.kind = 'captures'");expect(source).toContain("savedWork.query = ''");expect(source).toContain('revealSavedId = row.id');});@@ -402,7 +402,7 @@ describe('choosing which saved work is drawn', () => {it('asks the layer\'s own two questions where the layer is listed', () => {// the same state the Saved panel binds, so a map read here and a panel read// beside it cannot disagree about what the case holds- expect(source).toContain('controls: savedOverlay && savedWork.rows.length ? savedFilters : null');+ expect(source).toContain('controls: savedOverlay && savedAnything ? savedFilters : null');expect(source).toContain('pick: (id) => (savedWork.kind = id)');expect(source).toContain("pick: (id) => (savedWork.folder = id === 'all' ? null : id)");});@@ -427,6 +427,15 @@ describe('choosing which saved work is drawn', () => {it('counts what is drawn rather than what the case holds', () => {expect(source).toContain('detail: savedWork.shown.length ? String(savedWork.shown.length)');});++ it('offers the layer on either index, since media is not in the saved one', () => {+ // a case whose footage is placed and whose pins nobody dropped is exactly+ // the case the panel opens on Media for+ expect(source).toContain(+ 'const savedAnything = $derived(savedWork.rows.length > 0 || savedWork.media.length > 0)'+ );+ expect(source).toContain('disabled: !savedAnything');+ });});describe('tracing a place\'s footprint', () => {diff --git a/frontend/src/tools/compare/AnalyzerPanel.svelte b/frontend/src/tools/compare/AnalyzerPanel.svelteindex 41c0f24..f4dd0d5 100644--- a/frontend/src/tools/compare/AnalyzerPanel.svelte+++ b/frontend/src/tools/compare/AnalyzerPanel.svelte@@ -1,7 +1,7 @@<script>/**- * Detect mode's own column: sweep a drawn area at native resolution and keep- * what was found.+ * Detect mode's own column: sweep a drawn area of Copernicus Sentinel-2 at+ * native resolution and keep what was found.** The setup reads as three numbered steps because that is the order the work* actually happens in — an area first, then the images, then what to look for@@ -15,11 +15,15 @@import { ensureCase, reloadCase, toast } from '../../lib/state.svelte.js';import {SECONDS_PER_FRAME,+ STRENGTHS,clone,coverage,+ describeMeasure,framesPerTile,mapSource,readableDuration,+ sizeBand,+ sizeOf,sourceLabel,} from '../../lib/map/analyzers.js';import { acquisitionQuery, areaKey, coverageWarning, sweptNote } from '../../lib/map/acquisitions.js';@@ -30,7 +34,6 @@let {caseId,sources = {},- releases = [],zones = $bindable([]),drawing = $bindable('select'),selectedZone = $bindable(null),@@ -47,12 +50,19 @@onclose = () => {},} = $props();+ const EMPTY_SOURCE = { provider: 'sentinel2', date: '', layer: 'TRUE_COLOR', maxcc: 30 };+ const SIZES = [['small', 'Small'], ['medium', 'Medium'], ['large', 'Large'], ['all', 'All']];+ const INDICES = [+ ['ndvi', 'NDVI · vegetation'], ['nbr', 'NBR · burn scars'], ['mndwi', 'MNDWI · open water'],+ ['ndwi', 'NDWI · open water'], ['bsi', 'BSI · bare soil'], ['ndbi', 'NDBI · built-up'],+ ];+let catalogue = $state(null);let recipe = $state(null);let chosen = $state('');let title = $state('');- let a = $state({ provider: 'esri-wayback', date: '', release: null, layer: 'TRUE_COLOR', maxcc: 30 });- let b = $state({ provider: 'esri-wayback', date: '', release: null, layer: 'TRUE_COLOR', maxcc: 30 });+ let a = $state({ ...EMPTY_SOURCE });+ let b = $state({ ...EMPTY_SOURCE });let dateRule = $state('manual');/** The Sentinel-2 passes the drawn areas have, and the lookup that found them. */let passes = $state([]);@@ -71,13 +81,13 @@let lists = $state({ zones: [], followups: [], runs: [] });let current = $state(null);let candidateId = $state(null);- let part = $state(0);let busy = $state(false);let error = $state('');let view = $state('setup');let showImagery = $state(false);let showDetection = $state(false);let showRecipe = $state(false);+ let showNew = $state(false);/** Undefined until the first case is seen, so mounting is not a case switch. */let loadedCase;let lastMapKey = '';@@ -99,76 +109,69 @@counts.new === 0 ? `All ${candidates.length} reviewed · ${counts.kept} kept, ${counts.dismissed} dismissed`: `${counts.new} still to review · ${counts.kept} kept, ${counts.dismissed} dismissed`);- const compatible = $derived(!recipe || recipe.providers.includes(b.provider));/** What the method can do, straight from the catalogue rather than by name:* the panel should never keep its own list of which method is which. */const methodOf = (method) => catalogue?.methods?.find((m) => m.id === method) ?? {};const capability = $derived(methodOf(recipe?.method));+ /** Mine to change: a built-in is read-only, and an unsaved draft is not in the library yet. */+ const mine = $derived(!!(catalogue?.custom ?? []).some((r) => r.id === chosen));+ const draft = $derived(recipe?.id === 'custom');/** A vessel or a fire is present on a date, not a difference between two. */const single = $derived(!!capability.single);$effect(() => { singleImage = single; });$effect(() => { selectedResult = view === 'results' ? candidateId : null; });- const grid = $derived(catalogue?.grids?.[b.provider] ?? null);- const cost = $derived(coverage(zones, grid));+ const size = $derived(recipe ? sizeOf(recipe.parameters, capability.sizes) : '');+ const cost = $derived(coverage(zones, catalogue?.grid ?? null));const tooMany = $derived(catalogue && cost.tiles > catalogue.max_tiles);/** The same pair on both maps, or null when they cannot drive a run. */const mapPair = $derived.by(() => {const left = mapSource(sources.a);const right = mapSource(sources.b);- return left && right && left.provider === right.provider ? { left, right } : null;+ return left && right ? { left, right } : null;});- const tileCount = $derived(Number.isFinite(cost.tiles) ? String(cost.tiles) : 'over the limit');- const frames = $derived(cost.tiles * framesPerTile({ single, bands: !!capability.sentinel_only }));+ const frames = $derived(cost.tiles * framesPerTile({ single }));const duration = $derived(readableDuration(frames * SECONDS_PER_FRAME));const blocked = $derived(!zones.length ? 'Draw an area to analyze.': tooMany ? (Number.isFinite(cost.tiles)? `These areas need ${cost.tiles} tiles; the limit is ${catalogue.max_tiles}. Draw smaller areas.`: `These areas are far past the ${catalogue.max_tiles}-tile limit. Draw smaller areas.`)- : !compatible ? 'This analyzer does not support the chosen imagery source.'// Said here rather than discovered when the run comes back failed.- : dateRule === 'manual' && !isDated(b) ? `Choose the ${single ? 'image' : 'image to compare'}.`- : !single && !isDated(a) && !(dateRule === 'latest_previous' && followupId)+ : dateRule === 'manual' && !b.date ? `Choose the ${single ? 'image' : 'image to compare'}.`+ : !single && !a.date && !(dateRule === 'latest_previous' && followupId)? 'Choose the reference image.': pending ? 'A run is already working in this case.': '');- /** Named enough to run: a Sentinel day, or a Wayback release. */- const isDated = (source) =>- source.provider === 'sentinel2' ? !!source.date : source.release != null;const base = (id = caseId) => `/api/cases/${id}/analysis`;const statusLabel = (status) => ({ queued: 'Queued', running: 'Running', ready: 'Completed',failed: 'Failed', cancelled: 'Cancelled', no_new_imagery: 'No new imagery' }[status] ?? status);const focus = (coordinates) => onfocus(coordinates, current?.input?.b ?? b);const round = (value, digits = 1) => Number(value.toFixed(digits));-- /**- * One chip, two stores behind it. Sentinel-2's classification and a guess off- * the picture are not the same claim, so they are not the same field: the- * classification is trusted by default, the guess is never turned on for- * anyone. The chip hides that, the catalogue decides which applies.- */- const weatherOn = $derived(- capability.cloud_filter === 'classes'- ? recipe?.parameters?.ignore_clouds ?? false- : recipe?.parameters?.guess_clouds ?? false- );+ const plural = (count, word) => `${count} ${word}${count === 1 ? '' : 's'}`;+ const dates = (input) => methodOf(input.recipe.method).single || !(input.a?.date || input.a?.release)+ ? sourceLabel(input.b) : `${sourceLabel(input.a)} → ${sourceLabel(input.b)}`;+ /** A candidate's reading, in the words its method's catalogue entry gives. */+ const reading = (row, input) => [+ STRENGTHS[row.strength],+ describeMeasure(methodOf(input.recipe.method).measure, row.measure, input.recipe.parameters.index),+ ].filter(Boolean).join(' · ');function setWeather(on) {if (!recipe) return;- recipe.parameters = capability.cloud_filter === 'classes'- ? { ...recipe.parameters, ignore_clouds: on, ignore_shadows: on }- : { ...recipe.parameters, guess_clouds: on };+ recipe.parameters = { ...recipe.parameters, ignore_clouds: on, ignore_shadows: on };+ }++ function setSize(name) {+ if (!recipe || !capability.sizes?.[name]) return;+ recipe.parameters = { ...recipe.parameters, ...capability.sizes[name] };}/** The pass behind a chosen date, so its coverage can be said out loud. */const passOf = (day) => passes.find((entry) => entry.date === day) ?? null;const coverWarnings = $derived(- b.provider === 'sentinel2'- ? [coverageWarning(passOf(b.date)), single ? '' : coverageWarning(passOf(a.date))]- .filter(Boolean)- : []+ [coverageWarning(passOf(b.date)), single ? '' : coverageWarning(passOf(a.date))].filter(Boolean));/**@@ -250,7 +253,7 @@* On arrival the maps lead: whatever is above the stage is almost always what* you came to analyze, and inheriting it silently is the whole reason this* step usually needs no attention. From the first deliberate change here —- * or straight away when the maps show something this cannot read — the+ * or straight away when the maps show something other than Sentinel-2 — the* direction reverses and the stage follows this step, so what is on screen* is what a run would sweep. Keyed on values, so a parent re-render that* rebuilds the same objects changes nothing.@@ -319,13 +322,6 @@recipe = clone(found); chosen = id;if (recipe.zones.length) zones = clone(recipe.zones);attachZones = recipe.zones.length > 0;- if (methodOf(recipe.method).sentinel_only && b.provider !== 'sentinel2') setProvider('sentinel2');- }-- function setProvider(provider) {- pinned = true;- b = { ...b, provider };- a = { ...a, provider };}function followMaps() {@@ -346,9 +342,14 @@a: clone(a), b: clone(b), date_rule: dateRule, offline, followup_id: followupId };}+ /** Runs and watches saved before Detect went Copernicus-only name a Wayback+ * release; they reopen undated, which is what they are for Sentinel-2. */+ const sentinelSource = (source) => source?.provider === 'sentinel2'+ ? { ...EMPTY_SOURCE, ...clone(source) } : { ...EMPTY_SOURCE };+function hydrate(body) {title = body.title; zones = clone(body.zones); recipe = clone(body.recipe); chosen = recipe.id;- a = clone(body.a); b = clone(body.b); offline = body.offline;+ a = sentinelSource(body.a); b = sentinelSource(body.b); offline = body.offline;dateRule = body.date_rule; attachZones = recipe.zones.length > 0;followupId = body.followup_id;pinned = true;@@ -370,7 +371,35 @@if (epoch !== generation) return;if (kind === 'zones') { zones = clone(body.zones); zonesTitle = body.title; zonesId = id; view = 'setup'; }if (kind === 'followups') { hydrate(body); followupId = id; view = 'setup'; }- if (kind === 'runs') { hydrate(body.input); acceptRun(body); view = 'results'; part = 0; }+ if (kind === 'runs') { hydrate(body.input); acceptRun(body); view = 'results'; }+ }++ /**+ * Start an analyzer of your own, from this one or from a plain one.+ *+ * Built-ins cannot be written over, so "copy" is how an analyst keeps a tuned+ * version: the library is shared by every case, which is why it is explicit.+ */+ function startNew(from) {+ const base = from === 'copy'+ ? recipe+ : (catalogue?.builtins ?? []).find((r) => r.id === 'large-change') ?? catalogue?.builtins?.[0];+ if (!base) return;+ recipe = { ...clone(base), id: 'custom',+ name: from === 'copy' ? `${base.name} copy` : 'My analyzer' };+ chosen = 'custom';+ showNew = false;+ showRecipe = true;+ }++ async function deleteRecipe() {+ if (!mine) return;+ const gone = chosen;+ await api.del(`/api/compare/analyzers/${gone}`);+ catalogue = await api.get('/api/compare/analyzers');+ showRecipe = false;+ choose(catalogue?.builtins?.[0]?.id ?? '');+ toast('Analyzer removed from the library', 'ok');}async function saveRecipe(asNew = false) {@@ -423,7 +452,7 @@const index = candidates.findIndex((r) => r.id === candidateId);for (let i = 1; i <= candidates.length; i++) {const row = candidates[(index + i) % candidates.length];- if (row?.review === 'new') { candidateId = row.id; part = 0; focus(row.coordinates); return; }+ if (row?.review === 'new') { candidateId = row.id; focus(row.coordinates); return; }}}@@ -455,12 +484,12 @@function step(direction) {const index = candidates.findIndex((r) => r.id === candidateId);const row = candidates[(index + direction + candidates.length) % candidates.length];- if (row) { candidateId = row.id; part = 0; focus(row.coordinates); }+ if (row) { candidateId = row.id; focus(row.coordinates); }}export function pick(runId, resultId) {- const run = layers.find((r) => r.id === runId);- if (run) { current = run; candidateId = resultId; part = 0; view = 'results'; }+ const found = layers.find((r) => r.id === runId);+ if (found) { current = found; candidateId = resultId; view = 'results'; }}function removeZone(id) {@@ -494,10 +523,6 @@<Icon name="x" size={14} /></button></header>- <p class="cmp-dock-lead">- Sweeps the areas you draw at full resolution. What it finds is a list of candidates to check- one by one: only the ones you keep become pins in the case.- </p><div class="cmp-seg fill views"><button class:on={view === 'setup'} onclick={() => (view = 'setup')}>Setup</button>@@ -528,10 +553,10 @@</div>{#if drawing !== 'select'}<p class="hint">{drawing === 'polygon' ? 'Click corners on either map; Enter finishes, Escape cancels.' : 'Drag on either map. Escape cancels.'}</p>+ {:else if !zones.length}+ <p class="hint">Draw on either map, take the current view, or open a saved set.</p>{/if}- {#if !zones.length}- <p class="hint">Draw on either map, take the current view, or open a saved set from Saved.</p>- {:else}+ {#if zones.length}{#each zones as zone (zone.id)}<div class="row area-row"><button class="cmp-icon" aria-label={`Show ${zone.name}`}@@ -544,13 +569,11 @@</button></div>{/each}- <p class="hint" class:warn={tooMany}>- {round(cost.km2, cost.km2 < 10 ? 2 : 0)} km² · {tileCount} tiles of {cost.size}px- </p>- {#if !tooMany}- <p class="hint">{frames} frames to fetch, about {duration}. You can cancel a run once it starts.</p>- {/if}- <p class="hint">Drag an area by its edge to move it, or click the edge to edit its corners. Inside it, the map pans as usual.</p>+ <p class="hint" class:warn={tooMany}>{[+ `${round(cost.km2, cost.km2 < 10 ? 2 : 0)} km²`,+ Number.isFinite(cost.tiles) ? plural(cost.tiles, 'tile') : 'over the tile limit',+ tooMany ? '' : `${plural(frames, 'request')}, about ${duration}`,+ ].filter(Boolean).join(' · ')}</p><div class="row"><input class="grow" aria-label="Area set name" bind:value={zonesTitle} maxlength="120" /><button class="btn btn-sm" disabled={busy} onclick={() => act(() => saveAreas())}>Save</button>@@ -560,37 +583,25 @@</section><!-- 2 · Imagery -->- <section class="cmp-step" class:done={compatible && (pinned || !!mapPair)} aria-label="Imagery">+ <section class="cmp-step" class:done={pinned || !!mapPair} aria-label="Imagery"><header><span class="cmp-step-n">2</span><strong>Imagery</strong><span class="chip">{pinned ? 'On the maps' : 'From the maps'}</span></header>{#if tookOver}- <p class="hint">The maps were not showing a source this can analyze, so they now show the one below.</p>+ <p class="hint">Detect reads Sentinel-2, so the maps now show it.</p>{/if}<p class="pair">{#if !single}{sourceLabel(a)} <Icon name="arrowRight" size={11} />{/if} {sourceLabel(b)}</p>- {#if !compatible}<p class="warn">This analyzer supports {recipe.providers.map((p) => p === 'sentinel2' ? 'Sentinel-2' : 'Wayback').join(' and ')}.</p>{/if}- {#if capability.sentinel_only}- <p class="hint">- This analyzer measures Sentinel-2 bands as well as showing the picture, so a run fetches- {single ? 'two frames' : 'four frames'} per tile. All of them count toward your Copernicus usage.- </p>- {/if}<div class="row"><button class="link" onclick={() => (showImagery = !showImagery)} aria-expanded={showImagery}>- {showImagery ? 'Hide imagery settings' : 'Change imagery, dates or the rule…'}+ {showImagery ? 'Hide imagery settings' : 'Change dates or the rule…'}</button>{#if pinned && mapPair && !tookOver}<button class="link" onclick={followMaps}>Back to the map's imagery</button>{/if}</div>{#if showImagery}- <label title="Analyze Wayback or Copernicus Sentinel-2, with one provider for both dates.">Source- <select aria-label="Analyzer source" value={b.provider} onchange={(e) => setProvider(e.currentTarget.value)}>- <option value="esri-wayback">Wayback</option><option value="sentinel2">Copernicus Sentinel-2</option>- </select>- </label><label title="Keep explicit dates, compare to a fixed reference, or use the last completed run.">Dates<select aria-label="Date rule" bind:value={dateRule}><option value="manual">Choose images</option>@@ -598,8 +609,7 @@<option value="latest_previous">Latest against previous run</option></select></label>- {#if b.provider === 'sentinel2'}- {#if !single || dateRule === 'manual'}+ {#if !single || dateRule === 'manual'}<AcquisitionPickerlist={passes}days={passDays}@@ -617,138 +627,134 @@onlook={lookUpPasses}onpick={usePass}/>- {/if}- {#each coverWarnings as note}<p class="warn">{note}</p>{/each}- <label title="Both dates must use the same rendering, or style differences read as change.">Layer- <select value={b.layer} onchange={(e) => { pinned = true; b = { ...b, layer: e.currentTarget.value }; a = { ...a, layer: e.currentTarget.value }; }}>- <option value="TRUE_COLOR">True colour</option><option value="FALSE_COLOR">False colour</option><option value="SWIR">SWIR</option>- </select>- </label>- <label title="Reject scenes above this cloud ceiling; some cloud can remain within a scene.">Maximum cloud cover · {b.maxcc}%- <input type="range" min="0" max="100" value={b.maxcc} oninput={(e) => { pinned = true; b = { ...b, maxcc: Number(e.currentTarget.value) }; a = { ...a, maxcc: Number(e.currentTarget.value) }; }} />- </label>- {:else}- {#each ['a', 'b'] as letter}- {#if (letter === 'b' && dateRule === 'manual') || (letter === 'a' && !single)}- <label>Release {letter.toUpperCase()}- {#if releases.length}- <select aria-label={`Release ${letter.toUpperCase()}`} value={letter === 'a' ? a.release : b.release}- onchange={(e) => {- pinned = true;- const release = Number(e.currentTarget.value);- if (letter === 'a') a = { ...a, release };- else { b = { ...b, release }; if (single) a = { ...a, release }; }- }}>- <option value="">Choose a release</option>- {#each releases as r}<option value={r.release}>{r.date} · {r.release}</option>{/each}- </select>- {:else}- <input type="number" aria-label={`Release ${letter.toUpperCase()}`} min="1" value={letter === 'a' ? a.release : b.release}- oninput={(e) => {- pinned = true;- const release = Number(e.currentTarget.value);- if (letter === 'a') a = { ...a, release };- else { b = { ...b, release }; if (single) a = { ...a, release }; }- }} />- {/if}- </label>- {/if}- {/each}- <p class="hint">Wayback release dates are publication dates, not exact acquisition dates.</p>{/if}+ {#each coverWarnings as note}<p class="warn">{note}</p>{/each}+ <label title="The picture you review. Detection reads the bands, whatever this shows.">Picture+ <select value={b.layer} onchange={(e) => { pinned = true; b = { ...b, layer: e.currentTarget.value }; a = { ...a, layer: e.currentTarget.value }; }}>+ <option value="TRUE_COLOR">True colour</option><option value="FALSE_COLOR">False colour</option><option value="SWIR">SWIR</option>+ </select>+ </label>+ <label title="Reject scenes above this cloud ceiling; some cloud can remain within a scene.">Maximum cloud cover · {b.maxcc}%+ <input type="range" min="0" max="100" value={b.maxcc} oninput={(e) => { pinned = true; b = { ...b, maxcc: Number(e.currentTarget.value) }; a = { ...a, maxcc: Number(e.currentTarget.value) }; }} />+ </label>{#if dateRule !== 'manual'}- <p class="hint">Run looks for recent imagery at that moment. Nothing downloads on its own; save a watch to reuse the previous run as the reference.</p>+ <p class="hint">Run looks up recent passes when you press it. Nothing downloads on its own.</p>{/if}<label class="check" title="Read only the tile cache and frames kept from earlier runs; a missing input stops the run rather than reaching the network."><input type="checkbox" bind:checked={offline} /> Use local images only</label>- {#if offline}- <p class="hint">A finished run only keeps the tiles that found something, so a rerun offline covers what the cache still holds.</p>- {/if}{/if}</section><!-- 3 · What to look for --><section class="cmp-step done" aria-label="What to look for"><header><span class="cmp-step-n">3</span><strong>What to look for</strong></header>- <label>- <select aria-label="Analyzer" value={chosen} onchange={(e) => choose(e.currentTarget.value)}>- <optgroup label="Built in">{#each catalogue?.builtins ?? [] as r}<option value={r.id}>{r.name}</option>{/each}</optgroup>- {#if catalogue?.custom?.length}- <optgroup label="My analyzers">{#each catalogue.custom as r}<option value={r.id}>{r.name}</option>{/each}</optgroup>- {/if}- {#if ![...(catalogue?.builtins ?? []), ...(catalogue?.custom ?? [])].some((r) => r.id === chosen)}- <option value={chosen}>{recipe.name} (from a saved run)</option>- {/if}- </select>- </label>- <p class="hint">{recipe.description}</p>- <CloudFilter- kind={capability.cloud_filter ?? ''}- clouds={weatherOn}- shadows={capability.cloud_filter === 'classes' && recipe.parameters.ignore_shadows}- split={capability.cloud_filter === 'classes'}- ontoggle={setWeather}- />+ <div class="row">+ <label class="grow">+ <select aria-label="Analyzer" value={chosen} onchange={(e) => choose(e.currentTarget.value)}>+ <optgroup label="Built in">{#each catalogue?.builtins ?? [] as r}<option value={r.id}>{r.name}</option>{/each}</optgroup>+ {#if catalogue?.custom?.length}+ <optgroup label="Mine">{#each catalogue.custom as r}<option value={r.id}>{r.name}</option>{/each}</optgroup>+ {/if}+ {#if draft}+ <option value="custom">{recipe.name} — not saved yet</option>+ {:else if ![...(catalogue?.builtins ?? []), ...(catalogue?.custom ?? [])].some((r) => r.id === chosen)}+ <option value={chosen}>{recipe.name} (from a saved run)</option>+ {/if}+ </select>+ </label>+ <button class="cmp-icon" aria-label="New analyzer" aria-expanded={showNew}+ title="Make an analyzer of your own" onclick={() => (showNew = !showNew)}>+ <Icon name="plus" size={15} />+ </button>+ </div>+ {#if showNew}+ <div class="new-menu" role="group" aria-label="New analyzer">+ <button type="button" onclick={() => startNew('copy')}>+ Copy “{recipe.name}”<small>Its settings, under a name of your own.</small>+ </button>+ <button type="button" onclick={() => startNew('blank')}>+ Start from scratch<small>Any surface change, at a medium target size.</small>+ </button>+ </div>+ {/if}+ {#if recipe.description}<p class="hint">{recipe.description}</p>{/if}+ {#if capability.sizes}+ <div class="cmp-seg fill" role="group" aria-label="Target size">+ {#each SIZES as [name, label] (name)}+ {#if capability.sizes[name]}+ <button type="button" class:on={size === name} aria-pressed={size === name}+ title={sizeBand(capability.sizes[name])}+ onclick={() => setSize(name)}>{label}</button>+ {/if}+ {/each}+ </div>+ <p class="hint">+ {size ? sizeBand(capability.sizes[size]) : 'Sizes are set by hand below.'}+ </p>+ {/if}+ {#if capability.clouds}+ <CloudFilter+ clouds={recipe.parameters.ignore_clouds}+ shadows={recipe.parameters.ignore_shadows}+ ontoggle={setWeather}+ />+ {/if}<div class="row"><button class="link" onclick={() => (showDetection = !showDetection)} aria-expanded={showDetection}>{showDetection ? 'Hide thresholds' : 'Adjust thresholds…'}</button><button class="link" onclick={() => (showRecipe = !showRecipe)} aria-expanded={showRecipe}>- {showRecipe ? 'Hide analyzer' : 'Edit or duplicate…'}+ {showRecipe ? 'Hide this analyzer' : mine || draft ? 'Edit this analyzer…' : 'See how it is built…'}</button></div>{#if showDetection}- <label title="Higher values retain weaker differences and usually produce more noise.">Sensitivity · {recipe.parameters.sensitivity}+ <label title="Higher finds fainter signals, and more noise with them.">Sensitivity · {recipe.parameters.sensitivity}<input aria-label="Analyzer sensitivity" type="range" min="0" max="100" bind:value={recipe.parameters.sensitivity} /></label>- <label title="Drop candidate regions smaller than this ground area after grouping.">Minimum area (m²)- <input type="number" min="0" max="100000000" bind:value={recipe.parameters.min_area} />- </label>- <label title="Filter on visual signal strength. This is not the probability that an object was identified.">Minimum signal score · {recipe.parameters.min_score}- <input type="range" min="0" max="1" step="0.01" bind:value={recipe.parameters.min_score} />- </label>+ <div class="row">+ <label class="grow" title="Drop candidates smaller than this.">Min area (m²)+ <input aria-label="Minimum area" type="number" min="0" max="100000000" bind:value={recipe.parameters.min_area} />+ </label>+ <label class="grow" title="Drop candidates larger than this; 0 keeps them all.">Max area (m²)+ <input aria-label="Maximum area" type="number" min="0" max="100000000" bind:value={recipe.parameters.max_area} />+ </label>+ </div>{#if recipe.method === 'index'}- <label title="NDVI: vegetation; NDWI: water; NBR: burn scars; NDBI: built-up or bare ground.">Index- <select bind:value={recipe.parameters.index}>{#each ['ndvi', 'ndwi', 'nbr', 'ndbi'] as index}<option value={index}>{index.toUpperCase()}</option>{/each}</select>+ <label>Index+ <select aria-label="Spectral index" bind:value={recipe.parameters.index}>+ {#each INDICES as [id, label] (id)}<option value={id}>{label}</option>{/each}+ </select></label>{/if}- {#if capability.cloud_filter === 'classes'}- <label class="check"><input type="checkbox" bind:checked={recipe.parameters.ignore_clouds} /> Exclude cloud and snow pixels</label>- <label class="check"><input type="checkbox" bind:checked={recipe.parameters.ignore_shadows} /> Exclude shadow pixels</label>+ {#if !single}+ <label title="Keep what brightened, what darkened, or both.">Direction+ <select bind:value={recipe.parameters.direction}><option value="both">Both</option><option value="gain">Gain</option><option value="loss">Loss</option></select>+ </label>{/if}- {#if capability.cloud_filter}- <label title="Grow the cloud and shadow mask, to take the soft edge a mask leaves behind.">Mask margin · {recipe.parameters.cloud_margin}px+ {#if capability.clouds}+ <label class="check"><input type="checkbox" bind:checked={recipe.parameters.ignore_clouds} /> Exclude cloud and snow</label>+ <label class="check"><input type="checkbox" bind:checked={recipe.parameters.ignore_shadows} /> Exclude cloud shadow</label>+ <label title="Grow the mask past the edge the classification drew.">Mask margin · {recipe.parameters.cloud_margin}px<input aria-label="Cloud mask margin" type="range" min="0" max="10" bind:value={recipe.parameters.cloud_margin} /></label>{/if}<details><summary>Noise and grouping</summary>- <label title="Remove small speckles; stronger cleanup also removes small real objects.">Noise cleanup · {recipe.parameters.cleanup}px<input type="range" min="0" max="3" bind:value={recipe.parameters.cleanup} /></label>- <label title="Blur the difference before detecting regions; zero preserves small details.">Smoothing · {recipe.parameters.smoothing}px<input type="range" min="0" max="3" bind:value={recipe.parameters.smoothing} /></label>- <label title="Merge nearby candidate boxes; zero joins only overlapping or touching boxes.">Group within (m)<input type="number" min="0" max="500" bind:value={recipe.parameters.merge_metres} /></label>- {#if !single}- <label title="Keep strengthening, weakening or both directions of the signal.">Direction- <select bind:value={recipe.parameters.direction}><option value="both">Both</option><option value="gain">Gain</option><option value="loss">Loss</option></select>- </label>- {/if}- {#if !capability.sentinel_only}- <label class="check" title="Reduce lighting differences; this can also suppress broad real changes."><input type="checkbox" bind:checked={recipe.parameters.normalize} /> Correct overall brightness differences</label>- {/if}+ <label title="Remove specks narrower than this; it also removes small real objects.">Noise cleanup · {recipe.parameters.cleanup}px<input type="range" min="0" max="3" bind:value={recipe.parameters.cleanup} /></label>+ <label title="Blur the reading first; zero keeps the finest detail.">Smoothing · {recipe.parameters.smoothing}px<input type="range" min="0" max="3" bind:value={recipe.parameters.smoothing} /></label>+ <label title="Join candidates this close; zero joins only touching ones.">Group within (m)<input type="number" min="0" max="500" bind:value={recipe.parameters.merge_metres} /></label></details>{/if}{#if showRecipe}<label title="The name shown in the analyzer library across all cases.">Name<input aria-label="Analyzer name" bind:value={recipe.name} maxlength="120" /></label><label title="What this analyzer looks for, and what it cannot tell you.">Description<textarea bind:value={recipe.description} maxlength="500"></textarea></label>- <label title="The label each candidate carries. It does not change what the method can detect.">Candidate label<input bind:value={recipe.phenomenon} maxlength="120" /></label>- <label title="The local image-processing method. These analyzers measure signal; they do not recognize object identities.">Method- <select aria-label="Analyzer method" bind:value={recipe.method}- onchange={() => { if (methodOf(recipe.method).sentinel_only) { recipe.providers = ['sentinel2']; setProvider('sentinel2'); } }}>+ <label title="The label each candidate carries. It does not change what is detected.">Candidate label<input bind:value={recipe.phenomenon} maxlength="120" /></label>+ <label title="What is measured. None of these recognise objects.">Method+ <select aria-label="Analyzer method" bind:value={recipe.method}>{#each catalogue?.methods ?? [] as method}<option value={method.id}>{method.label}</option>{/each}</select></label>- <label class="check"><input type="checkbox" value="esri-wayback" bind:group={recipe.providers} disabled={capability.sentinel_only} /> Works on Wayback</label>- <label class="check"><input type="checkbox" value="sentinel2" bind:group={recipe.providers} /> Works on Copernicus Sentinel-2</label><div class="row"><label class="grow">Colour<input type="color" bind:value={recipe.colour} /></label><label class="grow">Layer style@@ -761,10 +767,22 @@<input type="checkbox" bind:checked={attachZones} /> Keep these areas with the analyzer</label><div class="row">- <button class="btn btn-sm" disabled={busy} onclick={() => act(() => saveRecipe())}>Save analyzer</button>- <button class="btn btn-sm" disabled={busy} onclick={() => act(() => saveRecipe(true))}>Duplicate</button>+ {#if mine || draft}+ <button class="btn btn-sm" disabled={busy} onclick={() => act(() => saveRecipe())}>+ {draft ? 'Add to my analyzers' : 'Save changes'}+ </button>+ {/if}+ {#if !draft}+ <button class="btn btn-sm" disabled={busy} onclick={() => act(() => saveRecipe(true))}>Save as a copy</button>+ {/if}+ {#if mine}+ <button class="btn btn-sm danger" disabled={busy} onclick={() => act(() => deleteRecipe())}>Delete</button>+ {/if}</div>- <p class="hint">Analyzers are shared by every case and travel in Settings backup.</p>+ <p class="hint">+ {mine || draft ? 'Shared by every case, and carried by Settings backup.'+ : 'A built-in cannot be written over. Saving a copy keeps your version beside it.'}+ </p>{/if}</section>{/if}@@ -772,8 +790,17 @@{#if view === 'results'}{#if current}<section class="run">- <strong>{current.title}</strong>- <p class="hint">{statusLabel(current.status)} · {current.progress}/{current.total} tiles</p>+ <div class="row run-head">+ <strong class="grow">{current.title}</strong>+ {#if current.status === 'ready'}+ <button class="link" onclick={() => { hydrate(current.input); view = 'setup'; }}>Edit and rerun</button>+ {/if}+ </div>+ <p class="hint">{[+ statusLabel(current.status),+ current.status === 'ready' ? plural(current.total, 'tile') : `${current.progress}/${current.total} tiles`,+ current.input?.b ? dates(current.input) : '',+ ].filter(Boolean).join(' · ')}</p>{#if pending}<progress max={current.total} value={current.progress}></progress><button class="btn btn-sm" disabled={busy}@@ -782,15 +809,7 @@{#if current.message}<p class="hint" role="status">{current.message}</p>{/if}<!-- "Nothing found" and "never looked" are not the same answer. -->{#if sweptNote(current.swept)}<p class="warn">{sweptNote(current.swept)}</p>{/if}- {#if current.status === 'ready'}- <p class="hint">- {#if methodOf(current.input.recipe.method).single}{sourceLabel(current.input.b)}- {:else}{sourceLabel(current.input.a)} → {sourceLabel(current.input.b)}{/if}- </p>- <p class="hint">{current.input.recipe.name} · {current.input.recipe.method} · engine {current.engine_version}</p>- <button class="btn btn-sm" onclick={() => { hydrate(current.input); view = 'setup'; }}>Edit settings and run again</button>- {#if !candidates.length}<p class="hint">Nothing passed these filters. That is not evidence that nothing changed.</p>{/if}- {/if}+ {#if current.status === 'ready' && !candidates.length}<p class="hint">Nothing passed these thresholds.</p>{/if}</section>{:else}<p class="hint">Run an analyzer, or open a saved run from Saved.</p>@@ -800,25 +819,26 @@<section class="candidate"><div class="row nav"><button class="cmp-icon" aria-label="Previous candidate" onclick={() => step(-1)}><Icon name="chevronLeft" size={14} /></button>- <span class="grow centre">Candidate {candidates.findIndex((r) => r.id === candidateId) + 1} of {candidates.length}</span>+ <span class="grow centre position">{candidates.findIndex((r) => r.id === candidateId) + 1} of {candidates.length}</span><button class="cmp-icon" aria-label="Next candidate" onclick={() => step(1)}><Icon name="chevronRight" size={14} /></button></div><strong>{candidate.phenomenon}</strong>- <img class="preview" src={`${base()}/runs/${current.id}/results/${candidate.id}/preview?part=${part}`}- alt={single ? 'Candidate evidence' : 'Candidate evidence: A on the left, B on the right'} />- {#if candidate.parts.length > 1}- <label>Evidence part<select bind:value={part}>{#each candidate.parts as _, i}<option value={i}>{i + 1} of {candidate.parts.length}</option>{/each}</select></label>+ <img class="preview" src={`${base()}/runs/${current.id}/results/${candidate.id}/preview`}+ alt={methodOf(current.input.recipe.method).single ? 'Candidate evidence' : 'Candidate evidence: A on the left, B on the right'} />+ {#if reading(candidate, current.input)}+ <p class={`strength ${candidate.strength ?? ''}`}>{reading(candidate, current.input)}</p>{/if}- <p class="facts">{Math.round(candidate.area)} m² · {Math.round(candidate.width)} × {Math.round(candidate.height)} m</p>- <p class="hint">Signal score {Math.round(candidate.signal_score * 100)}% · not a calibrated confidence</p>- <button class="link" onclick={() => focus(candidate.coordinates)}>- {candidate.coordinates[1].toFixed(6)}, {candidate.coordinates[0].toFixed(6)}- </button>+ <p class="facts">+ {Math.round(candidate.area)} m² · {Math.round(candidate.width)} × {Math.round(candidate.height)} m ·+ <button class="link inline" onclick={() => focus(candidate.coordinates)}>+ {candidate.coordinates[1].toFixed(5)}, {candidate.coordinates[0].toFixed(5)}+ </button>+ </p><!-- Two verdicts and nothing in between: keeping is what writes to thecase, dismissing is what takes a candidate off the map. -->{#if candidate.review === 'kept'}- <p class="verdict kept"><Icon name="check" size={13} /> Kept · in this case as a pin</p>+ <p class="verdict kept"><Icon name="check" size={13} /> Kept as a pin in this case</p><button class="link" disabled={busy} onclick={() => act(undoKeep)}>Undo and send the pin to Trash</button>{:else if candidate.review === 'dismissed'}<p class="verdict off"><Icon name="eyeOff" size={13} /> Dismissed · hidden on the map</p>@@ -828,7 +848,6 @@<button class="btn btn-primary grow" disabled={busy} onclick={() => act(keep)}>Keep as a pin</button><button class="btn btn-sm" disabled={busy} onclick={() => act(() => review('dismissed'))}>Dismiss</button></div>- <p class="hint">Keeping files this one candidate and its evidence in the case. Nothing else here reaches it.</p>{/if}<p class="hint">{tally}</p></section>@@ -843,7 +862,7 @@onclick={() => { layer.visible = !layer.visible; }}><Icon name={layer.visible ? 'eye' : 'eyeOff'} size={15} /></button>- <button class="link grow" onclick={() => { current = layer; candidateId = layer.results[0]?.id; part = 0; }}>+ <button class="link grow" onclick={() => { current = layer; candidateId = layer.results[0]?.id; }}>{layer.title} · {layer.count}</button></div>@@ -855,7 +874,7 @@{#if view === 'saved'}<section><strong>Watches</strong>- <p class="hint">An analyzer, its areas and a date rule, kept together. Run it again whenever you want a fresh pass; nothing runs on its own.</p>+ <p class="hint">An analyzer, its areas and a date rule. Run one again whenever you want; nothing runs on its own.</p>{#if !lists.followups.length}<p class="hint">None saved in this case.</p>{/if}{#each lists.followups as row (row.id)}<div class="row">@@ -909,6 +928,28 @@<style>.views { margin: 10px 12px 0; }+ /* The two ways to start one of your own, said in full rather than implied by+ a "duplicate" button next to a save. */+ .new-menu {+ display: grid;+ gap: 2px;+ padding: 4px;+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ background: var(--bg-2);+ }+ .new-menu button {+ display: grid;+ gap: 1px;+ padding: 6px 8px;+ border-radius: var(--r-sm);+ text-align: left;+ font-size: var(--fs-xs);+ color: var(--text-1);+ }+ .new-menu button:hover { background: var(--bg-3); }+ .new-menu small { color: var(--text-3); font-size: 10.5px; }+ .btn.danger { color: var(--warn); }.row.wrap { flex-wrap: wrap; }.area-row input { font-size: var(--fs-xs); }.count {@@ -935,18 +976,23 @@font-size: var(--fs-xs);overflow-wrap: anywhere;}- section { display: grid; gap: 8px; }+ section { display: grid; gap: 7px; }section.run, section.candidate { border-top: 1px solid var(--border); padding-top: 10px; }- section > strong { font-size: var(--fs-xs); }+ section > strong, .run-head strong { font-size: var(--fs-xs); }details { display: grid; gap: 8px; }details[open] { padding-top: 4px; }summary { color: var(--text-2); font-size: var(--fs-xs); cursor: pointer; }.link { color: var(--accent); font-size: var(--fs-xs); text-align: left; }.link:disabled { opacity: 0.5; }.link small { display: block; color: var(--text-3); font-size: 10px; }+ .link.inline { display: inline; font-family: var(--font-mono); font-size: 11px; }.centre { text-align: center; }.nav { justify-content: space-between; }- .facts { margin: 0; font-size: var(--fs-xs); }+ .position { color: var(--text-2); font-size: var(--fs-xs); }+ .facts { margin: 0; color: var(--text-2); font-size: var(--fs-xs); line-height: 1.5; }+ .strength { margin: 0; font-size: var(--fs-xs); font-weight: 600; color: var(--text-1); }+ .strength.strong { color: var(--ok); }+ .strength.weak { color: var(--text-3); }.verdict { display: flex; align-items: center; gap: 5px; margin: 0; font-size: var(--fs-xs); font-weight: 600; }.verdict.kept { color: var(--ok); }.verdict.off { color: var(--text-3); }diff --git a/frontend/src/tools/compare/AnalyzerPanel.test.js b/frontend/src/tools/compare/AnalyzerPanel.test.jsindex 427f12b..b300f5f 100644--- a/frontend/src/tools/compare/AnalyzerPanel.test.js+++ b/frontend/src/tools/compare/AnalyzerPanel.test.js@@ -2,30 +2,46 @@import { beforeEach, afterEach, expect, it, vi } from 'vitest';import { flushSync, mount, unmount } from 'svelte';-const recipe = { id: 'large-change', name: 'Large surface change', description: 'Candidate changes',- phenomenon: 'Change', method: 'colour', providers: ['esri-wayback', 'sentinel2'], zones: [],- colour: '#f6a81a', style: 'both', parameters: { sensitivity: 55, min_area: 20, min_score: 0,- cleanup: 1, smoothing: 0, normalize: false, index: 'ndvi', direction: 'both',- ignore_clouds: true, ignore_shadows: true, merge_metres: 0 } };+const sizes = {+ small: { min_area: 300, max_area: 0, cleanup: 0, smoothing: 0, merge_metres: 0 },+ medium: { min_area: 2000, max_area: 0, cleanup: 1, smoothing: 0, merge_metres: 30 },+ large: { min_area: 20000, max_area: 0, cleanup: 1, smoothing: 1, merge_metres: 100 },+};+const recipe = { id: 'large-change', name: 'Any surface change', description: 'Reflectance that moved',+ phenomenon: 'Surface change', method: 'surface', zones: [], colour: '#f6a81a', style: 'both',+ parameters: { sensitivity: 67, ...sizes.medium, index: 'ndvi', direction: 'both',+ ignore_clouds: true, ignore_shadows: true, cloud_margin: 5 } };+const vessels = { ...recipe, id: 'boats', name: 'Vessels', method: 'vessels', phenomenon: 'Vessel candidate' };+const methods = [+ { id: 'surface', label: 'Any reflectance change', single: false, clouds: true, sizes,+ measure: 'Reflectance moved by {value}%' },+ { id: 'vessels', label: 'Vessels', single: true, clouds: true, sizes,+ measure: '{value}× brighter than the water around it' },+ { id: 'hotspots', label: 'Hotspots', single: true, clouds: false, sizes,+ measure: 'Short-wave infrared {value}× the bands beside it' },+];+const catalogue = (extra = {}) => ({ builtins: [structuredClone(recipe), structuredClone(vessels)],+ custom: [], methods, max_tiles: 4096, max_results: 2000, grid: [13, 512], ...extra });const get = vi.fn();const post = vi.fn();const patch = vi.fn();-vi.mock('../../lib/api.js', () => ({ api: { get, post, patch, put: vi.fn(), del: vi.fn() } }));+const del = vi.fn();+vi.mock('../../lib/api.js', () => ({ api: { get, post, patch, put: vi.fn(), del } }));vi.mock('../../lib/state.svelte.js', () => ({ ensureCase: async () => ({ id: 'case-a' }),reloadCase: async () => {}, toast: vi.fn() }));const { default: Panel } = await import('./AnalyzerPanel.svelte');let live, target;const settle = async () => { for (let i = 0; i < 50; i++) await Promise.resolve(); flushSync(); };const button = (text) => [...target.querySelectorAll('button')].find((b) => b.textContent.trim() === text);-const wayback = { a: { provider: 'esri-wayback', wayback_release: 1 },- b: { provider: 'esri-wayback', wayback_release: 2 } };+const maps = {+ a: { provider: 'sentinel2', sentinel: { date: '2026-05-04', layer: 'TRUE_COLOR', maxcc: 30 } },+ b: { provider: 'sentinel2', sentinel: { date: '2026-05-11', layer: 'TRUE_COLOR', maxcc: 30 } },+};+const area = [{ id: 'area', name: 'Area', kind: 'rect', points: [[2, 48], [2.001, 48.001]] }];beforeEach(() => {vi.clearAllMocks();- get.mockImplementation(async (path) => path === '/api/compare/analyzers'- ? { builtins: [structuredClone(recipe)], custom: [], methods: [{ id: 'colour', label: 'Colour' }],- max_tiles: 256, max_results: 2000, grids: { sentinel2: [13, 512], 'esri-wayback': [19, 256] } }- : []);+ get.mockImplementation(async (path) => path === '/api/compare/analyzers' ? catalogue() : []);target = document.createElement('div'); document.body.append(target);});afterEach(() => { if (live) unmount(live); target.remove(); });@@ -43,56 +59,130 @@ it('opening reads local libraries without downloading imagery or starting a calc});it('takes its imagery from the two maps, and only Run sends anything', async () => {- const zones = [{ id: 'area', name: 'Area', kind: 'rect', points: [[2, 48], [2.001, 48.001]] }];post.mockImplementation(async (_, body) => ({ id: '123456789abc', title: body.title,status: 'failed', message: 'Offline fixture', progress: 0, total: 1, input: body, results: [] }));- live = mount(Panel, { target, props: { caseId: 'case-a', zones, sources: wayback } });+ live = mount(Panel, { target, props: { caseId: 'case-a', zones: area, sources: maps } });await settle();// No click on an imagery control: the maps above the stage already said it.expect(target.textContent).toContain('From the maps');+ expect(target.textContent).toContain('2026-05-04');expect(post).not.toHaveBeenCalled();button('Run on 1 area').click(); await settle();expect(post).toHaveBeenCalledWith('/api/cases/case-a/analysis/runs', expect.objectContaining({- zones, a: expect.objectContaining({ release: 1 }), b: expect.objectContaining({ release: 2 }),+ zones: area,+ a: { provider: 'sentinel2', date: '2026-05-04', layer: 'TRUE_COLOR', maxcc: 30 },+ b: { provider: 'sentinel2', date: '2026-05-11', layer: 'TRUE_COLOR', maxcc: 30 },}));expect(target.textContent).toContain('Offline fixture');});-it('prices an area in tiles and refuses one the engine would reject', async () => {- const zones = [{ id: 'big', name: 'Whole region', kind: 'rect', points: [[2, 48], [3, 49]] }];- live = mount(Panel, { target, props: { caseId: 'case-a', zones, sources: wayback } });+it('takes the wheel when the maps show imagery Detect cannot read', async () => {+ const onsources = vi.fn();+ const wayback = { a: { provider: 'esri-wayback', wayback_release: 1 }, b: { provider: 'esri-wayback', wayback_release: 2 } };+ live = mount(Panel, { target, props: { caseId: 'case-a', zones: area, sources: wayback, onsources } });await settle();- expect(target.textContent).toContain('tiles of 256px');+ expect(target.textContent).toContain('Detect reads Sentinel-2, so the maps now show it.');+ expect(onsources).toHaveBeenCalledWith(expect.objectContaining({+ a: expect.objectContaining({ provider: 'sentinel2' }), b: expect.objectContaining({ provider: 'sentinel2' }),+ }));+ expect(target.querySelector('select[aria-label="Analyzer source"]')).toBe(null);expect(button('Run on 1 area').disabled).toBe(true);- expect(target.textContent).toContain('256-tile limit');+ expect(target.textContent).toContain('Choose the image to compare');+});++it('prices an area in tiles and requests, and refuses one the engine would reject', async () => {+ const zones = [{ id: 'big', name: 'Whole region', kind: 'rect', points: [[2, 48], [8, 54]] }];+ get.mockImplementation(async (path) => path === '/api/compare/analyzers' ? catalogue({ max_tiles: 256 }) : []);+ live = mount(Panel, { target, props: { caseId: 'case-a', zones, sources: maps } });+ await settle();+ expect(button('Run on 1 area').disabled).toBe(true);+ expect(target.textContent).toContain('the limit is 256');+ unmount(live); target.remove();+ target = document.createElement('div'); document.body.append(target);+ live = mount(Panel, { target, props: { caseId: 'case-a', zones: area, sources: maps } });+ await settle();+ // one tile, a picture and a band product for each of two dates+ expect(target.textContent).toContain('1 tile · 4 requests');expect(post).not.toHaveBeenCalled();});-it('duplicates a built-in analyzer under a name of its own', async () => {+it('sets a size as a whole set of numbers, and shows when it was tuned by hand', async () => {+ live = mount(Panel, { target, props: { caseId: 'case-a' } });+ await settle();+ const pressed = () => [...target.querySelectorAll('[aria-label="Target size"] button')]+ .filter((b) => b.getAttribute('aria-pressed') === 'true').map((b) => b.textContent.trim());+ expect(pressed()).toEqual(['Medium']);+ button('Small').click(); await settle();+ expect(pressed()).toEqual(['Small']);+ button('Adjust thresholds…').click(); await settle();+ expect(target.querySelector('[aria-label="Minimum area"]').value).toBe('300');+ const minimum = target.querySelector('[aria-label="Minimum area"]');+ minimum.value = '120'; minimum.dispatchEvent(new Event('input', { bubbles: true })); await settle();+ expect(pressed()).toEqual([]);+});++it('offers the cloud switch on by default, and none for a method that rejects cloud itself', async () => {+ live = mount(Panel, { target, props: { caseId: 'case-a' } });+ await settle();+ const chip = [...target.querySelectorAll('button')].find((b) => b.textContent.includes('Clouds & shadows'));+ expect(chip.getAttribute('aria-pressed')).toBe('true');+ expect(target.textContent).toContain('traced from the sun');+ unmount(live); target.remove();+ target = document.createElement('div'); document.body.append(target);+ get.mockImplementation(async (path) => path === '/api/compare/analyzers'+ ? catalogue({ builtins: [{ ...structuredClone(recipe), id: 'anomaly', method: 'hotspots' }] }) : []);+ live = mount(Panel, { target, props: { caseId: 'case-a' } });+ await settle();+ expect(target.textContent).not.toContain('Clouds & shadows');+});++it('starts an analyzer of your own from the plus, and cannot write over a built-in', async () => {post.mockImplementation(async (_, body) => ({ ...body, id: 'custom-copy' }));live = mount(Panel, { target, props: { caseId: 'case-a' } }); await settle();- button('Edit or duplicate…').click(); await settle();+ // A built-in offers to be read and copied, never saved over.+ button('See how it is built…').click(); await settle();+ expect(target.textContent).not.toContain('Works on Wayback');+ expect(button('Save changes')).toBeUndefined();+ expect(button('Delete')).toBeUndefined();+ button('Hide this analyzer').click(); await settle();++ target.querySelector('button[aria-label="New analyzer"]').click(); await settle();+ const copy = [...target.querySelectorAll('.new-menu button')]+ .find((entry) => entry.textContent.includes(`Copy “${recipe.name}”`));+ copy.click(); await settle();+ expect(target.querySelector('[aria-label="Analyzer"]').value).toBe('custom');+ expect(target.textContent).toContain('not saved yet');const name = target.querySelector('[aria-label="Analyzer name"]');+ expect(name.value).toBe(`${recipe.name} copy`);name.value = 'Weekly harbour'; name.dispatchEvent(new Event('input', { bubbles: true }));- button('Duplicate').click(); await settle();+ button('Add to my analyzers').click(); await settle();expect(post).toHaveBeenCalledWith('/api/compare/analyzers', expect.objectContaining({ id: 'custom', name: 'Weekly harbour' }));});-it('reviews candidates one at a time, and only keeping reaches the case', async () => {- const zones = [{ id: 'area', name: 'Area', kind: 'rect', points: [[2, 48], [2.001, 48.001]] }];- const row = (id, lon) => ({ id, coordinates: [lon, 48], bbox: [lon, 48, lon + 0.001, 48.001],- area: 90, width: 15, height: 6, signal_score: 0.8, confidence: null, review: 'new',- phenomenon: 'Surface change', parts: [{ frames: ['a', 'b'], box: [0, 0, 4, 4] }] });+it('edits and removes an analyzer of its own, which the library never did offer', async () => {+ const own = { ...structuredClone(recipe), id: 'custom-1', name: 'Weekly harbour' };+ get.mockImplementation(async (path) => path === '/api/compare/analyzers' ? catalogue({ custom: [own] }) : []);+ live = mount(Panel, { target, props: { caseId: 'case-a' } }); await settle();+ const select = target.querySelector('[aria-label="Analyzer"]');+ select.value = 'custom-1'; select.dispatchEvent(new Event('change', { bubbles: true }));+ await settle();+ button('Edit this analyzer…').click(); await settle();+ expect(button('Save changes')).toBeDefined();+ button('Delete').click(); await settle();+ expect(del).toHaveBeenCalledWith('/api/compare/analyzers/custom-1');+});++it('reviews candidates one at a time, says how strong each is, and only keeping reaches the case', async () => {+ const row = (id, lon, strength, value) => ({ id, coordinates: [lon, 48], bbox: [lon, 48, lon + 0.001, 48.001],+ area: 90, width: 15, height: 6, margin: 2, strength, measure: { value }, review: 'new',+ phenomenon: 'Surface change', parts: [{ frames: ['a', 'b'], box: [0, 0, 4, 4] }, { frames: ['c', 'd'], box: [0, 0, 2, 4] }] });const saved = { id: '123456789abc', title: 'Harbour sweep', status: 'ready', progress: 1, total: 1,- count: 2, engine_version: 1, results: [row('0-1', 2), row('0-2', 2.002)],- input: { title: 'Harbour sweep', zones, recipe: structuredClone(recipe),- a: { provider: 'esri-wayback', release: 1 }, b: { provider: 'esri-wayback', release: 2 },+ count: 2, engine_version: 2, results: [row('0-1', 2, 'strong', 12.34), row('0-2', 2.002, 'weak', 8)],+ input: { title: 'Harbour sweep', zones: area, recipe: structuredClone(recipe),+ a: { provider: 'sentinel2', date: '2026-05-04' }, b: { provider: 'sentinel2', date: '2026-05-11' },offline: false, date_rule: 'manual', followup_id: null } };get.mockImplementation(async (path) => {- if (path === '/api/compare/analyzers') {- return { builtins: [structuredClone(recipe)], custom: [], methods: [{ id: 'colour', label: 'Colour' }],- max_tiles: 4096, max_results: 2000, grids: { 'esri-wayback': [19, 256] } };- }+ if (path === '/api/compare/analyzers') return catalogue();if (path === '/api/cases/case-a/analysis/runs/123456789abc') return structuredClone(saved);return [];});@@ -102,47 +192,43 @@ it('reviews candidates one at a time, and only keeping reaches the case', asynclive = mount(Panel, { target, props: { caseId: 'case-a', opening: 'runs-123456789abc' } });await settle();- expect(target.textContent).toContain('Candidate 1 of 2');+ expect(target.textContent).toContain('1 of 2');+ expect(target.textContent).toContain('Completed · 1 tile · 2026-05-04 → 2026-05-11');+ expect(target.textContent).toContain('Strong · Reflectance moved by 12.3%');expect(target.textContent).toContain('2 still to review · 0 kept, 0 dismissed');+ // a candidate across two tiles is one picture, not pages of parts+ expect(target.textContent).not.toContain('Evidence part');+ expect(target.textContent).not.toContain('Signal score');+ expect(target.querySelector('img.preview').getAttribute('src')).toBe(+ '/api/cases/case-a/analysis/runs/123456789abc/results/0-1/preview');// Dismissing is a verdict on this one, and it moves on to the next.button('Dismiss').click(); await settle();expect(patch).toHaveBeenCalledWith('/api/cases/case-a/analysis/runs/123456789abc/results/0-1', { review: 'dismissed' });expect(post).not.toHaveBeenCalled();- expect(target.textContent).toContain('Candidate 2 of 2');+ expect(target.textContent).toContain('2 of 2');+ expect(target.textContent).toContain('Weak · Reflectance moved by 8.0%');// Keeping is the one act that files a pin, and it says so where it happened.button('Keep as a pin').click(); await settle();expect(post).toHaveBeenCalledWith('/api/cases/case-a/analysis/runs/123456789abc/results/0-2/promote',{ title: 'Surface change · 48.0000, 2.0020' });- expect(target.textContent).toContain('Kept · in this case as a pin');+ expect(target.textContent).toContain('Kept as a pin in this case');expect(target.textContent).toContain('All 2 reviewed · 1 kept, 1 dismissed');});-const sentinelCatalogue = (methods) => ({- builtins: [structuredClone(recipe)], custom: [], methods,- max_tiles: 4096, max_results: 2000, grids: { sentinel2: [13, 512], 'esri-wayback': [19, 256] },-});-const sentinelMaps = {- a: { provider: 'sentinel2', sentinel: { date: '2026-05-04', layer: 'TRUE_COLOR', maxcc: 30 } },- b: { provider: 'sentinel2', sentinel: { date: '2026-05-11', layer: 'TRUE_COLOR', maxcc: 30 } },-};-it('picks Copernicus dates from passes the areas have, not from a calendar', async () => {- const zones = [{ id: 'area', name: 'Area', kind: 'rect', points: [[2, 48], [2.001, 48.001]] }];- get.mockImplementation(async (path) => path === '/api/compare/analyzers'- ? sentinelCatalogue([{ id: 'colour', label: 'Colour', cloud_filter: 'picture' }]) : []);post.mockImplementation(async (path) => path === '/api/satellite/sentinel/acquisitions'? { dates: [{ date: '2026-05-11', cloud: 3, granules: 2, coverage: 1 },{ date: '2026-05-04', cloud: 12, granules: 1, coverage: 0.62 },], truncated: false }: {});- live = mount(Panel, { target, props: { caseId: 'case-a', zones, sources: sentinelMaps } });+ live = mount(Panel, { target, props: { caseId: 'case-a', zones: area, sources: maps } });await settle();- button('Change imagery, dates or the rule…').click(); await settle();+ button('Change dates or the rule…').click(); await settle();// a bare date field offered every day since 2015 and knew nothing about anyexpect(target.querySelector('input[type="date"]')).toBe(null);@@ -151,59 +237,31 @@ it('picks Copernicus dates from passes the areas have, not from a calendar', asybutton('Find passes').click(); await settle();expect(post).toHaveBeenCalledWith('/api/satellite/sentinel/acquisitions',- expect.objectContaining({ zones }));+ expect.objectContaining({ zones: area }));expect(target.textContent).toContain('Full cover');expect(target.textContent).toContain('62% of the areas');});it('says what a partial pass will leave unswept before the run, not after', async () => {- const zones = [{ id: 'area', name: 'Area', kind: 'rect', points: [[2, 48], [2.001, 48.001]] }];- get.mockImplementation(async (path) => path === '/api/compare/analyzers'- ? sentinelCatalogue([{ id: 'colour', label: 'Colour', cloud_filter: 'picture' }]) : []);post.mockImplementation(async () => ({dates: [{ date: '2026-05-04', cloud: 12, granules: 1, coverage: 0.62 }], truncated: false,}));- live = mount(Panel, { target, props: { caseId: 'case-a', zones, sources: sentinelMaps } });+ live = mount(Panel, { target, props: { caseId: 'case-a', zones: area, sources: maps } });await settle();- button('Change imagery, dates or the rule…').click(); await settle();+ button('Change dates or the rule…').click(); await settle();button('Find passes').click(); await settle();button('B').click(); await settle();expect(target.textContent).toContain('reaches 62% of the areas');expect(target.textContent).toContain('not swept');});-it('offers the cloud guess off, and says it is a guess', async () => {- get.mockImplementation(async (path) => path === '/api/compare/analyzers'- ? sentinelCatalogue([{ id: 'colour', label: 'Colour', cloud_filter: 'picture' }]) : []);- live = mount(Panel, { target, props: { caseId: 'case-a', sources: wayback } });- await settle();- const chip = [...target.querySelectorAll('button')].find((b) => b.textContent.includes('Clouds & shadows'));- // a test that cannot tell cloud from a white roof is never on by default- expect(chip.getAttribute('aria-pressed')).toBe('false');- expect(target.textContent).toContain('A guess from the picture');- chip.click(); await settle();- expect(chip.getAttribute('aria-pressed')).toBe('true');-});--it('offers no cloud switch where masking cloud would mask the subject', async () => {- get.mockImplementation(async (path) => path === '/api/compare/analyzers'- ? sentinelCatalogue([{ id: 'colour', label: 'Smoke', cloud_filter: '' }]) : []);- live = mount(Panel, { target, props: { caseId: 'case-a', sources: wayback } });- await settle();- expect(target.textContent).not.toContain('Clouds & shadows');-});-it('runs a saved watch again without asking for its settings twice', async () => {- const zones = [{ id: 'area', name: 'Area', kind: 'rect', points: [[2, 48], [2.001, 48.001]] }];const watch = { id: 'abcdef123456', title: 'Harbour weekly', created_at: '2026-09-01T00:00:00Z',- zones, recipe: structuredClone(recipe), a: { provider: 'esri-wayback', release: 1 },- b: { provider: 'esri-wayback', release: 2 }, offline: false, date_rule: 'latest_previous',+ zones: area, recipe: structuredClone(recipe), a: { provider: 'sentinel2', date: '2026-05-04' },+ b: { provider: 'sentinel2', date: '' }, offline: false, date_rule: 'latest_previous',followup_id: 'abcdef123456' };get.mockImplementation(async (path) => {- if (path === '/api/compare/analyzers') {- return { builtins: [structuredClone(recipe)], custom: [], methods: [], max_tiles: 256,- grids: { 'esri-wayback': [19, 256] } };- }+ if (path === '/api/compare/analyzers') return catalogue();if (path === '/api/cases/case-a/analysis/followups') return [{ id: watch.id, title: watch.title, created_at: watch.created_at }];if (path === `/api/cases/case-a/analysis/followups/${watch.id}`) return watch;return [];@@ -215,6 +273,25 @@ it('runs a saved watch again without asking for its settings twice', async () =>button('Saved').click(); await settle();button('Run again').click(); await settle();expect(post).toHaveBeenCalledWith('/api/cases/case-a/analysis/runs', expect.objectContaining({- zones, date_rule: 'latest_previous', followup_id: watch.id,+ zones: area, date_rule: 'latest_previous', followup_id: watch.id,}));});++it('reopens a run saved against Wayback without pretending it had a Sentinel-2 date', async () => {+ const old = { id: 'aaaaaaaaaaaa', title: 'Old harbour', status: 'ready', progress: 1, total: 1, count: 0,+ engine_version: 1, results: [],+ input: { title: 'Old harbour', zones: area, recipe: { ...structuredClone(recipe), method: 'colour' },+ a: { provider: 'esri-wayback', release: 1 }, b: { provider: 'esri-wayback', release: 2 },+ offline: false, date_rule: 'manual', followup_id: null } };+ get.mockImplementation(async (path) => {+ if (path === '/api/compare/analyzers') return catalogue();+ if (path === '/api/cases/case-a/analysis/runs/aaaaaaaaaaaa') return structuredClone(old);+ return [];+ });+ live = mount(Panel, { target, props: { caseId: 'case-a', opening: 'runs-aaaaaaaaaaaa' } });+ await settle();+ expect(target.textContent).toContain('Wayback release 1 → Wayback release 2');+ button('Edit and rerun').click(); await settle();+ expect(target.textContent).toContain('no date yet');+ expect(button('Run on 1 area').disabled).toBe(true);+});diff --git a/frontend/src/tools/compare/AnnotationCanvas.svelte b/frontend/src/tools/compare/AnnotationCanvas.svelteindex 9240eb2..881b137 100644--- a/frontend/src/tools/compare/AnnotationCanvas.svelte+++ b/frontend/src/tools/compare/AnnotationCanvas.svelte@@ -4,7 +4,8 @@let { annotations = [], engine, letter = 'a', units = 'metric', active = true,tool = $bindable('select'), selectedId = $bindable(null), colour = '#f6a81a',- strokeWidth = 4, fillOpacity = 0, annotationSide = 'both', editVertices = false, onchange = () => {} } = $props();+ strokeWidth = 4, fillOpacity = 0, annotationSide = 'both', editVertices = false,+ edgeOnly = false, onchange = () => {} } = $props();let svg = $state();let revision = $state(0);let draft = $state(null);@@ -13,6 +14,10 @@/** Below this, a pointer press is a click: a shape is picked, never nudged. */const DRAG_SLOP = 4;+ // A note is a single anchor and a freehand stroke is hundreds of them, so+ // neither gains anything from grips: one is already dragged whole, the other+ // would be buried under its own handles.+ const GRIPPED = new Set(['arrow', 'line', 'measure', 'rect', 'ellipse', 'polygon']);$effect(() => {if (!engine) return;@@ -35,7 +40,7 @@const marks = $derived.by(() =>[...annotations.filter((mark) => onSide(mark, letter)), ...(draft ? [draft] : [])].map((mark) => ({ mark, shape: projectMark(mark, project), label: markLabel(mark, units),- vertices: editVertices ? mark.points.map(project) : [] }))+ vertices: editVertices && GRIPPED.has(mark.kind) ? mark.points.map(project) : [] })));const pathOf = (shape) => shape.path.map(([x, y], i) => `${i ? 'L' : 'M'}${x},${y}`).join(' ') + (shape.closed ? ' Z' : '');function point(event) {@@ -48,11 +53,42 @@return { id: crypto.randomUUID(), kind: tool, side: annotationSide, colour, points,stroke_width: strokeWidth, fill_opacity: fillOpacity, font_size: 16, text: '' };}+ /**+ * Anchor the tool in hand at a ground point and let the pointer draw the rest.+ *+ * The right-click menu acts on the point under the cursor, so a measure+ * started there already has its first end; the second is taken by the next+ * click rather than by a drag that would have to start somewhere else.+ */+ export function startFrom(at) {+ if (!at || tool === 'select' || tool === 'text' || tool === 'polygon') return;+ draft = makeMark([at, at]);+ gesture = { kind: 'trail', start: at };+ }++ /** The trailing end is set: keep the mark if it spans more than a click. */+ function settle() {+ const first = project(draft.points[0]);+ const last = project(draft.points.at(-1));+ if (Math.hypot(last[0] - first[0], last[1] - first[1]) >= 3) {+ onchange([...annotations, draft], true);+ selectedId = draft.id;+ }+ draft = null;+ gesture = null;+ tool = 'select';+ }+function begin(event) {if (!active || tool === 'select' || event.button > 0) return;const at = point(event);if (!at) return;event.preventDefault();+ if (gesture?.kind === 'trail' && draft) {+ draft = { ...draft, points: [draft.points[0], at] };+ settle();+ return;+ }if (tool === 'text') {editor = { mark: makeMark([at]), value: '' };return;@@ -78,6 +114,10 @@function move(event) {const at = point(event);if (!at) return;+ if (gesture?.kind === 'trail') {+ if (draft) draft = { ...draft, points: [draft.points[0], at] };+ return;+ }if (gesture && !dragging(event)) return;if (gesture?.kind === 'vertex') {const points = gesture.mark.points.map((p, i) => i === gesture.index ? at : p);@@ -93,7 +133,9 @@}}function finish(event) {- if (!gesture) return;+ // A trail is armed, not held: it ends on the next click, not on the release+ // of whatever press happened to be in flight.+ if (!gesture || gesture.kind === 'trail') return;move(event);svg.releasePointerCapture?.(event.pointerId);if (gesture.kind === 'move' || gesture.kind === 'vertex') {@@ -157,6 +199,33 @@editor = null;tool = 'select';}+ // Clicking the ground beside a mark lets it go. With Select in hand the map+ // owns the pointer, so that press never reaches this canvas and has to be read+ // off the document: only a press on a map surface counts, because the rail and+ // the panels are where a selected mark is worked on. A drag is a pan, not a+ // click, so the selection survives one. A Detect area is left out — its middle+ // belongs to the map, so a look inside one would drop the panel's own pick.+ $effect(() => {+ if (!active || !selectedId || tool !== 'select' || edgeOnly) return;+ let from = null;+ const down = (event) => {+ if (event.button > 0 || event.target?.closest?.('.annotation-canvas')) return;+ from = event.target?.closest?.('.map-wrap') ? { x: event.clientX, y: event.clientY } : null;+ };+ const up = (event) => {+ if (from && Math.hypot(event.clientX - from.x, event.clientY - from.y) < DRAG_SLOP) {+ selectedId = null;+ }+ from = null;+ };+ document.addEventListener('pointerdown', down, true);+ document.addEventListener('pointerup', up, true);+ return () => {+ document.removeEventListener('pointerdown', down, true);+ document.removeEventListener('pointerup', up, true);+ };+ });+onMount(() => {const key = (event) => {if (!active || event.target?.closest?.('input, textarea, select')) return;@@ -175,18 +244,18 @@onpointercancel={finish} ondblclick={finishPolygon}>{#each marks as { mark, shape, label, vertices } (mark.id)}<!-- svelte-ignore a11y_no_static_element_interactions -->- <g class="mark" class:area={editVertices} class:selected={selectedId === mark.id} style:color={mark.colour}+ <g class="mark" class:area={edgeOnly} class:selected={selectedId === mark.id} style:color={mark.colour}onpointerdown={(event) => select(event, mark)} ondblclick={(event) => edit(event, mark)}>{#if mark.kind !== 'text'}<path d={pathOf(shape)} stroke={mark.colour} stroke-width={mark.stroke_width}fill={shape.closed ? mark.colour : 'none'} fill-opacity={mark.fill_opacity}stroke-dasharray={mark.kind === 'measure' ? '8 6' : undefined} />- {#if editVertices}- <!-- An area is grabbed by its edge. Its middle belongs to the map, so- dragging inside one pans as it would anywhere else. -->- <path class="edge" d={pathOf(shape)} fill="none" stroke="transparent"- stroke-width={Math.max(16, mark.stroke_width * 4)} />- {/if}+ <!-- A band along the outline, wide enough to hit: a 4px arrow is a+ target nobody can reliably click twice. For an area it is the only+ target, its middle belonging to the map so dragging inside one pans+ as it would anywhere else. -->+ <path class="edge" d={pathOf(shape)} fill="none" stroke="transparent"+ stroke-width={Math.max(16, mark.stroke_width * 4)} />{#if shape.head}<polygon points={shape.head.map((p) => p.join(',')).join(' ')} fill={mark.colour} />{/if}{/if}{#if label}@@ -221,9 +290,9 @@.annotation-canvas { position: absolute; inset: 0; width: 100%; height: 100%; z-index: 550; pointer-events: none; overflow: hidden; }.annotation-canvas.drawing { pointer-events: auto; cursor: crosshair; touch-action: none; }.mark { pointer-events: visiblePainted; cursor: move; }+ .mark .edge { pointer-events: stroke; cursor: move; }.mark.area { pointer-events: none; }- .mark.area .edge { pointer-events: stroke; cursor: move; }- .drawing .mark { pointer-events: none; }+ .drawing .mark, .drawing .mark .edge { pointer-events: none; }.vertex { pointer-events: auto; cursor: crosshair; }.vertex .grip { pointer-events: all; }.mark path { stroke-linecap: round; stroke-linejoin: round; }diff --git a/frontend/src/tools/compare/AnnotationCanvas.test.js b/frontend/src/tools/compare/AnnotationCanvas.test.jsindex 8dbfa5d..c12347f 100644--- a/frontend/src/tools/compare/AnnotationCanvas.test.js+++ b/frontend/src/tools/compare/AnnotationCanvas.test.js@@ -68,11 +68,61 @@ it('treats a press that does not travel as a selection, never as a move', () =>expect(onchange.mock.calls.at(-1)[1]).toBe(true); // one entry to undo, at the end});-it('gives an area an edge to grab, so its middle still belongs to the map', () => {- stage({ annotations: [area()], editVertices: true, tool: 'select' });+it('gives every mark an edge to grab, and an area nothing else', () => {+ stage({ annotations: [area()], tool: 'select' });expect(target.querySelectorAll('.edge')).toHaveLength(1);+ expect(target.querySelector('.mark').classList.contains('area')).toBe(false);unmount(live);- stage({ annotations: [area()], tool: 'select' });- expect(target.querySelectorAll('.edge')).toHaveLength(0);+ // Only a Detect area gives its middle back to the map; an annotation stays+ // grabbable anywhere it is painted.+ stage({ annotations: [area()], edgeOnly: true, tool: 'select' });+ expect(target.querySelector('.mark').classList.contains('area')).toBe(true);+});++it('hands the selected mark its handles, and leaves a note without any', () => {+ stage({ annotations: [area()], editVertices: true, selectedId: 'z1', tool: 'select' });+ expect(target.querySelectorAll('.vertex')).toHaveLength(2);+ unmount(live);++ const note = { ...area(), kind: 'text', points: [[1, 1]], text: 'Here' };+ stage({ annotations: [note], editVertices: true, selectedId: 'z1', tool: 'select' });+ expect(target.querySelectorAll('.vertex')).toHaveLength(0);+});++it('lets a mark go when the ground beside it is clicked, but not when the map is panned', () => {+ const map = document.createElement('div');+ map.className = 'map-wrap';+ document.body.append(map);+ stage({ annotations: [area()], editVertices: true, selectedId: 'z1', tool: 'select' });+ const selected = () => target.querySelector('.mark').classList.contains('selected');+ expect(selected()).toBe(true);++ press(map, 'pointerdown', 300, 200);+ press(map, 'pointerup', 380, 240);+ expect(selected()).toBe(true); // a drag is a pan, and keeps the pick++ press(map, 'pointerdown', 300, 200);+ press(map, 'pointerup', 301, 200);+ expect(selected()).toBe(false);+ map.remove();+});++it('anchors a measure on a point handed to it, and closes it on the next click', () => {+ const onchange = vi.fn();+ const svg = stage({ annotations: [], editVertices: true, tool: 'measure', onchange });+ live.startFrom([1, 1]);+ flushSync();++ // Armed, not held: the release of whatever press was in flight keeps it open.+ press(svg, 'pointerup', 10, 10);+ expect(onchange).not.toHaveBeenCalled();++ press(svg, 'pointermove', 60, 10);+ press(svg, 'pointerdown', 60, 10);+ const [saved, commit] = onchange.mock.calls.at(-1);+ expect(commit).toBe(true);+ expect(saved[0].kind).toBe('measure');+ expect(saved[0].points[0]).toEqual([1, 1]);+ expect(saved[0].points[1][0]).toBeCloseTo(6);});diff --git a/frontend/src/tools/compare/AnnotationToolbar.svelte b/frontend/src/tools/compare/AnnotationToolbar.svelteindex 0b3d312..9be0f31 100644--- a/frontend/src/tools/compare/AnnotationToolbar.svelte+++ b/frontend/src/tools/compare/AnnotationToolbar.svelte@@ -30,9 +30,16 @@: (selected?.stroke_width ?? strokeWidth));let open = $state('');let flyout = $state({});+ // The panel floats free of the rail, so closing it on an outside press needs+ // both halves: the panel itself, and the button that opened it. Leaving the+ // button out would close the panel on the way down and let its own click+ // reopen it, which reads as a button that does nothing.+ let flyoutEl = $state();+ let opener = $state(null);function toggle(name, event) {open = open === name ? '' : name;+ opener = open ? event.currentTarget : null;if (!open) return;const box = event.currentTarget.getBoundingClientRect();flyout = box.top > window.innerHeight / 2@@ -40,13 +47,28 @@: { left: `${box.right + 6}px`, top: `${box.top}px` };}+ // The colour and size buttons vanish when the analyst goes back to Select with+ // nothing selected, or deletes what was selected. Drop the panel with them+ // rather than leaving it floating over the maps with nothing behind it.+ $effect(() => {+ if (!contextual || (open === 'fill' && !fillable)) open = '';+ });+$effect(() => {if (!open) return;- const close = (event) => {+ const key = (event) => {if (event.key === 'Escape') open = '';};- document.addEventListener('keydown', close);- return () => document.removeEventListener('keydown', close);+ const outside = (event) => {+ if (flyoutEl?.contains(event.target) || opener?.contains(event.target)) return;+ open = '';+ };+ document.addEventListener('keydown', key);+ document.addEventListener('mousedown', outside, true);+ return () => {+ document.removeEventListener('keydown', key);+ document.removeEventListener('mousedown', outside, true);+ };});</script>@@ -93,7 +115,7 @@</aside>{#if open === 'colour'}- <div class="flyout colours" style:left={flyout.left} style:top={flyout.top} style:bottom={flyout.bottom}>+ <div class="flyout colours" bind:this={flyoutEl} style:left={flyout.left} style:top={flyout.top} style:bottom={flyout.bottom}>{#each palette as entry (entry)}<buttonclass="colour-button"@@ -109,7 +131,7 @@</label></div>{:else if open === 'size'}- <div class="flyout slider" style:left={flyout.left} style:top={flyout.top} style:bottom={flyout.bottom}>+ <div class="flyout slider" bind:this={flyoutEl} style:left={flyout.left} style:top={flyout.top} style:bottom={flyout.bottom}><inputtype="range"min="1"@@ -120,7 +142,7 @@/></div>{:else if open === 'fill'}- <div class="flyout slider" style:left={flyout.left} style:top={flyout.top} style:bottom={flyout.bottom}>+ <div class="flyout slider" bind:this={flyoutEl} style:left={flyout.left} style:top={flyout.top} style:bottom={flyout.bottom}><inputtype="range"min="0"@@ -134,24 +156,33 @@{/if}<style>+ /* Two columns, like the Proof Maker rail this follows. In one column the nine+ tools plus the contextual controls ran past the bottom of a laptop window+ once the mode dock and the source cards had taken their share, and the+ colour and width buttons sat under a scrollbar nobody looks for. The second+ column is paid for out of the buttons rather than the stage: a 32px box+ still holds an 18px icon with room around it, so the rail ends up 24px+ wider and roughly half as tall. A separator spans both columns, so the+ groups it marks are kept by the grid itself. */.annotation-toolbar {position: relative;z-index: 610;- width: 52px;- flex: 0 0 52px;- display: flex;- flex-direction: column;- align-items: center;- gap: 3px;- padding: 7px 6px;+ width: 76px;+ flex: 0 0 76px;+ display: grid;+ grid-template-columns: repeat(2, 32px);+ justify-content: center;+ align-content: start;+ gap: 4px;+ padding: 8px 0;overflow-y: auto;+ overflow-x: hidden;border-right: 1px solid var(--border);background: var(--bg-1);}.tool-button {- width: 38px;- height: 38px;- flex: 0 0 38px;+ width: 32px;+ height: 32px;display: grid;place-items: center;border-radius: var(--r-sm);@@ -170,7 +201,13 @@font-size: 8px;line-height: 1;}- .separator { width: 28px; height: 1px; flex: 0 0 1px; margin: 3px 0; background: var(--border); }+ .separator {+ grid-column: 1 / -1;+ justify-self: stretch;+ height: 1px;+ margin: 3px 4px;+ background: var(--border);+ }.swatch { width: 19px; height: 19px; border: 2px solid rgba(255,255,255,.68); border-radius: 50%; box-shadow: 0 0 0 1px rgba(0,0,0,.5); }.fill-sample { width: 20px; height: 17px; border: 2px solid currentColor; border-radius: 2px; background: currentColor; }.flyout {@@ -189,5 +226,14 @@.colour-button input { position: absolute; width: 1px; height: 1px; opacity: 0; }.slider { width: 180px; }.slider input { width: 100%; accent-color: var(--accent); }- select { width: 42px; color: var(--text-1); background: var(--bg-2); font-size: 10px; }+ /* Which picture a mark belongs to is a word, not an icon, so it takes the+ whole width rather than being squeezed into one 32px cell. */+ select {+ grid-column: 1 / -1;+ justify-self: stretch;+ height: 24px;+ color: var(--text-1);+ background: var(--bg-2);+ font-size: 10px;+ }</style>diff --git a/frontend/src/tools/compare/AnnotationToolbar.test.js b/frontend/src/tools/compare/AnnotationToolbar.test.jsnew file mode 100644index 0000000..3131595--- /dev/null+++ b/frontend/src/tools/compare/AnnotationToolbar.test.js@@ -0,0 +1,117 @@+// @vitest-environment happy-dom+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { flushSync, mount, unmount } from 'svelte';+import AnnotationToolbar from './AnnotationToolbar.svelte';+import { ANNOTATION_COLOURS, ANNOTATION_TOOLS } from '../../lib/map/compareAnnotations.js';++// Read off the project root: under happy-dom `import.meta.url` is an http URL.+const source = readFileSync(resolve('src/tools/compare/AnnotationToolbar.svelte'), 'utf8');++let live;+let target;++function props(overrides = {}) {+ return {+ tool: 'select',+ selected: null,+ canUndo: false,+ canRedo: false,+ undo: vi.fn(),+ redo: vi.fn(),+ palette: ANNOTATION_COLOURS,+ colour: ANNOTATION_COLOURS[0],+ strokeWidth: 4,+ fillOpacity: 0,+ count: 0,+ side: 'both',+ ...overrides,+ };+}++function stage(overrides = {}) {+ target = document.createElement('div');+ document.body.append(target);+ live = mount(AnnotationToolbar, { target, props: props(overrides) });+ flushSync();+ return target;+}++afterEach(() => {+ if (live) unmount(live);+ live = null;+ document.body.innerHTML = '';+});++describe('the comparison annotation rail', () => {+ it('holds every drawing tool, undo and redo', () => {+ const rail = stage().innerHTML;+ for (const entry of ANNOTATION_TOOLS) expect(rail).toContain(entry.label);+ expect(rail).toContain('Undo (Ctrl+Z)');+ expect(rail).toContain('Redo (Ctrl+Shift+Z)');+ });++ it('packs into two columns, so the rail stays short enough to fit a laptop', () => {+ // Proof Maker's rail, followed here: two 32px columns, and a separator that+ // spans both so the groups it marks survive the grid.+ expect(source).toMatch(/grid-template-columns:\s*repeat\(2,\s*32px\)/);+ expect(source).toMatch(/\.separator\s*{[^}]*grid-column:\s*1 \/ -1/);+ expect(source).toMatch(/select\s*{[^}]*grid-column:\s*1 \/ -1/);+ });++ it('keeps colour, size and fill out of the way until something is being drawn', () => {+ expect(stage().innerHTML).not.toContain('Annotation colour');+ unmount(live);+ live = null;+ expect(stage({ tool: 'rect' }).innerHTML).toContain('Fill opacity');+ });+});++describe('the flyout a rail button opens', () => {+ const press = (node) => node.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));+ const panel = () => document.querySelector('.flyout');+ const trigger = (title) => target.querySelector(`button[title="${title}"]`);++ it('closes on a press outside it', () => {+ stage({ tool: 'rect' });+ trigger('Annotation colour').click();+ flushSync();+ expect(panel()).not.toBeNull();++ press(document.body);+ flushSync();+ expect(panel()).toBeNull();+ });++ it('stays open while it is being used, and shuts from its own button', () => {+ stage({ tool: 'rect' });+ trigger('Annotation colour').click();+ flushSync();++ press(panel().querySelector('.colour-button'));+ flushSync();+ expect(panel()).not.toBeNull();++ // The press on the opener must not close it, or the click that follows+ // would reopen what it was meant to shut.+ press(trigger('Annotation colour'));+ trigger('Annotation colour').click();+ flushSync();+ expect(panel()).toBeNull();+ });++ it('goes with the button behind it when that button leaves the rail', () => {+ stage({ tool: 'rect' });+ trigger('Fill opacity').click();+ flushSync();+ expect(panel()).not.toBeNull();++ // Back to Select with nothing picked: the contextual buttons go, and a+ // panel left behind would float over the maps with nothing behind it. The+ // click carries no mousedown, so this is the guard and not the outside press.+ trigger('Select and move (V)').click();+ flushSync();+ expect(panel()).toBeNull();+ });+});diff --git a/frontend/src/tools/compare/ChangePanel.svelte b/frontend/src/tools/compare/ChangePanel.svelteindex aef6aea..31fa072 100644--- a/frontend/src/tools/compare/ChangePanel.svelte+++ b/frontend/src/tools/compare/ChangePanel.svelte@@ -1,11 +1,16 @@<script>/*** Difference mode's own column. It reads the pixels the two maps are showing- * right now, so everything here is about *this view*: the reading follows the- * camera and is never saved. Detect mode, next to it in the dock, is the one- * that freezes an area and keeps what it found.+ * right now, so everything here is about *this view*, and nothing is saved.+ * Detect mode, next to it in the dock, freezes an area and keeps what it found.+ *+ * The reading follows the camera by itself, always. What it never does on a+ * pan is spend a request: a method that reads Sentinel-2 bands — a spectral+ * index, or the cloud filter over the picture methods — runs on the frames it+ * holds, and waits for Run once the camera leaves the ground they cover.*/- import { CHANGE_BASES, CHANGE_METHODS, CHANGE_INDICES, CHANGE_DISPLAYS, CHANGE_CLASSES, changeSettings } from '../../lib/map/changeAssist.js';+ import { CHANGE_BASES, CHANGE_METHODS, CHANGE_INDICES, CHANGE_DISPLAYS, CHANGE_CLASSES,+ changeNeedsFrames, changeSettings, indexThreshold } from '../../lib/map/changeAssist.js';import CloudFilter from './CloudFilter.svelte';import Icon from '../../components/Icon.svelte';@@ -23,11 +28,25 @@let tab = $state('detection');const runnable = $derived(status.ok && status.methods.includes(settings.method));+ // What this reading has to fetch, and therefore whether it can follow the map.+ const frames = $derived(changeNeedsFrames(settings, status));+ const index = $derived(CHANGE_INDICES.find((entry) => entry.id === settings.index));</script><aside class="cmp-dock" aria-label="Difference"><header><strong>Difference</strong>+ <button+ class="cmp-icon"+ class:on={settings.blink}+ disabled={!settings.visible}+ onclick={() => (settings = { ...settings, blink: !settings.blink })}+ aria-label={settings.blink ? 'Stop blinking the highlights' : 'Blink the highlights'}+ aria-pressed={settings.blink}+ title="Blink the highlights on and off, which is easier to catch over busy imagery"+ >+ <Icon name="blink" size={15} />+ </button><buttonclass="cmp-icon"class:on={settings.visible}@@ -43,8 +62,7 @@</button></header><p class="cmp-dock-lead">- Reads the pixels on screen. Panning or zooming changes what it reads, and nothing here is saved.- Use Detect for a fixed area at full resolution.+ Reads this view, and keeps nothing. Detect sweeps a fixed area at full resolution.</p><div class="cmp-dock-body">@@ -59,7 +77,7 @@<strong>{Math.round(result.share * 100)}%</strong><span>of the overlap highlighted</span><small>{Math.round(result.coverage * 100)}% coverage · {Math.round(result.area)} m²</small>- {#if stale}<small class="warn">The view moved. Run again to match it.</small>{/if}+ {#if stale}<small class="warn">Out of date. Run again to match this view.</small>{/if}</div>{/if}@@ -77,16 +95,25 @@</p></div>- <CloudFilter- kind={settings.method === 'index' ? 'classes' : 'picture'}- clouds={settings.ignore_clouds}- shadows={settings.ignore_shadows}- ontoggle={(on) => (settings = { ...settings, ignore_clouds: on, ignore_shadows: on })}- />+ {#if status.clouds}+ <CloudFilter+ clouds={settings.ignore_clouds}+ shadows={settings.ignore_shadows}+ ontoggle={(on) => {+ settings = { ...settings, ignore_clouds: on, ignore_shadows: on };+ // The click is the act that asks for the sky, so the reading follows+ // it rather than leaving an unfiltered mask up behind an "on" switch.+ queueMicrotask(() => onrun());+ }}+ />+ {/if}- <label class="check" title="Turn off to hold the current reading until Run; spectral analysis is always explicit.">- <input type="checkbox" bind:checked={settings.live} /> Follow the map automatically- </label>+ {#if frames}+ <p class="hint">+ Reads Sentinel-2 bands, one request a side. They are kept with a margin around+ this view: following the map costs nothing inside it, and waits for Run past it.+ </p>+ {/if}<div class="settings-tabs" role="tablist" aria-label="Difference parameters">{#each [['detection', 'Detection'], ['display', 'Display'], ['filters', 'Filters']] as [id, label]}@@ -102,16 +129,19 @@</label>{#if settings.method === 'index'}<label title="Select the spectral quantity to compare between the two passes.">Index- <select bind:value={settings.index}>{#each CHANGE_INDICES as index}<option value={index.id}>{index.label} · {index.hint}</option>{/each}</select>+ <select bind:value={settings.index}>{#each CHANGE_INDICES as entry}<option value={entry.id}>{entry.label} · {entry.hint}</option>{/each}</select>+ </label>+ {:else}+ <label title="Automatic adapts to this view; manual keeps a sensitivity-based threshold.">Threshold+ <select bind:value={settings.threshold}><option value="auto">Automatic</option><option value="manual">Manual</option></select></label>- <p class="hint">Run fetches two Sentinel-2 frames and counts toward your usage.</p>{/if}- <label title="Automatic adapts to this view; manual keeps a sensitivity-based threshold.">Threshold- <select bind:value={settings.threshold}><option value="auto">Automatic</option><option value="manual">Manual</option></select>- </label><label title="Higher values show weaker differences and more noise.">Sensitivity · {settings.sensitivity}<input aria-label="Change sensitivity" type="range" min="0" max="100" bind:value={settings.sensitivity} /></label>+ {#if settings.method === 'index'}+ <p class="hint">Highlights {index?.label} moved by {indexThreshold(settings.sensitivity).toFixed(2)} or more, the line Detect draws.</p>+ {/if}<button class="btn btn-sm" onclick={() => (settings = { ...settings, normalize: 'none', smoothing: 0, cleanup: 0, alignment: 0, threshold: 'manual', sensitivity: 90 })}>Preserve fine changes</button>@@ -132,15 +162,27 @@{#if tab === 'filters'}<label title="Reduce exposure differences; this may suppress broad real changes.">Tone matching- <select bind:value={settings.normalize}><option value="none">None</option><option value="mean">Mean brightness</option><option value="histogram">Histogram</option></select>+ <select bind:value={settings.normalize}>+ <option value="auto">Automatic</option><option value="none">None</option>+ <option value="mean">Mean brightness</option><option value="histogram">Histogram</option>+ </select></label>+ {#if settings.normalize === 'auto'}+ <p class="hint">+ {status.family === 'sentinel2'+ ? 'Nothing to match: both passes are corrected to surface reflectance.'+ : 'Histogram, because two releases carry two renderings.'}+ </p>+ {/if}<label title="Search for a small image offset before comparing pixels.">Alignment · ±{settings.alignment}px<input type="range" min="0" max="8" bind:value={settings.alignment} /></label><label title="Reduce pixel noise before thresholding; zero preserves small details.">Smoothing · {settings.smoothing}px<input type="range" min="0" max="4" bind:value={settings.smoothing} /></label><label title="Remove isolated speckles; larger settings can also remove small real changes.">Cleanup · {settings.cleanup}<input type="range" min="0" max="3" bind:value={settings.cleanup} /></label><label title="Discard connected regions below this ground area.">Minimum area (m²)<input type="number" min="0" max="1000000" bind:value={settings.min_area} /></label>- <label class="check" title="Exclude cloud; on a picture this is a guess at what cloud looks like."><input type="checkbox" bind:checked={settings.ignore_clouds} /> Mask clouds</label>- <label class="check" title="Exclude the shadow cloud casts, which moves with the sun."><input type="checkbox" bind:checked={settings.ignore_shadows} /> Mask shadows</label>- <label title="Grow the cloud and shadow mask, to take the soft edge a mask leaves behind.">Mask margin · {settings.cloud_margin}px<input aria-label="Cloud mask margin" type="range" min="0" max="10" bind:value={settings.cloud_margin} /></label>+ {#if status.clouds}+ <label class="check" title="Exclude cloud, read from Sentinel-2's scene classification."><input type="checkbox" bind:checked={settings.ignore_clouds} /> Mask clouds</label>+ <label class="check" title="Exclude the shadow cloud casts, which moves with the sun."><input type="checkbox" bind:checked={settings.ignore_shadows} /> Mask shadows</label>+ <label title="Grow the cloud and shadow mask, to take the soft edge a mask leaves behind.">Mask margin · {settings.cloud_margin} m<input aria-label="Cloud mask margin" type="range" min="0" max="200" step="10" bind:value={settings.cloud_margin} /></label>+ {/if}<label class="check"><input type="checkbox" bind:checked={settings.zones} /> List change zones</label><button class="link" onclick={() => (settings = changeSettings())}>Reset settings</button>{/if}@@ -150,7 +192,10 @@<strong>{result.zoneCount} change zones{result.zoneCount > result.zones.length ? ` · largest ${result.zones.length}` : ''}</strong><div class="zone-list">{#each result.zones as zone (zone.id)}- <button onclick={() => onzone(zone)}>Zone {zone.id} · {zone.kind} · {Math.round(zone.area)} m²</button>+ <button onclick={() => onzone(zone)}>+ <span class="zone-strength {zone.strength}">{zone.strength}</span>+ Zone {zone.id} · {zone.kind} · {Math.round(zone.area)} m²+ </button>{/each}</div></section>@@ -158,10 +203,14 @@</div><div class="cmp-dock-foot">- <button class="btn btn-primary" disabled={busy || !runnable} onclick={onrun}>+ <button class="btn btn-primary" disabled={busy || !runnable} onclick={() => onrun()}>{busy ? 'Reading…' : 'Read this view'}</button>- {#if !runnable}<span class="reason">{status.ok ? 'This method needs another imagery source.' : status.reason}</span>{/if}+ {#if !runnable}+ <span class="reason">{status.ok ? 'This method needs another imagery source.' : status.reason}</span>+ {:else if stale && result}+ <span class="reason warn">These highlights are from an earlier read.</span>+ {/if}</div></aside>@@ -188,5 +237,7 @@.zone-list { display: grid; gap: 4px; max-height: 170px; overflow: auto; }.zone-list button { padding: 5px; text-align: left; background: var(--bg-2); border-radius: var(--r-sm); font-size: 11px; }.zone-list button:hover { background: var(--bg-3); }+ .zone-strength { font-weight: 600; text-transform: capitalize; color: var(--text-2); }+ .zone-strength.strong { color: var(--accent); }.link { color: var(--accent); font-size: var(--fs-xs); text-align: left; }</style>diff --git a/frontend/src/tools/compare/ChangePanel.test.js b/frontend/src/tools/compare/ChangePanel.test.jsindex c8e63f5..35e5004 100644--- a/frontend/src/tools/compare/ChangePanel.test.js+++ b/frontend/src/tools/compare/ChangePanel.test.js@@ -4,7 +4,8 @@ import { flushSync, mount, unmount } from 'svelte';import ChangePanel from './ChangePanel.svelte';import { changeSettings } from '../../lib/map/changeAssist.js';-const ready = { ok: true, label: 'Two dated passes', methods: ['colour', 'brightness'], notes: [] };+const ready = { ok: true, label: 'Two dated passes', methods: ['colour', 'brightness'], notes: [],+ family: 'sentinel2', clouds: true };function render(props = {}) {const target = document.createElement('div');@@ -56,4 +57,65 @@ describe('Difference panel', () => {expect(onrun).toHaveBeenCalledTimes(1);done();});++ it('blinks the highlights on and off, which only touches the overlay', () => {+ const onrun = vi.fn();+ const { target, done } = render({ onrun });+ const blink = () => target.querySelector('button[aria-label$="the highlights"]');+ expect(blink().getAttribute('aria-pressed')).toBe('false');+ blink().click();+ flushSync();+ expect(blink().getAttribute('aria-label')).toBe('Stop blinking the highlights');+ expect(onrun).not.toHaveBeenCalled();+ // nothing to blink once the overlay is hidden+ target.querySelector('button[aria-label*="difference overlay"]').click();+ flushSync();+ expect(blink().disabled).toBe(true);+ done();+ });++ it('offers the cloud filter only where a scene classification exists', () => {+ const { target, done } = render();+ expect(target.textContent).toContain('Clouds & shadows');+ done();+ const esri = render({ status: { ...ready, family: 'esri', clouds: false } });+ expect(esri.target.textContent).not.toContain('Clouds & shadows');+ esri.done();+ });++ it('says when a reading reads bands, and never asks to be turned on', () => {+ // The reading always follows the camera. Reading bands is a different+ // question: it is what costs a request, and only off the held ground.+ const { target, done } = render({ settings: changeSettings({ ignore_clouds: true }) });+ expect(target.textContent).toContain('one request a side');+ done();+ const free = render();+ expect(free.target.textContent).not.toContain('one request a side');+ expect(free.target.textContent).not.toContain('Follow the map');+ free.done();+ });++ it('reads the view as soon as the cloud filter is switched on', async () => {+ // The switch says the sky is being read, so it cannot leave an unfiltered+ // reading up behind it.+ const onrun = vi.fn();+ const { target, done } = render({ onrun });+ target.querySelector('.cloud-filter button').click();+ flushSync();+ await Promise.resolve();+ expect(onrun).toHaveBeenCalledTimes(1);+ done();+ });++ it('says so in the footer when the highlights are from an earlier read', () => {+ const { target, done } = render({ stale: true, result: { share: 0.1, coverage: 1, area: 20, zones: [], zoneCount: 0 } });+ expect(target.querySelector('.cmp-dock-foot').textContent).toContain('from an earlier read');+ done();+ });++ it('states the index change it draws the line at', () => {+ const { target, done } = render({ settings: changeSettings({ method: 'index', index: 'nbr' }) });+ expect(target.textContent).toContain('NBR moved by 0.25');+ done();+ });});diff --git a/frontend/src/tools/compare/CloudFilter.svelte b/frontend/src/tools/compare/CloudFilter.svelteindex 93f4967..290e162 100644--- a/frontend/src/tools/compare/CloudFilter.svelte+++ b/frontend/src/tools/compare/CloudFilter.svelte@@ -2,53 +2,41 @@/*** Cloud and the shadow it casts, as one thing to click.*- * It sits at the top of both computing panels rather than inside a settings- * tab, because cloud is the first thing that goes wrong in a reading and- * hunting for the switch that fixes it is the wrong first minute. The split- * between cloud and shadow, and the margin, stay in the panel's own detail- * area: this is the one decision, and the rest is tuning.+ * It sits at the top of Detect's third step and of Difference's column rather+ * than inside the thresholds, because cloud is the first thing that goes+ * wrong in a reading and hunting for the switch that fixes it is the wrong+ * first minute. The split between cloud and shadow, and the margin, stay with+ * the thresholds: this is the one decision, and the rest is tuning.*- * `kind` comes from the method catalogue, never from a list kept here — a- * method that cannot separate cloud from what it looks for offers nothing.+ * Both modes read one sky, from Sentinel-2's own classification, so a caller+ * only shows this where that classification exists: the fire test rejects+ * cloud by its own band ratios, and a Wayback picture carries no classes.*/import Icon from '../../components/Icon.svelte';- let { kind = '', clouds = false, shadows = false, split = true, ontoggle } = $props();+ let { clouds = false, shadows = false, ontoggle } = $props();- const on = $derived(split ? clouds || shadows : clouds);+ const on = $derived(clouds || shadows);const name = $derived(- !split || !on || (clouds && shadows)- ? 'Clouds & shadows'- : clouds- ? 'Clouds only'- : 'Shadows only'- );- // Said every time it is on, because the two answers are not equally good and- // the panel must not let a guess pass for a measurement.- const how = $derived(- kind === 'classes'- ? "Sentinel-2's own scene classification."- : 'A guess from the picture: bright and colourless, or near-black.'+ !on || (clouds && shadows) ? 'Clouds & shadows' : clouds ? 'Clouds only' : 'Shadows only');</script>-{#if kind}- <div class="cloud-filter">- <button- type="button"- class="chip"- class:on- aria-pressed={on}- onclick={() => ontoggle(!on)}- title={on ? 'Stop excluding cloud and shadow' : 'Exclude cloud and the shadow it casts'}- >- <Icon name={on ? 'eyeOff' : 'eye'} size={13} />- {name}- <span class="state">{on ? 'on' : 'off'}</span>- </button>- <p class="how" class:dim={!on}>{how}</p>- </div>-{/if}+<div class="cloud-filter">+ <button+ type="button"+ class="chip"+ class:on+ aria-pressed={on}+ onclick={() => ontoggle(!on)}+ title={on ? 'Stop excluding cloud and shadow' : 'Exclude cloud and the shadow it casts'}+ >+ <Icon name={on ? 'eyeOff' : 'eye'} size={13} />+ {name}+ <span class="state">{on ? 'on' : 'off'}</span>+ </button>+ <p class="how" class:dim={!on}>Sentinel-2's scene classification, with shadows traced from the sun.</p>+</div><style>.cloud-filter {diff --git a/frontend/src/tools/compare/CloudFilter.test.js b/frontend/src/tools/compare/CloudFilter.test.jsindex a4cd2cd..8c4c913 100644--- a/frontend/src/tools/compare/CloudFilter.test.js+++ b/frontend/src/tools/compare/CloudFilter.test.js@@ -6,7 +6,7 @@ import CloudFilter from './CloudFilter.svelte';function render(props = {}) {const target = document.createElement('div');document.body.append(target);- const live = mount(CloudFilter, { target, props: { kind: 'classes', ontoggle: () => {}, ...props } });+ const live = mount(CloudFilter, { target, props: { ontoggle: () => {}, ...props } });flushSync();return { target, done: () => { unmount(live); target.remove(); } };}@@ -14,14 +14,6 @@ function render(props = {}) {const chip = (target) => target.querySelector('button');describe('the cloud and shadow filter', () => {- it('offers nothing for a method that cannot separate cloud from its subject', () => {- // smoke, bright shapes on water and a hotspot: masking cloud would mask- // the very thing they look for, so there is no switch to mislead with- const { target, done } = render({ kind: '' });- expect(chip(target)).toBe(null);- done();- });-it('turns both cloud and shadow on with one click', () => {const ontoggle = vi.fn();const { target, done } = render({ clouds: false, shadows: false, ontoggle });@@ -49,25 +41,10 @@ describe('the cloud and shadow filter', () => {shadow.done();});- it('says a guess is a guess, and a classification a classification', () => {- // the panel must never let a brightness test pass for a measurement- const { target, done } = render({ kind: 'classes', clouds: true });+ it('says what it reads, which is the sensor and the sun rather than a guess', () => {+ const { target, done } = render({ clouds: true });expect(target.textContent).toContain('scene classification');- expect(target.textContent).not.toContain('guess');- done();-- const guess = render({ kind: 'picture', clouds: true });- expect(guess.target.textContent).toContain('A guess from the picture');- guess.done();- });-- it('follows one switch when cloud and shadow cannot be split', () => {- const ontoggle = vi.fn();- const { target, done } = render({ kind: 'picture', split: false, clouds: true, ontoggle });- expect(chip(target).getAttribute('aria-pressed')).toBe('true');- expect(chip(target).textContent).toContain('Clouds & shadows');- chip(target).click();- expect(ontoggle).toHaveBeenCalledWith(false);+ expect(target.textContent).toContain('traced from the sun');done();});});diff --git a/frontend/src/tools/compare/compare.css b/frontend/src/tools/compare/compare.cssindex 667af9f..e4a20bb 100644--- a/frontend/src/tools/compare/compare.css+++ b/frontend/src/tools/compare/compare.css@@ -215,6 +215,7 @@font-size: var(--fs-xs);text-align: center;}+.cmp-dock-foot .reason.warn { color: var(--warn); }/* One numbered step. The number is the whole instruction about order. */.cmp-step { display: grid; gap: 8px; }@@ -242,8 +243,10 @@font: 700 10px/1 var(--font-sans);}.cmp-step.done .cmp-step-n { color: var(--bg-0); background: var(--accent); }-.cmp-step .hint { color: var(--text-3); font-size: var(--fs-xs); line-height: 1.45; margin: 0; }-.cmp-step .warn { color: var(--warn); font-size: var(--fs-xs); line-height: 1.45; margin: 0; }+/* Notes are small wherever they sit in a dock, not only inside a step: a+ paragraph that escapes this rule renders at body size and shouts. */+.cmp-dock .hint { color: var(--text-3); font-size: var(--fs-xs); line-height: 1.45; margin: 0; }+.cmp-dock .warn { color: var(--warn); font-size: var(--fs-xs); line-height: 1.45; margin: 0; }/* Inputs inside a dock: label above, control below, never side by side —the column is too narrow for a two-column form to stay readable. */diff --git a/frontend/src/tools/coordinates/PointPicker.svelte b/frontend/src/tools/coordinates/PointPicker.svelteindex 0595755..25a25cd 100644--- a/frontend/src/tools/coordinates/PointPicker.svelte+++ b/frontend/src/tools/coordinates/PointPicker.svelte@@ -10,7 +10,7 @@import SearchInput from '../../components/SearchInput.svelte';import FolderBrowser from '../../components/FolderBrowser.svelte';import Icon from '../../components/Icon.svelte';- import { KINDS, filterSaved, isLocated, oneEach, sortSaved } from '../../lib/geoTree.js';+ import { SAVED_KINDS, filterSaved, isLocated, oneEach, sortSaved } from '../../lib/geoTree.js';let { rows = [], onpick, onclose } = $props();@@ -25,8 +25,9 @@// Only what carries a position: this picker exists to fill a coordinate, and a// row without one has nothing to give.const placed = $derived(oneEach(rows).filter(isLocated));- // Proofs are a mode of the map's own panel, not a kind of point.- const kinds = KINDS.filter((k) => !k.mode);+ // The saved index and nothing else, so "All" here is all of it: located media+ // is a position of the map's own panel, and has no row in this list.+ const kinds = SAVED_KINDS;const found = $derived(sortSaved(filterSaved(placed, { kind, query }), 'newest'));const shown = $derived(found.slice(0, CAP));const entries = $derived(diff --git a/frontend/src/tools/coordinates/PointPicker.test.js b/frontend/src/tools/coordinates/PointPicker.test.jsindex ecb80bf..ccc9371 100644--- a/frontend/src/tools/coordinates/PointPicker.test.js+++ b/frontend/src/tools/coordinates/PointPicker.test.js@@ -24,8 +24,11 @@ describe('saved-point picker', () => {expect(picker).toContain('oneEach(rows).filter(isLocated)');});- it('drops the proofs position, which is a mode of the map panel', () => {- expect(picker).toContain('KINDS.filter((k) => !k.mode)');+ it('offers the saved kinds, where "All" is honestly all of them', () => {+ // located media has an index of its own and no row in this list, so the+ // map's three-position switch would offer a position with nothing in it+ expect(picker).toContain('const kinds = SAVED_KINDS');+ expect(picker).not.toMatch(/\bKINDS\b/);});it('stays read-only: editing saved work belongs to the map', () => {diff --git a/frontend/src/tools/overview/PlaceMap.svelte b/frontend/src/tools/overview/PlaceMap.svelteindex 3eccb9e..5e3cd87 100644--- a/frontend/src/tools/overview/PlaceMap.svelte+++ b/frontend/src/tools/overview/PlaceMap.svelte@@ -1,8 +1,10 @@<script>/**- * The case's saved points, on the ground they were saved from.+ * The case's located media, on the ground it was shot from or shows.*- * A reading and nothing else: satellite imagery under the points, the wheel and+ * The footage is what a case is built on, so it is what the home page draws: a+ * place nobody filmed is a pin, and the Map tool is where pins are read. A+ * reading and nothing else — satellite imagery under the points, the wheel and* the drag to look around them, and no act that writes. Everything a point can be* worked on with — the card, the capture frame, the other basemaps, the hover tie* to the tree — belongs to the Map tool, and the foot of this plate is the way@@ -55,11 +57,11 @@}/**- * One colour for every point, whatever was saved there.+ * One colour for every point, whatever stands there.*- * The Map tool tells a place from a capture because it is worked on there; here- * the points are one layer saying where the case is, and a legend nobody asked- * for would be the only thing to read.+ * The Map tool tells a photograph from a video because it is worked on there;+ * here the points are one layer saying where the case is, and a legend nobody+ * asked for would be the only thing to read.*/function dots() {const fill = themeColour('--accent', '#e8a33d');diff --git a/frontend/src/tools/satellite/MapContextMenu.svelte b/frontend/src/tools/satellite/MapContextMenu.svelteindex 3b2401d..83e0f11 100644--- a/frontend/src/tools/satellite/MapContextMenu.svelte+++ b/frontend/src/tools/satellite/MapContextMenu.svelte@@ -23,6 +23,8 @@fullscreen = false,/** `{ busy, text, error }` once "What is here?" was asked. */lookup = null,+ /** The acts offered, in `ACTIONS` order; a tool passes the subset it has. */+ actions = ACTIONS,/** `(id, value)`: `copy` with the text, or an action id from `ACTIONS`. */onpick,onclose,@@ -103,7 +105,7 @@<div class="rule" role="separator"></div>- {#each ACTIONS as action (action.id)}+ {#each actions as action (action.id)}<button class="item" role="menuitem" onclick={() => onpick(action.id)}><Icon name={action.icon} size={13} /><span>{action.label}</span>diff --git a/frontend/src/tools/satellite/MapContextMenu.test.js b/frontend/src/tools/satellite/MapContextMenu.test.jsindex 0156d6e..e307929 100644--- a/frontend/src/tools/satellite/MapContextMenu.test.js+++ b/frontend/src/tools/satellite/MapContextMenu.test.js@@ -1,6 +1,7 @@import { describe, expect, it, vi } from 'vitest';import { render } from 'svelte/server';import MapContextMenu from './MapContextMenu.svelte';+import { actionsFor } from '../../lib/map/contextMenu.js';function props(overrides = {}) {return {@@ -59,4 +60,17 @@ describe('the right-click menu', () => {render(MapContextMenu, { props: props({ lookup: { error: 'Lookup failed: offline' } }) }).body).toContain('Lookup failed: offline');});++ it('shows only the acts the tool passed, never a row that would do nothing', () => {+ const { body } = render(MapContextMenu, {+ props: props({ actions: actionsFor(['lookup', 'place', 'measure']) }),+ });+ expect(body).toContain('Measure from here');+ expect(body).not.toContain('Sun and moon from here');+ expect(body).not.toContain('Imagery history here');+ expect(body).not.toContain('Centre the map here');+ // The point is still copyable and still opens elsewhere: those are not acts.+ expect(body).toContain('DMS');+ expect(body).toContain('Open in…');+ });});diff --git a/frontend/src/tools/satellite/SavedOverlay.svelte b/frontend/src/tools/satellite/SavedOverlay.svelteindex 52abdea..5eea9fb 100644--- a/frontend/src/tools/satellite/SavedOverlay.svelte+++ b/frontend/src/tools/satellite/SavedOverlay.svelte@@ -22,15 +22,12 @@activeKey = null,onopen,onedit,- onproof,- onpost,- onshowproofs,onrefresh,ontrace,onmedia,} = $props();- const GLYPH = { place: 'pin', capture: 'satellite', screenshot: 'screen', proof: 'proof' };+ const GLYPH = { place: 'pin', capture: 'satellite', screenshot: 'screen' };/** True when every item under a mark is a located file: it opens the viewer. */const isMedia = (mark) => mark.kinds.every((kind) => kind === 'media');@@ -59,7 +56,7 @@: (GLYPH[kind] ?? 'pin');const count =mark.items.length > 1 ? `<i class="saved-mark-count">${mark.items.length}</i>` : '';- // A proof borrowing capture coordinates appears as a dot on that capture.+ // A proof stands on the point it argues, and appears as a dot on it.const worked = mark.items.some((row) => row.proofs > 0)? '<i class="saved-mark-worked"></i>': '';@@ -89,12 +86,9 @@fullscreen,onopen: close(onopen),onedit: close(onedit),- onproof: close(onproof),- onpost: close(onpost),// tracing takes over the map, so the card that armed it gets out of// the way first — the same rule as every other act hereontrace: ontrace && close(ontrace),- onshowproofs: close(onshowproofs),// opening a related media leaves the map, so close the card first — the// same gesture as every other row here, rather than a popup that// vanishes without saying it woulddiff --git a/frontend/src/tools/satellite/SavedPopup.svelte b/frontend/src/tools/satellite/SavedPopup.svelteindex 089bcd2..9285b36 100644--- a/frontend/src/tools/satellite/SavedPopup.svelte+++ b/frontend/src/tools/satellite/SavedPopup.svelte@@ -13,7 +13,6 @@import RelationList from '../../components/RelationList.svelte';import { api } from '../../lib/api.js';import { toast } from '../../lib/state.svelte.js';- import { postTarget } from '../../lib/post.js';import { loadRelationTypes, relationAction } from '../../lib/relations.svelte.js';import { stackOrder } from '../../lib/savedMarkers.js';@@ -24,33 +23,17 @@fullscreen = false,onopen,onedit,- onproof,ontrace,- onpost,- onshowproofs,onentity, // a related entity was picked: leave for its own toolonrefresh, // a relation was settled: sync the other surfaces} = $props();- const GLYPH = { place: 'pin', capture: 'satellite', screenshot: 'screen', proof: 'proof' };- const KIND = { place: 'Place', capture: 'Capture', screenshot: 'Screenshot', proof: 'Proof' };+ const GLYPH = { place: 'pin', capture: 'satellite', screenshot: 'screen' };+ const KIND = { place: 'Place', capture: 'Capture', screenshot: 'Screenshot' };- const linkedPosts = (row) => Array.isArray(row.linked_posts) ? row.linked_posts : [];- let expandedPostRows = $state([]);const rowKey = (row) => row.key ?? row.id;- const postsExpanded = (row) => expandedPostRows.includes(rowKey(row));- const visiblePosts = (row) =>- postsExpanded(row) ? linkedPosts(row) : linkedPosts(row).slice(0, 2);- const hiddenPostCount = (row) => Math.max(0, linkedPosts(row).length - 2);- function expandPosts(event, row) {- // A click that reaches the map closes the card. This control changes only- // the card's own contents, so the event stays inside it.- event.stopPropagation();- if (!postsExpanded(row)) expandedPostRows = [...expandedPostRows, rowKey(row)];- }-- /** What the dot on the mark meant. A proof borrows this capture's point, so+ /** What the dot on the mark meant. A proof stands on the point it argues, so* it is named here rather than drawn as a second mark. */const worked = (row) =>row.proofs > 0 ? `${row.proofs} proof${row.proofs > 1 ? 's' : ''} here` : null;@@ -141,7 +124,6 @@<div class="stack" class:scrolls={ordered.length > 2}>{#each ordered as row (row.key ?? row.id)}{@const flyable = row.lat != null && row.lon != null}- {@const rowPosts = linkedPosts(row)}<div class="entry"><buttontype="button"@@ -158,9 +140,7 @@</button><div class="body"><button type="button" class="title" onclick={() => onopen(row)}>- <!-- one proof, several points: the name is what tells this mark from- the others under the same title -->- {row.label ? `${row.title || 'Untitled'} · ${row.label}` : (row.title || 'Untitled')}+ {row.title || 'Untitled'}</button><p class="meta"><span class="kind"><Icon name={GLYPH[row.kind] ?? 'pin'} size={10} /> {KIND[row.kind]}</span>@@ -181,9 +161,6 @@<p class="worked"><span class="worked-dot"></span><span>{worked(row)}</span>- <button type="button" class="link" onclick={() => onshowproofs?.()}>- Show proofs- </button></p>{/if}{#if row.notes}<p class="note">{row.notes}</p>{/if}@@ -211,41 +188,8 @@{/if}</section>{/if}- {#if rowPosts.length}- <section class="linked-posts">- <p class="post-heading">- <Icon name="post" size={11} />- {rowPosts.length === 1 ? 'Linked post' : `Linked posts · ${rowPosts.length}`}- </p>- <div class="post-list" class:expanded={postsExpanded(row)}>- {#each visiblePosts(row) as post (post.id)}- <button- type="button"- class="post-row"- title={`Open "${post.title}" in Geo Report`}- onclick={() => onpost?.(post)}- >- <span class="post-target">{postTarget(post.target).label}</span>- <span class="post-title">{post.title}</span>- <Icon name="chevronRight" size={11} />- </button>- {/each}- {#if !postsExpanded(row) && hiddenPostCount(row)}- <button type="button" class="more-posts" onclick={(event) => expandPosts(event, row)}>- + {hiddenPostCount(row)} more- </button>- {/if}- </div>- </section>- {/if}<p class="acts">- {#if row.kind === 'proof'}- <button type="button" class="link" onclick={() => onproof?.(row)}>- Open in Geo Proof- </button>- {:else}- <button type="button" class="link" onclick={() => onedit(row)}>Edit</button>- {/if}+ <button type="button" class="link" onclick={() => onedit(row)}>Edit</button>{#if row.kind === 'place' && ontrace}<buttontype="button"@@ -393,8 +337,7 @@align-items: center;gap: 3px;}- /* the mark's dot, named: the card is where "already worked" becomes a number- and a way into the proofs view */+ /* the mark's dot, named: the card is where "already worked" becomes a number */.worked {display: flex;align-items: center;@@ -430,14 +373,12 @@.meta > .proposed::before {content: none;}- .linked-posts,.relations {margin-top: 4px;padding-top: 5px;border-top: 1px solid var(--border);}- .rel-heading,- .post-heading {+ .rel-heading {display: flex;align-items: center;gap: 4px;@@ -448,61 +389,6 @@letter-spacing: 0.04em;text-transform: uppercase;}- .post-list {- display: flex;- flex-direction: column;- gap: 2px;- }- .post-list.expanded {- max-height: 132px;- overflow-y: auto;- }- .post-row {- display: grid;- grid-template-columns: auto minmax(0, 1fr) auto;- align-items: center;- gap: 5px;- width: 100%;- padding: 3px 4px;- border: 0;- border-radius: var(--r-sm);- background: var(--bg-2);- color: var(--text-2);- text-align: left;- cursor: pointer;- }- .post-row:hover {- background: var(--bg-3);- color: var(--text-1);- }- .post-target {- min-width: 14px;- padding: 0 3px;- border: 1px solid var(--border-strong);- border-radius: 3px;- color: var(--text-3);- font-size: 9px;- line-height: 14px;- text-align: center;- }- .post-title {- overflow: hidden;- font-size: var(--fs-xs);- text-overflow: ellipsis;- white-space: nowrap;- }- .more-posts {- align-self: flex-start;- padding: 1px 4px;- border: 0;- background: none;- color: var(--accent);- font-size: var(--fs-xs);- cursor: pointer;- }- .more-posts:hover {- text-decoration: underline;- }.acts {display: flex;gap: 10px;diff --git a/frontend/src/tools/satellite/SavedPopup.test.js b/frontend/src/tools/satellite/SavedPopup.test.jsindex 1cbcf05..b4472dd 100644--- a/frontend/src/tools/satellite/SavedPopup.test.js+++ b/frontend/src/tools/satellite/SavedPopup.test.js@@ -86,63 +86,16 @@ describe('SavedPopup', () => {);});- it('opens a proof in its composer and previews its linked posts', () => {- const proof = {- id: 'pr1',- key: '[email protected],37.8029',- kind: 'proof',- name: 'kyiv-bridge',- title: 'Kyiv bridge',- lat: 48.0159,- lon: 37.8029,- path: 'proofs/kyiv-bridge.png',- thumbnail: 'media/.thumbs/pr.jpg',- fetched_at: '2026-07-21T09:12:04Z',- posts: 3,- linked_posts: [- { id: 'post-1', name: 'panorama-publication', title: 'Panorama publication', target: 'x' },- { id: 'post-2', name: 'source-follow-up', title: 'Follow-up with sources', target: 'bluesky' },- { id: 'post-3', name: 'later-note', title: 'Later note', target: 'mastodon' },- ],- };-- const body = at([proof]);- expect(body).toContain('Kyiv bridge');- expect(body).toContain('Proof');- expect(body).toContain('Open in Geo Proof');- expect(body).toContain('Linked posts · 3');- expect(body).toContain('Panorama publication');- expect(body).toContain('Follow-up with sources');- expect(body).not.toContain('Later note');- expect(body).toContain('+ 1 more');-- // a post is two hops from a point: it is a chip here, never its own mark- expect(at([{ ...proof, posts: 0, linked_posts: [] }])).not.toContain('Linked post');- });-- it('names one linked post directly', () => {- const body = at([{- ...capture,- kind: 'proof',- linked_posts: [- { id: 'post-1', name: 'panorama-publication', title: 'Panorama publication', target: 'x' },- ],- }]);-- expect(body).toContain('Linked post');- expect(body).not.toContain('Linked posts ·');- expect(body).toContain('Panorama publication');- });-- it('says a capture is already worked, and offers the proofs view from there', () => {+ it('says a capture is already worked', () => {+ // a proof stands on this very point, so it is named here rather than drawn+ // as a second mark on top of the captureconst body = at([{ ...capture, proofs: 2 }]);expect(body).toContain('2 proofs here');- expect(body).toContain('Show proofs');// the same dot the mark wears, so the card explains the markexpect(body).toContain('worked-dot');- expect(at([capture])).not.toContain('Show proofs');+ expect(at([capture])).not.toContain('proofs here');});it('holds back the links that would leave a fullscreen map', () => {@@ -158,7 +111,7 @@ describe('SavedOverlay popup wiring', () => {expect(overlay).toContain("import { mount, unmount } from 'svelte'");expect(overlay).toContain('mount(SavedPopup');expect(overlay).toContain('unmount(mounted)');- expect(overlay).toContain('onpost: close(onpost)');+ expect(overlay).toContain('onedit: close(onedit)');});it('opens a card for every mark of saved work, one item or a stack', () => {diff --git a/frontend/src/tools/satellite/SavedRow.svelte b/frontend/src/tools/satellite/SavedRow.svelteindex 8cc0990..a1e530f 100644--- a/frontend/src/tools/satellite/SavedRow.svelte+++ b/frontend/src/tools/satellite/SavedRow.svelte@@ -32,17 +32,16 @@onhover = () => {},} = $props();- const GLYPH = { place: 'pin', capture: 'satellite', screenshot: 'screen', proof: 'proof' };+ const GLYPH = { place: 'pin', capture: 'satellite', screenshot: 'screen' };const isPlace = $derived(row.kind === 'place');- const isProof = $derived(row.kind === 'proof');// a located file: pressing it plays it beside the map, and it is edited in Mediaconst isMedia = $derived(row.kind === 'media');const glyphName = $derived(isMedia ? (row.media_kind === 'video' ? 'video' : 'image') : (GLYPH[row.kind] ?? 'pin'));- // A proof borrows the point of the capture it composes, so `All` marks that- // capture instead of stacking a second mark on it.+ // A proof stands on the point it argues, which is a place this list already+ // draws: the point is marked as worked rather than drawn twice.const worked = $derived(row.proofs > 0 ? `${row.proofs} proof${row.proofs > 1 ? 's' : ''} built here` : null);const flyable = $derived(row.lat != null && row.lon != null);// a screenshot with no position can only be reopened where it came from@@ -98,9 +97,9 @@{#if worked}<span class="worked" role="img" aria-label={worked} title={worked}></span>{/if}</span><span class="text">- <!-- A proof arguing three points is three rows under one title. What the- analyst called each point is what tells them apart. -->- <span class="title">{row.title || 'Untitled'}{#if row.label}<span class="point">· {row.label}</span>{/if}</span>+ <!-- A file standing in two places is two rows under one title; the+ coordinates below are what tell them apart. -->+ <span class="title">{row.title || 'Untitled'}</span><span class="sub"><!-- a screenshot filed from a URL that carried no position has none:say so rather than printing 0°, 0° -->@@ -129,42 +128,31 @@<Icon name="check" size={13} /></button>{/if}- {#if isProof}- <!-- a proof is edited and deleted in the composer that owns it; here it- is a point on the map, and the one thing to do with it is open it -->+ {#if row.source_url}+ <a+ class="act"+ class:disabled={fullscreen}+ href={fullscreen ? undefined : row.source_url}+ target="_blank"+ rel="noreferrer"+ aria-disabled={fullscreen}+ title={blocked ?? `Open the source page (${row.site ?? 'external map'})`}+ ><Icon name="external" size={13} /></a>+ {/if}+ <button class="act" title="Edit title & note" onclick={() => onedit(row)}>+ <Icon name="note" size={13} />+ </button>+ {#if !isPlace}<buttonclass="act"disabled={fullscreen}- title={blocked ?? 'Open in Geo Proof'}+ title={blocked ?? 'Send to Geo Proof'}onclick={() => onproof(row)}><Icon name="proof" size={13} /></button>- {:else}- {#if row.source_url}- <a- class="act"- class:disabled={fullscreen}- href={fullscreen ? undefined : row.source_url}- target="_blank"- rel="noreferrer"- aria-disabled={fullscreen}- title={blocked ?? `Open the source page (${row.site ?? 'external map'})`}- ><Icon name="external" size={13} /></a>- {/if}- <button class="act" title="Edit title & note" onclick={() => onedit(row)}>- <Icon name="note" size={13} />- </button>- {#if !isPlace}- <button- class="act"- disabled={fullscreen}- title={blocked ?? 'Send to Geo Proof'}- onclick={() => onproof(row)}- ><Icon name="proof" size={13} /></button>- {/if}- <button class="act danger" title="Delete" onclick={() => ondelete(row)}>- <Icon name="trash" size={13} />- </button>{/if}+ <button class="act danger" title="Delete" onclick={() => ondelete(row)}>+ <Icon name="trash" size={13} />+ </button></div>{/if}</div>@@ -264,7 +252,6 @@text-overflow: ellipsis;white-space: nowrap;}- .title .point { margin-left: 5px; color: var(--text-3); }.open:hover:not(:disabled) .title {color: var(--accent);}diff --git a/frontend/src/tools/satellite/SavedSearch.svelte b/frontend/src/tools/satellite/SavedSearch.svelteindex a9203d0..577968a 100644--- a/frontend/src/tools/satellite/SavedSearch.svelte+++ b/frontend/src/tools/satellite/SavedSearch.svelte@@ -21,7 +21,7 @@coords,fullscreen = false,centre = null,- kind = $bindable('all'),+ kind = $bindable('media'),query = $bindable(''),hoveredId = $bindable(null),onclose,@@ -37,8 +37,8 @@const CAP = 200;let sort = $state('newest');- // one line per thing: a proof that touches two places is two marks on the- // map, but repeating it here would read as two proofs+ // one line per thing: a file standing in two places is two marks on the map,+ // but repeating it here would read as two filesconst found = $derived(sortSaved(oneEach(filterSaved(rows, { kind, query })), sort, centre));const shown = $derived(found.slice(0, CAP));@@ -55,7 +55,6 @@{#each KINDS as k (k.id)}<buttonclass="kind"- class:mode={k.mode}class:on={kind === k.id}onclick={() => (kind = k.id)}>{k.label}</button>@@ -133,13 +132,6 @@.kind:hover {color: var(--text-1);}- /* Proofs is a mode, not a refinement of the three to its left */- .kind.mode {- margin-left: 5px;- border-left: 1px solid var(--border);- padding-left: 12px;- border-radius: 0 2px 2px 0;- }.kind.on {background: var(--bg-3);color: var(--text-1);diff --git a/frontend/src/tools/satellite/SavedTree.svelte b/frontend/src/tools/satellite/SavedTree.svelteindex 1ccb891..8eecd58 100644--- a/frontend/src/tools/satellite/SavedTree.svelte+++ b/frontend/src/tools/satellite/SavedTree.svelte@@ -30,7 +30,7 @@caseId,coords,fullscreen = false,- kind = $bindable('all'),+ kind = $bindable('media'),query = $bindable(''),group = $bindable('geo'), // 'geo' | 'folders'hoveredId = $bindable(null),@@ -56,8 +56,9 @@? { levels: [], nodes: folderTree.nodes, trailing: folderTree.unfiled }: { levels: geoTree.levels, nodes: geoTree.nodes, trailing: geoTree.unlocated });- // Locate resolves saved entities. A proof states its own point or borrows one,- // so the pass has nothing to look up there and the errand must not be offered.+ // Locate resolves saved entities. A file borrows the point of whatever places+ // it, so the pass has nothing to look up there and the errand must not be+ // offered.const pending = $derived(isMode(kind) ? 0 : pendingLocate(rows));const searching = $derived(!!query.trim());const shown = $derived(@@ -150,7 +151,6 @@{#each KINDS as k (k.id)}<buttonclass="kind"- class:mode={k.mode}class:on={kind === k.id}onclick={() => (kind = k.id)}>{k.label}</button>@@ -350,14 +350,6 @@.kind:hover {color: var(--text-1);}- /* Proofs and Media are modes, not refinements of the three to their left: one- rule before the first of them says so without spending a word on it */- .kind:not(.mode) + .kind.mode {- margin-left: 5px;- border-left: 1px solid var(--border);- padding-left: 5px;- border-radius: 0 2px 2px 0;- }.kind.on {background: var(--bg-3);color: var(--text-1);diff --git a/frontend/src/tools/satellite/SavedTree.test.js b/frontend/src/tools/satellite/SavedTree.test.jsindex cc67a32..d146a22 100644--- a/frontend/src/tools/satellite/SavedTree.test.js+++ b/frontend/src/tools/satellite/SavedTree.test.js@@ -120,30 +120,32 @@ describe('SavedTree', () => {expect(at({ query: 'bridge' })).not.toContain('built here');});- it('does not offer Locate on proofs, which the pass cannot resolve', () => {- // Locate walks saved entities; a proof borrows or states its point, so the- // button would run and change nothing- const unplaced = { ...rows[0], id: 'pr1', key: 'pr1@x', kind: 'proof', geo: null };-- expect(at({ rows: [unplaced], kind: 'proofs' })).not.toContain('Locate');- expect(at({ rows: [unplaced], kind: 'all' })).toContain('Locate');+ it('does not offer Locate on media, which the pass cannot resolve', () => {+ // Locate walks saved entities; a file borrows the point of whatever places+ // it, so the button would run and change nothing+ const unplaced = { ...rows[0], id: 'm1', key: 'm1@x', kind: 'media', geo: null };++ expect(at({ rows: [unplaced], kind: 'media' })).not.toContain('Locate');+ // the same row as a saved point is exactly what the pass is for+ expect(+ at({ rows: [{ ...unplaced, kind: 'place' }], kind: 'places' })+ ).toContain('Locate');});- it('groups proofs by folder too, since a proof is filed like anything else', () => {- const proof = {- id: 'pr1',- key: '[email protected],30.52',- kind: 'proof',- name: 'kyiv-bridge',+ it('groups media by folder too, since a file is filed like anything else', () => {+ const clip = {+ id: 'm1',+ key: '[email protected],30.52',+ kind: 'media',+ media_kind: 'video',title: 'Kyiv bridge',lat: 50.45,lon: 30.52,geo: ua('Kyiv Oblast'),continent: 'Europe',fetched_at: '2026-07-21T09:12:04Z',- posts: 0,};- const body = at({ rows: [proof], kind: 'proofs', query: 'kyiv' });+ const body = at({ rows: [clip], kind: 'media', query: 'kyiv' });expect(body).toContain('Kyiv bridge');expect(body).toContain('Kyiv Oblast');@@ -152,8 +154,8 @@ describe('SavedTree', () => {expect(body).not.toContain('disabled=""');const filed = at({- rows: [{ ...proof, folder: 'recon/bridges' }],- kind: 'proofs',+ rows: [{ ...clip, folder: 'recon/bridges' }],+ kind: 'media',group: 'folders',folders: ['recon', 'recon/bridges'],query: 'kyiv',@@ -169,15 +171,21 @@ describe('SavedTree', () => {it('offers Locate only when something is still resolvable', () => {// nocoords and nocountry are settled — asking again would waste a lookup- expect(at()).not.toContain('Locate');- expect(at({ rows: [...rows, { ...rows[0], id: 'p2', geo: null }] })).toContain('Locate');- expect(at({ rows: [...rows, { ...rows[0], id: 'p2', geo: { state: 'failed' } }] })).toContain(- 'Locate'- );+ expect(at({ kind: 'places' })).not.toContain('Locate');+ expect(+ at({ kind: 'places', rows: [...rows, { ...rows[0], id: 'p2', geo: null }] })+ ).toContain('Locate');+ expect(+ at({ kind: 'places', rows: [...rows, { ...rows[0], id: 'p2', geo: { state: 'failed' } }] })+ ).toContain('Locate');});it('reports progress and offers a way out while a pass runs', () => {- const body = at({ locating: { done: 12, total: 134 }, rows: [...rows, { ...rows[0], id: 'p2', geo: null }] });+ const body = at({+ kind: 'places',+ locating: { done: 12, total: 134 },+ rows: [...rows, { ...rows[0], id: 'p2', geo: null }],+ });expect(body).toContain('12');expect(body).toContain('134');@@ -192,7 +200,9 @@ describe('SavedTree', () => {});it('says what an empty panel is empty of, and what a dead search found', () => {- expect(at({ rows: [] })).toContain('Save a place or capture a crop');+ expect(at({ rows: [], kind: 'places' })).toContain('Save a place or capture a crop');+ // the position the panel opens on is empty of something else entirely+ expect(at({ rows: [] })).toContain('No photo or video is placed yet');expect(at({ query: 'zzzz' })).toContain('Nothing saved matches that');});});diff --git a/frontend/src/tools/satellite/state/saved.svelte.js b/frontend/src/tools/satellite/state/saved.svelte.jsindex eb11cf5..c1b2691 100644--- a/frontend/src/tools/satellite/state/saved.svelte.js+++ b/frontend/src/tools/satellite/state/saved.svelte.js@@ -1,12 +1,11 @@/*** The case's saved work, as the Map's panel reads it.*- * Three indexes, not one: places, captures and filed screenshots come back in- * one compact index when a case opens, while proofs and located media are each- * read only once their position is opened — a case must not pay for a view it- * may never show. Both lazy ones are keyed on the case *and its revision*,- * because filing a proof reloads the case and a stale list would still show the- * folder the proof just left.+ * Two indexes, not one: places, captures and filed screenshots come back in one+ * compact index when a case opens, while located media is read only once its+ * position is opened — a case must not pay for a view it may never show. The+ * lazy one is keyed on the case *and its revision*, because placing a file+ * reloads the case and a stale list would still show the folder it just left.** `runLocate` is the one long act here: filling in the country of everything* that still has none, one batch at a time because Nominatim allows one lookup@@ -32,16 +31,13 @@ function loadGroup() {}}-/** Where each mode's rows come from. */-const MODE_INDEX = {- proofs: (caseId) => `/api/cases/${caseId}/proofs/index`,- media: (caseId) => `/api/cases/${caseId}/satellite/media`,-};+/** Where the Media position's rows come from. */+const MEDIA_INDEX = (caseId) => `/api/cases/${caseId}/satellite/media`;export function createSavedState({ api, notify, assignFolder, reloadCase }) {let rows = $state([]);- // one list per mode, read the first time that position is opened- let modeRows = $state({ proofs: [], media: [] });+ // the located files, read the first time that position is opened+ let mediaRows = $state([]);// Media first: a map opened on a case answers "what footage do I have, and// where" before it lists every pin the analyst has dropped.let kind = $state('media');@@ -59,15 +55,15 @@ export function createSavedState({ api, notify, assignFolder, reloadCase }) {let acceptingId = $state(null);let rowsFor = null; // the case id every index was loaded for- let modeFor = { proofs: null, media: null }; // the case id *and revision* each was read for+ let mediaFor = null; // the case id *and revision* the media index was read forlet locateStopped = false;let locateGeneration = 0;/** Everything a different case must not inherit. */function reset() {rows = [];- modeRows = { proofs: [], media: [] };- modeFor = { proofs: null, media: null };+ mediaRows = [];+ mediaFor = null;locateStopped = true;locateGeneration += 1;locating = null;@@ -98,26 +94,25 @@ export function createSavedState({ api, notify, assignFolder, reloadCase }) {}/**- * The index behind the open mode, the first time that position is opened.+ * The media index, the first time that position is opened.** An answer lands only while its case and revision are still the ones asked* about. Leaving the position before it arrives keeps it rather than throwing* it away: that stamp is already spent, and coming back would find nothing.*/function loadMode(caseId, rev) {- const mode = kind;const stamp = `${caseId}:${rev}`;- if (!caseId || !isMode(mode) || modeFor[mode] === stamp) return;- modeFor = { ...modeFor, [mode]: stamp };+ if (!caseId || !isMode(kind) || mediaFor === stamp) return;+ mediaFor = stamp;api- .get(MODE_INDEX[mode](caseId))+ .get(MEDIA_INDEX(caseId)).then((answer) => {- if (modeFor[mode] === stamp) modeRows = { ...modeRows, [mode]: answer };+ if (mediaFor === stamp) mediaRows = answer;}).catch(() => {- if (modeFor[mode] !== stamp) return;- modeRows = { ...modeRows, [mode]: [] };- modeFor = { ...modeFor, [mode]: null };+ if (mediaFor !== stamp) return;+ mediaRows = [];+ mediaFor = null;});}@@ -198,11 +193,11 @@ export function createSavedState({ api, notify, assignFolder, reloadCase }) {*/async function move(caseId, row, folder) {// the row's kind *is* its entity type, bar the screenshot that rides the- // capture type. Filing a proof as a capture would route it to PATCH /media,+ // capture type. Filing a place as a capture would route it to PATCH /media,// the sidecar of an image it is not.const entity = {id: row.id,- type: ['place', 'proof', 'media'].includes(row.kind) ? row.kind : 'capture',+ type: ['place', 'media'].includes(row.kind) ? row.kind : 'capture',attrs: { path: row.path },};try {@@ -228,11 +223,8 @@ export function createSavedState({ api, notify, assignFolder, reloadCase }) {set rows(value) {rows = value;},- get proofs() {- return modeRows.proofs;- },get media() {- return modeRows.media;+ return mediaRows;},get kind() {return kind;@@ -274,9 +266,9 @@ export function createSavedState({ api, notify, assignFolder, reloadCase }) {return acceptingId;},- /** Proofs and media are positions of their own, and read their own index. */+ /** Media is a position of its own, and reads its own index. */get shownRows() {- return isMode(kind) ? modeRows[kind] : rows;+ return isMode(kind) ? mediaRows : rows;},/** What the panel is showing, which is also what the map layer draws. */get shown() {diff --git a/frontend/src/tools/satellite/state/saved.svelte.test.js b/frontend/src/tools/satellite/state/saved.svelte.test.jsindex 41e29c6..0e50c06 100644--- a/frontend/src/tools/satellite/state/saved.svelte.test.js+++ b/frontend/src/tools/satellite/state/saved.svelte.test.js@@ -15,7 +15,6 @@ const ROWS = [{ id: 'e2', kind: 'capture', path: 'media/a.png', title: 'a' },{ id: 'e3', kind: 'screenshot', path: 'media/b.png', title: 'b' },];-const PROOFS = [{ id: 'p1', kind: 'proof', path: 'proofs/x.png', name: 'x', title: 'x' }];const MEDIA = [{ id: 'm1', key: 'm1@1,2', kind: 'media', media_kind: 'video', path: 'media/clip.mp4', title: 'clip', lat: 1, lon: 2 },{ id: 'm1', key: 'm1@3,4', kind: 'media', media_kind: 'video', path: 'media/clip.mp4', title: 'clip', lat: 3, lon: 4 },@@ -40,7 +39,6 @@ beforeEach(() => {api = {get: vi.fn(async (path) => {calls.push(path);- if (path.includes('/proofs/index')) return PROOFS;if (path.includes('/satellite/media')) return MEDIA;return ROWS;}),@@ -62,19 +60,15 @@ describe('opening a case', () => {expect(store().kind).toBe('media');});- it('pays nothing for the proofs index until that position is opened', async () => {+ it('pays nothing for the media index while another position is open', async () => {const saved = store();- saved.kind = 'all';+ saved.kind = 'places';saved.load('case-1');saved.loadMode('case-1', 3);await vi.waitFor(() => expect(saved.rows).toHaveLength(3));expect(calls).toEqual(['/api/cases/case-1/satellite/index']);-- saved.kind = 'proofs';- saved.loadMode('case-1', 3);- await vi.waitFor(() => expect(saved.proofs).toHaveLength(1));- // …and the proofs position reads its own rows, not the compact index- expect(saved.shownRows).toEqual(PROOFS);+ // the two that filter read the compact index and nothing else+ expect(saved.shownRows).toEqual(ROWS);expect(calls.some((path) => path.includes('/satellite/media'))).toBe(false);});@@ -87,13 +81,12 @@ describe('opening a case', () => {expect(saved.shown.map((row) => row.key)).toEqual(['m1@1,2', 'm1@3,4']);});- it('re-reads a mode index when the case is reloaded, not only when it changes', async () => {- // filing a proof reloads the case; keying only on the id would leave the- // panel showing the folder the proof just left+ it('re-reads the media index when the case is reloaded, not only when it changes', async () => {+ // filing a file reloads the case; keying only on the id would leave the+ // panel showing the folder it just leftconst saved = store();- saved.kind = 'proofs';saved.loadMode('case-1', 3);- await vi.waitFor(() => expect(saved.proofs).toHaveLength(1));+ await vi.waitFor(() => expect(saved.media).toHaveLength(2));const before = api.get.mock.calls.length;saved.loadMode('case-1', 3);expect(api.get).toHaveBeenCalledTimes(before); // same revision: nothing to re-read@@ -108,7 +101,7 @@ describe('opening a case', () => {api.get = vi.fn(() => new Promise((resolve) => (release = () => resolve(MEDIA))));const saved = store();saved.loadMode('case-1', 1);- saved.kind = 'all';+ saved.kind = 'places';release();await vi.waitFor(() => expect(saved.media).toHaveLength(2));});@@ -117,13 +110,10 @@ describe('opening a case', () => {const saved = store();saved.load('case-1');saved.loadMode('case-1', 1);- saved.kind = 'proofs';- saved.loadMode('case-1', 1);- await vi.waitFor(() => expect(saved.proofs).toHaveLength(1));+ await vi.waitFor(() => expect(saved.rows).toHaveLength(3));await vi.waitFor(() => expect(saved.media).toHaveLength(2));saved.load('case-2');expect(saved.rows).toEqual([]);- expect(saved.proofs).toEqual([]);expect(saved.media).toEqual([]);});@@ -291,13 +281,13 @@ describe('acting on a row', () => {});it('files a dragged row through its own entity type', async () => {- // a proof filed as a capture would be routed to PATCH /media, the sidecar- // of an image the proof is not+ // a place filed as a capture would be routed to PATCH /media, the sidecar+ // of an image the place is notconst saved = store();- await saved.move('case-1', { id: 'p1', kind: 'proof', path: 'proofs/x.png' }, 'Quays');+ await saved.move('case-1', { id: 'e1', kind: 'place', path: null }, 'Quays');expect(assignFolder).toHaveBeenCalledWith('case-1',- { id: 'p1', type: 'proof', attrs: { path: 'proofs/x.png' } },+ { id: 'e1', type: 'place', attrs: { path: null } },'Quays');await saved.move('case-1', { id: 'e3', kind: 'screenshot', path: 'media/b.png' }, '');diff --git a/src/azimut/api/analyzers.py b/src/azimut/api/analyzers.pyindex da81766..802638b 100644--- a/src/azimut/api/analyzers.py+++ b/src/azimut/api/analyzers.py@@ -30,7 +30,7 @@ def recipes() -> dict[str, Any]:continuereturn {"builtins": [r.model_dump() for r in BUILTINS], "custom": custom, "methods": METHODS,"max_tiles": engine.MAX_TILES, "max_results": engine.MAX_RESULTS,- "grids": {name: list(pair) for name, pair in engine.GRIDS.items()}}+ "grid": list(engine.GRID)}@router.post("/compare/analyzers")@@ -180,12 +180,15 @@ def review_result(case_id: str, ident: str, result_id: str, body: Review) -> dic# invents nothing, so what is on screen is still the sensor's own reading.PREVIEW_EDGE = 320PREVIEW_MARGIN = 20+# The most of the sweep one preview shows, in source pixels. A burn scar can be+# kilometres across; past this the crop is centred on the candidate.+PREVIEW_SPAN = 1024def source_label(source: dict[str, Any]) -> str:- if source.get("provider") == "sentinel2":- return str(source.get("date") or "Sentinel-2")- return f"Release {source.get('release')}"+ if source.get("provider") == "esri-wayback":+ return f"Release {source.get('release')}"+ return str(source.get("date") or "Sentinel-2")def kept_entity(case: Any, result: dict[str, Any]) -> dict[str, Any] | None:@@ -194,22 +197,65 @@ def kept_entity(case: Any, result: dict[str, Any]) -> dict[str, Any] | None:return case.get_entity(ident) if ident else None-def preview_bytes(case: Any, saved: dict[str, Any], result: dict[str, Any], part: int = 0) -> bytes:- if part >= len(result["parts"]):- raise HTTPException(404, "candidate evidence part not found")- evidence = result["parts"][part]- x, y, width, height = evidence["box"]+def _tile_image(case: Any, saved: dict[str, Any], source: dict[str, Any],+ tile: tuple[int, int, int]) -> Image.Image | None:+ for record in saved["frames"].values():+ if record.get("index") is None and tuple(record["tile"]) == tile and \+ record["source"] == source:+ path = case.resolve_inside(record["path"])+ if path.is_file():+ with Image.open(path) as image:+ if max(image.size) > 512:+ raise HTTPException(422, "evidence frame has an unexpected size")+ return image.convert("RGB")+ return None+++def preview_bytes(case: Any, saved: dict[str, Any], result: dict[str, Any]) -> bytes:+ """One picture per date, stitched across every tile the candidate touches.++ A candidate that crosses a tile edge is still one thing, so it is shown as+ one: the tiles its parts came from are laid side by side on the sweep's own+ grid, and a neighbour the sweep kept no copy of is left dark rather than+ guessed at.+ """+ first = saved["frames"].get(result["parts"][0]["frames"][0])+ if first is None:+ raise HTTPException(404, "candidate evidence is missing")+ z = first["tile"][0]+ with Image.open(case.resolve_inside(first["path"])) as image:+ size = image.width+ sources = [saved["frames"][key]["source"] for key in result["parts"][0]["frames"]]+ boxes = []+ for part in result["parts"]:+ record = saved["frames"].get(part["frames"][0])+ if record is None:+ continue+ _, tx, ty = record["tile"]+ x, y, width, height = part["box"]+ boxes.append((tx * size + x, ty * size + y, tx * size + x + width, ty * size + y + height))+ if not boxes:+ raise HTTPException(404, "candidate evidence is missing")+ left = min(b[0] for b in boxes) - PREVIEW_MARGIN+ top = min(b[1] for b in boxes) - PREVIEW_MARGIN+ right = max(b[2] for b in boxes) + PREVIEW_MARGIN+ bottom = max(b[3] for b in boxes) + PREVIEW_MARGIN+ if right - left > PREVIEW_SPAN:+ centre = (left + right) // 2+ left, right = centre - PREVIEW_SPAN // 2, centre + PREVIEW_SPAN // 2+ if bottom - top > PREVIEW_SPAN:+ centre = (top + bottom) // 2+ top, bottom = centre - PREVIEW_SPAN // 2, centre + PREVIEW_SPAN // 2+crops = []- for key in evidence["frames"]:- record = saved["frames"][key]- path = case.resolve_inside(record["path"])- with Image.open(path) as image:- if max(image.size) > 512:- raise HTTPException(422, "evidence frame has an unexpected size")- crops.append(image.convert("RGB").crop((- max(0, x - PREVIEW_MARGIN), max(0, y - PREVIEW_MARGIN),- min(image.width, x + width + PREVIEW_MARGIN),- min(image.height, y + height + PREVIEW_MARGIN))))+ for source in sources:+ canvas = Image.new("RGB", (right - left, bottom - top), (20, 24, 32))+ for ty in range(top // size, (bottom - 1) // size + 1):+ for tx in range(left // size, (right - 1) // size + 1):+ tile = _tile_image(case, saved, source, (z, tx, ty))+ if tile is not None:+ canvas.paste(tile, (tx * size - left, ty * size - top))+ crops.append(canvas)edge = max(max(crop.size) for crop in crops)zoom = max(1, min(12, round(PREVIEW_EDGE / edge))) if edge else 1if zoom > 1:@@ -230,13 +276,13 @@ def preview_bytes(case: Any, saved: dict[str, Any], result: dict[str, Any], partpreview = Image.new("RGB", (sum(c.width for c in crops) + gap * (len(crops) - 1),body + band * 2), (20, 24, 32))drawing = ImageDraw.Draw(preview)- left = 0+ offset = 0for label, crop in zip(labels, crops):- preview.paste(crop, (left, band))- drawing.text((left + 4, 4), label, fill="white", font=font)- left += crop.width + gap- attribution = ("Copernicus Sentinel data / Sentinel Hub" if- saved["input"]["b"]["provider"] == "sentinel2" else "Esri World Imagery Wayback")+ preview.paste(crop, (offset, band))+ drawing.text((offset + 4, 4), label, fill="white", font=font)+ offset += crop.width + gap+ attribution = ("Esri World Imagery Wayback" if saved["input"]["b"].get("provider") ==+ "esri-wayback" else "Copernicus Sentinel data / Sentinel Hub")drawing.text((4, band + body + 5), attribution, fill="#c8ced6", font=small)output = io.BytesIO()preview.save(output, "PNG")@@ -244,13 +290,11 @@ def preview_bytes(case: Any, saved: dict[str, Any], result: dict[str, Any], part@router.get("/cases/{case_id}/analysis/runs/{ident}/results/{result_id}/preview")-def preview(case_id: str, ident: str, result_id: str, part: int = 0) -> Response:- if part < 0:- raise HTTPException(422, "invalid evidence part")+def preview(case_id: str, ident: str, result_id: str) -> Response:case = get_case(case_id)saved = read(case, "runs", ident)result = result_of(saved, result_id)- return Response(preview_bytes(case, saved, result, part), media_type="image/png")+ return Response(preview_bytes(case, saved, result), media_type="image/png")class Promotion(Model):diff --git a/src/azimut/api/compare.py b/src/azimut/api/compare.pyindex 50ea88e..2e0e1d6 100644--- a/src/azimut/api/compare.py+++ b/src/azimut/api/compare.py@@ -2,7 +2,7 @@A session stores the reading, not its pixels: the two providers and theirvariants, independent reference layers, the shared camera, the comparison mode,-Change assist settings and ground-anchored annotations. It lives under+Difference settings and ground-anchored annotations. It lives under``.compare/``.Its rendered image is a media working file, filed through the media pipeline@@ -98,18 +98,22 @@ def _change_classes() -> list[ChangeClass]:class CompareChangeAssist(BaseModel):method: Literal["colour", "structure", "brightness", "index"] = "colour"- index: Literal["ndvi", "ndwi", "nbr", "ndbi"] = "ndvi"+ index: Literal["ndvi", "ndwi", "mndwi", "nbr", "ndbi", "bsi"] = "ndvi"threshold: Literal["auto", "manual"] = "auto"sensitivity: int = Field(default=55, ge=0, le=100)- normalize: Literal["none", "mean", "histogram"] = "histogram"+ # "auto" is nothing on Sentinel-2, whose passes are already corrected, and a+ # histogram on Esri releases, which carry two renderings.+ normalize: Literal["auto", "none", "mean", "histogram"] = "auto"smoothing: int = Field(default=1, ge=0, le=4)alignment: int = Field(default=4, ge=0, le=8)cleanup: int = Field(default=1, ge=0, le=3)min_area: float = Field(default=0, ge=0, le=1_000_000)ignore_clouds: bool = Falseignore_shadows: bool = False- # How far to grow the cloud and shadow mask, in working pixels.- cloud_margin: int = Field(default=2, ge=0, le=10)+ # How far to grow the cloud and shadow mask, in ground metres: the reading+ # follows the camera, so a count of pixels would mean a different distance+ # at every zoom.+ cloud_margin: int = Field(default=50, ge=0, le=200)classes: list[ChangeClass] = Field(default_factory=_change_classes, max_length=3)@@ -120,7 +124,8 @@ class CompareChangeAssist(BaseModel):# "side" lays the same reading over both images instead of one of them.base: Literal["a", "b", "side"] = "b"visible: bool = True- live: bool = True+ # Flashing the overlay on and off, which is easier to catch than a still one.+ blink: bool = FalseAnnotationKind = Literal[@@ -247,7 +252,7 @@ def change_refusal(a: dict[str, Any], b: dict[str, Any], method: str = "colour")grade is explanation, and the browser shows it."""if not a["present"] or not b["present"]:- return "Change assist needs imagery A and B"+ return "Difference needs imagery A and B"if method == "index":if a["provider"] != "sentinel2" or b["provider"] != "sentinel2":return "Spectral indices need Sentinel-2 on both sides"@@ -296,7 +301,7 @@ def change_refusal(a: dict[str, Any], b: dict[str, Any], method: str = "colour")if not _same_layers(a, b, skip="nightlights"):return "Match every other layer on A and B"return None- return "Change assist reads Sentinel-2, Esri imagery releases or VIIRS night-light pairs"+ return "Difference reads Sentinel-2, Esri imagery releases or VIIRS night-light pairs"def _read_session(case: Case, name: str) -> dict[str, Any] | None:@@ -596,8 +601,8 @@ async def export_gif(return {"file": path.name, "path": str(export_destination), "animation": animation}-class IndexFrameIn(BaseModel):- """A Web Mercator box, its pixel size, and the pass to read an index from."""+class BandFrameIn(BaseModel):+ """A Web Mercator box, its pixel size, and the pass to read a band frame from."""west: floatsouth: float@@ -606,18 +611,19 @@ class IndexFrameIn(BaseModel):width: int = Field(ge=1, le=sentinel.PRODUCT_MAX_EDGE)height: int = Field(ge=1, le=sentinel.PRODUCT_MAX_EDGE)day: str = Field(pattern=r"^\d{4}-\d{2}-\d{2}$")- index: Literal["ndvi", "ndwi", "nbr", "ndbi"]+ # A spectral index, or `sky` alone for a cloud filter over the picture methods.+ product: Literal["ndvi", "ndwi", "mndwi", "nbr", "ndbi", "bsi", "sky"]maxcc: int = Field(default=100, ge=0, le=100)layer: str = Field(default="TRUE_COLOR", min_length=1, max_length=40)[email protected]("/compare/sentinel-index")-def sentinel_index(body: IndexFrameIn) -> Response:- """Render one Sentinel-2 spectral index over the compared frame.[email protected]("/compare/sentinel-frame")+def sentinel_frame(body: BandFrameIn) -> Response:+ """Render one Sentinel-2 band frame over the compared view.- Asked only when the analyst runs Change assist in index mode. One metered- Sentinel Hub request per side, refused like the tiles once the monthly- free tier is nearly spent.+ Asked only when the analyst runs Difference with a spectral index or with the+ cloud filter over Sentinel-2. One metered Sentinel Hub request per side,+ refused like the tiles once the monthly free tier is nearly spent."""instance = (config.load_settings().get("api_keys") or {}).get("sentinelhub")if not instance:@@ -635,7 +641,7 @@ def sentinel_index(body: IndexFrameIn) -> Response:body.width,body.height,body.day,- body.index,+ f"change-{body.product}",body.maxcc,layer=body.layer,)@@ -644,6 +650,6 @@ def sentinel_index(body: IndexFrameIn) -> Response:raise HTTPException(status_code=422, detail=str(exc)) from excexcept Exception as exc:config.record_usage("sentinelhub", 1)- raise HTTPException(status_code=502, detail=f"index request failed: {exc}") from exc+ raise HTTPException(status_code=502, detail=f"band request failed: {exc}") from excconfig.record_usage("sentinelhub", 1)return Response(content=data, media_type="image/png", headers={"Cache-Control": "no-store"})diff --git a/src/azimut/api/ingest.py b/src/azimut/api/ingest.pyindex 828a47d..19b47dc 100644--- a/src/azimut/api/ingest.py+++ b/src/azimut/api/ingest.py@@ -33,7 +33,7 @@ import warningsimport zipfilefrom collections.abc import Callablefrom datetime import datetime, timezone-from typing import Any+from typing import Any, Literalfrom urllib.parse import urlsplitfrom fastapi import (@@ -517,18 +517,33 @@ class GridMarksIn(BaseModel):@router.get("/saved", dependencies=[Depends(require_token)])-def saved_points(case_id: str) -> list[dict[str, Any]]:- """The case's saved points, for drawing over another map.+def saved_points(+ case_id: str, kind: Literal["media", "places", "captures"] = "media"+) -> list[dict[str, Any]]:+ """The case's points, for drawing over another map.- Trimmed to what a pin needs. The app's own index carries thumbnails, folder+ One position at a time, the same three the app's own panel offers and in the+ same order: the located footage, the points dropped by hand, the imagery+ captured. Media reads its own index — a file carries no coordinates and+ stands where the graph puts it — and the other two filter the saved one.++ Trimmed to what a pin needs. The app's own indexes carry thumbnails, foldercounts, continents and link tallies, all of which would cross into theextension for no use: it draws a dot with a name on it."""- rows = satellite_engine.saved_index(get_case(case_id))+ case = get_case(case_id)+ if kind == "media":+ rows = satellite_engine.media_index(case)+ else:+ wanted = ("place",) if kind == "places" else ("capture", "screenshot")+ rows = [row for row in satellite_engine.saved_index(case) if row["kind"] in wanted]return [{"id": row["id"],"kind": row["kind"],+ # a photograph and a video are drawn with their own glyph, as the app+ # draws them; absent on everything else+ **({"media_kind": row["media_kind"]} if row.get("media_kind") else {}),"title": row["title"],"lat": row["lat"],"lon": row["lon"],diff --git a/src/azimut/api/proofs.py b/src/azimut/api/proofs.pyindex 1f25cf0..46f7399 100644--- a/src/azimut/api/proofs.py+++ b/src/azimut/api/proofs.py@@ -37,7 +37,6 @@ from ..engine import thumbnails as thumbnail_enginefrom ..workspace import Case, CaseError, ensure_dirfrom .cases import delete_by_path, get_casefrom .cases.common import delete_entity_deep-from .drafts import list_draftsfrom .naming import read_created_at, slugifyfrom .satellite import locate_on_savefrom .. import layout@@ -237,18 +236,6 @@ def _write_assets(folder: Path, incoming: dict[str, bytes], keep: set[str]) -> Nfolder.rmdir()[email protected]("/cases/{case_id}/proofs/index")-def proof_index(case_id: str) -> list[dict[str, Any]]:- """Proofs as map rows, for the Saved panel's Proofs position.-- Declared above ``/proofs/{name}`` so ``index`` is read as this route and not- as a proof called "index". Lazy by design: the Saved panel loads it the- first time that position is opened, never on case open.- """- case = get_case(case_id)- return satellite_engine.proof_index(case, list_proofs(case_id), list_drafts(case_id))--@router.get("/cases/{case_id}/proofs")def list_proofs(case_id: str) -> list[dict[str, Any]]:case = get_case(case_id)diff --git a/src/azimut/engine/analysis_models.py b/src/azimut/engine/analysis_models.pyindex f12bf45..e020d97 100644--- a/src/azimut/engine/analysis_models.py+++ b/src/azimut/engine/analysis_models.py@@ -1,56 +1,50 @@-"""Portable recipes and geographic inputs for Compare analyzers.+"""Portable recipes and geographic inputs for Compare's Detect mode.-Models describe capabilities by stable ids. A later model adapter can join the-method registry without changing saved runs or accepting executable recipes.+Detect reads Copernicus Sentinel-2 only. Every method measures reflectance,+which a rendered picture has already stretched away, so a source that serves+pictures has nothing to offer it. Models describe capabilities by stable ids,+and a saved run keeps meaning what it meant when it ran."""from __future__ import annotationsimport mathfrom datetime import date-from typing import Annotated, Literal+from typing import Annotated, Any, Literalfrom pydantic import BaseModel, ConfigDict, Field, FiniteFloat, model_validator-Provider = Literal["esri-wayback", "sentinel2"]-Method = Literal["colour", "structure", "brightness", "index", "water_objects", "smoke",- "vessels", "hotspots"]+Method = Literal["vessels", "hotspots", "structure", "spots", "surface", "index"]+Index = Literal["ndvi", "ndwi", "mndwi", "nbr", "ndbi", "bsi"]ShortId = Annotated[str, Field(pattern=r"^[a-zA-Z0-9_-]{1,48}$")]Colour = Annotated[str, Field(pattern=r"^#[0-9a-fA-F]{6}$")]# Methods that read one image instead of a pair. A vessel or a fire is a thing-# present on a date, not a difference between two of them, so asking for a-# reference image would be asking for something the method cannot use.-SINGLE_METHODS = frozenset({"water_objects", "vessels", "hotspots"})--# Methods that measure reflectance, which a rendered picture has already-# stretched away. Each needs the band product named here, fetched beside the-# picture the analyst reviews. `index` picks its product from the recipe's-# parameters instead, so it is not in this table.-PRODUCT_METHODS: dict[str, str] = {"vessels": "vessel", "hotspots": "fire"}--# Reflectance is Copernicus only: Wayback serves pictures, not bands.-SENTINEL_ONLY = frozenset({"index", *PRODUCT_METHODS})--# How each method can exclude cloud and the shadow it casts.-#-# ``classes`` reads Sentinel-2's own per-pixel scene classification, which is-# the real answer. ``picture`` has only the rendered image, so it goes on what-# cloud looks like — bright and colourless, its shadow near-black — which is a-# guess, and the UI says so rather than dressing it up.-#-# Three methods are absent on purpose. The fire test rejects cloud by its band-# ratios and spends its fourth channel on the data mask instead. Smoke and-# bright shapes on water *are* bright and colourless: there, the picture test-# would mask the very thing the method looks for.-CLOUD_FILTERS: dict[str, str] = {- "index": "classes", "vessels": "classes",- "colour": "picture", "structure": "picture", "brightness": "picture",+# present on a date, not a difference between two of them.+SINGLE_METHODS = frozenset({"vessels", "hotspots"})++# The band product each method measures, fetched beside the picture the analyst+# reviews. `index` reads the one its parameters name.+PRODUCT_METHODS: dict[str, str] = {+ "vessels": "vessel", "hotspots": "fire",+ "structure": "surface", "spots": "surface", "surface": "surface",}+# Where the cloud and shadow switches mean something. The fire test rejects+# cloud through its own band ratios, and a mask would also take the smoke a+# fire burns under.+CLOUD_METHODS = frozenset({"vessels", "structure", "spots", "surface", "index"})-def both_providers() -> list[Provider]:- return ["esri-wayback", "sentinel2"]+# What a recipe saved before Detect went Copernicus-only asked for. The picture+# methods measured colour on a rendered image; reflectance change is what they+# were reaching for.+LEGACY_METHODS = {"colour": "surface", "brightness": "surface", "smoke": "surface",+ "water_objects": "vessels"}+LEGACY_PARAMETERS = ("min_score", "normalize", "guess_clouds")+++def product_for(method: str, index: str) -> str:+ return f"index-{index}" if method == "index" else PRODUCT_METHODS[method]class Model(BaseModel):@@ -58,31 +52,59 @@ class Model(BaseModel):class Parameters(Model):- sensitivity: int = Field(default=55, ge=0, le=100)- min_area: FiniteFloat = Field(default=20, ge=0, le=100_000_000)- min_score: FiniteFloat = Field(default=0, ge=0, le=1)- cleanup: int = Field(default=1, ge=0, le=3)+ # Moves each method's threshold inside the range it was calibrated over+ # (engine/analyzers.py), so the same number means "about as picky" everywhere.+ sensitivity: int = Field(default=60, ge=0, le=100)+ min_area: FiniteFloat = Field(default=0, ge=0, le=100_000_000)+ # 0 is no ceiling. A cloud bank or an island is far bigger than any hull,+ # and a ceiling is what stops it being offered as one.+ max_area: FiniteFloat = Field(default=0, ge=0, le=100_000_000)+ cleanup: int = Field(default=0, ge=0, le=3)smoothing: int = Field(default=0, ge=0, le=3)- normalize: bool = False- index: Literal["ndvi", "ndwi", "nbr", "ndbi"] = "ndvi"+ index: Index = "ndvi"direction: Literal["both", "gain", "loss"] = "both"- # Sentinel-2's own scene classification: the sensor says which pixels are- # cloud, so this is on by default.ignore_clouds: bool = Trueignore_shadows: bool = True- # The same exclusion where there is no classification to ask, read off the- # rendered picture instead. Off by default, and it stays off by default:- # bright and colourless is what a white roof, a gravel pad and fresh snow- # look like too, and those are things analysts come here to find. A guess- # this broad is the analyst's to make, never one made for them.- guess_clouds: bool = False- # A cloud fades out at its edges and its shadow has no edge at all, so both- # masks stop short of what a reader would call the cloud. Growing them by a- # couple of pixels takes the fringe that otherwise survives as a ring of- # candidates around every mask.- cloud_margin: int = Field(default=2, ge=0, le=10)+ # Metres are what a reader thinks in, but the mask is grown on the grid, and+ # a pixel there is 9.55 m at the equator: 5 takes the soft rim a scene+ # classification calls ground.+ cloud_margin: int = Field(default=5, ge=0, le=10)merge_metres: FiniteFloat = Field(default=0, ge=0, le=500)+ @model_validator(mode="before")+ @classmethod+ def legacy(cls, data: Any) -> Any:+ if isinstance(data, dict):+ return {key: value for key, value in data.items() if key not in LEGACY_PARAMETERS}+ return data+++# What Small, Medium, Large and All set, per method. A size is a coherent set of+# numbers rather than one: a smaller target needs a smaller floor *and* no+# morphological cleanup, which would erase it, and a larger one wants nearby+# pieces grouped. The panel applies these; nothing stores which size was picked.+_SIZE_KEYS = ("min_area", "max_area", "cleanup", "smoothing", "merge_metres")+#: No floor and no ceiling, so nothing is dropped for its size. A mark that+#: falls between two sizes is the one an analyst hunts for and never sees.+_ALL = dict(zip(_SIZE_KEYS, (0.0, 0.0, 0, 0, 0.0)))+++def _sizes(*rows: tuple[float, float, int, int, float]) -> dict[str, dict[str, float]]:+ named = {name: dict(zip(_SIZE_KEYS, row))+ for name, row in zip(("small", "medium", "large"), rows)}+ return {**named, "all": dict(_ALL)}+++_CHANGE_SIZES = _sizes((300, 0, 0, 0, 0), (2000, 0, 1, 0, 30), (20000, 0, 1, 1, 100))+SIZES: dict[str, dict[str, dict[str, float]]] = {+ "vessels": _sizes((0, 150_000, 0, 0, 30), (250, 150_000, 0, 0, 50), (2500, 400_000, 0, 0, 100)),+ "hotspots": _sizes((0, 0, 0, 0, 30), (250, 0, 0, 0, 60), (3000, 0, 0, 0, 200)),+ "structure": _sizes((100, 3000, 0, 0, 0), (600, 200_000, 0, 0, 20), (8000, 0, 1, 1, 60)),+ "spots": _sizes((0, 800, 0, 0, 0), (100, 2500, 0, 0, 0), (400, 8000, 0, 0, 20)),+ "surface": _CHANGE_SIZES,+ "index": _CHANGE_SIZES,+}+class Zone(Model):id: ShortId@@ -127,33 +149,41 @@ class Recipe(Model):name: str = Field(min_length=1, max_length=120)description: str = Field(default="", max_length=500)phenomenon: str = Field(default="Surface change", min_length=1, max_length=120)- method: Method = "colour"- providers: list[Provider] = Field(- default_factory=both_providers, min_length=1, max_length=2- )+ method: Method = "surface"parameters: Parameters = Field(default_factory=Parameters)colour: Colour = "#f6a81a"style: Literal["pins", "outlines", "both"] = "both"zones: list[Zone] = Field(default_factory=list, max_length=32)- @model_validator(mode="after")- def compatible(self) -> Recipe:- if self.method in SENTINEL_ONLY and self.providers != ["sentinel2"]:- raise ValueError("this method reads Copernicus Sentinel-2 bands, so it is "- "compatible with that source only")- return self+ @model_validator(mode="before")+ @classmethod+ def legacy(cls, data: Any) -> Any:+ if not isinstance(data, dict):+ return data+ data = {key: value for key, value in data.items() if key != "providers"}+ if data.get("method") in LEGACY_METHODS:+ data["method"] = LEGACY_METHODS[data["method"]]+ return dataclass Source(Model):- provider: Provider = "esri-wayback"+ provider: Literal["sentinel2"] = "sentinel2"date: str = Field(default="", max_length=10)- release: int | None = Field(default=None, ge=1, le=999999999)layer: str = Field(default="TRUE_COLOR", pattern=r"^[A-Z0-9_]{1,40}$")maxcc: int = Field(default=30, ge=0, le=100)+ @model_validator(mode="before")+ @classmethod+ def legacy(cls, data: Any) -> Any:+ # A Wayback release names no Sentinel-2 day, so a watch saved against+ # one comes back undated and asks for a date rather than failing to load.+ if isinstance(data, dict) and data.get("provider") == "esri-wayback":+ data = {key: value for key, value in data.items() if key not in ("provider", "release")}+ return data+@model_validator(mode="after")def dated(self) -> Source:- if self.provider == "sentinel2" and self.date:+ if self.date:try:date.fromisoformat(self.date)except ValueError as exc:@@ -176,69 +206,86 @@ class RunInput(ZoneSet):@model_validator(mode="after")def pair(self) -> RunInput:- if self.a.provider != self.b.provider or self.b.provider not in self.recipe.providers:- raise ValueError("use one compatible provider for both images")- if self.recipe.method != "index" and self.a.layer != self.b.layer:- raise ValueError("use the same rendering layer for both images")if len({zone.id for zone in self.zones}) != len(self.zones):raise ValueError("area ids must be unique")- single = self.recipe.method in SINGLE_METHODSrequired = []if self.date_rule == "manual":required.append(self.b)- if not single and (self.date_rule != "latest_previous" or not self.followup_id):+ if self.recipe.method not in SINGLE_METHODS and (+ self.date_rule != "latest_previous" or not self.followup_id+ ):required.append(self.a)- for source in required:- if source.provider == "sentinel2" and not source.date:- raise ValueError("choose a dated Sentinel-2 acquisition")- if source.provider == "esri-wayback" and source.release is None:- raise ValueError("choose a named Wayback release")+ if any(not source.date for source in required):+ raise ValueError("choose a dated Sentinel-2 acquisition")return self-# The names say what is measured, never what it means. "Vessels on water" is a-# claim about infrared contrast over sea, and the description is where the-# limits of that claim live — a preset called "Boats" would promise recognition-# no method here performs.+def _recipe(size: str = "medium", **fields: Any) -> Recipe:+ parameters = {**SIZES[fields["method"]][size], **fields.pop("parameters", {})}+ return Recipe(parameters=Parameters(**parameters), **fields)+++# Names say what an analyst is looking for; descriptions say what is measured+# and where that stops. None of these recognise an object: each one flags a+# reading, and the review is where it becomes a finding.BUILTINS = [- Recipe(id="large-change", name="Large surface change",- description="Broad changes in colour between two dated images. New construction, "- "clearing, earthworks and flooding all read as change; so does a different season.",- parameters=Parameters(min_area=500)),- Recipe(id="boats", name="Vessels on water (Sentinel-2)", method="vessels",- phenomenon="Vessel candidate",- providers=["sentinel2"],- description="Targets brighter than the sea around them in the near-infrared, which "- "water absorbs almost completely. Ships, rigs, buoys and breaking waves all qualify; "- "at 10 m a pixel, anything under about 20 m is unlikely to appear at all.",- parameters=Parameters(min_area=200, min_score=0.2, cleanup=0), colour="#38bdf8"),- Recipe(id="structures", name="New structures or ground disturbance", method="structure",- phenomenon="Possible structure or disturbed ground",- description="New or lost edges; buildings, roads and bare ground need visual review.",- parameters=Parameters(min_area=80), colour="#a78bfa"),- Recipe(id="anomaly", name="Active fire or hotspot (Sentinel-2)", method="hotspots",- phenomenon="Hotspot candidate",- providers=["sentinel2"],- description="Short-wave infrared high in absolute terms and high against the bands "- "either side of it, which is the published active-fire test. It sees flame through "- "smoke, and says nothing about what is burning or why.",- parameters=Parameters(min_area=100, cleanup=0), colour="#fb7185"),+ _recipe(id="boats", name="Vessels", method="vessels", phenomenon="Vessel candidate",+ description="Brighter than the water around it in near and short-wave infrared, "+ "which breaking waves and glint are not. Boats under about 20 m rarely show.",+ parameters={"sensitivity": 70}, colour="#38bdf8"),+ _recipe(id="anomaly", name="Fires and gas flares", method="hotspots",+ phenomenon="Hotspot candidate",+ description="Short-wave infrared well above the bands beside it, the published "+ "active-fire test. It sees flame through smoke, not what is burning.",+ parameters={"sensitivity": 60}, colour="#fb7185"),+ _recipe(id="structures", name="Construction and earthworks", method="structure",+ phenomenon="Possible structure or disturbed ground",+ description="Ground that turned brighter or darker in every band while its "+ "vegetation held. Crops are left out; wet soil and new shadows are not.",+ parameters={"sensitivity": 78}, colour="#a78bfa"),+ _recipe(id="impacts", name="Small spots: impacts, burns, vehicles", method="spots",+ phenomenon="Small change",+ description="A few pixels that changed while everything around them held still. "+ "A vehicle is smaller than a pixel, so look for the mark it left.",+ parameters={"sensitivity": 67}, colour="#f97316"),+ _recipe(id="large-change", name="Any surface change", method="surface",+ phenomenon="Surface change",+ description="Reflectance that moved in red, near or short-wave infrared, "+ "whatever moved it. Harvests and seasons show too.",+ parameters={"sensitivity": 67}),+ _recipe(id="burn-scars", name="Burn scars", method="index", phenomenon="Burn scar",+ description="The burn ratio dropped on ground that had vegetation. The default "+ "sits at 0.27, the published mark for moderate severity.",+ parameters={"sensitivity": 51, "index": "nbr", "direction": "loss"},+ colour="#ef4444"),+ _recipe(id="vegetation-loss", name="Vegetation loss", method="index",+ phenomenon="Vegetation loss",+ description="NDVI dropped by a quarter or more from green cover: clearing, "+ "harvest, fire or drought.",+ parameters={"sensitivity": 56, "index": "ndvi", "direction": "loss"},+ colour="#84cc16"),+ _recipe(id="new-water", name="Flooding and new water", method="index",+ phenomenon="New water",+ description="Ground that now reads as open water in the modified water index.",+ parameters={"sensitivity": 56, "index": "mndwi", "direction": "gain"},+ colour="#0ea5e9"),]# What the panel reads so it never has to know a method by name: `single` stops-# it asking for a reference image, `sentinel_only` stops it offering Wayback,-# and `classes` decides whether the cloud and shadow switches mean anything.+# it asking for a reference image, `clouds` says whether the cloud switch means+# anything, `sizes` fills Small/Medium/Large and `measure` words a candidate's+# reading ({value}, {signed}, {before}, {after} and {index} are filled in).METHODS = [{"id": method, "label": label, "single": method in SINGLE_METHODS,- "sentinel_only": method in SENTINEL_ONLY, "cloud_filter": CLOUD_FILTERS.get(method, "")}- for method, label in [- ("colour", "Colour change"),- ("structure", "Edge change"),- ("brightness", "Brightness change"),- ("index", "Spectral index change (Sentinel-2)"),- ("vessels", "Infrared contrast over water (Sentinel-2)"),- ("hotspots", "Short-wave infrared hotspot (Sentinel-2)"),- ("water_objects", "Bright shapes on water (picture only)"),- ("smoke", "Smoke-like visual change (picture only)"),+ "clouds": method in CLOUD_METHODS, "sizes": SIZES[method], "measure": measure}+ for method, label, measure in [+ ("vessels", "Vessels: infrared contrast over water",+ "{value}× brighter than the water around it"),+ ("hotspots", "Hotspots: short-wave infrared ratios",+ "Short-wave infrared {value}× the bands beside it"),+ ("structure", "Ground change in every band", "Reflectance {signed}% in every band"),+ ("spots", "Isolated small change", "Reflectance {signed}% against its surroundings"),+ ("surface", "Any reflectance change", "Reflectance moved by {value}%"),+ ("index", "Spectral index change", "{index} {before} → {after}"),]]diff --git a/src/azimut/engine/analyzers.py b/src/azimut/engine/analyzers.pyindex 3c01e4f..3d9d5ba 100644--- a/src/azimut/engine/analyzers.py+++ b/src/azimut/engine/analyzers.py@@ -2,6 +2,15 @@Source frames are owned evidence, not an expiring map cache. Completed runsnever change when their recipe, area, camera or provider catalogue changes.++Every detector here reads Copernicus Sentinel-2 band products. Their thresholds+were set against real scenes, not synthetic ones: sea under glint and in rough+weather (Bab-el-Mandeb), a dense anchorage under cumulus (Singapore Strait),+wakes (Gibraltar), empty calm sea (Dover Strait), flares and an oil fire+(Rumaila), active wildfires (California, Cerrado), bright industrial roofs+(Jebel Ali), a construction site across seven months (Egypt's new capital),+dry-season clearing (Rondônia) and irrigated desert. The numbers below say what+each of them taught."""from __future__ import annotations@@ -12,6 +21,7 @@ import jsonimport mathimport secretsimport threading+from dataclasses import dataclass, fieldfrom datetime import date, datetime, timedelta, timezonefrom typing import Any@@ -20,61 +30,128 @@ from PIL import Imagefrom .. import config, layoutfrom ..workspace import Case-from . import media, sentinel, tilecache, tiles, wayback, workqueue+from . import media, sentinel, tilecache, tiles, workqueuefrom .analysis_models import (- CLOUD_FILTERS,- PRODUCT_METHODS,+ CLOUD_METHODS,SINGLE_METHODS,Parameters,RunInput,Source,Zone,+ product_for,)# What one run may sweep. The ceiling is not memory — tiles are read one at a# time — it is the permanent copy of every tile read, which `prune_frames`-# now drops for tiles that found nothing. What is left to bound is the-# provider's own metering and the analyst's patience, and both of those the-# panel states before the run starts and the cancel button ends after.+# drops for tiles that found nothing. What is left to bound is the provider's+# own metering and the analyst's patience, and both of those the panel states+# before the run starts and the cancel button ends after.#-# At Sentinel's 4.89 km tile that is 313 km on a side; at Wayback's 76 m one,-# 4.9 km.+# At Sentinel's 4.89 km tile that is 313 km on a side.MAX_TILES = 4096MAX_RESULTS = 2000MAX_FRAME_BYTES = 8_000_000-# Sentinel-2's own scene classification, as the classes worth excluding.-CLOUD_CLASSES = (0, 1, 8, 9, 10, 11)-SHADOW_CLASSES = (2, 3)-# What cloud looks like with no classification to ask: bright and colourless,-# its shadow near-black. Deliberately tight — a guess this filter makes on a-# rendered picture also eats a white roof, a sand flat and fresh snow, so it-# waits for cloud-like rather than merely pale.-PICTURE_CLOUD_LEVEL = 205-PICTURE_CLOUD_SPREAD = 28-PICTURE_SHADOW_LEVEL = 28-# A pixel on the Sentinel analysis grid is 9.55 m across, so the ring the-# vessel detector measures its background over spans 583 m of sea, and the hole-# punched in its middle is 105 m — wider than all but the largest hulls, which-# is what stops a ship from quietly raising its own background.-VESSEL_RING = 61-VESSEL_GUARD = 11-# The ring has to be mostly sea for its statistics to mean anything; below this-# fraction the pixel is a shoreline or an island, not a place a ship can be.-VESSEL_WATER_SHARE = 0.5-# Below this short-wave reflectance there is no fire to discuss, whatever the-# band ratios say. It is the floor the published Sentinel-2 test uses.-HOTSPOT_FLOOR = 0.15+# Sentinel's 512px WMTS tiles use grid level 13 (view level 14), which lands on+# 9.55 m/px at the equator: the sensor's own resolution. The panel reads this to+# say what a run will cost before it starts, so it is published, not copied.+GRID = (13, 512)+# Band products are read with this much of the neighbouring tiles around them.+# Without it a ship's background ring, a coastline and a cloud's edge all stop+# at the tile's border, and whatever lies on it is judged on half the evidence.+# 32 px is 306 m, which covers the ring. It costs 27% more pixels per product.+PAD = 32+# Bumped when a product's layout changes, so a frame kept from an older run is+# never decoded as a newer one.+PRODUCT_VERSION = 2+ENGINE_VERSION = 2+LOCK = threading.RLock()+KINDS = {"zones": "analysis-zones", "followups": "analysis-follow-up", "runs": "analysis-run"}+ACTIVE = {"queued", "running"}+JOB = "compare-analyzer"+WORLD = 40_075_016.68557849# How far back an automatic date rule looks for its latest usable pass.LOOKBACK_DAYS = 90# Coverage at or above this counts as covering the whole area. It is not 1.0# because coverage is measured by sampling, and a ring's own edge lands a point# or two outside the granule that in truth reaches it.FULL_COVER = 0.98-WORLD = 40_075_016.68557849-LOCK = threading.RLock()-KINDS = {"zones": "analysis-zones", "followups": "analysis-follow-up", "runs": "analysis-run"}-ACTIVE = {"queued", "running"}-JOB = "compare-analyzer"++# --- Sky ------------------------------------------------------------------+# Sentinel-2's scene classes, as the products carry them.+SCL_DEFECTIVE, SCL_SHADOW, SCL_WATER, SCL_SNOW = 1, 3, 6, 11+CLOUD_CORE = (8, 9, 10)+# "Unclassified or low-probability cloud". Alone it is too timid to trust; next+# to a real cloud it is that cloud's thin edge or the veil around it.+CLOUD_EDGE = (7, 8, 9, 10)+# A classified cloud smaller than this is not one. Sen2Cor calls white hulls+# and bright roofs cloud all the time — in the Singapore anchorage it masked+# the very tankers the sweep was for — and no cumulus worth masking is under 5 ha.+MIN_CLOUD_M2 = 50_000+# Shadows the classification misses are found where they must be: the cloud's+# own outline moved away from the sun by its height times the tangent of the+# sun's zenith, on pixels dark enough to be shaded. Heights span low cumulus to+# mid-level cloud.+CLOUD_HEIGHTS = (200.0, 5000.0)+MAX_SHADOW_M = 4000.0+# Sen2Cor reads a deep cloud shadow as water: under the cumulus over the+# Kakhovka reservoir bed it called a fifth of the land water, and the cast+# shadow, which spares water, found none of it. Where a second date is there to+# ask, water is only water when both dates say so.+# The largest global shift between two dates still read as light rather than+# change. Atmospheric correction leaves 2-3% between passes over the same+# desert; a burn that covers most of a tile moves the median by 10%, and+# subtracting that would erase it.+MAX_SHIFT = 0.03++# --- Vessels ---------------------------------------------------------------+# A pixel on the analysis grid is 9.55 m across, so the ring the background is+# measured over spans 583 m of sea, and the hole punched in its middle is 105 m —+# wider than all but the largest hulls, which is what stops a ship from quietly+# raising its own background.+VESSEL_RING = 61+VESSEL_GUARD = 11+# The ring has to be mostly sea for its statistics to mean anything.+VESSEL_WATER_SHARE = 0.5+# A target has to beat its sea by this much reflectance in both bands as well as+# in deviations: over glassy water one deviation is a rounding step.+VESSEL_EXCESS = 0.01+# Non-water this big is land, and a candidate touching it is a coastline or an+# island. The largest ship in the calibration scenes was 1.3 ha of non-water.+LAND_M2 = 50_000++# --- Hotspots ----------------------------------------------------------------+# Below this short-wave reflectance there is no fire to discuss, whatever the+# band ratios say. It is the floor of the published test (Murphy et al. 2016).+HOTSPOT_FLOOR = 0.15++# --- Change -------------------------------------------------------------------+# Construction is ground that brightened or darkened in every band; a field+# that greened moved red and near-infrared in opposite directions. Past this+# NDVI change it is vegetation, and not what this method is for.+STRUCTURE_NDVI = 0.1+# A spot is isolated when at most this share of a neighbourhood four times its+# largest size changed. A spot that size fills a sixteenth of it; the corner of+# a field that changed fills a quarter, and its edge half.+SPOT_SHARE = 0.15+# The background around a spot is read from a ring this many times the target's+# width, with a hole of its own punched in the middle: wide enough that the+# target cannot sit in its own background, narrow enough to stay local.+SPOT_GUARD = 4.0+SPOT_RING = 8.0+# Where each index reads "absent" and "present". A loss has to cross from one to+# the other, and so does a gain the other way: a drop that stays green is a+# dry season, not a clearing. Rondônia's pastures fall from 0.52 to 0.09 in+# burn ratio between June and September without a fire, and a burn ends below+# zero. The water indices cross zero; vegetation crosses from 0.4 to 0.3.+INDEX_STATES = {"ndvi": (0.3, 0.4), "ndwi": (0.0, 0.1), "mndwi": (0.0, 0.1),+ "nbr": (0.0, 0.05), "ndbi": (-0.05, 0.0), "bsi": (-0.05, 0.0)}+# A region grows from its strongest pixels out to this share of the threshold.+# Half joined whole neighbourhoods across a season's change in light.+GROW = 0.7+# Dry soil has a negative burn ratio too. What it does not have is char's+# darkness: burns in California and the Cerrado ended at 12% near-infrared, the+# dried pastures and bare lots at 21% or more. So a burn has to end dark.+DARK_ABSENT = frozenset({"nbr"})def now() -> str:@@ -152,22 +229,11 @@ def geographic(x: float, y: float) -> tuple[float, float]:return (x * 360 - 180, math.degrees(math.atan(math.sinh(math.pi * (1 - 2 * y)))))-# Same native grids as the tile proxy. Sentinel's 512px WMTS tiles use grid-# level 13 (view level 14), which lands on 9.55 m/px — the sensor's own-# resolution; Wayback uses 256px at level 19. The panel reads these to say what-# a run will cost before it starts, so they are published rather than copied.-GRIDS: dict[str, tuple[int, int]] = {"sentinel2": (13, 512), "esri-wayback": (19, 256)}---def grid(body: RunInput) -> tuple[int, int]:- return GRIDS.get(body.b.provider, GRIDS["esri-wayback"])--def plan(body: RunInput) -> list[tuple[int, int]]:import cv2import numpy as np- z, size = grid(body)+ z, size = GRIDcount = 1 << zfound: set[tuple[int, int]] = set()# One scratch mask for the whole plan: a large area visits tens of@@ -205,9 +271,17 @@ def check_active(case: Case, ident: str) -> None:raise workqueue.JobCancelled() from exc-def _key(source: Source, z: int, x: int, y: int, index: str | None) -> str:- encoded = json.dumps([source.model_dump(), z, x, y, index], sort_keys=True).encode()- return hashlib.sha256(encoded).hexdigest()[:32]+def _key(source: Source, z: int, x: int, y: int, product: str | None) -> str:+ parts: list[Any] = [source.model_dump(), z, x, y, product]+ if product:+ parts.append(PRODUCT_VERSION)+ return hashlib.sha256(json.dumps(parts, sort_keys=True).encode()).hexdigest()[:32]+++def product_cache_id(source: Source, product: str) -> str:+ """The tile-cache folder a band product lives in, beside its picture's."""+ variant = sentinel.variant_id("sentinel2", source.layer, source.date, source.date, source.maxcc)+ return f"{variant}~{product}~v{PRODUCT_VERSION}"def _decode(raw: bytes, size: int) -> Any:@@ -221,11 +295,19 @@ def _decode(raw: bytes, size: int) -> Any:return np.array(image.convert("RGBA"))+def _instance() -> str:+ instance = (config.load_settings().get("api_keys") or {}).get("sentinelhub")+ if not instance:+ raise ValueError("configure Copernicus Sentinel Hub in Settings")+ return str(instance)++def frame(case: Case, run: dict[str, Any], source: Source, x: int, y: int,- index: str | None = None) -> Any:- body = RunInput.model_validate(run["input"])- z, size = grid(body)- key = _key(source, z, x, y, index)+ product: str | None = None) -> Any:+ """One tile's picture, or its band product with PAD pixels of context."""+ z, size = GRID+ edge = size + 2 * PAD if product else size+ key = _key(source, z, x, y, product)name = f"{key}.png"assets_rel = layout.analysis_assets_rel(f"runs-{run['id']}")destination = case.resolve_inside(f"{assets_rel}/{name}")@@ -236,52 +318,39 @@ def frame(case: Case, run: dict[str, Any], source: Source, x: int, y: int,if cached.is_file() and cached.stat().st_size <= MAX_FRAME_BYTES:raw = cached.read_bytes()break- provider_id = (f"esri-wayback~{source.release}" if source.provider == "esri-wayback" else- sentinel.variant_id("sentinel2", source.layer, source.date, source.date,- source.maxcc))- if raw is None and index is None:- cached_tile = tilecache.get(provider_id, z, x, y)+ cache_id = (product_cache_id(source, product) if product else+ sentinel.variant_id("sentinel2", source.layer, source.date, source.date,+ source.maxcc))+ if raw is None:+ cached_tile = tilecache.get(cache_id, z, x, y)if cached_tile:raw = cached_tile[0]if raw is None:- if body.offline:+ if run["input"].get("offline"):raise ValueError("some required images are unavailable offline; no request was sent")check_active(case, run["id"])- if source.provider == "sentinel2" and config.usage_blocked("sentinelhub"):+ if config.usage_blocked("sentinelhub"):raise ValueError("Sentinel Hub usage limit reached; review Settings")- if index:- instance = (config.load_settings().get("api_keys") or {}).get("sentinelhub")- if not instance:- raise ValueError("configure Copernicus Sentinel Hub in Settings")- box = (x / (1 << z) * WORLD - WORLD / 2,- WORLD / 2 - (y + 1) / (1 << z) * WORLD,- (x + 1) / (1 << z) * WORLD - WORLD / 2,- WORLD / 2 - y / (1 << z) * WORLD)+ instance = _instance()+ if product:+ pixel = WORLD / ((1 << z) * size)+ box = (x / (1 << z) * WORLD - WORLD / 2 - PAD * pixel,+ WORLD / 2 - (y + 1) / (1 << z) * WORLD - PAD * pixel,+ (x + 1) / (1 << z) * WORLD - WORLD / 2 + PAD * pixel,+ WORLD / 2 - y / (1 << z) * WORLD + PAD * pixel)try:- raw = sentinel.band_frame(instance, box, size, size, source.date, index,- source.maxcc, layer=source.layer)+ raw = sentinel.band_frame(instance, box, edge, edge, source.date, product,+ source.maxcc, layer=source.layer)finally:config.record_usage("sentinelhub", 1)else:- # A named Wayback release never needs a catalogue lookup to fetch- # its tiles. In particular, cached runs can work without network.- if source.provider == "esri-wayback":- assert source.release is not None- url = wayback.tile_url(source.release)- offset = 0- else:- instance = (config.load_settings().get("api_keys") or {}).get("sentinelhub")- if not instance:- raise ValueError("configure Copernicus Sentinel Hub in Settings")- url = sentinel.wmts_url(source.layer, source.date, source.date, source.maxcc)- url = url.replace("{key}", instance)- offset = 1- with httpx.stream("GET", tiles.tile_url(url, z, x, y, offset), timeout=30) as response:+ url = sentinel.wmts_url(source.layer, source.date, source.date, source.maxcc)+ url = url.replace("{key}", instance)+ with httpx.stream("GET", tiles.tile_url(url, z, x, y, 1), timeout=30) as response:if response.status_code == 404:raise ValueError("imagery is missing at the requested resolution or date")response.raise_for_status()- if source.provider == "sentinel2":- config.record_usage("sentinelhub", 1)+ config.record_usage("sentinelhub", 1)chunks = bytearray()for chunk in response.iter_bytes():check_active(case, run["id"])@@ -291,7 +360,8 @@ def frame(case: Case, run: dict[str, Any], source: Source, x: int, y: int,raw = bytes(chunks)if tiles.is_placeholder_tile(raw):raise ValueError("provider has no imagery here at native resolution")- pixels = _decode(raw, size)+ tilecache.put(cache_id, z, x, y, raw, "image/png")+ pixels = _decode(raw, edge)# Canonical PNGs preserve the exact decoded input, independently of cache TTL.with LOCK, case._lock:check_active(case, run["id"])@@ -299,7 +369,7 @@ def frame(case: Case, run: dict[str, Any], source: Source, x: int, y: int,if not destination.exists():Image.fromarray(pixels).save(destination, "PNG")run["frames"][key] = {"path": f"{assets_rel}/{name}", "source": source.model_dump(),- "tile": [z, x, y], "index": index,+ "tile": [z, x, y], "index": product,"sha256": hashlib.sha256(destination.read_bytes()).hexdigest()}return pixels@@ -317,18 +387,13 @@ def mask_for(zones: list[Zone], z: int, size: int, x: int, y: int) -> Any:return mask-def local_contrast(values: Any, water: Any, outer: int, guard: int) -> tuple[Any, Any]:- """How far each pixel stands above the water around it, in deviations.+def ring_statistics(values: Any, water: Any, outer: int, guard: int) -> tuple[Any, Any, Any]:+ """Mean, deviation and water share of the ring around every pixel.- A vessel is not bright, it is brighter than its own patch of sea — which is- what lets one threshold work over a calm lagoon and a sunlit swell alike,- where an absolute cut-off would have to be retuned for every scene. The- statistics come from a ring, a square window with its middle punched out,- so a large hull cannot raise the background it is then measured against.-- Only water contributes. The second value returned is the ring's water- share, which is how a pixel says whether it is at sea at all: the target- itself reflects infrared and so is never classed as water.+ The ring is a square window with its middle punched out, so a large hull+ cannot raise the background it is then measured against. Only water+ contributes; the share says whether a pixel is at sea at all, because the+ target itself reflects infrared and so is never classed as water."""import cv2import numpy as np@@ -343,169 +408,411 @@ def local_contrast(values: Any, water: Any, outer: int, guard: int) -> tuple[AnyborderType=cv2.BORDER_REFLECT))count = ring(weight)- total = ring(signal)- squares = ring(signal * values)safe = np.maximum(count, 1)- mean = total / safe- deviation = np.sqrt(np.maximum(squares / safe - mean * mean, 0))+ mean = ring(signal) / safe+ deviation = np.sqrt(np.maximum(ring(signal * values) / safe - mean * mean, 0))+ return mean, deviation, count / float(outer * outer - guard * guard)+++def local_contrast(values: Any, water: Any, outer: int, guard: int) -> tuple[Any, Any]:+ """How far each pixel stands above the water around it, in deviations.++ A vessel is not bright, it is brighter than its own patch of sea — which is+ what lets one threshold work over a calm lagoon and a sunlit swell alike.+ """+ import numpy as np++ mean, deviation, share = ring_statistics(values, water, outer, guard)# A flat patch of water has no deviation to divide by, and one quantisation# step would then read as a hundred-sigma detection. One digital number is# the floor because one digital number is the smallest difference there is.contrast = (values - mean) / np.maximum(deviation, 1.0)- share = count / float(outer * outer - guard * guard)- # Too little water in the ring and the background is somebody else's.return np.where(share > 0, contrast, 0.0), share-def weather_mask(frames: tuple[Any, ...], kind: str, options: Parameters) -> Any:- """Pixels to drop as cloud or the shadow it casts, or None when nothing is.+def sun_position(day: str, lat: float) -> tuple[float, float]:+ """Solar azimuth and zenith, in degrees, when Sentinel-2 flies over.++ The satellite crosses the equator at 10:30 local solar time and reaches+ the northern latitudes a little later. Against the angle bands of scenes+ from 10°S to 51°N this lands within a few degrees, which is plenty for a+ search that sweeps every cloud height anyway, and it spends no band.+ """+ local = 10.5 + lat / 72+ when = date.fromisoformat(day)+ g = math.tau / 365 * (when.timetuple().tm_yday - 1 + (local - 12) / 24)+ declination = (0.006918 - 0.399912 * math.cos(g) + 0.070257 * math.sin(g)+ - 0.006758 * math.cos(2 * g) + 0.000907 * math.sin(2 * g)+ - 0.002697 * math.cos(3 * g) + 0.00148 * math.sin(3 * g))+ minutes = 229.18 * (0.000075 + 0.001868 * math.cos(g) - 0.032077 * math.sin(g)+ - 0.014615 * math.cos(2 * g) - 0.040849 * math.sin(2 * g))+ hour = math.radians((local * 60 + minutes) / 4 - 180)+ phi = math.radians(lat)+ cosine = (math.sin(phi) * math.sin(declination)+ + math.cos(phi) * math.cos(declination) * math.cos(hour))+ zenith = math.degrees(math.acos(max(-1.0, min(1.0, cosine))))+ azimuth = math.degrees(math.atan2(+ math.sin(hour), math.cos(hour) * math.sin(phi) - math.tan(declination) * math.cos(phi)+ )) + 180+ return azimuth % 360, zenith+++def smear(mask: Any, dx: float, dy: float, start: int, length: int) -> Any:+ """The mask moved every distance from `start` to `start + length` along (dx, dy).++ Doubling: each pass ORs the result with itself shifted by what it already+ covers, so a reach of 400 pixels takes nine warps rather than 400.+ """+ import cv2+ import numpy as np++ height, width = mask.shape+ if length <= 0 or not mask.any():+ return np.zeros_like(mask)++ def shift(source: Any, distance: float) -> Any:+ matrix = np.array([[1, 0, dx * distance], [0, 1, dy * distance]], np.float32)+ return cv2.warpAffine(source, matrix, (width, height), flags=cv2.INTER_NEAREST)++ covered, span = shift(mask, start), 1+ while span < length:+ step = min(span, length - span)+ covered = np.maximum(covered, shift(covered, step))+ span += step+ return covered- ``classes`` reads Sentinel-2's scene classification out of the band frame's- second channel, and ``ignore_clouds``/``ignore_shadows`` pick which of them- to drop. ``picture`` has no classification to ask and goes on what cloud- looks like in a rendered image, so it is one switch — ``guess_clouds`` — and- it is off until someone asks for it.- Either mask is then grown by the margin, because both stop short of where a- reader would put the cloud's edge and the fringe left behind is what turns- up as a ring of candidates around every mask.+def components_over(binary: Any, pixels_m2: float, minimum_m2: float) -> Any:+ """The parts of `binary` whose connected area reaches `minimum_m2`."""+ import cv2+ import numpy as np++ count, labels, stats, _ = cv2.connectedComponentsWithStats(binary.astype(np.uint8),+ connectivity=8)+ keep = np.zeros(count, bool)+ keep[1:] = stats[1:, cv2.CC_STAT_AREA] * pixels_m2 >= minimum_m2+ return keep[labels]+++def hysteresis(seed: Any, grow: Any) -> Any:+ """Regions of `grow` that contain at least one `seed` pixel.++ A strict threshold finds a target; a looser one then takes all of it, so its+ measured size is the object's and not just its brightest pixels'.+ """+ import cv2+ import numpy as np++ count, labels = cv2.connectedComponents((grow | seed).astype(np.uint8), connectivity=8)+ keep = np.zeros(count, bool)+ keep[np.unique(labels[seed])] = True+ keep[0] = False+ return keep[labels]+- Cloud on *either* date invalidates the pixel: a difference is only a+def sky(product: Any, day: str, lat: float, metres: float,+ other: Any = None) -> tuple[Any, Any]:+ """Cloud and cloud shadow in one band product, before any margin.++ Cloud starts from the scene classification's cloud classes, drops what is+ too small to be cloud, and then takes every unsure pixel touching what is+ left: that is the edge and the veil a classification calls ground. Shadow+ is the classified shadow plus the cloud's outline cast away from the sun,+ wherever the ground under it is dark and not water. `other` is the pass on+ the other side of a pair, which settles whether that dark is water.+ """+ import numpy as np++ classes = product[:, :, 3] & 15+ dark = (product[:, :, 3] & sentinel.DARK_FLAG) > 0+ core = components_over(np.isin(classes, CLOUD_CORE), metres * metres, MIN_CLOUD_M2)+ cloud = hysteresis(core, np.isin(classes, CLOUD_EDGE))+ cloud |= np.isin(classes, (SCL_DEFECTIVE, SCL_SNOW))+ shadow = classes == SCL_SHADOW+ if cloud.any():+ azimuth, zenith = sun_position(day, lat)+ tangent = math.tan(math.radians(zenith))+ start = int(CLOUD_HEIGHTS[0] * tangent / metres)+ length = int(min(CLOUD_HEIGHTS[1] * tangent, MAX_SHADOW_M) / metres) - start+ water = classes == SCL_WATER+ if other is not None:+ water &= (other[:, :, 3] & 15) == SCL_WATER+ # Image rows run south, so the shadow's step is (-sin, +cos) of the azimuth.+ cast = smear(cloud.astype(np.uint8), -math.sin(math.radians(azimuth)),+ math.cos(math.radians(azimuth)), start, length).astype(bool)+ shadow |= cast & dark & ~water & ~cloud+ return cloud, shadow+++def weather_mask(products: list[Any], days: list[str], lat: float, metres: float,+ options: Parameters) -> Any:+ """Pixels to drop as cloud or shadow on any of the dates, grown by the margin.++ Cloud on *either* date invalidates a pixel: a difference is only ameasurement when both sides of it are ground."""import cv2import numpy as np- if kind == "classes":- wanted = options.ignore_clouds or options.ignore_shadows- else:- wanted = kind == "picture" and options.guess_clouds- if not wanted:+ if not (options.ignore_clouds or options.ignore_shadows):return None- blocked = None- for image in frames:- if image is None:- continue- if kind == "classes":- classes = image[:, :, 1]- hit = np.zeros(classes.shape, dtype=bool)- if options.ignore_clouds:- hit |= np.isin(classes, CLOUD_CLASSES)- if options.ignore_shadows:- hit |= np.isin(classes, SHADOW_CLASSES)- else:- pixels = image[:, :, :3].astype(np.int16)- level = pixels.mean(axis=2)- spread = pixels.max(axis=2) - pixels.min(axis=2)- hit = ((level >= PICTURE_CLOUD_LEVEL) & (spread <= PICTURE_CLOUD_SPREAD)) | (- level <= PICTURE_SHADOW_LEVEL- )- blocked = hit if blocked is None else (blocked | hit)- if blocked is None or not options.cloud_margin or not blocked.any():- return blocked- kernel = np.ones((options.cloud_margin * 2 + 1,) * 2, np.uint8)- grown = cv2.dilate(blocked.astype(np.uint8), kernel, borderType=cv2.BORDER_REPLICATE)- return grown.astype(bool)---def detect(a: Any, b: Any, mask: Any, body: RunInput, index_a: Any = None,- index_b: Any = None) -> tuple[Any, Any]:- """One deterministic tile. Score is signal strength, never model confidence."""+ blocked = np.zeros(products[0].shape[:2], bool)+ for side, (product, when) in enumerate(zip(products, days)):+ other = products[1 - side] if len(products) == 2 else None+ cloud, shadow = sky(product, when, lat, metres, other)+ if options.ignore_clouds:+ blocked |= cloud+ if options.ignore_shadows:+ blocked |= shadow+ if options.cloud_margin and blocked.any():+ kernel = np.ones((options.cloud_margin * 2 + 1,) * 2, np.uint8)+ blocked = cv2.dilate(blocked.astype(np.uint8), kernel).astype(bool)+ return blocked+++@dataclass+class Reading:+ """One tile's verdict, cropped back to the tile.++ `stat` is the method's own detection statistic and `threshold` the value it+ had to reach, so a candidate's margin is how far past the line it got.+ `measures` are what the candidate says in words: arrays reduced over its+ pixels by `max` or `mean`.+ """++ binary: Any+ stat: Any+ threshold: float+ measures: dict[str, tuple[Any, str]] = field(default_factory=dict)+++def _scale(sensitivity: int, loosest: float, strictest: float) -> float:+ return loosest + (strictest - loosest) * (1 - sensitivity / 100)+++def _reflectance(product: Any) -> list[Any]:+ import numpy as np++ return [product[:, :, 0].astype(np.float32) / (255 * sentinel.BAND_GAIN),+ product[:, :, 1].astype(np.float32) / (255 * sentinel.BAND_GAIN),+ product[:, :, 2].astype(np.float32) / (255 * sentinel.SWIR_GAIN)]+++def _vessels(product: Any, inside: Any, blocked: Any, metres: float,+ options: Parameters) -> tuple[Any, Any, float, dict[str, tuple[Any, str]]]:+ import cv2+ import numpy as np++ nir = product[:, :, 0].astype(np.float64)+ swir = product[:, :, 1].astype(np.float64)+ data = product[:, :, 0] > 0+ wet = product[:, :, 2] > 127+ water = wet & data & ~blocked+ # Land is non-water in bulk. A hull is non-water too, but a small one.+ land = components_over(data & ~wet, metres * metres, LAND_M2)+ land = cv2.dilate(land.astype(np.uint8), np.ones((5, 5), np.uint8)).astype(bool)+ mean8, deviation8, share = ring_statistics(nir, water, VESSEL_RING, VESSEL_GUARD)+ mean11, deviation11, _ = ring_statistics(swir, water, VESSEL_RING, VESSEL_GUARD)+ near = np.where(share > 0, (nir - mean8) / np.maximum(deviation8, 1.0), 0.0)+ short = np.where(share > 0, (swir - mean11) / np.maximum(deviation11, 1.0), 0.0)+ unit = 255 * sentinel.BAND_GAIN+ ok = inside & data & ~blocked & ~land & (share > VESSEL_WATER_SHARE)+ # Calibrated between 3 deviations, where small boats start to show among+ # wave crests, and 12, past every false hit in rough sea under glint.+ threshold = _scale(options.sensitivity, 3.0, 12.0)+ seed = ok & (near >= threshold) & ((nir - mean8) / unit >= VESSEL_EXCESS)+ grown = hysteresis(seed, ok & (near >= max(2.5, threshold / 2)))+ # Near-infrared finds bright things on water; short-wave infrared keeps the+ # ones that are not a breaking wave. It is 20 m data, so it is asked of the+ # whole object rather than of each pixel.+ count, labels = cv2.connectedComponents(grown.astype(np.uint8), connectivity=8)+ flat = labels.ravel()+ best_short = np.full(count, -np.inf)+ np.maximum.at(best_short, flat, short.ravel())+ best_excess = np.full(count, -np.inf)+ np.maximum.at(best_excess, flat, ((swir - mean11) / unit).ravel())+ accepted = (best_short >= threshold) & (best_excess >= VESSEL_EXCESS)+ accepted[0] = False+ binary = accepted[labels]+ ratio = nir / np.maximum(mean8, 1.0)+ return binary, near, threshold, {"value": (ratio, "max")}+++def _hotspots(product: Any, inside: Any,+ options: Parameters) -> tuple[Any, Any, float, dict[str, tuple[Any, str]]]:+ import numpy as np++ b12 = product[:, :, 0].astype(np.float32) / (255 * sentinel.BAND_GAIN)+ ratio = np.minimum(product[:, :, 1], product[:, :, 2]).astype(np.float32) / sentinel.RATIO_GAIN+ # 1.4 at the default is the published ratio; the loosest end is the+ # normalised hotspot indices' "any positive difference", the strictest is+ # well into unambiguous flame.+ threshold = _scale(options.sensitivity, 1.0, 2.0)+ binary = inside & (product[:, :, 0] > 0) & (b12 >= HOTSPOT_FLOOR) & (ratio >= threshold)+ return binary, ratio, threshold, {"value": (ratio, "max")}+++def _changes(before: Any, after: Any, valid: Any) -> tuple[Any, Any]:+ """Per-band change with the passes' overall shift in light taken out."""+ import numpy as np++ deltas = []+ for old, new in zip(_reflectance(before), _reflectance(after)):+ delta = new - old+ shift = float(np.median(delta[valid])) if valid.any() else 0.0+ deltas.append(delta - max(-MAX_SHIFT, min(MAX_SHIFT, shift)))+ stacked = np.stack(deltas, -1)+ return stacked, stacked.mean(-1)+++def _spots(before: Any, after: Any, metres: float, threshold: float,+ options: Parameters) -> tuple[Any, Any, Any]:+ """Change against the change around it, and whether the surroundings held.++ The background is read from a ring with a hole punched in its middle, the+ hole wide enough to hold the target: a median box the size of the target+ takes the target itself for background, and a 90 m mark in the Yemeni desert+ then measured 3.5% where it had really moved 7%.+ """+ import cv2+ import numpy as np++ largest = math.sqrt(options.max_area or 2500) / metres+ odd = lambda value, low, high: int(min(high, max(low, round(value) | 1))) # noqa: E731+ guard = odd(SPOT_GUARD * largest, 5, 41)+ ring = odd(SPOT_RING * largest, guard + 4, 81)+ wide = odd(4 * largest, 15, 61)+ everywhere = np.ones(before.shape[:2], bool)+ residual, moved = [], []+ for old, new in zip(_reflectance(before), _reflectance(after)):+ delta = (new - old).astype(np.float64)+ mean, _, share = ring_statistics(delta, everywhere, ring, guard)+ residual.append(np.where(share > 0, delta - mean, 0.0))+ # The passes' overall shift in light is not the neighbourhood changing.+ shift = float(np.median(delta))+ moved.append(delta - max(-MAX_SHIFT, min(MAX_SHIFT, shift)))+ spot = np.stack(residual, -1)+ changed = (np.sqrt((np.stack(moved, -1) ** 2).mean(-1)) >= threshold * GROW).astype(np.float32)+ share = cv2.blur(changed, (wide, wide))+ return np.sqrt((spot ** 2).mean(-1)), spot.mean(-1), share < SPOT_SHARE+++def detect(pictures: tuple[Any, Any], products: tuple[Any, Any], mask: Any, body: RunInput,+ lat: float) -> Reading:+ """One deterministic tile. Products carry PAD pixels of context on every side."""import cv2import numpy as npoptions = body.recipe.parameters- left, right = a[:, :, :3].astype(np.float32), b[:, :, :3].astype(np.float32)- valid = mask.astype(bool) & (a[:, :, 3] > 0) & (b[:, :, 3] > 0)- kind = CLOUD_FILTERS.get(body.recipe.method, "")- weather = weather_mask(- (index_a, index_b) if body.recipe.method == "index"- else (index_b,) if kind == "classes" else (a, b),- kind, options,- )- if weather is not None:- valid &= ~weather- if options.normalize and body.recipe.method != "index":- # Optional local brightness correction; off by default because it can- # erase the large changes an analyst came here to find.- right = np.clip(right + np.median(left - right, axis=(0, 1)), 0, 255)method = body.recipe.method- delta = right.mean(axis=2) - left.mean(axis=2)- if method == "index":- delta = (index_b[:, :, 0].astype(np.float32) - index_a[:, :, 0]) / 127.5- valid &= (index_a[:, :, 3] > 0) & (index_b[:, :, 3] > 0)- strength = np.abs(delta)- elif method == "vessels":- # Near-infrared over water, against the water around it. NDWI rides in- # the same frame, so deciding what is sea costs no extra request.- nir = index_b[:, :, 0].astype(np.float64)- ndwi = (index_b[:, :, 2].astype(np.float32) - 127.5) / 127.5- valid &= index_b[:, :, 3] > 0- # Cloud is bright in the near-infrared too, so it has to leave the sea- # the background is measured over *and* stop being a candidate itself.- water = ndwi > 0- if weather is not None:- water &= ~weather- contrast, share = local_contrast(nir, water, VESSEL_RING, VESSEL_GUARD)- valid &= share > VESSEL_WATER_SHARE- # Two deviations is noise anywhere; twelve is a hull. Sensitivity then- # moves the cut inside that range rather than across an absolute scale.- strength = np.clip((contrast - 2) / 10, 0, 1)+ single = method in SINGLE_METHODS+ z, size = GRID+ metres = WORLD * math.cos(math.radians(lat)) / ((1 << z) * size)+ inside = np.zeros(products[1].shape[:2], bool)+ core = (slice(PAD, PAD + size), slice(PAD, PAD + size))+ inside[core] = mask.astype(bool) & (pictures[1][:, :, 3] > 0)+ if not single:+ inside[core] &= pictures[0][:, :, 3] > 0+ blocked = None+ if method in CLOUD_METHODS:+ dated = [products[1]] if single else list(products)+ days = [body.b.date] if single else [body.a.date, body.b.date]+ blocked = weather_mask(dated, days, lat, metres, options)+ if blocked is None:+ blocked = np.zeros(inside.shape, bool)+ measures: dict[str, tuple[Any, str]]++ if method == "vessels":+ binary, stat, threshold, measures = _vessels(products[1], inside, blocked, metres, options)elif method == "hotspots":- swir = index_b[:, :, 0].astype(np.float32) / (255 * sentinel.SWIR_GAIN)- over11 = index_b[:, :, 1].astype(np.float32) / sentinel.RATIO_GAIN- over08 = index_b[:, :, 2].astype(np.float32) / sentinel.RATIO_GAIN- valid &= (index_b[:, :, 3] > 0) & (swir >= HOTSPOT_FLOOR)- # Cloud is bright in the short-wave too, but bright in its neighbours- # as well, so its ratios sit near one. Fire pulls both of them up.- strength = np.clip((np.minimum(over11, over08) - 1) / 2, 0, 1)- elif method == "structure":- def edges(image: Any) -> Any:- grey = image.mean(axis=2)- return cv2.magnitude(cv2.Sobel(grey, cv2.CV_32F, 1, 0),- cv2.Sobel(grey, cv2.CV_32F, 0, 1))- delta = edges(right) - edges(left)- strength = np.abs(delta) / 255- elif method == "water_objects":- grey = right.mean(axis=2).astype(np.uint8)- background = cv2.medianBlur(grey, 15).astype(np.float32)- strength = np.maximum(0, grey.astype(np.float32) - background) / 100- # User draws the water area. Dark local surroundings reject broad land- # surfaces, but this deliberately remains a visual candidate detector.- valid &= background < 120- elif method == "smoke":- strength = np.maximum(0, delta) / 100- valid &= (right.max(axis=2) - right.min(axis=2) < 45) & (right.mean(axis=2) > 110)- elif method == "brightness":- strength = np.abs(delta) / 255+ binary, stat, threshold, measures = _hotspots(products[1], inside, options)else:- strength = np.linalg.norm(right - left, axis=2) / (255 * math.sqrt(3))- if options.direction != "both" and method not in SINGLE_METHODS:- valid &= delta > 0 if options.direction == "gain" else delta < 0- strength = np.clip(strength, 0, 1).astype(np.float32)- if options.smoothing:- strength = cv2.GaussianBlur(strength, (options.smoothing * 2 + 1,) * 2, 0)- threshold = 0.02 + (1 - options.sensitivity / 100) * 0.48- binary = ((strength >= threshold) & valid).astype(np.uint8)- if options.cleanup:- kernel = np.ones((2 * options.cleanup + 1,) * 2, np.uint8)- binary = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel,- borderType=cv2.BORDER_REPLICATE)- binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8),- borderType=cv2.BORDER_REPLICATE)- binary &= valid.astype(np.uint8)- return binary, strength---def _candidates(binary: Any, strength: Any, body: RunInput, x: int, y: int,+ before, after = products+ valid = inside & ~blocked+ if method == "index":+ old = before[:, :, 0].astype(np.float32) / 127.5 - 1+ new = after[:, :, 0].astype(np.float32) / 127.5 - 1+ valid &= (before[:, :, 0] > 0) & (after[:, :, 0] > 0)+ delta = new - old+ absent, present = INDEX_STATES[options.index]+ gone, came = new < absent, old < absent+ if options.index in DARK_ABSENT:+ gone &= (after[:, :, 3] & sentinel.DARK_FLAG) > 0+ came &= (before[:, :, 3] & sentinel.DARK_FLAG) > 0+ state = np.where(delta < 0, (old >= present) & gone, (new >= present) & came)+ # 0.27 burn ratio, 0.25 NDVI: the published marks sit mid-range.+ threshold = _scale(options.sensitivity, 0.05, 0.5)+ stat = np.abs(delta)+ signed = delta+ measures = {"before": (old, "mean"), "after": (new, "mean")}+ else:+ valid &= (before[:, :, 0] > 0) & (after[:, :, 0] > 0)+ state = np.ones(valid.shape, bool)+ # In reflectance: 2% is noise over bright desert in a week, 20% is+ # a new roof on sand.+ threshold = _scale(options.sensitivity, 0.02, 0.2)+ if method == "spots":+ stat, signed, state = _spots(before, after, metres, threshold, options)+ measures = {"signed": (signed * 100, "mean")}+ else:+ deltas, signed = _changes(before, after, valid)+ if method == "structure":+ old_red, old_nir, _ = _reflectance(before)+ new_red, new_nir, _ = _reflectance(after)+ ndvi = ((new_nir - new_red) / np.maximum(new_nir + new_red, 1e-6)+ - (old_nir - old_red) / np.maximum(old_nir + old_red, 1e-6))+ # Every band the same way: the weakest of them, signed.+ stat = np.where(signed > 0, deltas.min(-1), -deltas.max(-1))+ state = np.abs(ndvi) < STRUCTURE_NDVI+ measures = {"signed": (signed * 100, "mean")}+ else:+ stat = np.sqrt((deltas ** 2).mean(-1))+ measures = {"value": (stat * 100, "max")}+ if options.direction != "both":+ valid &= signed > 0 if options.direction == "gain" else signed < 0+ stat = np.clip(stat, -10, 10).astype(np.float32)+ if options.smoothing:+ stat = cv2.GaussianBlur(stat, (options.smoothing * 2 + 1,) * 2, 0)+ grow = valid & (np.abs(signed if method == "structure" else stat) >= threshold * GROW)+ binary = hysteresis(valid & state & (stat >= threshold), grow & state)+ if options.cleanup:+ kernel = np.ones((2 * options.cleanup + 1,) * 2, np.uint8)+ cleaned = cv2.morphologyEx(binary.astype(np.uint8), cv2.MORPH_OPEN, kernel,+ borderType=cv2.BORDER_REPLICATE)+ cleaned = cv2.morphologyEx(cleaned, cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8),+ borderType=cv2.BORDER_REPLICATE)+ binary = cleaned.astype(bool) & valid++ return Reading(binary=binary[core].astype(np.uint8), stat=stat[core], threshold=threshold,+ measures={name: (values[core], how) for name, (values, how) in measures.items()})+++def strength(margin: float) -> str:+ return "strong" if margin >= 3 else "clear" if margin >= 1.5 else "weak"+++def _candidates(reading: Reading, body: RunInput, x: int, y: int,part: int, frame_keys: list[str]) -> list[dict[str, Any]]:import cv2import numpy as np- z, size = grid(body)- n, labels, stats, centres = cv2.connectedComponentsWithStats(binary, connectivity=8)+ z, size = GRID+ n, labels, stats, centres = cv2.connectedComponentsWithStats(reading.binary, connectivity=8)if n > MAX_RESULTS * 4:- raise ValueError("too many fragments; increase cleanup or reduce sensitivity")+ raise ValueError("too many fragments; lower the sensitivity or pick a larger size")+ flat = labels.ravel()+ peaks = np.full(n, -np.inf)+ np.maximum.at(peaks, flat, reading.stat.ravel().astype(np.float64))+ counts = np.maximum(np.bincount(flat, minlength=n), 1)+ reduced = {}+ for name, (values, how) in reading.measures.items():+ values = values.ravel().astype(np.float64)+ if how == "max":+ best = np.full(n, -np.inf)+ np.maximum.at(best, flat, values)+ reduced[name] = best+ else:+ reduced[name] = np.bincount(flat, weights=values, minlength=n) / countsrows = []for label in range(1, n):px, py, width, height, pixels = map(int, stats[label])@@ -516,18 +823,24 @@ def _candidates(binary: Any, strength: Any, body: RunInput, x: int, y: int,west, north = geographic((x + px / size) / (1 << z), (y + py / size) / (1 << z))east, south = geographic((x + (px + width) / size) / (1 << z),(y + (py + height) / size) / (1 << z))- score = float(np.mean(strength[labels == label]))+ margin = float(peaks[label]) / reading.threshold if reading.threshold else 0.0rows.append({"id": f"{part}-{label}", "bbox": [west, south, east, north],"coordinates": [lon, lat], "area": pixels * mpp * mpp,"width": width * mpp, "height": height * mpp,- "signal_score": round(score, 4), "confidence": None,+ "margin": round(margin, 3), "strength": strength(margin),+ "measure": {name: round(float(values[label]), 3)+ for name, values in reduced.items()},"phenomenon": body.recipe.phenomenon, "review": "new","parts": [{"frames": frame_keys, "box": [px, py, width, height]}]})return rowsdef merge(rows: list[dict[str, Any]], distance: float) -> list[dict[str, Any]]:- """Join touching seam components or explicitly requested nearby candidates."""+ """Join touching seam components or explicitly requested nearby candidates.++ A joined candidate keeps the reading of its stronger half: the margin is+ how far the best of it got past the line, and that is what it is sorted by.+ """kept: list[dict[str, Any]] = []for row in rows:i = 0@@ -540,10 +853,10 @@ def merge(rows: list[dict[str, Any]], distance: float) -> list[dict[str, Any]]:if a[0] <= b[2] + dx + 1e-10 and b[0] <= a[2] + dx + 1e-10 and \a[1] <= b[3] + dy + 1e-10 and b[1] <= a[3] + dy + 1e-10:kept.pop(i)- area = row["area"] + other["area"]- row["signal_score"] = (row["signal_score"] * row["area"] +- other["signal_score"] * other["area"]) / area- row["area"] = area+ if other["margin"] > row["margin"]:+ row.update(margin=other["margin"], strength=other["strength"],+ measure=other["measure"])+ row["area"] += other["area"]row["bbox"] = [min(a[0], b[0]), min(a[1], b[1]), max(a[2], b[2]), max(a[3], b[3])]row["parts"].extend(other["parts"])a = row["bbox"]@@ -555,7 +868,7 @@ def merge(rows: list[dict[str, Any]], distance: float) -> list[dict[str, Any]]:i += 1kept.append(row)if len(kept) > MAX_RESULTS * 2:- raise ValueError("too many candidates; reduce the area or increase cleanup")+ raise ValueError("too many candidates; reduce the area or pick a larger size")return kept@@ -588,34 +901,31 @@ def resolve_dates(case: Case, body: RunInput) -> RunInput:if body.offline:raise ValueError("latest-date lookup needs network; select explicit dates for offline runs")source = body.b.model_copy(deep=True)- if source.provider == "esri-wayback":- source.release = wayback.releases()[0].number- else:- instance = (config.load_settings().get("api_keys") or {}).get("sentinelhub")- if not instance or config.usage_blocked("sentinelhub"):- raise ValueError("Copernicus is unavailable or its usage limit is reached")- # One lookup over every area at once, answering about the areas rather- # than about their centres: a pass can reach a centre and miss most of- # the shape around it, and picking that date sweeps mostly nodata.- try:- found = sentinel.acquisitions(- instance, [list(zone.ring()) for zone in body.zones],- (date.today() - timedelta(days=LOOKBACK_DAYS)).isoformat(),- date.today().isoformat(),- )- finally:- config.record_usage("sentinelhub", 1)- allowed = [entry for entry in found["dates"]- if entry.get("cloud") is not None and entry["cloud"] <= source.maxcc]- whole = [entry for entry in allowed if entry["coverage"] >= FULL_COVER]- if not whole:- best = max((entry["coverage"] for entry in allowed), default=0)- raise ValueError(- "no recent pass covers the whole area under the cloud limit"- + (f"; the best reaches {round(best * 100)}% of it, so choose the dates by hand"- if best else "")- )- source.date = whole[0]["date"] # newest first+ instance = (config.load_settings().get("api_keys") or {}).get("sentinelhub")+ if not instance or config.usage_blocked("sentinelhub"):+ raise ValueError("Copernicus is unavailable or its usage limit is reached")+ # One lookup over every area at once, answering about the areas rather+ # than about their centres: a pass can reach a centre and miss most of+ # the shape around it, and picking that date sweeps mostly nodata.+ try:+ found = sentinel.acquisitions(+ instance, [list(zone.ring()) for zone in body.zones],+ (date.today() - timedelta(days=LOOKBACK_DAYS)).isoformat(),+ date.today().isoformat(),+ )+ finally:+ config.record_usage("sentinelhub", 1)+ allowed = [entry for entry in found["dates"]+ if entry.get("cloud") is not None and entry["cloud"] <= source.maxcc]+ whole = [entry for entry in allowed if entry["coverage"] >= FULL_COVER]+ if not whole:+ best = max((entry["coverage"] for entry in allowed), default=0)+ raise ValueError(+ "no recent pass covers the whole area under the cloud limit"+ + (f"; the best reaches {round(best * 100)}% of it, so choose the dates by hand"+ if best else "")+ )+ source.date = whole[0]["date"] # newest firstreference = body.aif body.date_rule == "latest_previous" and body.followup_id:for summary in listing(case, "runs"):@@ -623,13 +933,10 @@ def resolve_dates(case: Case, body: RunInput) -> RunInput:if previous.get("status") == "ready" and \previous["input"].get("followup_id") == body.followup_id:candidate = Source.model_validate(previous["input"]["b"])- if candidate.provider == source.provider and candidate.layer == source.layer:+ if candidate.layer == source.layer and candidate.date:reference = candidatebreak- if body.recipe.method not in SINGLE_METHODS and (- reference.provider == "sentinel2" and not reference.date or- reference.provider == "esri-wayback" and reference.release is None- ):+ if body.recipe.method not in SINGLE_METHODS and not reference.date:raise ValueError("choose a reference image for the first execution of this follow-up")return body.model_copy(update={"a": reference, "b": source})@@ -649,59 +956,53 @@ def execute(case: Case, job: dict[str, Any]) -> None:persist_run(case, run)returnplanned = plan(body)- z, size = grid(body)+ z, size = GRIDrun.update(status="running", total=len(planned), resolution={"grid_zoom": z,- "tile_size": size}, engine_version=1)+ "tile_size": size, "pad": PAD}, engine_version=ENGINE_VERSION)persist_run(case, run)+ product = product_for(body.recipe.method, body.recipe.parameters.index)results: list[dict[str, Any]] = []- identical = True# What the sweep actually read, against what was asked for. A date the# granules only half reach comes back half nodata, and without this the# run reports "nothing found" over ground it never saw.asked = imaged = 0for part, (x, y) in enumerate(planned):check_active(case, ident)- b = frame(case, run, body.b, x, y)- a = b if single else frame(case, run, body.a, x, y)- identical &= bool((a == b).all())- index_a = index_b = None- product = PRODUCT_METHODS.get(body.recipe.method)- if body.recipe.method == "index":- index_a = frame(case, run, body.a, x, y, body.recipe.parameters.index)- index_b = frame(case, run, body.b, x, y, body.recipe.parameters.index)- identical &= bool((index_a == index_b).all())- elif product:- # Two frames for one tile: the picture the analyst reviews, and- # the bands the detector measures. Both are metered.- index_b = frame(case, run, body.b, x, y, product)+ picture_b = frame(case, run, body.b, x, y)+ picture_a = picture_b if single else frame(case, run, body.a, x, y)+ # Two frames for one date: the picture the analyst reviews, and the+ # bands the detector measures. Both are metered.+ product_b = frame(case, run, body.b, x, y, product)+ product_a = product_b if single else frame(case, run, body.a, x, y, product)mask = mask_for(body.zones, z, size, x, y)inside = mask.astype(bool)asked += int(inside.sum())- imaged += int((inside & (a[:, :, 3] > 0) & (b[:, :, 3] > 0)).sum())- binary, strength = detect(a, b, mask, body, index_a, index_b)+ imaged += int((inside & (picture_a[:, :, 3] > 0) & (picture_b[:, :, 3] > 0)).sum())+ _, lat = geographic((x + .5) / (1 << z), (y + .5) / (1 << z))+ reading = detect((picture_a, picture_b), (product_a, product_b), mask, body, lat)# One image analyzed, one frame of evidence: a vessel's "before" and# "after" would be the same picture twice.sources = [body.b] if single else [body.a, body.b]keys = [_key(source, z, x, y, None) for source in sources]- results.extend(_candidates(binary, strength, body, x, y, part, keys))+ results.extend(_candidates(reading, body, x, y, part, keys))if len(results) > MAX_RESULTS * 4:- raise ValueError("too many fragments; increase cleanup or use smaller areas")+ raise ValueError("too many fragments; lower the sensitivity or use smaller areas")run["progress"] = part + 1persist_run(case, run)- joined = merge(results, body.recipe.parameters.merge_metres)- kept = [r for r in joined if r["area"] >= body.recipe.parameters.min_area and- r["signal_score"] >= body.recipe.parameters.min_score]+ options = body.recipe.parameters+ joined = merge(results, options.merge_metres)+ kept = [r for r in joined if r["area"] >= options.min_area and+ (not options.max_area or r["area"] <= options.max_area)]if len(kept) > MAX_RESULTS:- raise ValueError("too many results; increase minimum area or signal threshold")- kept.sort(key=lambda row: row["area"] * row["signal_score"], reverse=True)+ raise ValueError("too many results; raise the minimum area or lower the sensitivity")+ kept.sort(key=lambda row: row["margin"], reverse=True)for row in kept:w, s, e, n = row["bbox"]row["geometry"] = {"type": "Polygon", "coordinates": [[[w, s], [e, s], [e, n],[w, n], [w, s]]]}swept = round(imaged / asked, 3) if asked else 0.0- run.update(results=kept, count=len(kept), status="ready", swept=swept,- message="The imagery pixels are identical" if identical and not single else "",+ run.update(results=kept, count=len(kept), status="ready", swept=swept, message="",completed_at=now())prune_frames(case, run)persist_run(case, run)diff --git a/src/azimut/engine/satellite.py b/src/azimut/engine/satellite.pyindex b8ce1a7..00ffc2f 100644--- a/src/azimut/engine/satellite.py+++ b/src/azimut/engine/satellite.py@@ -30,7 +30,6 @@ from . import countriesfrom . import geo as geo_enginefrom . import linksfrom . import media as media_engine-from .. import layout# Saved work is places plus captures; a screenshot filed by the capture# extension is a capture with a different origin, not a third entity type.@@ -878,65 +877,6 @@ def state_points(spec: dict[str, Any], entries: list[dict[str, Any]]) -> dict[streturn spec-def _source_points(- case: Case, proof_id: str, incident: list[dict[str, Any]] | None = None-) -> list[dict[str, Any]]:- """The distinct points a proof's panels were composed from.-- Read one hop back along ``derived-from``: a proof carries no coordinates of- its own, only the sources it composes. Two panels cropped from one capture,- or two captures of one roof, are one point and come back once — the point is- what they share. Panels with no point (a photo, a frame) contribute nothing.- """- seen: dict[tuple[Any, Any], dict[str, Any]] = {}- for link in incident if incident is not None else case.links_of(proof_id):- if link["type"] != links.DERIVED_FROM or link["from"] != proof_id:- continue- source = case.get_entity(link["to"])- attrs = (source or {}).get("attrs") or {}- lat, lon = attrs.get("lat"), attrs.get("lon")- if lat is None or lon is None:- continue- seen.setdefault((lat, lon), attrs)- return [{"lat": lat, "lon": lon, "attrs": attrs} for (lat, lon), attrs in seen.items()]---def _linked_posts(- proof_id: str,- incident: list[dict[str, Any]],- post_entities: dict[str, dict[str, Any]],- drafts: dict[str, dict[str, Any]],-) -> list[dict[str, Any]]:- """Saved post drafts directly derived from this proof, newest first."""- linked: list[dict[str, Any]] = []- for link in incident:- if link["type"] != links.DERIVED_FROM or link["to"] != proof_id:- continue- entity = post_entities.get(link["from"])- if entity is None:- continue- draft_path = (entity.get("attrs") or {}).get("draft")- draft = drafts.get(draft_path) if isinstance(draft_path, str) else None- draft = draft or {}- draft_name = draft.get("name")- if not draft_name and isinstance(draft_path, str):- draft_name = draft_path.removeprefix(layout.DRAFTS_DIR + "/").removesuffix(".json")- linked.append(- {- "id": entity["id"],- "name": draft_name,- "title": draft.get("title") or entity.get("label") or "Untitled post",- "target": draft.get("target"),- "updated_at": draft.get("updated_at"),- }- )- linked.sort(- key=lambda post: (post.get("updated_at") or "", post["title"].casefold()),- reverse=True,- )- return linked--def _at(lat: Any, lon: Any) -> tuple[float, float] | None:"""One point rounded to about a metre — the precision the map groups marks at."""try:@@ -951,27 +891,6 @@ def _located(attrs: dict[str, Any]) -> bool:return isinstance(geo, dict) and geo.get("state") == "ok"-def _place_geo(case: Case) -> dict[tuple[float, float], dict[str, Any]]:- """The geography of the case's places, by the point each one stands on.-- A proof carries no geography of its own and no Locate pass ever gives it one- (``saved_entities`` is places and captures). But the point it states in the- composer is filed as a ``place``, whose country is resolved right there- (``api/proofs._state_points``) — so the answer is already in the case, one- node away, for exactly the proofs whose panels place nothing: a frame and a- photo carry no point, and their proof would otherwise file under Unlocated- while the place it just wrote knows the country.-- Read once per index rather than once per row, since a case holds far fewer- places than the proofs index has rows.-- A located place wins a point two of them share: a pin dropped before the- Locate pass ran and the place a proof filed on the same metre are one spot,- and only the one that knows its country answers anything.- """- return _geo_by_point(_page_all(case, ["place"]))--def _geo_by_point(entities: list[dict[str, Any]],) -> dict[tuple[float, float], dict[str, Any]]:@@ -985,117 +904,6 @@ def _geo_by_point(return found-def _geo_at(- sources: list[dict[str, Any]],- point: dict[str, float],- places: dict[tuple[float, float], dict[str, Any]] | None = None,-) -> dict[str, Any]:- """The attrs of whatever stands on this exact point, or nothing.-- A source the proof composes answers first — it is what the proof was built- from. Failing that, the place standing there does, which is how a proof made- of photos still files under its country.- """- here = _at(point["lat"], point["lon"])- if here is None:- return {}- for source in sources:- if _at(source["lat"], source["lon"]) == here:- return dict(source["attrs"])- return dict((places or {}).get(here) or {})---def _proof_row(- proof: dict[str, Any], entity: dict[str, Any], point: dict[str, Any] | None-) -> dict[str, Any]:- entity_id = entity["id"]- attrs = (point or {}).get("attrs") or {}- geo = attrs.get("geo") if isinstance(attrs.get("geo"), dict) else None- lat, lon = (point or {}).get("lat"), (point or {}).get("lon")- return {- "id": entity_id,- # one proof can hold two points, and the two rows must not collide as- # render keys or as marker identities- "key": f"{entity_id}@{lat},{lon}",- "kind": "proof",- "name": proof["name"],- "title": proof.get("title") or proof["name"],- # a proof is filed like any other artifact, so the panel groups it by- # folder as well as by place- "folder": (entity.get("attrs") or {}).get("folder") or "",- "notes": "",- # what the analyst called this point, when they called it anything. It is- # what tells three rows of one proof apart: same title, same thumbnail,- # three places.- "label": (point or {}).get("label") or "",- "lat": lat,- "lon": lon,- "geo": geo,- "continent": continents.continent_for((geo or {}).get("country_code"), lat, lon),- "country_en": countries.name_for((geo or {}).get("country_code")),- "path": proof.get("png"),- "thumbnail": proof.get("thumb"),- "fetched_at": _utc_stamp(proof.get("updated_at")),- "posts": proof.get("posts", 0),- "linked_posts": proof.get("linked_posts", []),- }---def proof_index(- case: Case,- listing: list[dict[str, Any]],- draft_listing: list[dict[str, Any]] | None = None,-) -> list[dict[str, Any]]:- """Proofs as map rows, newest first — one row per distinct point.-- ``listing`` is the proofs listing (title, export, thumbnail, the points its- spec states), which the proofs API owns; everything geographic is read here so- the Saved panel gets the row shape it already knows. A proof stating three- points is three rows: the map is about places, and a proof arguing three of- them draws three marks. A proof whose panels are all unlocated still comes- back, without a point, and files under ``Unlocated`` in the tree.-- Kept out of ``saved_index`` on purpose: that one is read on every case open,- this one only when the Proofs position of the switch is first opened.- """- by_spec = {- (entity.get("attrs") or {}).get("spec"): entity- for entity in _page_all(case, ["proof"])- }- post_entities = {entity["id"]: entity for entity in _page_all(case, ["post"])}- drafts = {- layout.draft_rel(draft["name"]): draft for draft in (draft_listing or [])- }- places = _place_geo(case)- rows: list[dict[str, Any]] = []- for proof in listing:- entity = by_spec.get(proof.get("spec_path"))- if entity is None:- continue # a spec file with no entity is not in the graph to place- incident = case.links_of(entity["id"])- linked_posts = _linked_posts(entity["id"], incident, post_entities, drafts)- proof = {**proof, "posts": len(linked_posts), "linked_posts": linked_posts}- sources = _source_points(case, entity["id"], incident)- stated = proof_points(case, entity["id"], proof.get("points") or [], incident)- if stated:- # the proof says where it is, so what it composes stops answering for- # it. Each point's geography is borrowed only from what stands on that- # same point: a source it composes, or the place the save filed there.- # A neighbouring capture's country would be a guess, and a place the- # analyst linked by hand from somewhere else is about somewhere else —- # a wrong country files the proof under the wrong branch.- points: list[dict[str, Any] | None] = [- {**point, "attrs": _geo_at(sources, point, places)} for point in stated- ]- else:- # a proof none of whose panels carry a point still lists, without- # one: it files under Unlocated rather than leaving its own tool- points = list(sources) or [None]- rows.extend(_proof_row(proof, entity, point) for point in points)- rows.sort(key=lambda r: r["fetched_at"], reverse=True)- return rows--#: What the Media position draws: photographs and footage. Audio has a place it was#: recorded but nothing to look at beside the imagery, and a document has neither.MAP_MEDIA_KINDS = ("image", "video")@@ -1280,8 +1088,8 @@ def _media_row(# -- placement: where the chain puts an entity (ONTOLOGY §3) ----------------------## The chain is read backwards as geography: a proof with no point of its own stands-# at the point of every capture it composes. `proof_index` does that one hop back-# for the map. This walks the same edges in both directions and further, because+# at the point of every capture it composes, one hop back. This walks the same edges+# in both directions and further, because# the artifact holding the point is rarely the one being read: a video reaches its# capture through a proof that composed a frame of it, three hops away through a# shared descendant. That V is what the geolocation gesture actually looks like —@@ -1351,12 +1159,11 @@ def placements(point comes back with the entity it was read off — the *via* the panel names —and the entity's own point comes back with none, because nothing placed it.- **An artifact that carries a point is where the walk stops.** ``proof_index``- already settles this for the map — a proof that states where it is answers with- its own points, rather than also drawing at the panels it overrode — and a panel- that listed both would contradict the map about the same proof. Stopping there is also what keeps- a video to its own argument: the capture behind its proof is reached, the second- proof that happens to reuse that capture is not.+ **An artifact that carries a point is where the walk stops.** A proof that states+ where it is answers with its own points, rather than also reporting the panels it+ overrode, and a panel that listed both would contradict itself about one proof.+ Stopping there is also what keeps a video to its own argument: the capture behind+ its proof is reached, the second proof that happens to reuse that capture is not.Points are deduplicated on the exact pair, never on a rounded one: two capturesof the same roof are metres apart, and merging them would assert they are onediff --git a/src/azimut/engine/sentinel.py b/src/azimut/engine/sentinel.pyindex 60c9a37..059dc57 100644--- a/src/azimut/engine/sentinel.py+++ b/src/azimut/engine/sentinel.py@@ -260,127 +260,151 @@ class CoverageError(RuntimeError):"""Sentinel Hub did not return a usable dataMask image."""-# Spectral indices Compare's change reading can ask for. Each is a normalised-# difference of two L2A bands, so it lands in -1…1 whatever the light that day,-# which is what makes two dates comparable where two true-colour renders are not.-# Only these expressions ever reach an evalscript: the request names a key.-INDEX_BANDS: dict[str, tuple[str, str]] = {- "ndvi": ("B08", "B04"), # vegetation vigour- "ndwi": ("B03", "B08"), # open water- "nbr": ("B08", "B12"), # burn scars- "ndbi": ("B11", "B08"), # built-up and bare surfaces-}PRODUCT_MAX_EDGE = 2048_PRODUCT_MAX_BYTES = 24_000_000_WEB_MERCATOR_LIMIT = 20_037_508.342789244-def _index_evalscript(index: str) -> str:- high, low = INDEX_BANDS[index]- # R carries the index scaled to a byte, G the scene classification (cloud,- # shadow, snow…), A the data mask. The browser decodes all three.+# Detect's band products. Each one is what a single detector measures, rounded+# into the four bytes of a PNG so one metered request carries all of it.+#+# The first channel is never zero where the sensor saw something, which is how+# the engine tells a dark reading from no reading. The fourth carries+# Sentinel-2's own view of the sky: the scene class in the low four bits, and a+# flag for pixels dark enough in the near-infrared to be in a cloud's shadow.+# The engine turns those into a mask, with the sun's direction for the shadows+# the classification misses (engine/analyzers.py).+#+# Reflectance is stretched by a gain before rounding. Sea under sun glint sits+# near 9% in the near-infrared, so a gain that spends the byte on the bottom few+# percent saturates hulls and wave crests alike; at 2 the byte spans 0-50% in+# steps of 0.2%, which still resolves calm water and leaves a hull its contrast.+# Short-wave infrared over desert reaches 50%, so the change product gives it+# a little more room.+BAND_GAIN = 2.0+SWIR_GAIN = 1.6+# Band ratios are stretched the same way, and 64 puts the useful 1-4 range+# across the byte.+RATIO_GAIN = 64.0+DARK_FLAG = 16+DARK_REFLECTANCE = 0.15++# The spectral indices both modes read, as sums of bands over sums of bands so+# the bare soil index fits beside the normalised differences. Each lands in -1…1+# whatever the light that day, which is what makes two dates comparable where+# two true-colour renders are not. Only these expressions reach an evalscript:+# a request names a key.+SPECTRAL_INDEX: dict[str, tuple[tuple[str, ...], tuple[str, ...]]] = {+ "ndvi": (("B08",), ("B04",)), # green vegetation+ "ndwi": (("B03",), ("B08",)), # open water+ "mndwi": (("B03",), ("B11",)), # open water, fewer false hits on built-up land+ "nbr": (("B08",), ("B12",)), # burn scars+ "ndbi": (("B11",), ("B08",)), # built-up surfaces+ "bsi": (("B11", "B04"), ("B08", "B02")), # bare soil+}+++def _byte(expression: str, gain: float, floor: int = 0) -> str:+ return f"Math.max({floor}, Math.min(255, Math.round(({expression}) * {255 * gain:g})))"+++def _detect_script(bands: list[str], values: list[str], dark: str = "B08") -> str:+ wanted = list(dict.fromkeys([*bands, dark, "SCL", "dataMask"]))+ listed = ", ".join(f'"{band}"' for band in wanted)script = f"""//VERSION=3function setup() {{- return {{- input: [{{ bands: ["{high}", "{low}", "SCL", "dataMask"] }}],- output: {{ bands: 4, sampleType: "UINT8" }}- }};+ return {{ input: [{{ bands: [{listed}] }}], output: {{ bands: 4, sampleType: "UINT8" }} }};}}function evaluatePixel(p) {{- const sum = p.{high} + p.{low};- const value = sum === 0 ? 0 : (p.{high} - p.{low}) / sum;- const clamped = Math.max(-1, Math.min(1, value));- return [Math.round((clamped + 1) * 127.5), p.SCL, 0, p.dataMask * 255];+ if (!p.dataMask) return [0, 0, 0, 0];+ return [{", ".join(values)}, p.SCL + (p.{dark} < {DARK_REFLECTANCE} ? {DARK_FLAG} : 0)];}}"""return base64.b64encode(script.encode("ascii")).decode("ascii")-# How much a reflectance is stretched before it is rounded into a byte. A-# detector that thresholds against its own local background needs resolution-# where the signal lives, not a scale that reaches 100% reflectance: open water-# in the near-infrared sits under 3%, so at this gain it spans the bottom fifth-# of the byte instead of two or three values. Anything above 1/gain saturates,-# which costs nothing — these are detections, not measurements.-NIR_GAIN = 8.0-SWIR_GAIN = 4.0-# Band ratios are stretched the same way, and 64 puts the useful 1…4 range-# across the byte.-RATIO_GAIN = 64.0---def _vessel_evalscript() -> str:- """Bands for finding something floating: infrared, water, and the classes.-- Water absorbs near-infrared almost completely, so a hull, a wake or a rig- is an outlier against a near-black background — which is why this reads- B08 rather than the rendered picture, where the stretch has already thrown- the difference away. NDWI rides along in B so the detector can tell which- pixels are sea without a second request.- """- script = """//VERSION=3-function setup() {- return {- input: [{ bands: ["B03", "B08", "SCL", "dataMask"] }],- output: { bands: 4, sampleType: "UINT8" }- };-}-function evaluatePixel(p) {- const sum = p.B03 + p.B08;- const ndwi = sum === 0 ? 0 : (p.B03 - p.B08) / sum;- return [- Math.min(255, Math.round(p.B08 * 255 * %(nir)s)),- p.SCL,- Math.round((Math.max(-1, Math.min(1, ndwi)) + 1) * 127.5),- p.dataMask * 255- ];-}-""" % {"nir": NIR_GAIN}- return base64.b64encode(script.encode("ascii")).decode("ascii")---def _fire_evalscript() -> str:- """Bands for the published Sentinel-2 active-fire test.-- Flame radiates in the short-wave infrared, so B12 rises first and hardest- and does it through smoke. Absolute brightness alone would call every- cloud a fire; the two ratios are what separate them, because cloud is- bright in all three bands at once and sits near a ratio of one.-- No scene classification here: the ratios already reject cloud, and the- fourth channel is worth more as the data mask.- """- script = """//VERSION=3-function setup() {- return {- input: [{ bands: ["B08", "B11", "B12", "dataMask"] }],- output: { bands: 4, sampleType: "UINT8" }- };-}-function evaluatePixel(p) {- const over11 = p.B11 <= 0 ? 0 : p.B12 / p.B11;- const over08 = p.B08 <= 0 ? 0 : p.B12 / p.B08;- return [- Math.min(255, Math.round(p.B12 * 255 * %(swir)s)),- Math.min(255, Math.round(over11 * %(ratio)s)),- Math.min(255, Math.round(over08 * %(ratio)s)),- p.dataMask * 255- ];-}-""" % {"swir": SWIR_GAIN, "ratio": RATIO_GAIN}+def _ratio(high: str, low: str) -> str:+ return f"Math.min(255, Math.round((p.{low} <= 0 ? 0 : p.{high} / p.{low}) * {RATIO_GAIN:g}))"+++def _detect_evalscript(product: str) -> str:+ if product == "vessel":+ # Water absorbs near-infrared, so a hull is an outlier against a dark+ # sea; short-wave infrared is what tells it from a breaking wave, which+ # is bright in the one and not the other. NDWI says which pixels are sea.+ ndwi = "(p.B03 + p.B08 === 0 ? 0 : (p.B03 - p.B08) / (p.B03 + p.B08))"+ return _detect_script(["B03", "B08", "B11"], [+ _byte("p.B08", BAND_GAIN, 1), _byte("p.B11", BAND_GAIN),+ f"Math.round((Math.max(-1, Math.min(1, {ndwi})) + 1) * 127.5)",+ ])+ if product == "fire":+ # The published active-fire test: B12 high in absolute terms and against+ # both B11 and B8A. B8A rather than B08 because it shares B12's 20 m+ # grid, so a sharp roof edge cannot fake a ratio.+ return _detect_script(["B8A", "B11", "B12"], [+ _byte("p.B12", BAND_GAIN, 1), _ratio("B12", "B11"), _ratio("B12", "B8A"),+ ], dark="B8A")+ if product == "surface":+ # Red, near and short-wave infrared: enough to see soil, vegetation and+ # water move, and to tell a field that greened from ground that was dug.+ return _detect_script(["B04", "B08", "B11"], [+ _byte("p.B04", BAND_GAIN, 1), _byte("p.B08", BAND_GAIN), _byte("p.B11", SWIR_GAIN),+ ])+ high, low = SPECTRAL_INDEX[product.removeprefix("index-")]+ return _detect_script([*high, *low], [+ f"Math.max(1, Math.round((Math.max(-1, Math.min(1, {_index(high, low)})) + 1) * 127.5))", "0", "0",+ ])+++def _index(high: tuple[str, ...], low: tuple[str, ...]) -> str:+ top = " + ".join(f"p.{band}" for band in high)+ bottom = " + ".join(f"p.{band}" for band in low)+ return f"(({top}) + ({bottom}) === 0 ? 0 : (({top}) - ({bottom})) / (({top}) + ({bottom})))"+++def _change_evalscript(product: str) -> str:+ # Difference mode draws its frames into a canvas and decodes them there+ # (lib/map/changeDetect.js). A canvas premultiplies alpha, so alpha stays+ # the data mask and the sky byte rides in green: the same byte Detect's+ # products carry fourth, so the two modes read one sky. `change-sky` is that+ # byte alone, for a cloud filter over the picture methods.+ name = product.removeprefix("change-")+ if name == "sky":+ bands: list[str] = []+ value = "0"+ else:+ high, low = SPECTRAL_INDEX[name]+ bands = [*high, *low]+ value = f"Math.round((Math.max(-1, Math.min(1, {_index(high, low)})) + 1) * 127.5)"+ wanted = list(dict.fromkeys([*bands, "B08", "SCL", "dataMask"]))+ listed = ", ".join(f'"{band}"' for band in wanted)+ script = f"""//VERSION=3+function setup() {{+ return {{ input: [{{ bands: [{listed}] }}], output: {{ bands: 4, sampleType: "UINT8" }} }};+}}+function evaluatePixel(p) {{+ if (!p.dataMask) return [0, 0, 0, 0];+ return [{value}, p.SCL + (p.B08 < {DARK_REFLECTANCE} ? {DARK_FLAG} : 0), 0, 255];+}}+"""return base64.b64encode(script.encode("ascii")).decode("ascii")-# Everything a caller may ask `band_frame` for. Indices are normalised-# differences the change reading compares between two dates; the other two are-# detector inputs, read from one date.-PRODUCTS: frozenset[str] = frozenset({*INDEX_BANDS, "vessel", "fire"})+# Everything a caller may ask `band_frame` for: Detect's products, measured on+# the server, and Difference's frames, decoded in the browser.+DETECT_PRODUCTS: frozenset[str] = frozenset(+ {"vessel", "fire", "surface", *(f"index-{name}" for name in SPECTRAL_INDEX)}+)+CHANGE_PRODUCTS: frozenset[str] = frozenset(+ {"change-sky", *(f"change-{name}" for name in SPECTRAL_INDEX)}+)+PRODUCTS: frozenset[str] = frozenset({*CHANGE_PRODUCTS, *DETECT_PRODUCTS})def _evalscript(product: str) -> str:- if product in INDEX_BANDS:- return _index_evalscript(product)- return _vessel_evalscript() if product == "vessel" else _fire_evalscript()+ if product in CHANGE_PRODUCTS:+ return _change_evalscript(product)+ return _detect_evalscript(product)def band_frame(@@ -436,13 +460,13 @@ def band_frame(response.raise_for_status()body = response.contentif len(body) > _PRODUCT_MAX_BYTES:- raise CoverageError("the index frame is too large")+ raise CoverageError("the band frame is too large")try:with Image.open(io.BytesIO(body)) as frame:if frame.format != "PNG" or frame.size != (width, height):- raise CoverageError("Sentinel Hub returned an unexpected index frame")+ raise CoverageError("Sentinel Hub returned an unexpected band frame")except (OSError, UnidentifiedImageError) as exc:- raise CoverageError("Sentinel Hub returned no readable index frame") from exc+ raise CoverageError("Sentinel Hub returned no readable band frame") from excreturn bodydiff --git a/tests/analyzerfixture.py b/tests/analyzerfixture.pyindex bb97d1f..bd704c0 100644--- a/tests/analyzerfixture.py+++ b/tests/analyzerfixture.py@@ -1,124 +1,159 @@-"""Synthetic imagery inputs for analyzer and full-case integration gates."""+"""Synthetic Copernicus inputs for analyzer and full-case integration gates.++Pictures and band products go where an offline run finds them: the tile cache,+under the keys the engine itself computes. Products are built in the byte+layout the evalscripts return (engine/sentinel.py), padded the way the engine+asks for them, so a test that passes here reads what a real sweep reads.+"""import ioimport numpy as npfrom PIL import Image-from azimut import layoutfrom azimut.engine import analyzers, sentinel, tilecache-from azimut.engine.analysis_models import BUILTINS, PRODUCT_METHODS, RunInput-+from azimut.engine.analysis_models import BUILTINS, RunInput, Source, product_for-def sample_input():- # One complete interior patch, in exactly one native Wayback tile.- z, x, y = 19, 265056, 182248- west, north = analyzers.geographic((x + .1) / 2**z, (y + .1) / 2**z)- east, south = analyzers.geographic((x + .9) / 2**z, (y + .9) / 2**z)- recipe = BUILTINS[0].model_dump()- recipe["parameters"].update(min_area=0, cleanup=0, smoothing=0)- return {"title": "Harbour check", "recipe": recipe,- "zones": [{"id": "harbour", "name": "Harbour", "kind": "rect",- "points": [[west, south], [east, north]]}],- "a": {"provider": "esri-wayback", "release": 1},- "b": {"provider": "esri-wayback", "release": 2}, "offline": True}---def seed_images(body):- for x, y in analyzers.plan(RunInput.model_validate(body)):- for release in (1, 2):- pixels = np.full((256, 256, 3), 40, np.uint8)- if release == 2:- pixels[90:120, 100:150] = 230- out = io.BytesIO()- Image.fromarray(pixels).save(out, "PNG")- tilecache.put(f"esri-wayback~{release}", 19, x, y, out.getvalue(), "image/png")---# One native Sentinel tile: level 13 of the 512px grid, which is 9.55 m a pixel.+# One native Sentinel tile: level 13 of the 512px grid, 6.5 m a pixel at this latitude.SENTINEL_TILE = (13, 4230, 2930)-SENTINEL_DAY = "2026-05-11"+DAY_A = "2026-05-04"+DAY_B = "2026-05-11"+PAD = analyzers.PAD+EDGE = 512 + 2 * PAD+# Scene classes and the dark flag, as the fourth channel carries them.+VEGETATION, BARE, WATER, UNSURE, CLOUD, SHADOW = 4, 5, 6, 7, 9, 3+DARK = sentinel.DARK_FLAG+++def zone(x0=.1, y0=.1, x1=.9, y1=.9, tile=SENTINEL_TILE, ident="patch"):+ z, x, y = tile+ west, north = analyzers.geographic((x + x0) / 2**z, (y + y0) / 2**z)+ east, south = analyzers.geographic((x + x1) / 2**z, (y + y1) / 2**z)+ return {"id": ident, "name": "Patch", "kind": "rect", "points": [[west, south], [east, north]]}def sentinel_input(recipe_id, **parameters):- """A one-tile Copernicus run for a detector that reads bands, not pictures.+ """A one-tile Copernicus run for a built-in analyzer.Keeps the preset's own thresholds unless a test says otherwise: they arepart of what is being tested, and a detector tuned down to catch everythingwould prove nothing about the one it ships with."""- z, x, y = SENTINEL_TILE- west, north = analyzers.geographic((x + .1) / 2**z, (y + .1) / 2**z)- east, south = analyzers.geographic((x + .9) / 2**z, (y + .9) / 2**z)recipe = next(r for r in BUILTINS if r.id == recipe_id).model_dump()recipe["parameters"].update(parameters)- source = {"provider": "sentinel2", "date": SENTINEL_DAY,- "layer": "TRUE_COLOR", "maxcc": 30}- return {"title": f"{recipe_id} sweep", "recipe": recipe,- "zones": [{"id": "patch", "name": "Patch", "kind": "rect",- "points": [[west, south], [east, north]]}],- "a": dict(source), "b": dict(source), "offline": True}+ return {"title": f"{recipe_id} sweep", "recipe": recipe, "zones": [zone()],+ "a": {"provider": "sentinel2", "date": DAY_A, "layer": "TRUE_COLOR", "maxcc": 30},+ "b": {"provider": "sentinel2", "date": DAY_B, "layer": "TRUE_COLOR", "maxcc": 30},+ "offline": True}-def seed_sentinel(case, body, bands):- """Put one picture and one band product where an offline run will find them.+def _png(pixels):+ out = io.BytesIO()+ Image.fromarray(pixels).save(out, "PNG")+ return out.getvalue()- The product lands under a preserved run's assets, which is the path a- reopened case takes, and its filename comes from the engine's own key- function — a copy of that naming here would be a second source of truth- that silently stops matching.- """- z, x, y = SENTINEL_TILE++def put_picture(source, tile=SENTINEL_TILE, shade=40):+ parsed = Source.model_validate(source)+ z, x, y = tile+ tilecache.put(sentinel.variant_id("sentinel2", parsed.layer, parsed.date, parsed.date,+ parsed.maxcc),+ z, x, y, _png(np.full((512, 512, 3), shade, np.uint8)), "image/png")+++def put_product(body, letter, bands, tile=SENTINEL_TILE):parsed = RunInput.model_validate(body)- picture = io.BytesIO()- Image.fromarray(np.full((512, 512, 3), 30, np.uint8)).save(picture, "PNG")- tilecache.put(- sentinel.variant_id("sentinel2", parsed.b.layer, parsed.b.date,- parsed.b.date, parsed.b.maxcc),- z, x, y, picture.getvalue(), "image/png",- )- product = PRODUCT_METHODS[parsed.recipe.method]- folder = case.subdir(layout.ANALYSIS_DIR) / "runs-seed.assets"- folder.mkdir(parents=True, exist_ok=True)- frame = io.BytesIO()- Image.fromarray(bands, "RGBA").save(frame, "PNG")- (folder / f"{analyzers._key(parsed.b, z, x, y, product)}.png").write_bytes(frame.getvalue())---def vessel_bands(targets):- """Near-infrared over a sea that brightens across the tile, plus targets.-- The ramp is the point: a sunlit swell can be brighter than a hull half a- kilometre away, so an absolute threshold has to be retuned per scene and a- local one does not. Channels are what the vessel evalscript returns —- infrared, scene class, NDWI, data mask.- """- ramp = np.linspace(10, 130, 512, dtype=np.float32)- bands = np.zeros((512, 512, 4), np.uint8)- bands[:, :, 0] = np.broadcast_to(ramp, (512, 512)).astype(np.uint8)- bands[:, :, 1] = 6 # Sentinel-2 scene class 6 is water- bands[:, :, 2] = 178 # NDWI ≈ +0.4- bands[:, :, 3] = 255- for px, py, width, height in targets:- bands[py:py + height, px:px + width, 0] = np.clip(- bands[py:py + height, px:px + width, 0].astype(np.int16) + 100, 0, 255).astype(np.uint8)- bands[py:py + height, px:px + width, 2] = 64 # a hull is not water+ source = parsed.a if letter == "a" else parsed.b+ product = product_for(parsed.recipe.method, parsed.recipe.parameters.index)+ z, x, y = tile+ tilecache.put(analyzers.product_cache_id(source, product), z, x, y, _png(bands), "image/png")+++def seed(body, before=None, after=None, tile=SENTINEL_TILE):+ """Pictures for both dates, and whichever products the test built."""+ for letter, bands in (("a", before), ("b", after)):+ put_picture(body[letter], tile)+ if bands is not None:+ put_product(body, letter, bands, tile)+++def at(px, py, width, height):+ """A core rectangle as a slice of a padded product."""+ return slice(PAD + py, PAD + py + height), slice(PAD + px, PAD + px + width)+++def surface(red=0.10, nir=0.30, swir=0.20, sky=VEGETATION):+ """Red, near and short-wave infrared over the whole padded frame."""+ bands = np.zeros((EDGE, EDGE, 4), np.uint8)+ bands[:, :] = code(red, nir, swir, sky)return bands-def fire_bands(fire, cloud):- """Short-wave infrared and the two band ratios the fire test reads.+def code(red, nir, swir, sky=VEGETATION):+ """One pixel as the surface evalscript writes it, saturation included."""+ def byte(value, gain, floor=0):+ return max(floor, min(255, round(value * 255 * gain)))- The cloud patch is the trap: bright in B12 like a fire, but bright in its- neighbours too, so its ratios sit at one and the test must pass it over.- """- bands = np.zeros((512, 512, 4), np.uint8)- bands[:, :, 0] = 102 # B12 ≈ 0.10 reflectance, under the fire floor- bands[:, :, 1] = 70 # B12/B11 ≈ 1.1- bands[:, :, 2] = 51 # B12/B08 ≈ 0.8- bands[:, :, 3] = 255- px, py, width, height = cloud- bands[py:py + height, px:px + width] = [255, 64, 64, 255] # bright, ratios at one- px, py, width, height = fire- bands[py:py + height, px:px + width] = [255, 160, 192, 255] # bright, ratios well over+ return [byte(red, sentinel.BAND_GAIN, 1), byte(nir, sentinel.BAND_GAIN),+ byte(swir, sentinel.SWIR_GAIN), sky + (DARK if nir < 0.15 else 0)]+++def index_frame(value, sky=VEGETATION):+ bands = np.zeros((EDGE, EDGE, 4), np.uint8)+ bands[:, :] = [index_byte(value), 0, 0, sky]+ return bands+++def index_byte(value):+ return max(1, round((value + 1) * 127.5))+++def sample_input():+ """Any surface change, sized so a single bright patch is one candidate."""+ return sentinel_input("large-change", min_area=0, max_area=0, cleanup=0, smoothing=0,+ merge_metres=0)+++def seed_images(body, tile=SENTINEL_TILE, changed=True):+ before = surface()+ after = surface()+ if changed:+ after[at(100, 90, 50, 30)] = code(0.30, 0.35, 0.40) # new bare ground+ seed(body, before, after, tile)+++def sea(rng_seed=3):+ """Open water under a little glint: a ramp of infrared, a whisper of noise."""+ rng = np.random.default_rng(rng_seed)+ ramp = np.linspace(0.02, 0.10, EDGE, dtype=np.float32)+ nir = np.broadcast_to(ramp, (EDGE, EDGE)) + rng.normal(0, 0.002, (EDGE, EDGE))+ bands = np.zeros((EDGE, EDGE, 4), np.uint8)+ bands[:, :, 0] = np.clip(np.round(nir * 255 * sentinel.BAND_GAIN), 1, 255)+ bands[:, :, 1] = np.clip(np.round((0.01 + rng.normal(0, 0.002, (EDGE, EDGE)))+ * 255 * sentinel.BAND_GAIN), 0, 255)+ bands[:, :, 2] = 178 # NDWI ≈ +0.4+ bands[:, :, 3] = WATER + DARK+ return bands+++def hull(bands, px, py, width, height, swir=True):+ """A target on the sea. Without short-wave infrared it is a breaking wave."""+ region = bands[at(px, py, width, height)]+ region[:, :, 0] = np.clip(region[:, :, 0].astype(int) + 100, 0, 255)+ if swir:+ region[:, :, 1] = np.clip(region[:, :, 1].astype(int) + 90, 0, 255)+ region[:, :, 2] = 64 # a hull is not water+ region[:, :, 3] = BARE+++def fire_frame():+ """B12, its ratios to B11 and B8A, and the sky, over quiet ground."""+ bands = np.zeros((EDGE, EDGE, 4), np.uint8)+ bands[:, :] = [round(0.10 * 255 * sentinel.BAND_GAIN), 70, 51, BARE] # ratios 1.1 and 0.8return bands+++def flame(bands, px, py, width, height, b12=0.5, ratio=2.5):+ bands[at(px, py, width, height)] = [min(255, round(b12 * 255 * sentinel.BAND_GAIN)),+ round(ratio * sentinel.RATIO_GAIN),+ round(ratio * sentinel.RATIO_GAIN), BARE]diff --git a/tests/test_analyzers.py b/tests/test_analyzers.pyindex 6febb2f..de85e5d 100644--- a/tests/test_analyzers.py+++ b/tests/test_analyzers.py@@ -8,18 +8,41 @@ import pytestfrom PIL import Imagefrom azimut import config, layout-from azimut.engine import analysis_models as analyzers_modelsfrom azimut.engine import analyzers, tilecache, workqueue-from azimut.engine.analysis_models import METHODS, Recipe, RunInput, Zone+from azimut.engine.analysis_models import (+ BUILTINS,+ METHODS,+ SIZES,+ Parameters,+ Recipe,+ RunInput,+ Zone,+)from azimut.workspace import Casefrom analyzerfixture import (+ BARE,+ CLOUD,+ DARK,+ EDGE,+ PAD,SENTINEL_TILE,- fire_bands,+ UNSURE,+ VEGETATION,+ WATER,+ at,+ code,+ fire_frame,+ flame,+ hull,+ index_byte,+ index_frame,sample_input,+ sea,+ seed,seed_images,- seed_sentinel,sentinel_input,- vessel_bands,+ surface,+ zone,)@@ -30,10 +53,13 @@ def scenario(client, monkeypatch):case = Case.open(ident)body = sample_input()seed_images(body)+def forbidden(*args, **kwargs):raise AssertionError("unexpected network")+monkeypatch.setattr(analyzers.httpx, "stream", forbidden)- monkeypatch.setattr(analyzers.wayback, "releases", forbidden)+ monkeypatch.setattr(analyzers.sentinel, "band_frame", forbidden)+ monkeypatch.setattr(analyzers.sentinel, "acquisitions", forbidden)return case, body@@ -44,14 +70,18 @@ def run(client, case, body):return client.get(f"/api/cases/{case.id}/analysis/runs/{result.json()['id']}").json()+# -- runs, review and evidence ------------------------------------------------------++def test_local_run_keeps_frames_and_review_without_network(client, scenario):case, body = scenariosaved = run(client, case, body)assert saved["status"] == "ready", saved+ assert saved["engine_version"] == analyzers.ENGINE_VERSIONassert saved["count"] == 1- assert len(saved["frames"]) == 2+ # two pictures to review and two band products measured+ assert len(saved["frames"]) == 4row = saved["results"][0]- assert row["confidence"] is Noneassert row["area"] > 0assert row["geometry"]["type"] == "Polygon"for frame in saved["frames"].values():@@ -65,7 +95,19 @@ def test_local_run_keeps_frames_and_review_without_network(client, scenario):# Promoted evidence survives deletion of the working analysis.assert client.delete(f"/api/cases/{case.id}/analysis/runs/{saved['id']}").status_code == 200assert case.resolve_inside(promoted["image"]).is_file()- assert not case.resolve_inside(layout.analysis_assets_rel(f"runs-{saved['id']}" )).exists()+ assert not case.resolve_inside(layout.analysis_assets_rel(f"runs-{saved['id']}")).exists()+++def test_a_candidate_says_how_strong_it_is_in_words_and_units(client, scenario):+ """A percentage of nothing in particular told nobody anything. A candidate+ now carries how far past its threshold it got, and the reading behind it."""+ case, body = scenario+ row = run(client, case, body)["results"][0]+ assert row["strength"] in {"weak", "clear", "strong"}+ assert row["margin"] >= 1+ # 0.30 → 0.10 red, 0.35 → 0.30 near, 0.40 → 0.20 short-wave: the reading is in percent+ assert 10 < row["measure"]["value"] < 25+ assert "signal_score" not in row and "confidence" not in rowdef test_keeping_a_candidate_is_the_only_thing_that_reaches_the_case(client, scenario):@@ -96,13 +138,7 @@ def test_keeping_a_candidate_is_the_only_thing_that_reaches_the_case(client, scedef test_a_candidate_preview_is_enlarged_so_its_pixels_can_be_read(client, scenario):- """Legibility comes from whole-number nearest-neighbour zoom, not smoothing.-- A candidate can be a dozen pixels across. Served at that size the browser- stretches it into a blur, so the server does the enlarging itself, by an- integer factor and with no interpolation: bigger, and still the pixels the- sensor recorded.- """+ """Legibility comes from whole-number nearest-neighbour zoom, not smoothing."""case, body = scenariosaved = run(client, case, body)row = saved["results"][0]@@ -116,6 +152,37 @@ def test_a_candidate_preview_is_enlarged_so_its_pixels_can_be_read(client, scenaassert preview.height == (box[3] + 2 * 20) * zoom + 48+def test_a_candidate_across_a_tile_edge_is_one_candidate_with_one_picture(client, scenario):+ """What crossed the seam used to come back as "evidence parts" to page+ through. It is one thing on the ground, so it is one candidate, and its+ preview is the two tiles laid side by side."""+ case, body = scenario+ z, x, y = SENTINEL_TILE+ body["zones"] = [zone(0.5, 0.1, 1.5, 0.9)]+ left, right = surface(), surface()+ left_after, right_after = surface(), surface()+ left_after[at(492, 200, 20, 20)] = code(0.30, 0.35, 0.40)+ right_after[at(0, 200, 20, 20)] = code(0.30, 0.35, 0.40)+ # the padding is the neighbour's pixels, as the provider serves it+ left_after[at(512, 200, PAD, 20)] = code(0.30, 0.35, 0.40)+ right_after[PAD + 200:PAD + 220, PAD - 20:PAD] = code(0.30, 0.35, 0.40)+ seed(body, left, left_after)+ seed(body, right, right_after, tile=(z, x + 1, y))+ saved = run(client, case, body)+ assert saved["status"] == "ready", saved+ assert saved["count"] == 1+ row = saved["results"][0]+ assert len(row["parts"]) == 2+ endpoint = f"/api/cases/{case.id}/analysis/runs/{saved['id']}/results/{row['id']}"+ response = client.get(endpoint + "/preview")+ assert response.status_code == 200+ with Image.open(io.BytesIO(response.content)) as preview:+ # 40 px of candidate across the seam plus the margins, twice, zoomed together+ crop = 40 + 2 * 20+ zoom = round(320 / crop)+ assert preview.width == 2 * crop * zoom + 8++def test_reading_saved_items_never_starts_jobs(client, scenario):case, body = scenariobefore = case.list_jobs()@@ -123,9 +190,9 @@ def test_reading_saved_items_never_starts_jobs(client, scenario):for kind in ("zones", "followups", "runs"):assert client.get(f"/api/cases/{case.id}/analysis/{kind}").json() == []assert case.list_jobs() == before- zone = client.post(f"/api/cases/{case.id}/analysis/zones", json={"title": "Port", "zones": body["zones"]}).json()+ area = client.post(f"/api/cases/{case.id}/analysis/zones", json={"title": "Port", "zones": body["zones"]}).json()follow = client.post(f"/api/cases/{case.id}/analysis/followups", json=body).json()- for kind, saved in (("zones", zone), ("followups", follow)):+ for kind, saved in (("zones", area), ("followups", follow)):assert client.get(f"/api/cases/{case.id}/analysis/{kind}/{saved['id']}").status_code == 200assert case.list_jobs() == before@@ -171,19 +238,22 @@ def test_reexecution_uses_preserved_frames_after_tile_cache_loss(client, scenaridef test_missing_offline_frames_fail_without_partial_results(client, scenario):case, body = scenario- body["b"]["release"] = 3+ body["b"]["date"] = "2026-05-18"saved = run(client, case, body)assert saved["status"] == "failed"assert "offline" in saved["message"]assert saved["results"] == []-def test_tile_ceiling_and_provider_validation_before_job_creation(client, scenario):+def test_tile_ceiling_and_source_validation_before_job_creation(client, scenario):case, body = scenario- # The panel prices an area against this number, so it has to be published.- assert client.get("/api/compare/analyzers").json()["max_tiles"] == analyzers.MAX_TILES- body["zones"][0]["points"] = [[0, 0], [1, 1]]- response = client.post(f"/api/cases/{case.id}/analysis/runs", json=body)+ # The panel prices an area against these numbers, so they are published.+ catalogue = client.get("/api/compare/analyzers").json()+ assert catalogue["max_tiles"] == analyzers.MAX_TILES+ assert catalogue["grid"] == list(analyzers.GRID)+ big = deepcopy(body)+ big["zones"][0]["points"] = [[0, 0], [5, 5]]+ response = client.post(f"/api/cases/{case.id}/analysis/runs", json=big)assert response.status_code == 422assert "smaller" in response.textassert case.list_jobs() == []@@ -191,6 +261,17 @@ def test_tile_ceiling_and_provider_validation_before_job_creation(client, scenarassert client.post(f"/api/cases/{case.id}/analysis/runs", json=body).status_code == 422+def test_detect_reads_copernicus_only_and_a_wayback_watch_asks_for_a_date(client, scenario):+ case, body = scenario+ old = deepcopy(body)+ old["a"] = {"provider": "esri-wayback", "release": 1}+ old["b"] = {"provider": "esri-wayback", "release": 2}+ response = client.post(f"/api/cases/{case.id}/analysis/runs", json=old)+ assert response.status_code == 422+ assert "dated Sentinel-2" in response.text+ assert case.list_jobs() == []++def test_zone_union_does_not_duplicate_detections(client, scenario):case, body = scenariofirst = run(client, case, body)@@ -200,234 +281,175 @@ def test_zone_union_does_not_duplicate_detections(client, scenario):assert second["total"] == first["total"]-def test_masks_filters_and_methods():- body = RunInput.model_validate(sample_input())- a = np.full((64, 64, 4), 30, np.uint8)- a[:, :, 3] = 255- b = a.copy()- b[10:20, 10:20, :3] = 240- b[40, 40, :3] = 240- mask = np.ones((64, 64), np.uint8)- for method in ("colour", "structure", "brightness", "water_objects", "smoke"):- body.recipe.method = method- binary, _ = analyzers.detect(a, b, mask, body)- assert binary[8:22, 8:22].any(), method- body.recipe.method = "colour"- body.recipe.parameters.cleanup = 1- binary, _ = analyzers.detect(a, b, mask, body)- assert binary[15, 15] and not binary[40, 40]- mask[:30] = 0- binary, _ = analyzers.detect(a, b, mask, body)- assert not binary[:30].any()---def _spectral_pair():- a = np.zeros((16, 16, 4), np.uint8)- a[:, :, 3] = 255- a[:, :, 1] = 4- b = a.copy()- b[:, :, 0] = 200- b[:8, :, 1] = 9 # the top half is cloud, by Sentinel-2's own classification- return a, b---def test_spectral_cloud_mask_and_native_grid():- body = sample_input()- body["a"] = {"provider": "sentinel2", "date": "2026-08-01"}- body["b"] = {"provider": "sentinel2", "date": "2026-09-01"}- body["recipe"].update(method="index", providers=["sentinel2"])- body["recipe"]["parameters"]["cloud_margin"] = 0- model = RunInput.model_validate(body)- assert analyzers.grid(model) == (13, 512)- a, b = _spectral_pair()- mask = np.ones((16, 16), np.uint8)- binary, _ = analyzers.detect(a, b, mask, model, a, b)- assert not binary[:8].any()- assert binary[8:].all()---def test_the_cloud_margin_grows_the_mask_past_the_classified_edge():- """A classification calls the cloud's soft edge ground, and that edge is- where the ring of false candidates around every mask comes from. The margin- is what takes it, so it has to cost exactly the pixels it claims."""- body = sample_input()- body["a"] = {"provider": "sentinel2", "date": "2026-08-01"}- body["b"] = {"provider": "sentinel2", "date": "2026-09-01"}- body["recipe"].update(method="index", providers=["sentinel2"])- body["recipe"]["parameters"]["cloud_margin"] = 2- model = RunInput.model_validate(body)- a, b = _spectral_pair()- binary, _ = analyzers.detect(a, b, np.ones((16, 16), np.uint8), model, a, b)- assert not binary[:10].any()- assert binary[10:].all()---def test_named_followup_freezes_input_and_previous_date(client, scenario, monkeypatch):+def test_a_sweep_keeps_only_the_tiles_that_found_something(client, scenario):+ """What a case stores follows what was found, not how much was swept."""case, body = scenario- follow = client.post(f"/api/cases/{case.id}/analysis/followups", json=body).json()- body["followup_id"] = follow["id"]- previous = run(client, case, body)- newer = {**body, "offline": False, "date_rule": "latest_previous"}- monkeypatch.setattr(analyzers.wayback, "releases", lambda: [type("Release", (), {"number": 3})()])- resolved = analyzers.resolve_dates(case, RunInput.model_validate(newer))- assert resolved.a.release == 2 and resolved.b.release == 3- changed = deepcopy(body)- changed["zones"][0]["name"] = "New name"- assert client.put(f"/api/cases/{case.id}/analysis/followups/{follow['id']}", json=changed).status_code == 200- assert analyzers.read(case, "runs", previous["id"])["input"]["zones"][0]["name"] == "Harbour"---def _picture_pair():- """A flat grey tile, and the same with a bright colourless patch added.+ z, x, y = SENTINEL_TILE+ body["zones"] = [zone(0.1, 0.1, 1.9, 0.9)]+ seed_images(body, (z, x + 1, y), changed=False)+ saved = run(client, case, body)+ assert saved["status"] == "ready", saved+ assert saved["total"] == 2+ assert saved["count"] == 1+ assert len(saved["frames"]) == 4+ assert {tuple(record["tile"]) for record in saved["frames"].values()} == {(z, x, y)}+ folder = case.resolve_inside(layout.analysis_assets_rel(f"runs-{saved['id']}"))+ assert {path.name for path in folder.iterdir()} == {+ record["path"].rsplit("/", 1)[1] for record in saved["frames"].values()+ }+ for row in saved["results"]:+ for part in row["parts"]:+ for key in part["frames"]:+ assert case.resolve_inside(saved["frames"][key]["path"]).is_file()- Which is the whole difficulty: on a rendered picture that patch is equally- a cloud, a white roof and a gravel pad, and nothing in the image says which.- """- a = np.zeros((32, 32, 4), np.uint8)- a[:, :, :3] = 60- a[:, :, 3] = 255- b = a.copy()- b[10:20, 10:20, :3] = 235- return a, b+def test_a_run_reports_the_share_of_its_areas_that_had_imagery(client, scenario):+ case, body = scenario+ saved = run(client, case, body)+ assert saved["swept"] == 1.0-def test_the_picture_cloud_guess_is_off_until_it_is_asked_for():- """It cannot tell cloud from a white roof, so it is never turned on for- anyone: a saved recipe must keep finding what it found yesterday."""- body = sample_input()- assert Recipe.model_validate(body["recipe"]).parameters.guess_clouds is False- model = RunInput.model_validate(body)- a, b = _picture_pair()- binary, _ = analyzers.detect(a, b, np.ones((32, 32), np.uint8), model)- assert binary[10:20, 10:20].any()+# -- models, catalogue and saved recipes -----------------------------------------------def test_the_picture_cloud_guess_masks_bright_colourless_pixels_when_asked():- body = sample_input()- body["recipe"]["parameters"].update(guess_clouds=True, cloud_margin=0)- model = RunInput.model_validate(body)- a, b = _picture_pair()- binary, _ = analyzers.detect(a, b, np.ones((32, 32), np.uint8), model)- assert not binary.any()---def test_no_cloud_filter_is_offered_where_it_would_eat_the_signal():- """Smoke, bright shapes on water and a short-wave hotspot are bright and- colourless themselves. There the picture test would mask the method's own- subject, so the catalogue offers nothing rather than a switch that ruins it."""- offered = {entry["id"]: entry["cloud_filter"] for entry in METHODS}- assert offered["smoke"] == "" and offered["water_objects"] == ""- assert offered["hotspots"] == "" # its band ratios reject cloud already- assert offered["index"] == "classes" and offered["vessels"] == "classes"- assert offered["colour"] == "picture"- body = sample_input()- body["recipe"].update(method="smoke")- body["recipe"]["parameters"].update(guess_clouds=True, cloud_margin=0, sensitivity=90)- model = RunInput.model_validate(body)- a, b = _picture_pair()- binary, _ = analyzers.detect(a, b, np.ones((32, 32), np.uint8), model)- # the switch is set and the method ignores it, because it has to- assert binary[10:20, 10:20].any()[email protected]("points", [[[0, 0], [0, 1]], [[179, 0], [-179, 1]], [[0, 86], [1, 87]]])+def test_invalid_areas_are_rejected(points):+ with pytest.raises(ValueError):+ Zone(id="zone", points=points)-def _sentinel_rule(body, rule="latest_reference"):- sentinel_body = deepcopy(body)- sentinel_body["recipe"]["providers"] = ["sentinel2"]- sentinel_body["a"] = {"provider": "sentinel2", "date": "2026-04-01", "maxcc": 30}- sentinel_body["b"] = {"provider": "sentinel2", "date": "2026-04-01", "maxcc": 30}- return {**sentinel_body, "offline": False, "date_rule": rule}+def test_models_cannot_smuggle_executable_recipes():+ with pytest.raises(ValueError):+ Recipe(name="Bad", method="python", code="anything")+ assert config.DEFAULT_SETTINGS["analyzers"] == []-def test_an_automatic_date_rule_takes_the_newest_pass_that_covers_the_whole_area(- client, scenario, monkeypatch-):- """The old rule asked about each area's *centre*, which a swath can reach- while missing most of the shape around it. Picking that date sweeps nodata."""- case, body = scenario- client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})- asked = {}+def test_a_recipe_saved_before_detect_went_copernicus_only_still_loads():+ old = {"id": "custom-1a2b3c4d5e6f", "name": "Harbour", "method": "colour",+ "providers": ["esri-wayback", "sentinel2"],+ "parameters": {"sensitivity": 40, "min_area": 20, "min_score": 0.2, "cleanup": 1,+ "smoothing": 0, "normalize": True, "index": "ndvi",+ "direction": "both", "ignore_clouds": True, "ignore_shadows": True,+ "guess_clouds": False, "cloud_margin": 2, "merge_metres": 0}}+ recipe = Recipe.model_validate(old)+ assert recipe.method == "surface"+ assert recipe.parameters.sensitivity == 40 and recipe.parameters.cloud_margin == 2+ assert Recipe.model_validate({**old, "method": "water_objects"}).method == "vessels"+ assert "providers" not in recipe.model_dump()+++def test_every_method_publishes_sizes_and_words_for_its_reading():+ methods = {entry["id"]: entry for entry in METHODS}+ assert set(methods) == {"vessels", "hotspots", "structure", "spots", "surface", "index"}+ for entry in METHODS:+ assert set(entry["sizes"]) == {"small", "medium", "large", "all"}+ for size in entry["sizes"].values():+ Parameters(**size) # every size is a valid set of parameters+ smaller, larger = entry["sizes"]["small"], entry["sizes"]["large"]+ assert smaller["min_area"] < larger["min_area"]+ # "All" drops nothing for its size, which is the answer to a mark that+ # falls between two bands and is found by neither.+ assert entry["sizes"]["all"]["min_area"] == 0+ assert entry["sizes"]["all"]["max_area"] == 0+ assert "{" in entry["measure"]+ # the fire test rejects cloud itself; everything else can use the mask+ assert [m for m, entry in methods.items() if not entry["clouds"]] == ["hotspots"]+ assert methods["vessels"]["single"] and methods["hotspots"]["single"]+ # a small target is never morphologically cleaned away+ assert all(entry["sizes"]["small"]["cleanup"] == 0 for entry in METHODS)+++def test_builtins_cover_big_and_small_things_and_start_at_medium():+ ids = {recipe.id for recipe in BUILTINS}+ assert {"boats", "anomaly", "structures", "impacts", "large-change", "burn-scars",+ "vegetation-loss", "new-water"} <= ids+ for recipe in BUILTINS:+ medium = SIZES[recipe.method]["medium"]+ assert {key: getattr(recipe.parameters, key) for key in medium} == medium, recipe.id+ assert len(recipe.description) < 200, recipe.id+++# -- vessels ---------------------------------------------------------------------------- def acquisitions(instance, rings, start, end):- asked.update(instance=instance, rings=rings, start=start, end=end)- return {"dates": [- {"date": "2026-05-20", "cloud": 5.0, "granules": 1, "coverage": 0.61},- {"date": "2026-05-11", "cloud": 5.0, "granules": 2, "coverage": 1.0},- {"date": "2026-05-04", "cloud": 5.0, "granules": 1, "coverage": 1.0},- ], "truncated": False}- monkeypatch.setattr(analyzers.sentinel, "acquisitions", acquisitions)- resolved = analyzers.resolve_dates(case, RunInput.model_validate(_sentinel_rule(body)))- # the newest is 2026-05-20 and it reaches 61% of the area, so it is not it- assert resolved.b.date == "2026-05-11"- # one lookup for the whole set, not one per area- assert len(asked["rings"]) == 1+def copernicus(client, monkeypatch):+ monkeypatch.setattr(workqueue, "start_workers", False)+ ident = client.post("/api/cases", json={"name": "Copernicus detectors"}).json()["id"]+ case = Case.open(ident)+ def forbidden(*args, **kwargs):+ raise AssertionError("unexpected network")-def test_an_automatic_date_rule_says_how_far_the_best_pass_reached(- client, scenario, monkeypatch-):- case, body = scenario- client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})- monkeypatch.setattr(analyzers.sentinel, "acquisitions", lambda *a, **k: {"dates": [- {"date": "2026-05-20", "cloud": 5.0, "granules": 1, "coverage": 0.61},- ], "truncated": False})- with pytest.raises(ValueError) as raised:- analyzers.resolve_dates(case, RunInput.model_validate(_sentinel_rule(body)))- # naming the number turns "it failed" into "pick the dates by hand"- assert "61%" in str(raised.value)+ monkeypatch.setattr(analyzers.httpx, "stream", forbidden)+ monkeypatch.setattr(analyzers.sentinel, "band_frame", forbidden)+ return case-def test_an_automatic_date_rule_still_honours_the_cloud_ceiling(client, scenario, monkeypatch):- case, body = scenario- client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})- monkeypatch.setattr(analyzers.sentinel, "acquisitions", lambda *a, **k: {"dates": [- {"date": "2026-05-20", "cloud": 80.0, "granules": 1, "coverage": 1.0},- {"date": "2026-05-11", "cloud": 5.0, "granules": 1, "coverage": 1.0},- ], "truncated": False})- resolved = analyzers.resolve_dates(case, RunInput.model_validate(_sentinel_rule(body)))- assert resolved.b.date == "2026-05-11"+def test_vessels_are_found_and_breaking_waves_are_not(client, copernicus):+ """Wave crests are as bright as hulls in the near-infrared. Short-wave+ infrared is where they part: in the calibration scenes hulls stood 28 to 37+ deviations above their sea there, and 90% of wave crests under 3.5."""+ body = sentinel_input("boats")+ water = sea()+ hull(water, 120, 140, 6, 3)+ hull(water, 300, 220, 8, 4)+ hull(water, 200, 400, 6, 3, swir=False) # a breaking wave+ seed(body, after=water)+ saved = run(client, copernicus, body)+ assert saved["status"] == "ready", saved+ assert saved["count"] == 2, [r["coordinates"] for r in saved["results"]]+ assert {r["phenomenon"] for r in saved["results"]} == {"Vessel candidate"}+ for row in saved["results"]:+ assert row["strength"] == "strong"+ assert row["measure"]["value"] > 2 # times the water around it+ assert len(saved["frames"]) == 2 # the picture reviewed, and the bands measured-def test_a_run_reports_the_share_of_its_areas_that_had_imagery(client, scenario):- """"Nothing found" and "never looked" are not the same answer, and a date- whose granules only half reach the area produces the second while reading- like the first."""- case, body = scenario- saved = run(client, case, body)- assert saved["status"] == "ready"- # the fixture's frames are fully opaque, so the sweep saw all of it- assert saved["swept"] == 1.0+def test_a_hull_the_scene_classification_calls_cloud_is_still_a_hull(client, copernicus):+ """Sen2Cor tags white and red hulls as cloud; in Singapore it masked the tankers."""+ body = sentinel_input("boats")+ water = sea()+ hull(water, 250, 250, 8, 4)+ water[at(250, 250, 8, 4)][:, :, 3] = CLOUD+ seed(body, after=water)+ assert run(client, copernicus, body)["count"] == 1[email protected]("points", [[[0, 0], [0, 1]], [[179, 0], [-179, 1]], [[0, 86], [1, 87]]])-def test_invalid_areas_are_rejected(points):- with pytest.raises(ValueError):- Zone(id="zone", points=points)+def test_a_coastline_is_not_a_vessel(client, copernicus):+ body = sentinel_input("boats")+ water = sea()+ land = water[at(0, 300, 512, 212)]+ land[:, :, 0], land[:, :, 1], land[:, :, 2], land[:, :, 3] = 150, 150, 64, BARE+ # a bright headland sticking out into the water+ hull(water, 250, 290, 12, 10)+ seed(body, after=water)+ assert run(client, copernicus, body)["count"] == 0-def test_models_cannot_smuggle_executable_recipes():- with pytest.raises(ValueError):- Recipe(name="Bad", method="python", code="anything")- assert config.DEFAULT_SETTINGS["analyzers"] == []+def test_vessel_sweep_asks_for_one_date_and_never_for_a_reference(client, copernicus):+ body = sentinel_input("boats")+ water = sea()+ hull(water, 200, 200, 6, 3)+ seed(body, after=water)+ body["a"] = {"provider": "sentinel2", "date": "", "layer": "TRUE_COLOR", "maxcc": 30}+ saved = run(client, copernicus, body)+ assert saved["status"] == "ready", saved+ assert saved["input"]["a"] == saved["input"]["b"]+ assert saved["count"] == 1def test_local_contrast_reads_a_target_against_its_own_patch_of_sea():- """The same hull, on calm water and on water twice as bright, reads the same.-- That is the whole reason the detector is local: an absolute cut-off would- need a different number for every scene, and would call a sunlit swell a- fleet.- """+ """The same hull, on calm water and on water twice as bright, reads the same."""rng = np.random.default_rng(7)calm = np.full((200, 200), 20.0) + rng.normal(0, 1.5, (200, 200))water = np.ones((200, 200), bool)readings = []- for sea in (calm, calm + 120):- empty, share = analyzers.local_contrast(sea, water, 61, 11)+ for patch in (calm, calm + 120):+ empty, share = analyzers.local_contrast(patch, water, 61, 11)assert share.min() > 0.99assert abs(empty[100, 100]) < 4- target = sea.copy()+ target = patch.copy()target[99:102, 99:102] += 100contrast, _ = analyzers.local_contrast(target, water, 61, 11)readings.append(contrast[100, 100])@@ -445,119 +467,340 @@ def test_local_contrast_treats_land_in_the_ring_as_missing_background():assert share[80, 60] < 0.5 # a shoreline is not somewhere a ship can be-def sea(client, monkeypatch):- monkeypatch.setattr(workqueue, "start_workers", False)- ident = client.post("/api/cases", json={"name": "Copernicus detectors"}).json()["id"]- case = Case.open(ident)- def forbidden(*args, **kwargs):- raise AssertionError("unexpected network")- monkeypatch.setattr(analyzers.httpx, "stream", forbidden)- monkeypatch.setattr(analyzers.sentinel, "band_frame", forbidden)- return case---def test_vessel_sweep_finds_the_targets_and_not_the_bright_water(client, sea):- body = sentinel_input("boats")- seed_sentinel(sea, body, vessel_bands([(120, 140, 3, 3), (300, 220, 4, 2)]))- saved = run(client, sea, body)- assert saved["status"] == "ready", saved- assert saved["count"] == 2, [r["coordinates"] for r in saved["results"]]- assert {r["phenomenon"] for r in saved["results"]} == {"Vessel candidate"}- for row in saved["results"]:- # Nine pixels of 9.55 m is a little over 800 m²; two of them, 180 m².- assert 150 < row["area"] < 1000- assert row["signal_score"] > 0.2- # A signal score is not a probability, and nothing here pretends it is.- assert row["confidence"] is None- assert len(saved["frames"]) == 2 # the picture reviewed, and the bands measured---def test_vessel_sweep_asks_for_one_date_and_never_for_a_reference(client, sea):- body = sentinel_input("boats")- seed_sentinel(sea, body, vessel_bands([(200, 200, 3, 3)]))- body["a"] = {"provider": "sentinel2", "date": "", "layer": "TRUE_COLOR", "maxcc": 30}- saved = run(client, sea, body)- assert saved["status"] == "ready", saved- assert saved["input"]["a"] == saved["input"]["b"]- assert saved["count"] == 1+# -- hotspots -----------------------------------------------------------------------------def test_hotspot_sweep_separates_fire_from_a_cloud_that_is_just_as_bright(client, sea):+def test_hotspot_sweep_separates_fire_from_a_cloud_that_is_just_as_bright(client, copernicus):body = sentinel_input("anomaly")- seed_sentinel(sea, body, fire_bands(fire=(150, 160, 3, 3), cloud=(300, 300, 40, 40)))- saved = run(client, sea, body)+ ground = fire_frame()+ flame(ground, 150, 160, 3, 3)+ flame(ground, 300, 300, 40, 40, b12=0.5, ratio=1.0) # cloud: bright, ratios at one+ seed(body, after=ground)+ saved = run(client, copernicus, body)assert saved["status"] == "ready", savedassert saved["count"] == 1, [r["area"] for r in saved["results"]]row = saved["results"][0]assert row["phenomenon"] == "Hotspot candidate"- # The fire patch, not the cloud forty times its size.assert row["area"] < 2000+ assert row["measure"]["value"] == pytest.approx(2.5, abs=0.05)z, x, y = SENTINEL_TILEwest, north = analyzers.geographic((x + 150 / 512) / 2**z, (y + 160 / 512) / 2**z)assert abs(row["coordinates"][0] - west) < 0.001assert abs(row["coordinates"][1] - north) < 0.001-def test_hotspot_sweep_ignores_short_wave_below_the_published_floor(client, sea):+def test_hotspot_sweep_ignores_short_wave_below_the_published_floor(client, copernicus):body = sentinel_input("anomaly")- bands = fire_bands(fire=(150, 160, 3, 3), cloud=(300, 300, 40, 40))- # Right ratios, not enough energy: warm ground is not a fire.- bands[160:163, 150:153, 0] = int(255 * (analyzers.HOTSPOT_FLOOR - 0.02) * 4)- seed_sentinel(sea, body, bands)- saved = run(client, sea, body)+ ground = fire_frame()+ flame(ground, 150, 160, 3, 3, b12=analyzers.HOTSPOT_FLOOR - 0.02)+ seed(body, after=ground)+ saved = run(client, copernicus, body)assert saved["status"] == "ready", savedassert saved["count"] == 0[email protected]("recipe_id", ["boats", "anomaly"])-def test_band_detectors_refuse_a_provider_that_serves_pictures(recipe_id):- recipe = next(r for r in analyzers_models.BUILTINS if r.id == recipe_id)- assert recipe.providers == ["sentinel2"]- with pytest.raises(ValueError):- recipe.model_copy(update={"providers": ["esri-wayback", "sentinel2"]}).compatible()+def test_the_default_hotspot_ratio_is_the_published_one():+ recipe = next(r for r in BUILTINS if r.id == "anomaly")+ assert analyzers._scale(recipe.parameters.sensitivity, 1.0, 2.0) == pytest.approx(1.4)-def seed_tile(x, y, changed):- """One Wayback tile pair, with the change only where a test asks for it."""- for release in (1, 2):- pixels = np.full((256, 256, 3), 40, np.uint8)- if release == 2 and changed:- pixels[90:120, 100:150] = 230- out = io.BytesIO()- Image.fromarray(pixels).save(out, "PNG")- tilecache.put(f"esri-wayback~{release}", 19, x, y, out.getvalue(), "image/png")+# -- change between two dates ------------------------------------------------------------def test_a_sweep_keeps_only_the_tiles_that_found_something(client, scenario):- """What a case stores follows what was found, not how much was swept.+def test_construction_is_ground_that_moved_the_same_way_in_every_band(client, copernicus):+ body = sentinel_input("structures")+ before, after = surface(0.20, 0.28, 0.32), surface(0.20, 0.28, 0.32) # bare ground+ after[at(100, 100, 20, 20)] = code(0.33, 0.40, 0.45) # new pad: brighter everywhere+ before[at(300, 300, 40, 40)] = code(0.05, 0.40, 0.18) # a field that greened...+ after[at(300, 300, 40, 40)] = code(0.03, 0.60, 0.15) # ...moved red and NIR apart+ seed(body, before, after)+ saved = run(client, copernicus, body)+ assert saved["status"] == "ready", saved+ assert saved["count"] == 1+ assert saved["results"][0]["measure"]["signed"] > 5- This is what lets the allowed area be large: two tiles are read, one shows- nothing, and only the tile behind the candidate keeps a permanent copy.++def test_small_spots_are_found_where_everything_around_them_held_still(client, copernicus):+ body = sentinel_input("impacts")+ before, after = surface(0.20, 0.30, 0.30), surface(0.20, 0.30, 0.30)+ after[at(100, 100, 2, 2)] = code(0.08, 0.12, 0.10) # a burn mark two pixels wide+ after[at(300, 300, 120, 120)] = code(0.35, 0.40, 0.45) # a whole field changed+ after[at(300, 300, 2, 2)] = code(0.05, 0.05, 0.05) # a spot inside that field+ seed(body, before, after)+ saved = run(client, copernicus, body)+ assert saved["status"] == "ready", saved+ assert saved["count"] == 1, [r["coordinates"] for r in saved["results"]]+ row = saved["results"][0]+ assert row["measure"]["signed"] < 0+ assert row["area"] < 500+++def test_a_mark_wider_than_its_window_still_reads_its_own_contrast(client, copernicus):+ """A median box the size of the target takes the target for its background.++ The background is read from a ring with a hole in it instead, so a 90 m mark+ in the desert measures what it really moved. Small then drops it for its+ size, with nothing to show for it — which is what All is for."""- case, body = scenario- z, x, y = 19, 265056, 182248- west, north = analyzers.geographic((x + .1) / 2**z, (y + .1) / 2**z)- east, south = analyzers.geographic((x + 1.9) / 2**z, (y + .9) / 2**z)- body["zones"][0]["points"] = [[west, south], [east, north]]- seed_tile(x, y, changed=True)- seed_tile(x + 1, y, changed=False)+ ground = surface(0.37, 0.40, 0.55)+ marked = surface(0.37, 0.40, 0.55)+ marked[at(200, 200, 10, 10)] = code(0.29, 0.30, 0.45)- saved = run(client, case, body)+ body = sentinel_input("impacts")+ seed(body, ground, marked)+ assert run(client, copernicus, body)["count"] == 0++ body = sentinel_input("impacts", **SIZES["spots"]["all"])+ seed(body, ground, marked)+ saved = run(client, copernicus, body)+ assert saved["status"] == "ready", saved+ assert saved["count"] == 1, [r["area"] for r in saved["results"]]+ row = saved["results"][0]+ assert row["area"] > 800 # too big for Small+ assert row["measure"]["signed"] < -5 # and it moved 8-10%+++def test_a_burn_has_to_end_dark_and_a_dried_pasture_does_not(client, copernicus):+ """Dry soil has a negative burn ratio too; char is what is dark."""+ body = sentinel_input("burn-scars")+ before, after = index_frame(0.5), index_frame(0.5)+ after[at(100, 100, 40, 40)] = [index_byte(-0.3), 0, 0, BARE + DARK] # burned+ after[at(300, 300, 40, 40)] = [index_byte(-0.1), 0, 0, BARE] # dried, still bright+ seed(body, before, after)+ saved = run(client, copernicus, body)assert saved["status"] == "ready", saved- assert saved["total"] == 2assert saved["count"] == 1- assert len(saved["frames"]) == 2- assert {tuple(record["tile"]) for record in saved["frames"].values()} == {(z, x, y)}- folder = case.resolve_inside(layout.analysis_assets_rel(f"runs-{saved['id']}"))- assert {path.name for path in folder.iterdir()} == {- record["path"].rsplit("/", 1)[1] for record in saved["frames"].values()- }- # Whatever a candidate points at still resolves, which is the invariant- # the preview and the bundle both rely on.- for row in saved["results"]:- for part in row["parts"]:- for key in part["frames"]:- assert case.resolve_inside(saved["frames"][key]["path"]).is_file()- endpoint = f"/api/cases/{case.id}/analysis/runs/{saved['id']}/results/{saved['results'][0]['id']}"- assert client.get(endpoint + "/preview").content.startswith(b"\x89PNG")+ row = saved["results"][0]+ assert row["measure"]["before"] == pytest.approx(0.5, abs=0.02)+ assert row["measure"]["after"] == pytest.approx(-0.3, abs=0.02)+++def test_an_index_loss_has_to_start_from_something_there(client, copernicus):+ """NDVI noise over bare ground is not vegetation loss."""+ body = sentinel_input("vegetation-loss")+ before, after = index_frame(0.1), index_frame(0.1)+ before[at(100, 100, 40, 40)] = [index_byte(0.7), 0, 0, VEGETATION]+ after[at(100, 100, 40, 40)] = [index_byte(0.2), 0, 0, BARE] # cleared+ before[at(300, 300, 40, 40)] = [index_byte(0.35), 0, 0, BARE] # never green+ after[at(300, 300, 40, 40)] = [index_byte(-0.1), 0, 0, BARE]+ before[at(100, 300, 40, 40)] = [index_byte(0.8), 0, 0, VEGETATION] # still green+ after[at(100, 300, 40, 40)] = [index_byte(0.45), 0, 0, VEGETATION]+ seed(body, before, after)+ saved = run(client, copernicus, body)+ assert saved["status"] == "ready", saved+ assert saved["count"] == 1+++def test_a_whole_tile_that_burned_is_not_taken_for_a_change_in_light(client, copernicus):+ """The overall shift between passes is taken out, but only up to 3%: a burn+ that covers most of the tile moves the median itself."""+ body = sentinel_input("large-change", min_area=0, max_area=0)+ before = surface(0.10, 0.30, 0.25)+ after = surface(0.06, 0.12, 0.12)+ after[at(0, 0, 100, 512)] = code(0.10, 0.30, 0.25)+ seed(body, before, after)+ saved = run(client, copernicus, body)+ assert saved["status"] == "ready", saved+ assert saved["count"] >= 1+ assert max(row["area"] for row in saved["results"]) > 1_000_000+++def test_candidates_come_strongest_first(client, copernicus):+ body = sentinel_input("large-change", min_area=0, max_area=0, cleanup=0, merge_metres=0)+ before, after = surface(), surface()+ after[at(50, 50, 20, 20)] = code(0.19, 0.39, 0.29) # a modest change+ after[at(300, 300, 20, 20)] = code(0.40, 0.45, 0.50) # a large one+ seed(body, before, after)+ saved = run(client, copernicus, body)+ margins = [row["margin"] for row in saved["results"]]+ assert len(margins) == 2 and margins == sorted(margins, reverse=True)+ assert saved["results"][0]["strength"] == "strong"+++def test_direction_keeps_only_the_way_that_was_asked_for(client, copernicus):+ body = sentinel_input("large-change", min_area=0, max_area=0, direction="loss")+ before, after = surface(), surface()+ after[at(50, 50, 20, 20)] = code(0.40, 0.50, 0.50) # brighter+ after[at(300, 300, 20, 20)] = code(0.02, 0.05, 0.02) # darker+ seed(body, before, after)+ saved = run(client, copernicus, body)+ assert saved["count"] == 1+ assert saved["results"][0]["coordinates"][0] > body["zones"][0]["points"][0][0]+++# -- sky ----------------------------------------------------------------------------------+++def _sky_body(**parameters):+ return RunInput.model_validate(sentinel_input("large-change", **parameters))+++def test_a_cloud_takes_its_unsure_edge_but_a_small_bright_tag_is_not_cloud():+ frame = surface()+ frame[at(100, 100, 20, 20)][:, :, 3] = CLOUD # 1.8 ha: a white roof+ frame[at(250, 250, 120, 120)][:, :, 3] = CLOUD # a real cloud+ frame[at(240, 250, 10, 120)][:, :, 3] = UNSURE # its thin western edge+ frame[at(20, 20, 10, 10)][:, :, 3] = UNSURE # an unsure pixel on its own+ metres = 6.7+ cloud, _ = analyzers.sky(frame, "2026-05-11", 45.5, metres)+ core = cloud[PAD:-PAD, PAD:-PAD]+ assert not core[100:120, 100:120].any()+ assert core[250:370, 250:370].all()+ assert core[250:370, 240:250].all()+ assert not core[20:30, 20:30].any()+++def test_a_shadow_the_classification_missed_is_found_away_from_the_sun():+ """In May at 45°N the satellite sees the sun in the south-east, so a cloud's+ shadow falls to its north-west, on ground dark enough to be shaded."""+ frame = surface()+ frame[at(300, 300, 80, 80)][:, :, 3] = CLOUD+ shaded = frame[at(200, 180, 90, 90)]+ shaded[:, :, 3] = VEGETATION + DARK # north-west: shadow+ darkness = frame[at(420, 420, 60, 60)]+ darkness[:, :, 3] = VEGETATION + DARK # south-east: just dark ground+ _, shadow = analyzers.sky(frame, "2026-05-11", 45.5, 6.7)+ core = shadow[PAD:-PAD, PAD:-PAD]+ assert core[200:270, 200:270].any()+ assert not core[420:480, 420:480].any()+++def test_a_shadow_the_classification_called_water_is_still_a_shadow():+ """Sen2Cor reads a deep cloud shadow as water, and a cast that spares water+ then finds none of it. A second pass settles it: water is water when both+ dates say so, and a shadow is what only one of them calls water."""+ frame = surface()+ frame[at(300, 300, 80, 80)][:, :, 3] = CLOUD+ frame[at(200, 180, 45, 90)][:, :, 3] = WATER + DARK # shadow, read as water+ frame[at(245, 180, 45, 90)][:, :, 3] = WATER + DARK # a real lake+ clear = surface()+ clear[at(245, 180, 45, 90)][:, :, 3] = WATER # the lake, on the other date+ _, alone = analyzers.sky(frame, "2026-05-11", 45.5, 6.7)+ _, paired = analyzers.sky(frame, "2026-05-11", 45.5, 6.7, clear)+ assert not alone[PAD:-PAD, PAD:-PAD][200:270, 200:245].any()+ assert paired[PAD:-PAD, PAD:-PAD][200:270, 200:245].any()+ assert not paired[PAD:-PAD, PAD:-PAD][200:270, 245:290].any()+++def test_the_sun_is_where_the_satellite_saw_it():+ """Checked against the angle bands of real scenes, to within a few degrees."""+ for day, lat, azimuth, zenith in [("2026-09-08", 12.6, 108.2, 20.4),+ ("2026-08-12", 1.24, 57.6, 26.5),+ ("2026-09-13", 39.24, 157.6, 37.8),+ ("2026-09-12", -9.79, 61.0, 27.5)]:+ found_azimuth, found_zenith = analyzers.sun_position(day, lat)+ assert abs(found_azimuth - azimuth) < 6+ assert abs(found_zenith - zenith) < 3+++def test_the_cloud_margin_grows_the_mask_past_the_classified_edge():+ body = _sky_body(cloud_margin=3)+ frame = surface()+ frame[at(200, 200, 100, 100)][:, :, 3] = CLOUD+ blocked = analyzers.weather_mask([frame, frame], ["2026-05-04", "2026-05-11"], 45.5, 6.7,+ body.recipe.parameters)+ core = blocked[PAD:-PAD, PAD:-PAD]+ assert core[197:303, 197:303].all()+ assert not core[190:196, 190:196].any()+++def test_turning_both_switches_off_masks_nothing():+ body = _sky_body(ignore_clouds=False, ignore_shadows=False)+ frame = surface()+ frame[:, :, 3] = CLOUD+ assert analyzers.weather_mask([frame], ["2026-05-11"], 45.5, 6.7,+ body.recipe.parameters) is None+++def test_a_change_under_cloud_on_either_date_is_not_a_change(client, copernicus):+ body = sentinel_input("large-change", min_area=0, max_area=0, cleanup=0)+ before, after = surface(), surface()+ after[at(200, 200, 120, 120)] = code(0.45, 0.50, 0.45, sky=CLOUD)+ seed(body, before, after)+ assert run(client, copernicus, body)["count"] == 0+++# -- follow-ups and date rules -------------------------------------------------------------+++def test_named_followup_freezes_input_and_previous_date(client, scenario, monkeypatch):+ case, body = scenario+ follow = client.post(f"/api/cases/{case.id}/analysis/followups", json=body).json()+ body["followup_id"] = follow["id"]+ previous = run(client, case, body)+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})+ monkeypatch.setattr(analyzers.sentinel, "acquisitions", lambda *a, **k: {"dates": [+ {"date": "2026-05-18", "cloud": 5.0, "granules": 1, "coverage": 1.0},+ ], "truncated": False})+ newer = {**body, "offline": False, "date_rule": "latest_previous"}+ resolved = analyzers.resolve_dates(case, RunInput.model_validate(newer))+ assert resolved.a.date == previous["input"]["b"]["date"] and resolved.b.date == "2026-05-18"+ changed = deepcopy(body)+ changed["zones"][0]["name"] = "New name"+ assert client.put(f"/api/cases/{case.id}/analysis/followups/{follow['id']}", json=changed).status_code == 200+ assert analyzers.read(case, "runs", previous["id"])["input"]["zones"][0]["name"] == "Patch"+++def _rule(body, rule="latest_reference"):+ return {**deepcopy(body), "offline": False, "date_rule": rule}+++def test_an_automatic_date_rule_takes_the_newest_pass_that_covers_the_whole_area(+ client, scenario, monkeypatch+):+ """The old rule asked about each area's *centre*, which a swath can reach+ while missing most of the shape around it. Picking that date sweeps nodata."""+ case, body = scenario+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})+ asked = {}++ def acquisitions(instance, rings, start, end):+ asked.update(instance=instance, rings=rings, start=start, end=end)+ return {"dates": [+ {"date": "2026-05-20", "cloud": 5.0, "granules": 1, "coverage": 0.61},+ {"date": "2026-05-11", "cloud": 5.0, "granules": 2, "coverage": 1.0},+ {"date": "2026-05-04", "cloud": 5.0, "granules": 1, "coverage": 1.0},+ ], "truncated": False}++ monkeypatch.setattr(analyzers.sentinel, "acquisitions", acquisitions)+ resolved = analyzers.resolve_dates(case, RunInput.model_validate(_rule(body)))+ # the newest is 2026-05-20 and it reaches 61% of the area, so it is not it+ assert resolved.b.date == "2026-05-11"+ # one lookup for the whole set, not one per area+ assert len(asked["rings"]) == 1+++def test_an_automatic_date_rule_says_how_far_the_best_pass_reached(+ client, scenario, monkeypatch+):+ case, body = scenario+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})+ monkeypatch.setattr(analyzers.sentinel, "acquisitions", lambda *a, **k: {"dates": [+ {"date": "2026-05-20", "cloud": 5.0, "granules": 1, "coverage": 0.61},+ ], "truncated": False})+ with pytest.raises(ValueError) as raised:+ analyzers.resolve_dates(case, RunInput.model_validate(_rule(body)))+ # naming the number turns "it failed" into "pick the dates by hand"+ assert "61%" in str(raised.value)+++def test_an_automatic_date_rule_still_honours_the_cloud_ceiling(client, scenario, monkeypatch):+ case, body = scenario+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})+ monkeypatch.setattr(analyzers.sentinel, "acquisitions", lambda *a, **k: {"dates": [+ {"date": "2026-05-20", "cloud": 80.0, "granules": 1, "coverage": 1.0},+ {"date": "2026-05-11", "cloud": 5.0, "granules": 1, "coverage": 1.0},+ ], "truncated": False})+ resolved = analyzers.resolve_dates(case, RunInput.model_validate(_rule(body)))+ assert resolved.b.date == "2026-05-11"+++def test_band_products_are_padded_and_keyed_apart_from_older_layouts():+ body = RunInput.model_validate(sample_input())+ z, x, y = SENTINEL_TILE+ picture = analyzers._key(body.b, z, x, y, None)+ product = analyzers._key(body.b, z, x, y, "surface")+ assert picture != product+ assert analyzers.product_cache_id(body.b, "surface").endswith(f"~surface~v{analyzers.PRODUCT_VERSION}")+ assert EDGE == 512 + 2 * analyzers.PAD+ assert WATER == analyzers.SCL_WATERdiff --git a/tests/test_compare_api.py b/tests/test_compare_api.pyindex e00caca..8814081 100644--- a/tests/test_compare_api.py+++ b/tests/test_compare_api.py@@ -1,4 +1,4 @@-"""Compare sessions, their media working file, animated exports and index frames."""+"""Compare sessions, their media working file, animated exports and band frames."""import iofrom pathlib import Path@@ -101,6 +101,7 @@ def test_compare_session_roundtrip_rename_and_sidebar_delete(client):"min_area": 250,"ignore_clouds": False,"ignore_shadows": True,+ "cloud_margin": 80,"classes": ["loss", "gain", "loss"],"display": "outline","palette": "colourblind",@@ -108,6 +109,7 @@ def test_compare_session_roundtrip_rename_and_sidebar_delete(client):"opacity": 71,"base": "side","visible": True,+ "blink": True,}spec["blink"] = {"interval": 1200}spec["annotations"] = [@@ -140,6 +142,9 @@ def test_compare_session_roundtrip_rename_and_sidebar_delete(client):assert {key: assist[key] for key in ("method", "min_area", "display")} == {"method": "structure", "min_area": 250, "display": "outline",}+ # The overlay's own blink, and a mask margin in ground metres because the+ # reading follows the camera.+ assert (assist["blink"], assist["cloud_margin"]) == (True, 80)assert loaded["spec"]["blink"] == {"interval": 1200}assert loaded["spec"]["annotations"][0]["side"] == "a"assert loaded["spec"]["annotations"][1]["points"][2] == [2.30, 48.86]@@ -269,7 +274,7 @@ def test_change_assist_refuses_misleading_pairs(client, a, b, method, reason):def test_change_refusal_needs_both_sides():- assert change_refusal(_side(present=False), _side()) == "Change assist needs imagery A and B"+ assert change_refusal(_side(present=False), _side()) == "Difference needs imagery A and B"# -- the rendered image is a media working file ----------------------------------@@ -455,23 +460,23 @@ def test_compare_gif_scales_large_frames_before_building_the_animation():assert frames[0].size == (MAX_GIF_EDGE, 150)-# -- Sentinel-2 index frames ------------------------------------------------------+# -- Sentinel-2 band frames -------------------------------------------------------INDEX_BODY = {+FRAME_BODY = {"west": 250_000, "south": 6_250_000, "east": 251_000, "north": 6_250_600,- "width": 320, "height": 192, "day": "2026-05-11", "index": "ndvi", "maxcc": 40,+ "width": 320, "height": 192, "day": "2026-05-11", "product": "ndvi", "maxcc": 40,}def test_band_frame_needs_a_key_and_refuses_when_the_tier_is_spent(client, monkeypatch):sent = []monkeypatch.setattr(compare_api.sentinel, "band_frame", lambda *a, **k: sent.append(a) or b"")- assert client.post("/api/compare/sentinel-index", json=INDEX_BODY).status_code == 404+ assert client.post("/api/compare/sentinel-frame", json=FRAME_BODY).status_code == 404client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})monkeypatch.setattr(compare_api.config, "usage_blocked", lambda meter: True)- assert client.post("/api/compare/sentinel-index", json=INDEX_BODY).status_code == 429+ assert client.post("/api/compare/sentinel-frame", json=FRAME_BODY).status_code == 429assert sent == []@@ -479,21 +484,21 @@ def test_band_frame_is_metered_and_answered_as_a_png(client, monkeypatch):client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})asked = {}- def frame(instance, bbox, width, height, day, index, maxcc, *, layer):+ def frame(instance, bbox, width, height, day, product, maxcc, *, layer):asked.update(instance=instance, bbox=bbox, size=(width, height), day=day,- index=index, maxcc=maxcc, layer=layer)+ product=product, maxcc=maxcc, layer=layer)return _png((1, 2, 3), (width, height))monkeypatch.setattr(compare_api.sentinel, "band_frame", frame)before = config.month_usage("sentinelhub")- response = client.post("/api/compare/sentinel-index", json=INDEX_BODY)+ response = client.post("/api/compare/sentinel-frame", json=FRAME_BODY)assert response.status_code == 200, response.textassert response.headers["content-type"] == "image/png"assert asked == {"instance": "inst-uuid", "bbox": (250_000, 6_250_000, 251_000, 6_250_600),- "size": (320, 192), "day": "2026-05-11", "index": "ndvi", "maxcc": 40,+ "size": (320, 192), "day": "2026-05-11", "product": "change-ndvi", "maxcc": 40,"layer": "TRUE_COLOR",}assert config.month_usage("sentinelhub") == before + 1@@ -506,7 +511,7 @@ def test_band_frame_validates_before_asking(client, monkeypatch):lambda *a, **k: (_ for _ in ()).throw(ValueError("the frame is empty")),)before = config.month_usage("sentinelhub")- assert client.post("/api/compare/sentinel-index", json={**INDEX_BODY, "index": "evi"}).status_code == 422- assert client.post("/api/compare/sentinel-index", json={**INDEX_BODY, "width": 5000}).status_code == 422- assert client.post("/api/compare/sentinel-index", json=INDEX_BODY).status_code == 422+ assert client.post("/api/compare/sentinel-frame", json={**FRAME_BODY, "product": "evi"}).status_code == 422+ assert client.post("/api/compare/sentinel-frame", json={**FRAME_BODY, "width": 5000}).status_code == 422+ assert client.post("/api/compare/sentinel-frame", json=FRAME_BODY).status_code == 422assert config.month_usage("sentinelhub") == beforediff --git a/tests/test_ingest_maptools.py b/tests/test_ingest_maptools.pyindex 783ae14..0c0486c 100644--- a/tests/test_ingest_maptools.py+++ b/tests/test_ingest_maptools.py@@ -17,6 +17,8 @@ import ioimport pytestfrom PIL import Image+import graph_read+def _token(client):return client.post("/api/settings/ingest-token").json()["ingest_token"]@@ -66,19 +68,30 @@ def test_writing_a_grid_needs_the_token(client):assert client.post("/api/ingest/grid/marks", json=marks).status_code == 401-def test_saved_points_are_trimmed_to_what_a_pin_draws(client):- headers = _headers(client)- cid = _case(client, "Pins")+def _drop_pin(client, headers, cid, title="Gate"):client.post("/api/ingest/place",headers=headers,data={"url": "https://www.google.com/maps/@48.8584,2.2945,17z","case_id": cid,- "title": "Gate",+ "title": title,},)- rows = client.get("/api/ingest/saved", params={"case_id": cid}, headers=headers).json()+++def _saved(client, headers, cid, kind=None):+ params = {"case_id": cid, **({"kind": kind} if kind else {})}+ res = client.get("/api/ingest/saved", params=params, headers=headers)+ assert res.status_code == 200, res.text+ return res.json()+++def test_saved_points_are_trimmed_to_what_a_pin_draws(client):+ headers = _headers(client)+ cid = _case(client, "Pins")+ _drop_pin(client, headers, cid)+ rows = _saved(client, headers, cid, "places")assert len(rows) == 1# the app's own index carries thumbnails, folders, continents and link# tallies; none of that crosses into a browser extension@@ -87,6 +100,65 @@ def test_saved_points_are_trimmed_to_what_a_pin_draws(client):assert rows[0]["lat"] == pytest.approx(48.8584)+def test_saved_points_answer_one_position_at_a_time(client):+ # the panel draws the position it is on, as the app's own switch does: a+ # capture listed under Places would be a filter that filters nothing+ headers = _headers(client)+ cid = _case(client, "Positions")+ _drop_pin(client, headers, cid)+ buf = io.BytesIO()+ Image.new("RGB", (48, 32), (30, 90, 30)).save(buf, format="PNG")+ shot = client.post(+ "/api/ingest/screenshot",+ files={"image": ("shot.png", buf.getvalue(), "image/png")},+ data={+ "url": "https://yandex.com/maps/?ll=2.2945,48.8584&z=17",+ "case_id": cid,+ "lat": "48.8584",+ "lon": "2.2945",+ "zoom": "17",+ },+ headers=headers,+ )+ assert shot.status_code == 200, shot.text++ assert [row["kind"] for row in _saved(client, headers, cid, "places")] == ["place"]+ assert [row["kind"] for row in _saved(client, headers, cid, "captures")] == ["screenshot"]+ # and the footage, which the saved index never held, is what it opens on+ assert _saved(client, headers, cid) == []+++def test_saved_points_offer_the_footage_by_default(client):+ headers = _headers(client)+ cid = _case(client, "Footage")+ photo = _upload(client, cid, "quay.png")["path"]+ photo_id = graph_read.entity(cid, path=photo)["id"]+ place = client.post(+ f"/api/cases/{cid}/satellite/place", json={"lat": 48.0159, "lon": 37.8029}+ ).json()["id"]+ client.post(+ f"/api/cases/{cid}/links",+ json={"from_id": photo_id, "to_id": place, "type": "located-at"},+ )++ [row] = _saved(client, headers, cid)+ assert row["kind"] == "media"+ # the one field a pin needs beyond the others: a video is drawn as a video+ assert row["media_kind"] == "image"+ assert (row["lat"], row["lon"]) == pytest.approx((48.0159, 37.8029))+ # and the point the file borrows is still its own row under Places+ assert [r["kind"] for r in _saved(client, headers, cid, "places")] == ["place"]+++def test_saved_points_refuse_a_position_that_does_not_exist(client):+ headers = _headers(client)+ cid = _case(client, "Unknown")+ res = client.get(+ "/api/ingest/saved", params={"case_id": cid, "kind": "proofs"}, headers=headers+ )+ assert res.status_code == 422++def test_saved_points_drop_rows_with_no_position(client):headers = _headers(client)cid = _case(client, "Mixed")@@ -96,7 +168,7 @@ def test_saved_points_drop_rows_with_no_position(client):data={"url": "https://example.com/article", "case_id": cid, "title": "Article"},)# a bookmark has no coordinates, so there is nowhere to draw it- assert client.get("/api/ingest/saved", params={"case_id": cid}, headers=headers).json() == []+ assert _saved(client, headers, cid, "places") == []def _upload(client, cid, name, colour=(30, 90, 30)):diff --git a/tests/test_proofs_api.py b/tests/test_proofs_api.pyindex 0125319..201217f 100644--- a/tests/test_proofs_api.py+++ b/tests/test_proofs_api.py@@ -385,265 +385,6 @@ def _sat(client, cid, lat, lon):).json()-def _proof_index(client, cid):- return client.get(f"/api/cases/{cid}/proofs/index").json()---def test_index_inherits_the_point_from_the_capture_it_composes(client, sat_tiles):- cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]- cap = _sat(client, cid, 50.4501, 30.5234)- client.post(- f"/api/cases/{cid}/proofs", json={"title": "Kyiv bridge", "spec": _panels(cap["path"])}- )-- row = _proof_index(client, cid)[0]- assert row["kind"] == "proof"- assert row["title"] == "Kyiv bridge"- assert row["name"] == "Kyiv bridge"- assert (row["lat"], row["lon"]) == (50.4501, 30.5234)- assert row["notes"] == ""- assert row["folder"] == "" # unfiled, never null---def test_index_places_a_proof_at_each_of_its_source_points(client, sat_tiles):- cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]- kyiv = _sat(client, cid, 50.4501, 30.5234)- paris = _sat(client, cid, 48.8584, 2.2945)- client.post(- f"/api/cases/{cid}/proofs",- json={"title": "Two cities", "spec": _panels(kyiv["path"], paris["path"])},- )-- rows = _proof_index(client, cid)- assert len({r["id"] for r in rows}) == 1 # one proof…- assert sorted(r["lat"] for r in rows) == [48.8584, 50.4501] # …at both its places- assert len({r["key"] for r in rows}) == 2 # but two marks, so two render keys---def test_index_folds_panels_that_share_one_point_into_one_row(client, sat_tiles):- """Two zooms of the same roof are one place, so they are one mark."""- cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]- a = _sat(client, cid, 50.4501, 30.5234)- b = _sat(client, cid, 50.4501, 30.5234)- client.post(- f"/api/cases/{cid}/proofs",- json={"title": "Same roof", "spec": _panels(a["path"], b["path"])},- )-- rows = _proof_index(client, cid)- assert [(r["title"], r["lat"]) for r in rows] == [("Same roof", 50.4501)]---def test_index_lists_a_proof_with_no_located_source_without_a_point(client):- cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]- client.post(- f"/api/cases/{cid}/proofs", json={"title": "Photos only", "spec": _panels("media/x.jpg")}- )-- row = _proof_index(client, cid)[0]- assert row["lat"] is None and row["lon"] is None # it files under Unlocated- assert row["title"] == "Photos only"---def test_index_carries_the_geography_of_the_source(client, sat_tiles, monkeypatch):- from azimut.engine import geo-- monkeypatch.setattr(- geo,- "reverse_geocode",- lambda lat, lon, timeout=8, language=None: {- "display_name": "x",- "attribution": "x",- "address": {"country_code": "ua", "country": "Ukraine", "state": "Donetsk Oblast"},- },- )- cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]- cap = _sat(client, cid, 48.0159, 37.8029)- client.post(f"/api/cases/{cid}/proofs", json={"title": "Donetsk", "spec": _panels(cap["path"])})-- row = _proof_index(client, cid)[0]- assert row["geo"]["country"] == "Ukraine"- assert row["continent"] == "Europe"- assert row["country_en"] == "Ukraine"---def test_index_carries_the_geography_of_the_place_the_proof_filed(client, monkeypatch):- """Panels of photos place nothing, and no Locate pass ever reaches a proof.- But the point the analyst typed was filed as a place and that one has a- country, so the proof files under it instead of under Unlocated."""- from azimut.engine import geo-- monkeypatch.setattr(- geo,- "reverse_geocode",- lambda lat, lon, timeout=8, language=None: {- "display_name": "x",- "attribution": "x",- "address": {"country_code": "is", "country": "Ísland"},- },- )- cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]- client.post(- f"/api/cases/{cid}/proofs",- json={- "title": "Photos only",- "spec": {**_panels("media/x.jpg"), "coordsText": "64.1466, -21.9426"},- },- )-- row = _proof_index(client, cid)[0]- assert (row["lat"], row["lon"]) == (64.1466, -21.9426)- assert row["geo"]["country"] == "Ísland"- assert row["country_en"] == "Iceland"- assert row["continent"] == "Europe"---def test_index_ignores_the_geography_of_a_place_somewhere_else(client, monkeypatch):- """Only the point itself answers. A place across the continent is another- claim about another spot, and borrowing its country would file the proof- under the wrong branch."""- from azimut.engine import geo-- monkeypatch.setattr(- geo,- "reverse_geocode",- lambda lat, lon, timeout=8, language=None: {- "display_name": "x",- "attribution": "x",- "address": {"country_code": "ua", "country": "Україна"},- },- )- cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]- client.post(f"/api/cases/{cid}/satellite/place", json={"lat": 50.4501, "lon": 30.5234})- # the proof states a point of its own, and nothing is filed there to know it- client.put("/api/settings/prefs", json={"proof_place_auto": False})- client.post(- f"/api/cases/{cid}/proofs",- json={- "title": "Elsewhere",- "spec": {**_panels("media/x.jpg"), "coordsText": "48.8584, 2.2945"},- },- )-- row = _proof_index(client, cid)[0]- assert (row["lat"], row["lon"]) == (48.8584, 2.2945)- assert row["geo"] is None # placed on the map, unlocated in the tree---def test_index_lists_the_posts_written_from_a_proof(client, sat_tiles):- cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]- cap = _sat(client, cid, 50.4501, 30.5234)- saved = client.post(- f"/api/cases/{cid}/proofs",- json={"title": "Cited", "spec": _panels(cap["path"]), "png_base64": _png_b64()},- ).json()- client.post(- f"/api/cases/{cid}/drafts",- json={- "title": "First thread",- "state": {"proofPng": saved["png"], "target": "bluesky"},- },- )- client.post(- f"/api/cases/{cid}/drafts",- json={- "title": "Follow-up",- "state": {"proofPng": saved["png"], "target": "mastodon"},- },- )-- row = _proof_index(client, cid)[0]- assert row["posts"] == 2- assert {post["title"] for post in row["linked_posts"]} == {- "First thread",- "Follow-up",- }- assert {post["target"] for post in row["linked_posts"]} == {- "bluesky",- "mastodon",- }- assert {post["name"] for post in row["linked_posts"]} == {- "First thread",- "Follow-up",- }---# -- a proof's own point ----------------------------------------------------------------# A proof does carry coordinates: `coordsText` is what the analyst typed in the-# composer, `coords` is what the panels gave it, frozen at save. Both outlive the-# capture they came from, so they are read before the derivation is walked.---def test_index_prefers_the_coordinates_typed_into_the_composer(client, sat_tiles):- cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]- cap = _sat(client, cid, 50.4501, 30.5234)- client.post(- f"/api/cases/{cid}/proofs",- json={- "title": "Corrected",- "spec": {**_panels(cap["path"]), "coordsText": "48.8584, 2.2945"},- },- )-- rows = _proof_index(client, cid)- # the analyst overrode the imagery: one point, theirs- assert [(r["lat"], r["lon"]) for r in rows] == [(48.8584, 2.2945)]---def test_index_reads_a_hand_typed_point_in_any_supported_format(client):- cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]- client.post(- f"/api/cases/{cid}/proofs",- json={"title": "Typed", "spec": {"panels": [], "coordsText": "48°51'30.2\"N 2°17'40.2\"E"}},- )-- row = _proof_index(client, cid)[0]- assert row["lat"] == pytest.approx(48.8584, abs=1e-3)- assert row["lon"] == pytest.approx(2.2945, abs=1e-3)---def test_index_keeps_the_point_after_the_capture_is_deleted(client, sat_tiles):- """The whole reason a proof stores its own point: outputs outlive sources."""- cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]- cap = _sat(client, cid, 50.4501, 30.5234)- client.post(- f"/api/cases/{cid}/proofs",- json={- "title": "Orphaned",- "spec": {**_panels(cap["path"]), "coords": {"lat": 50.4501, "lon": 30.5234}},- },- )- entity = next(e for e in graph_read.entities(cid) if e["type"] == "capture")- client.delete(f"/api/cases/{cid}/entities/{entity['id']}")-- row = _proof_index(client, cid)[0]- assert (row["lat"], row["lon"]) == (50.4501, 30.5234) # scarred, not unplaced---def test_index_ignores_a_hand_typed_point_it_cannot_read(client, sat_tiles):- cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]- cap = _sat(client, cid, 50.4501, 30.5234)- client.post(- f"/api/cases/{cid}/proofs",- json={"title": "Prose", "spec": {**_panels(cap["path"]), "coordsText": "near the bridge"}},- )-- # unreadable text is not a point, so the derivation still answers- assert [(r["lat"], r["lon"]) for r in _proof_index(client, cid)] == [(50.4501, 30.5234)]---def test_index_carries_the_my_work_folder_of_the_proof(client, sat_tiles):- """A proof is filed like any other artifact, so the panel can group it by- folder as well as by place."""- cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]- cap = _sat(client, cid, 50.4501, 30.5234)- client.post(f"/api/cases/{cid}/proofs", json={"title": "Filed", "spec": _panels(cap["path"])})- entity = next(e for e in graph_read.entities(cid) if e["type"] == "proof")- client.patch(f"/api/cases/{cid}/entities/{entity['id']}", json={"attrs": {"folder": "recon/bridges"}})-- assert _proof_index(client, cid)[0]["folder"] == "recon/bridges"--# -- the place a proof files (engine/satellite.place_for_proof) -----------------## A geolocation is concluded in the composer, so the point becomes a node here@@ -1085,12 +826,11 @@ def test_a_spec_with_no_list_still_states_its_one_point(client):cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]_save(client, cid, "Old shape", _with_coords("50.4501, 30.5234", None, pov=True))- rows = _proof_index(client, cid)- assert [(r["lat"], r["lon"], r["label"]) for r in rows] == [(50.4501, 30.5234, "")]- assert len(_places(cid)) == 1+ [place] = _places(cid)+ assert (place["attrs"]["lat"], place["attrs"]["lon"]) == (50.4501, 30.5234)-def test_every_point_becomes_a_row_and_a_place(client):+def test_every_point_becomes_a_place(client):cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]saved = _save(client, cid, "Harbour strike", _points(("64.1466, -21.9426", "impact 1", False),@@ -1098,11 +838,9 @@ def test_every_point_becomes_a_row_and_a_place(client):("64.1502, -21.9350", "caméra", True),))- # one row per point, all under one proof: the map is about places- rows = _proof_index(client, cid)- assert len({r["id"] for r in rows}) == 1- assert [r["label"] for r in rows] == ["impact 1", "impact 2", "caméra"]- assert len({r["key"] for r in rows}) == 3 # three marks, three render keys+ # one place per point: the map is about places, and that is where a proof's+ # three points are read from+ assert sorted(p["attrs"]["lat"] for p in _places(cid)) == [64.1466, 64.1481, 64.1502]# and the label names the ground, since a place is otherwise called by its numbersassert sorted(p["label"] for p in _places(cid)) == ["caméra", "impact 1", "impact 2"]assert len(saved["place"]["filed"]) == 3@@ -1204,7 +942,6 @@ def test_two_points_a_metre_apart_are_one_place(client):))assert len(_places(cid)) == 1- assert len(_proof_index(client, cid)) == 1def test_one_place_keeps_the_pov_the_second_line_ticked(client):@@ -1287,9 +1024,9 @@ def test_only_the_conclusion_is_looked_up_at_save(client, monkeypatch):))assert asked == [(64.1466, -21.9426)]- rows = {r["label"]: r["geo"] for r in _proof_index(client, cid)}- assert rows["impact 1"]["country"] == "Ísland"- assert rows["impact 2"] is None # born unlocated, for the Locate pass to pick up+ geo_by_label = {p["label"]: (p["attrs"].get("geo") or {}).get("country") for p in _places(cid)}+ assert geo_by_label["impact 1"] == "Ísland"+ assert geo_by_label["impact 2"] is None # born unlocated, for Locate to pick updef test_stating_a_point_writes_the_list_and_the_mirror():@@ -1314,7 +1051,7 @@ def test_stating_one_point_over_a_list_replaces_it(client):]-def test_a_point_filed_by_another_road_is_a_row_and_a_mark(client):+def test_a_point_filed_by_another_road_is_a_place_of_its_own(client):"""A sheet row files a point for a proof it never composed. The graph knewtwo places while the composer opened on one, so the proof said two things."""cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]@@ -1328,8 +1065,7 @@ def test_a_point_filed_by_another_road_is_a_row_and_a_mark(client):case.update_entity(elsewhere["id"], {"label": "impact 2"})case.add_link(proof["id"], elsewhere["id"], "depicts", by="sheet-build")- rows = _proof_index(client, cid)- assert [(r["lat"], r["label"]) for r in rows] == [+ assert sorted((p["attrs"]["lat"], p["label"]) for p in _places(cid)) == [(48.65614, "impact 1"), (48.656289, "impact 2"),]# and the composer opens on both, the analyst's own row still the conclusiondiff --git a/tests/test_sentinel.py b/tests/test_sentinel.pyindex 991ee77..0b7e2e3 100644--- a/tests/test_sentinel.py+++ b/tests/test_sentinel.py@@ -530,7 +530,7 @@ def test_capabilities_layers_drops_names_that_could_not_be_asked_for():assert all(" " not in entry["id"] for entry in sentinel.capabilities_layers("i", get=get))-# -- spectral index frames ------------------------------------------------------+# -- band frames ----------------------------------------------------------------def _rgba_response(url, size):@@ -553,11 +553,11 @@ def test_band_frame_asks_for_the_named_normalised_difference(index, high, low):captured.update(params)return _rgba_response(url, (320, 192))- body = sentinel.band_frame("inst-uuid", BOX, 320, 192, "2026-05-11", index, 30, get=get)+ body = sentinel.band_frame("inst-uuid", BOX, 320, 192, "2026-05-11", f"change-{index}", 30, get=get)script = base64.b64decode(captured["EVALSCRIPT"]).decode("ascii")- assert f'bands: ["{high}", "{low}", "SCL", "dataMask"]' in script- assert f"p.{high} - p.{low}" in script+ assert f'bands: ["{high}", "{low}"' in script+ assert f"(p.{high}) - (p.{low})" in scriptassert captured["CRS"] == "EPSG:3857"assert captured["BBOX"] == "250000.0,6250000.0,251000.0,6250600.0"assert (captured["WIDTH"], captured["HEIGHT"]) == ("320", "192")@@ -569,7 +569,7 @@ def test_band_frame_asks_for_the_named_normalised_difference(index, high, low):@pytest.mark.parametrize("kwargs",[- {"index": "evi"},+ {"index": "change-evi"},{"bbox": (10.0, 10.0, 5.0, 20.0)},{"bbox": (0.0, 0.0, 30_000_000.0, 10.0)},{"width": 4096},@@ -577,7 +577,7 @@ def test_band_frame_asks_for_the_named_normalised_difference(index, high, low):],)def test_band_frame_refuses_a_malformed_request_before_sending_it(kwargs):- asked = dict(bbox=BOX, width=64, height=64, day="2026-05-11", index="ndvi")+ asked = dict(bbox=BOX, width=64, height=64, day="2026-05-11", index="change-ndvi")asked.update(kwargs)def get(*args, **kw): # pragma: no cover - must never run@@ -593,45 +593,73 @@ def test_band_frame_refuses_a_malformed_request_before_sending_it(kwargs):def test_band_frame_refuses_an_image_of_the_wrong_size():with pytest.raises(sentinel.CoverageError):sentinel.band_frame(- "inst-uuid", BOX, 64, 64, "2026-05-11", "ndvi",+ "inst-uuid", BOX, 64, 64, "2026-05-11", "change-ndvi",get=lambda url, **kw: _rgba_response(url, (32, 32)),)-def test_band_frame_asks_for_infrared_and_water_when_looking_for_vessels():+def _detect_script(product):captured = {}def get(url, params=None, **kwargs):captured.update(params)return _rgba_response(url, (64, 64))- sentinel.band_frame("inst-uuid", BOX, 64, 64, "2026-05-11", "vessel", get=get)+ sentinel.band_frame("inst-uuid", BOX, 64, 64, "2026-05-11", product, get=get)+ return base64.b64decode(captured["EVALSCRIPT"]).decode("ascii")+++def test_the_vessel_product_reads_both_infrareds_water_and_the_sky():+ script = _detect_script("vessel")+ assert 'bands: ["B03", "B08", "B11", "SCL", "dataMask"]' in script+ # Near-infrared first and never zero where there is data, so a dark sea+ # still reads as a reading; short-wave infrared, NDWI, then the sky byte.+ assert f"Math.max(1, Math.min(255, Math.round((p.B08) * {255 * sentinel.BAND_GAIN:g})))" in script+ assert f"Math.round((p.B11) * {255 * sentinel.BAND_GAIN:g})" in script+ assert "(p.B03 - p.B08) / (p.B03 + p.B08)" in script+ assert f"p.SCL + (p.B08 < {sentinel.DARK_REFLECTANCE} ? {sentinel.DARK_FLAG} : 0)" in script+ assert "if (!p.dataMask) return [0, 0, 0, 0];" in script+++def test_the_fire_product_measures_against_b8a_on_b12s_own_grid():+ script = _detect_script("fire")+ assert 'bands: ["B8A", "B11", "B12", "SCL", "dataMask"]' in script+ assert "p.B12 / p.B11" in script+ assert "p.B12 / p.B8A" in script+ assert "p.B08" not in script # 10 m against 20 m fakes ratios along sharp edges+ assert f"p.B8A < {sentinel.DARK_REFLECTANCE}" in script- script = base64.b64decode(captured["EVALSCRIPT"]).decode("ascii")- assert 'bands: ["B03", "B08", "SCL", "dataMask"]' in script- # Near-infrared first, stretched so open water spans a usable part of the- # byte, then the scene class, then NDWI, then the data mask.- assert f"p.B08 * 255 * {sentinel.NIR_GAIN}" in script- assert "p.B03 - p.B08" in script- assert "p.SCL" in script+def test_the_surface_product_gives_short_wave_infrared_room_over_desert():+ script = _detect_script("surface")+ assert 'bands: ["B04", "B08", "B11", "SCL", "dataMask"]' in script+ assert f"Math.round((p.B11) * {255 * sentinel.SWIR_GAIN:g})" in script-def test_band_frame_asks_for_the_short_wave_ratios_when_looking_for_fire():++def test_detect_indices_are_sums_of_bands_so_bare_soil_fits():+ script = _detect_script("index-bsi")+ assert '"B11", "B04", "B08", "B02", "SCL", "dataMask"' in script+ assert "((p.B11 + p.B04) - (p.B08 + p.B02))" in script+ # the dark flag still needs B08, and a normalised difference that lacks it asks for it+ assert '"B03", "B11", "B08", "SCL", "dataMask"' in _detect_script("index-mndwi")+++def test_difference_frames_carry_the_same_sky_byte_detect_measures():+ """The browser decodes R = index, G = sky, A = data; a canvas needs that alpha."""captured = {}def get(url, params=None, **kwargs):captured.update(params)return _rgba_response(url, (64, 64))- sentinel.band_frame("inst-uuid", BOX, 64, 64, "2026-05-11", "fire", get=get)-+ sentinel.band_frame("inst-uuid", BOX, 64, 64, "2026-05-11", "change-ndvi", get=get)script = base64.b64decode(captured["EVALSCRIPT"]).decode("ascii")- assert 'bands: ["B08", "B11", "B12", "dataMask"]' in script- assert "p.B12 / p.B11" in script- assert "p.B12 / p.B08" in script- # No scene class: the ratios are what reject cloud, and the fourth channel- # is worth more as the data mask.- assert "SCL" not in script+ assert f"p.SCL + (p.B08 < {sentinel.DARK_REFLECTANCE} ? {sentinel.DARK_FLAG} : 0), 0, 255]" in script+ # The cloud filter over the picture methods asks for the sky and nothing else.+ sentinel.band_frame("inst-uuid", BOX, 64, 64, "2026-05-11", "change-sky", get=get)+ sky = base64.b64decode(captured["EVALSCRIPT"]).decode("ascii")+ assert 'bands: ["B08", "SCL", "dataMask"]' in sky+ assert "return [0, p.SCL" in skydef test_band_frame_refuses_a_product_it_has_no_evalscript_for():@@ -640,4 +668,8 @@ def test_band_frame_refuses_a_product_it_has_no_evalscript_for():with pytest.raises(ValueError):sentinel.band_frame("inst-uuid", BOX, 64, 64, "2026-05-11", "thermal", get=get)- assert sentinel.PRODUCTS == {"ndvi", "ndwi", "nbr", "ndbi", "vessel", "fire"}+ assert sentinel.PRODUCTS == {+ "vessel", "fire", "surface", "change-sky",+ *(f"index-{name}" for name in ("ndvi", "ndwi", "mndwi", "nbr", "ndbi", "bsi")),+ *(f"change-{name}" for name in ("ndvi", "ndwi", "mndwi", "nbr", "ndbi", "bsi")),+ }diff --git a/tests/test_updates.py b/tests/test_updates.pyindex 0469c17..2d42b90 100644--- a/tests/test_updates.py+++ b/tests/test_updates.py@@ -139,7 +139,7 @@ def test_update_endpoint_with_check_queries_github(client, monkeypatch):# shipped file really changes, set the manifest to the current __version__ and# record the new digest here (the failing test prints it).EXTENSION_VERSION = "0.3.0"-EXTENSION_PAYLOAD = "a91b35eaeb29427e0519963c6a0a74e67670fbf38f6090b8c553125e7111e96a"+EXTENSION_PAYLOAD = "9c890067aa7271ca97e30ce999bf600a97fe261ef8a43316d021541aa4798c65"# The digest itself lives in engine/extinstall.py, because the update button# compares the same number: what the app ships against what the installed folder