Skip to content

The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.

JavaScript

Release: v0.2.5 — Sentinel-2 cloud ceiling (#37)

OsintMeThat8344543c0935
diff --git a/README.md b/README.md
index fe325dd..9f0af70 100644
--- a/README.md
+++ b/README.md
@@ -9,14 +9,18 @@ case is a plain folder that can be reopened, archived or shared.
*The name is the French word for azimuth, the compass bearing you sight along
to fix a point on the map.*
-## v0.2.4: Saved work and scalable browsing
+## v0.2.5: Notebook diagrams and clearer Sentinel imagery
+
+<video src="https://github.com/OsintMeThat/azimut/releases/download/v0.2.5/azimut-demo-1920x1080.mp4" controls muted playsinline width="880"></video>
+
+[Watch the tour](https://github.com/OsintMeThat/azimut/releases/download/v0.2.5/azimut-demo-1920x1080.mp4) (2 min 30).
| Tool | What it does |
|------|--------------|
| **Media** | Import local files or download by URL (X, Telegram, TikTok, YouTube, Instagram and more via yt-dlp, with a gallery-dl fallback for image-only posts). Public media is fetched cookie-less; a login-walled post prompts once for a browser session or an exported `cookies.txt`. Each item gets a clean local file, metadata and a SHA-256. Multi-photo posts open a picker. |
| **Reverse Search** | Prepare an image or a video frame for keyless reverse-image services. Nothing uploads on its own. |
| **Inspect** | A scratch workspace over any photo or video: frame adjustments, editable crop, sharpest-frame capture, hand-made collage with per-piece warp/scale/rotate, auto-stitch to solve a panorama's layout, and ELA hints. Nothing enters the case until you save. |
-| **Satellite** | Coordinates or a place name become an imagery crop, with select-area capture, map rotation, measurement tools, reference overlays and editable AOI grids for area review. Esri/OSM by default; add a Mapbox or Google key for more basemaps. |
+| **Satellite** | Coordinates or a place name become an imagery crop, with select-area capture, map rotation, measurement tools, reference overlays and editable AOI grids for area review. Esri/OSM by default, plus Sentinel-2 with a date calendar and a cloud-ceiling slider; add a Mapbox or Google key for more basemaps. |
| **Coordinates** | Convert common coordinate formats, copy the result, and open map or geocoding links. |
| **Geo Proof** | Start a named proof from a reusable house style, select case panels with search, compose them in a grid or free layout, annotate with colored shapes/freehand/text, and export `proof.png` plus a re-editable spec. |
| **Geo Report** | Turn a proof into a prepared thread for X, Bluesky, or Mastodon: coordinates, plus code, attribution, target-specific character counts, media, and a structured Markdown case note with linked evidence. |
@@ -29,18 +33,15 @@ extension, and cross-platform binaries with a bundled ffmpeg.
Every tool works one-shot (a scratch session, no setup) or inside a case, a
plain directory holding the whole investigation.
-New in v0.2.4:
-
-- Saved places, captures, filed screenshots and proofs are easier to find,
- preview and place on the map.
-- The case sidebar and Files now support search, filters, folder browsing,
- multi-select filing and a details list.
-- Media and Files use bounded SQLite queries, including complete category
- counts and search results beyond the first page.
-- Inspect, Geo Proof and Geo Report use named saves. Their pickers can search
- and browse folders.
-- Release binaries now fetch pinned, SHA-256-verified ffmpeg archives. Images
- above 100 MP are rejected before decode.
+New in v0.2.5:
+
+- Notebook notes render `mermaid` fences as diagrams, in the preview and in the
+ PDF. The library loads only when a note holds one, and it draws offline.
+- Sentinel-2 imagery shows cloudy passes by default, with a slider to set the
+ cloud ceiling. The tiles, the date calendar and "most recent" all follow it.
+- The logo is redrawn as a north arrow that stays legible at favicon size.
+- Thumbnails no longer fail with a path error when several downloads finish at
+ once on Windows.
## Install & run
diff --git a/docs/IMAGERY_PROVIDERS.md b/docs/IMAGERY_PROVIDERS.md
index 853a2a8..11f872d 100644
--- a/docs/IMAGERY_PROVIDERS.md
+++ b/docs/IMAGERY_PROVIDERS.md
@@ -167,7 +167,7 @@ Satellite Compare.
```
https://sh.dataspace.copernicus.eu/ogc/wmts/{key}?SERVICE=WMTS&REQUEST=GetTile
&VERSION=1.0.0&LAYER=TRUE_COLOR&TILEMATRIXSET=PopularWebMercator512
- &TILEMATRIX={z}&TILECOL={x}&TILEROW={y}&FORMAT=image/jpeg
+ &TILEMATRIX={z}&TILECOL={x}&TILEROW={y}&FORMAT=image/jpeg&MAXCC=100
```
`{key}` is a configuration-instance UUID from Dashboard → Configuration Utility.
@@ -179,8 +179,16 @@ because the server burns both into every tile.
`TIME` is a **mosaicking window**, so this layer is "mosaic over range X", not "the
imagery". Omitted, the layer's own default applies (the most recent pass).
-The provider id carries the layer and window:
-`sentinel2~SWIR~2026-05-01~2026-05-31`
+**`MAXCC` is always sent, and defaults to 100.** A configuration instance carries
+a cloud-coverage data filter of its own — the standard template ships 20% — and a
+scene above it is dropped before rendering, so the tile comes back empty rather
+than cloudy. Left implicit that reads as the app hiding cloudy days: a date the
+calendar offered renders black, and the dataMask probe calls it a coverage gap.
+Stating the ceiling on every request (tiles, the probe, the WFS date list) means
+what filters a date is our number, not the instance's.
+
+The provider id carries the layer, the window and the ceiling:
+`sentinel2~SWIR~2026-05-01~2026-05-31~CC20`
(`engine/sentinel.py`, mirrored in `frontend/src/lib/sentinel.js`). That is what
solves the cache trap this section used to warn about: the disk cache keys on
`provider.id`, so a window in the id *is* a window in the cache key and two dates
@@ -194,6 +202,7 @@ window and file under another. `tiles.get_provider()` parses the variant;
|--------|----|-------|
| Layer | picker populated from **GetCapabilities** on first open | `LAYERS` in `engine/sentinel.py` is a four-entry fallback; the instance is authoritative, so unsupported layers are not offered |
| Date | a **calendar**: candidate pass days are coloured by cloud, then checked at the crosshair | one day, not a range. Sent as `TIME=day/day` |
+| Cloud | a **slider**, 0–100%, default 100 (no filter) | lower it and cloudier passes leave the tiles, the calendar and "most recent" together. Commits on release, so a drag is not a tile per step |
### Dates come from WFS, and cost one request
diff --git a/docs/RELEASE_NOTES.md b/docs/RELEASE_NOTES.md
index fcbdf96..372fb22 100644
--- a/docs/RELEASE_NOTES.md
+++ b/docs/RELEASE_NOTES.md
@@ -1,4 +1,4 @@
-# Azimut v0.2.4
+# Azimut v0.2.5
## OSINT toolkit at a glance
@@ -13,7 +13,29 @@
- **Publishing:** build annotated Geo Proofs and prepare evidence-linked Geo
Reports for X, Bluesky or Mastodon without posting automatically.
-## What changed
+## What changed in v0.2.5
+
+Mostly additions, with two fixes.
+
+- **Diagrams in case notes.** A ```` ```mermaid ```` fence in a Notebook note
+ renders as a diagram, in the preview and in the exported PDF, so a movement
+ timeline or a chain of inference stays in the case instead of moving to an
+ external drawing tool. The library loads the first time a note holds a
+ diagram, never on open, and it draws offline.
+- **Sentinel-2 cloud ceiling.** Cloudy passes now render by default, and a
+ slider sets the ceiling. The tiles, the date calendar and "most recent" all
+ follow the same number. Previously a configuration instance could apply its
+ own cloud filter, so a date the calendar offered came back as an empty tile
+ and read as a coverage gap.
+- **New logo.** The mark is redrawn as a cartographic north arrow, split on the
+ north-south axis, and stays legible at favicon size on both themes. The app
+ icon, the favicon, the extension icons and the Windows `.exe` icon are all
+ generated from one geometry definition.
+- **Windows thumbnail fix.** Several downloads finishing at once could raise a
+ path error instead of retrying, because the thumbnail directory was resolved
+ before it existed. It is created first now.
+
+## Also in v0.2.4
- **Saved work on the map.** Places, captures and filed screenshots can be
browsed by geography or case folder, searched in English or the local name,
diff --git a/docs/SPEC.md b/docs/SPEC.md
index 20ab5c1..4288fe5 100644
--- a/docs/SPEC.md
+++ b/docs/SPEC.md
@@ -93,6 +93,7 @@ proof for publication.
| ✅ **Geo Report** | Prepares sourced proof threads and saved drafts without posting automatically. |
| ✅ **Case sidebar** | Searches and filters the case, manages notes, suggestions, folders, multi-row filing, a details drawer and synchronized artifact deletion. |
| ✅ **Imagery providers** | Supports Esri, OSM, OpenTopoMap, Sentinel-2 and optional Mapbox/Google with usage controls. |
+| ✅ **Sentinel-2 cloud ceiling** | Renders cloudy passes by default and lets a slider set the ceiling, which the tiles, the calendar and "most recent" all follow. |
| ✅ **Capture extension** | Files user-initiated map screenshots with URL metadata, attribution and provenance; also saves a map's point as a place, or any page as a bookmark. |
| ✅ **Distribution** | Bundles the browser UI, launcher, cross-platform binaries, ffmpeg, locked builds and server hardening. |
@@ -137,7 +138,7 @@ Each version delivers one complete daily workflow. Firm ideas move here from
| **Case Sheet** | The same case as a table: a row is an entity, columns are its attributes plus free ones the analyst adds, sorted, filtered and edited in place. Imports a CSV as loose rows that stay out of the graph until promoted, and exports back to CSV or GeoJSON. |
| **Camera Resection (GCP)** | Marks matching points photo↔map, then solves camera position, viewing azimuth and rough FOV (OpenCV `solvePnP`) and saves the match as evidence. |
| **Command palette** | Ctrl+K reaches a tool, a case or an artifact. |
-| **Sun and local time** | Local time, sunrise/sunset and solar azimuth for a point and date, in Coordinates. |
+| **Sun, moon and local time** | Sunrise/sunset, solar and lunar azimuth, moon phase and bright-limb angle for a point and date, in Coordinates, each time in civil local time and UTC. Polar day/night and days with no moonrise are states, not errors; the moon needs topocentric parallax and sampled rise/set, and civil time adds `timezonefinder` + `tzdata` to bundle. |
| **Capture scale and north** | Preference-controlled scale bar, north arrow and graticule on app and extension captures. |
| **Report an issue** | Opens a pre-filled GitHub issue with version, OS and recent log lines. |
diff --git a/extension/manifest.json b/extension/manifest.json
index b6ac7de..31bd11f 100644
--- a/extension/manifest.json
+++ b/extension/manifest.json
@@ -1,7 +1,7 @@
{
"manifest_version": 3,
"name": "Azimut Capture",
- "version": "0.2.4",
+ "version": "0.2.5",
"description": "File into Azimut: screenshot the map you are looking at (coordinates from the URL), or save any other page as a bookmark.",
"permissions": ["activeTab", "scripting", "storage", "notifications"],
"host_permissions": ["http://127.0.0.1/*", "http://localhost/*"],
diff --git a/frontend/src/lib/sentinel.js b/frontend/src/lib/sentinel.js
index 58e782a..91febe7 100644
--- a/frontend/src/lib/sentinel.js
+++ b/frontend/src/lib/sentinel.js
@@ -16,18 +16,70 @@ const SEP = '~';
export const DEFAULT_LAYER = 'TRUE_COLOR';
/**
- * Pack a layer + window into a provider id. The plain default (true colour,
- * most recent) stays the bare id: it must not read as a second provider.
+ * The cloud ceiling in percent, sent on every request. 100 means no filter,
+ * which is the default because a configuration instance ships one of its own
+ * (20% in the standard template) and a scene above it renders as nothing at
+ * all. Lower it and cloudy passes drop out of the calendar, out of "most
+ * recent" and out of the tiles together — one number, one meaning.
*/
-export function variantId(baseId, { layer = DEFAULT_LAYER, from = '', to = '' } = {}) {
+export const DEFAULT_MAXCC = 100;
+
+/**
+ * Pack a layer + window + cloud ceiling into a provider id. The plain default
+ * (true colour, most recent, no ceiling) stays the bare id: it must not read as
+ * a second provider.
+ */
+export function variantId(
+ baseId,
+ { layer = DEFAULT_LAYER, from = '', to = '', maxcc = DEFAULT_MAXCC } = {}
+) {
if (baseId !== SENTINEL_ID) return baseId;
const windowed = from && to;
- if ((layer || DEFAULT_LAYER) === DEFAULT_LAYER && !windowed) return baseId;
+ const ceiling = validMaxcc(maxcc) ? Math.round(maxcc) : DEFAULT_MAXCC;
+ if ((layer || DEFAULT_LAYER) === DEFAULT_LAYER && !windowed && ceiling === DEFAULT_MAXCC) {
+ return baseId;
+ }
const parts = [baseId, layer || DEFAULT_LAYER];
if (windowed) parts.push(from, to);
+ if (ceiling !== DEFAULT_MAXCC) parts.push(`CC${ceiling}`);
return parts.join(SEP);
}
+/** True for a cloud ceiling the backend will accept: a whole 0…100. */
+export function validMaxcc(value) {
+ return Number.isFinite(value) && value >= 0 && value <= 100 && Number.isInteger(value);
+}
+
+/** How a ceiling reads in the UI. */
+export function maxccLabel(maxcc) {
+ return maxcc >= DEFAULT_MAXCC ? 'Any cloud' : `Up to ${maxcc}%`;
+}
+
+/**
+ * Is this pass above the ceiling? Sentinel Hub drops such a scene before
+ * rendering, so the day is not selectable — the calendar says so rather than
+ * spending a tile on a black square. A pass the service gave no figure for is
+ * never filtered: an unknown is not a reason to hide real imagery.
+ */
+export function overCloudCeiling(cloud, maxcc = DEFAULT_MAXCC) {
+ if (cloud === null || cloud === undefined) return false;
+ return cloud > maxcc;
+}
+
+/**
+ * The newest pass at or before `today` that the ceiling still allows — what
+ * "most recent" actually renders once a ceiling is set. `days` is the
+ * `{ 'YYYY-MM-DD': {cloud} }` map a month lookup returns.
+ */
+export function latestAllowedPass(days, today, maxcc = DEFAULT_MAXCC) {
+ return (
+ Object.keys(days || {})
+ .filter((day) => day <= today && !overCloudCeiling(days[day]?.cloud, maxcc))
+ .sort()
+ .at(-1) ?? ''
+ );
+}
+
/** ISO date (YYYY-MM-DD) for a Date, in UTC — the calendar Sentinel-2 passes
* are dated by, not the viewer's timezone. */
export function isoDay(date) {
@@ -133,12 +185,13 @@ export function sentinelPlaceKey(lat, lon) {
}
/** Local API request that verifies rendered coverage for one candidate day. */
-export function coverageRequestPath({ lat, lon, layer, date }) {
+export function coverageRequestPath({ lat, lon, layer, date, maxcc = DEFAULT_MAXCC }) {
const query = new URLSearchParams({
lat: String(lat),
lon: String(lon),
layer,
date,
+ maxcc: String(validMaxcc(maxcc) ? maxcc : DEFAULT_MAXCC),
});
return `/api/satellite/sentinel/coverage?${query}`;
}
diff --git a/frontend/src/lib/sentinel.test.js b/frontend/src/lib/sentinel.test.js
index c59d738..e4f247d 100644
--- a/frontend/src/lib/sentinel.test.js
+++ b/frontend/src/lib/sentinel.test.js
@@ -1,6 +1,11 @@
import { describe, it, expect } from 'vitest';
import {
variantId,
+ DEFAULT_MAXCC,
+ validMaxcc,
+ maxccLabel,
+ overCloudCeiling,
+ latestAllowedPass,
isoDay,
daysBefore,
validWindow,
@@ -50,6 +55,53 @@ describe('variantId', () => {
});
});
+describe('cloud ceiling', () => {
+ it('leaves the default ceiling off the id', () => {
+ // 100 is "no filter", which is the plain basemap — naming it would file the
+ // same tiles under a second id
+ expect(variantId(SENTINEL_ID, { maxcc: DEFAULT_MAXCC })).toBe('sentinel2');
+ });
+
+ it('packs a ceiling last, after any window', () => {
+ expect(variantId(SENTINEL_ID, { maxcc: 20 })).toBe('sentinel2~TRUE_COLOR~CC20');
+ expect(
+ variantId(SENTINEL_ID, { layer: 'SWIR', from: '2026-05-01', to: '2026-05-01', maxcc: 0 })
+ ).toBe('sentinel2~SWIR~2026-05-01~2026-05-01~CC0');
+ });
+
+ it('ignores a ceiling the backend would refuse', () => {
+ expect(variantId(SENTINEL_ID, { maxcc: 150 })).toBe('sentinel2');
+ expect(variantId(SENTINEL_ID, { maxcc: 12.5 })).toBe('sentinel2');
+ expect(validMaxcc(20)).toBe(true);
+ expect(validMaxcc(-1)).toBe(false);
+ });
+
+ it('reads as a ceiling, or as no ceiling at all', () => {
+ expect(maxccLabel(100)).toBe('Any cloud');
+ expect(maxccLabel(20)).toBe('Up to 20%');
+ });
+
+ it('filters a pass over the ceiling but never one with no figure', () => {
+ expect(overCloudCeiling(38, 20)).toBe(true);
+ expect(overCloudCeiling(20, 20)).toBe(false);
+ // an unknown is not a reason to hide real imagery
+ expect(overCloudCeiling(null, 20)).toBe(false);
+ });
+
+ it('names the newest pass the ceiling still allows as "most recent"', () => {
+ const days = {
+ '2026-05-03': { cloud: 80 },
+ '2026-05-08': { cloud: 12 },
+ '2026-05-13': { cloud: 60 },
+ };
+ expect(latestAllowedPass(days, '2026-05-31', 100)).toBe('2026-05-13');
+ expect(latestAllowedPass(days, '2026-05-31', 20)).toBe('2026-05-08');
+ // a future pass is not "most recent", whatever the ceiling
+ expect(latestAllowedPass(days, '2026-05-10', 100)).toBe('2026-05-08');
+ expect(latestAllowedPass(days, '2026-05-31', 0)).toBe('');
+ });
+});
+
describe('isoDay / daysBefore', () => {
it('dates by the UTC calendar, not the viewer timezone', () => {
expect(isoDay(new Date(Date.UTC(2026, 6, 14, 23, 30)))).toBe('2026-07-14');
@@ -190,9 +242,18 @@ describe('coverage checks', () => {
lon: '2.2945',
layer: 'FALSE_COLOR',
date: '2026-05-11',
+ maxcc: '100',
});
});
+ it('probes at the cloud ceiling the map will render with', () => {
+ const url = new URL(
+ coverageRequestPath({ lat: 48, lon: 2, layer: 'TRUE_COLOR', date: '2026-05-11', maxcc: 20 }),
+ 'http://localhost'
+ );
+ expect(url.searchParams.get('maxcc')).toBe('20');
+ });
+
it('keeps the working date when the candidate has no imagery', () => {
expect(dateAfterCoverage('2026-05-06', '2026-05-11', false)).toBe('2026-05-06');
expect(dateAfterCoverage('2026-05-06', '2026-05-11', true)).toBe('2026-05-11');
diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelte
index c3c663c..7e10869 100644
--- a/frontend/src/tools/Satellite.svelte
+++ b/frontend/src/tools/Satellite.svelte
@@ -26,8 +26,13 @@
import {
SENTINEL_ID,
DEFAULT_LAYER,
+ DEFAULT_MAXCC,
variantId,
validDay,
+ validMaxcc,
+ maxccLabel,
+ overCloudCeiling,
+ latestAllowedPass,
cloudLabel,
cloudClass,
isoDay,
@@ -138,6 +143,11 @@
// window underneath is a range, so we send day/day — but a range is a mosaic
// of several passes, which is not a thing you can point at and date.)
let s2Date = $state(''); // '' = the layer's default, i.e. the most recent pass
+ // Cloud ceiling, in percent. 100 = render whatever passed overhead, which is
+ // the default because the *instance* has a filter of its own (20% in the
+ // standard template) and a scene above it renders as nothing at all: without
+ // saying MAXCC=100 we would be hiding cloudy days without ever saying so.
+ let s2Maxcc = $state(DEFAULT_MAXCC);
let s2MenuOpen = $state(false);
let s2MenuEl = $state(); // bound to the popover wrapper — outside-click detection
let s2Layers = $state([]); // [{id,label,hint}] — catalogue until the instance is asked
@@ -232,7 +242,9 @@
// disk cache. For Sentinel-2 the layer and window ride *on the id*
// (lib/sentinel.js), so none of them can be rendered from one window and
// filed as another.
- const displayedProviderId = $derived(variantId(displayedBaseId, { layer: s2Layer, ...s2Window }));
+ const displayedProviderId = $derived(
+ variantId(displayedBaseId, { layer: s2Layer, ...s2Window, maxcc: s2Maxcc })
+ );
// memoized so the layer is only rebuilt when the cell actually changes
// (i.e. crossing the z17 boost bracket), not on every zoom step
const displayedCell = $derived(
@@ -559,8 +571,10 @@
const s2PassPending = new Map();
const s2CoverageCache = new Map();
const s2PlaceKey = () => sentinelPlaceKey(center.lat, center.lon);
- const s2CoverageKey = (day, place = s2PlaceKey(), layer = s2Layer) =>
- `${layer}@${day}@${place}`;
+ // the ceiling is part of the question: the same day is available under 100%
+ // and a gap under 20%, so a cached answer must not outlive the number
+ const s2CoverageKey = (day, place = s2PlaceKey(), layer = s2Layer, maxcc = s2Maxcc) =>
+ `${layer}@${maxcc}@${day}@${place}`;
let s2PassRequestId = 0;
let s2PickRequestId = 0;
@@ -646,22 +660,26 @@
*/
async function resolveS2Latest() {
const place = s2PlaceKey();
- if (s2LatestFor === place) return;
+ const maxcc = s2Maxcc;
+ const key = `${place}@${maxcc}`;
+ if (s2LatestFor === key) return;
const today = isoDay(new Date());
for (const month of [monthOf(today), addMonths(monthOf(today), -1)]) {
const days = await fetchS2Month(month, place);
if (days === null) return; // lookup failed — say nothing rather than guess
- const past = Object.keys(days).filter((d) => d <= today).sort();
- if (past.length) {
- s2Latest = past.at(-1);
- s2LatestFor = place;
+ // the ceiling drops cloudy passes from the tiles, so "most recent" is the
+ // newest pass it still allows, not the newest pass there is
+ const latest = latestAllowedPass(days, today, maxcc);
+ if (latest) {
+ s2Latest = latest;
+ s2LatestFor = key;
return;
}
}
// no pass in ~2 months: real (deep polar winter, persistent gaps) — the
// pill falls back to "most recent" rather than inventing a date
s2Latest = '';
- s2LatestFor = place;
+ s2LatestFor = key;
}
function clearS2Date() {
@@ -675,18 +693,46 @@
return s2CoverageCache.get(s2CoverageKey(day));
}
+ /** Is this day's pass above the ceiling, i.e. filtered out of the tiles? */
+ function s2Filtered(day) {
+ return overCloudCeiling(s2Passes[day]?.cloud, s2Maxcc);
+ }
+
+ /**
+ * A new cloud ceiling. It reaches the tiles through the provider id, so the
+ * only thing left to settle is a pinned date the new ceiling excludes: that
+ * day renders nothing, so it goes back to most recent rather than to a blank
+ * map nobody asked for.
+ */
+ function setS2Maxcc(value) {
+ const ceiling = Math.round(Number(value));
+ if (!validMaxcc(ceiling) || ceiling === s2Maxcc) return;
+ s2Maxcc = ceiling;
+ if (s2Date && overCloudCeiling(s2Passes[s2Date]?.cloud, ceiling)) {
+ const cloud = cloudLabel(s2Passes[s2Date].cloud);
+ const day = s2Date;
+ clearS2Date();
+ toast(`${day} is ${cloud}, over the ${ceiling}% ceiling. Back to most recent.`, 'warn');
+ }
+ }
+
async function pickS2Date(day) {
if (day === s2Date) {
clearS2Date();
return;
}
if (!s2Passes[day] || s2PassesStale || s2PassesBusy || s2VerifyingDate) return;
+ if (s2Filtered(day)) {
+ toast(`${day} is ${cloudLabel(s2Passes[day].cloud)}, over the ${s2Maxcc}% ceiling.`, 'warn');
+ return;
+ }
const lat = center.lat;
const lon = center.lon;
const place = s2PlaceKey();
const layer = s2Layer;
- const key = s2CoverageKey(day, place, layer);
+ const maxcc = s2Maxcc;
+ const key = s2CoverageKey(day, place, layer, maxcc);
const known = s2CoverageCache.get(key);
if (known === true) {
s2Date = day;
@@ -700,13 +746,13 @@
const requestId = ++s2PickRequestId;
s2VerifyingDate = day;
try {
- const result = await api.get(coverageRequestPath({ lat, lon, layer, date: day }));
+ const result = await api.get(coverageRequestPath({ lat, lon, layer, date: day, maxcc }));
s2CoverageCache.set(key, result.available === true);
s2CoverageRev += 1;
refreshUsage();
if (requestId !== s2PickRequestId) return;
- if (place !== s2PlaceKey() || layer !== s2Layer) {
- toast('The map moved. Pick the date again.', 'warn');
+ if (place !== s2PlaceKey() || layer !== s2Layer || maxcc !== s2Maxcc) {
+ toast('The view changed. Pick the date again.', 'warn');
return;
}
s2Date = dateAfterCoverage(s2Date, day, result.available);
@@ -746,6 +792,7 @@
if (!mapReady || displayedBaseId !== SENTINEL_ID) return;
center.lat;
center.lon;
+ s2Maxcc; // a new ceiling can make a different pass the most recent one
clearTimeout(s2LatestTimer);
// debounced: panning must not spend a request per frame
s2LatestTimer = setTimeout(() => resolveS2Latest().catch(() => {}), 900);
@@ -2854,6 +2901,11 @@
{#if s2Layer !== DEFAULT_LAYER}
<span class="tag layer">{s2LayerShort}</span>
{/if}
+ {#if s2Maxcc !== DEFAULT_MAXCC}
+ <span class="tag" title="Passes over this cloud cover are not rendered"
+ >≤{s2Maxcc}% cloud</span
+ >
+ {/if}
</span>
{:else if imageryDate?.supported}
<span
@@ -2924,6 +2976,10 @@
layersSource={s2LayersSource}
loadLayers={loadS2Layers}
bind:date={s2Date}
+ maxcc={s2Maxcc}
+ setMaxcc={setS2Maxcc}
+ {maxccLabel}
+ filtered={s2Filtered}
month={s2Month}
{monthLabel}
stepMonth={stepS2Month}
diff --git a/frontend/src/tools/satellite/SentinelPicker.svelte b/frontend/src/tools/satellite/SentinelPicker.svelte
index 05461d0..0289e09 100644
--- a/frontend/src/tools/satellite/SentinelPicker.svelte
+++ b/frontend/src/tools/satellite/SentinelPicker.svelte
@@ -11,6 +11,10 @@
layersSource,
loadLayers,
date = $bindable(),
+ maxcc,
+ setMaxcc,
+ maxccLabel,
+ filtered,
month,
monthLabel,
stepMonth,
@@ -27,6 +31,12 @@
clearDate,
loadPasses,
} = $props();
+
+ // The readout tracks the drag; the ceiling only moves on release. Every step
+ // in between would be a provider id of its own, and Sentinel-2 tiles are
+ // billed — you pay for the number you stopped on, not the ones you passed.
+ let dragging = $state(null);
+ const shown = $derived(dragging ?? maxcc);
</script>
<div class="s2-wrap" bind:this={menuEl}>
@@ -57,6 +67,31 @@
<div class="menu-sep" aria-hidden="true"></div>
+ <div class="menu-row">
+ <span class="menu-label">Cloud</span>
+ <div class="cc">
+ <input
+ type="range"
+ min="0"
+ max="100"
+ step="5"
+ value={shown}
+ oninput={(e) => (dragging = Number(e.currentTarget.value))}
+ onchange={(e) => {
+ dragging = null;
+ setMaxcc(Number(e.currentTarget.value));
+ }}
+ aria-label="Maximum cloud cover"
+ />
+ <span class="cc-value mono">{maxccLabel(shown)}</span>
+ </div>
+ </div>
+ <div class="menu-hint dim">
+ Passes cloudier than this are not rendered, and drop out of the calendar.
+ </div>
+
+ <div class="menu-sep" aria-hidden="true"></div>
+
<div class="menu-row">
<span class="menu-label">Date</span>
<div class="chips">
@@ -84,7 +119,8 @@
{:else}
{@const pass = passes[day]}
{@const status = dateStatus(day)}
- {@const unavailable = status === false}
+ {@const overCeiling = filtered(day)}
+ {@const unavailable = status === false || overCeiling}
{@const verifying = verifyingDate === day}
<button
class="cal-day {pass ? cloudClass(pass.cloud) : ''}"
@@ -94,15 +130,17 @@
class:verifying
disabled={date !== day && (!pass || passesStale || passesBusy || unavailable || !!verifyingDate)}
onclick={() => pickDate(day)}
- title={unavailable
- ? `No imagery at the crosshair on ${day}`
- : verifying
- ? `Checking imagery for ${day}`
- : passesStale
- ? `Refreshing dates for this location`
- : pass
- ? `${day}: ${cloudLabel(pass.cloud) || 'cloud cover unknown'}`
- : `${day}: no Sentinel-2 pass`}
+ title={overCeiling
+ ? `${day}: ${cloudLabel(pass.cloud)}, over the ${maxcc}% ceiling`
+ : unavailable
+ ? `No imagery at the crosshair on ${day}`
+ : verifying
+ ? `Checking imagery for ${day}`
+ : passesStale
+ ? `Refreshing dates for this location`
+ : pass
+ ? `${day}: ${cloudLabel(pass.cloud) || 'cloud cover unknown'}`
+ : `${day}: no Sentinel-2 pass`}
>{Number(day.slice(8))}</button>
{/if}
{/each}
@@ -161,6 +199,9 @@
}
.chip:hover { color: var(--text-1); border-color: var(--border-strong); }
.chip.on { border-color: var(--accent); background: var(--accent-soft); color: var(--accent); }
+ .cc { display: flex; align-items: center; gap: 8px; }
+ .cc input[type='range'] { width: 120px; accent-color: var(--accent); cursor: pointer; }
+ .cc-value { font-size: 10px; color: var(--text-2); min-width: 58px; text-align: right; }
.menu-hint { font-size: 10px; color: var(--text-3); margin: -1px 0 5px; }
.menu-hint.dim { opacity: 0.75; }
.menu-hint .warn, .menu-hint.warn { color: var(--warn, #e2a03f); }
diff --git a/frontend/src/tools/satellite/SentinelPicker.test.js b/frontend/src/tools/satellite/SentinelPicker.test.js
index f76a29a..dee060f 100644
--- a/frontend/src/tools/satellite/SentinelPicker.test.js
+++ b/frontend/src/tools/satellite/SentinelPicker.test.js
@@ -12,6 +12,10 @@ function props(overrides = {}) {
layersSource: 'instance',
loadLayers: vi.fn(),
date: '',
+ maxcc: 100,
+ setMaxcc: vi.fn(),
+ maxccLabel: (v) => (v >= 100 ? 'Any cloud' : `Up to ${v}%`),
+ filtered: () => false,
month: '2026-05',
monthLabel: () => 'May 2026',
stepMonth: vi.fn(),
@@ -47,6 +51,26 @@ describe('SentinelPicker date safety', () => {
expect(body).toMatch(/<button[^>]*class="cal-day clear [^"]*has unavailable"[^>]*disabled/);
});
+ it('greys out a pass over the cloud ceiling', () => {
+ const { body } = render(SentinelPicker, {
+ props: props({ maxcc: 20, passes: { '2026-05-11': { cloud: 38, granules: 1 } },
+ cloudLabel: () => '38% cloud', filtered: () => true }),
+ });
+ // above the ceiling Sentinel Hub renders nothing, so the day says why
+ // rather than costing a tile to find out
+ expect(body).toContain('over the 20% ceiling');
+ expect(body).toMatch(/<button[^>]*class="cal-day[^"]*unavailable"[^>]*disabled/);
+ });
+
+ it('shows the ceiling and only commits it on release', () => {
+ const setMaxcc = vi.fn();
+ const { body } = render(SentinelPicker, { props: props({ maxcc: 20, setMaxcc }) });
+ expect(body).toContain('Up to 20%');
+ expect(body).toMatch(/<input[^>]*type="range"/);
+ // dragging must not spend a tile per step: nothing fires from rendering
+ expect(setMaxcc).not.toHaveBeenCalled();
+ });
+
it('shows which date is being checked', () => {
const { body } = render(SentinelPicker, {
props: props({ verifyingDate: '2026-05-11' }),
diff --git a/src/azimut/__init__.py b/src/azimut/__init__.py
index 9aa7930..709b639 100644
--- a/src/azimut/__init__.py
+++ b/src/azimut/__init__.py
@@ -9,7 +9,7 @@ from PIL import Image as _Image
# extension manifest is kept in lock-step by a test, so a release is bumped in
# exactly one place. Getting this wrong nags every user with a false update
# (the binary's self-check compares this against the latest GitHub tag).
-__version__ = "0.2.4"
+__version__ = "0.2.5"
# Cap the pixels Pillow will decode from a file, process-wide. A tiny,
# highly-compressed image can otherwise expand to gigabytes in memory and take
diff --git a/src/azimut/api/satellite.py b/src/azimut/api/satellite.py
index da6e66c..dd2a1dc 100644
--- a/src/azimut/api/satellite.py
+++ b/src/azimut/api/satellite.py
@@ -236,9 +236,14 @@ def sentinel_dates(lat: float, lon: float, start: str, end: str) -> dict[str, An
@router.get("/satellite/sentinel/coverage")
def sentinel_coverage(
- lat: float, lon: float, layer: str, date: str
+ lat: float, lon: float, layer: str, date: str, maxcc: int = sentinel.DEFAULT_MAXCC
) -> dict[str, Any]:
- """Verify a candidate date against the configured layer at the crosshair."""
+ """Verify a candidate date against the configured layer at the crosshair.
+
+ ``maxcc`` is the cloud ceiling the map will render with: above it Sentinel
+ Hub returns nothing, so a probe run at a different ceiling would answer a
+ question the user didn't ask.
+ """
instance = _sentinel_instance()
if config.usage_blocked("sentinelhub"):
raise HTTPException(
@@ -247,7 +252,7 @@ def sentinel_coverage(
"free tier is used; enable the override in Settings to keep going",
)
try:
- result = sentinel.coverage(instance, lat, lon, layer, date)
+ result = sentinel.coverage(instance, lat, lon, layer, date, maxcc)
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
except Exception as exc:
diff --git a/src/azimut/engine/sentinel.py b/src/azimut/engine/sentinel.py
index aee5d06..f9dfe23 100644
--- a/src/azimut/engine/sentinel.py
+++ b/src/azimut/engine/sentinel.py
@@ -94,22 +94,40 @@ DEFAULT_LAYER = LAYERS[0].id
# surprises on any of the three OSes we ship.
_LAYER_RE = re.compile(r"^[A-Z0-9_]{1,40}$")
_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
+# The cloud ceiling as a variant token: CC0 … CC100, and nothing else.
+_MAXCC_RE = re.compile(r"^CC(100|[0-9]{1,2})$")
VARIANT_SEP = "~"
-
-def wmts_url(layer: str = DEFAULT_LAYER, start: str | None = None, end: str | None = None) -> str:
+# Every request states its cloud ceiling, and the default states "no ceiling".
+# A configuration instance carries a cloud-coverage data filter of its own (the
+# standard Sentinel-2 template ships 20%), and a scene above it is dropped
+# *before* rendering: the tile comes back empty, not cloudy. Left implicit, that
+# reads as the app hiding cloudy days — a date the calendar offered renders
+# black, and the coverage probe calls it a gap. So MAXCC is always sent, and
+# what filters a date is our number, not the instance's.
+DEFAULT_MAXCC = 100
+
+
+def wmts_url(
+ layer: str = DEFAULT_LAYER,
+ start: str | None = None,
+ end: str | None = None,
+ maxcc: int = DEFAULT_MAXCC,
+) -> str:
"""The WMTS GetTile template for one layer and window: ``{key}``/``{z}``/``{x}``/``{y}``.
``start``/``end`` (YYYY-MM-DD) become the ``TIME`` mosaicking window, which
is inclusive of both days. Omitted, no TIME is sent and the layer's own
default applies — "most recent", the honest default for "just show me it".
+ ``maxcc`` is the cloud ceiling in percent; scenes above it are not rendered.
"""
url = (
f"{BASE}/wmts/{{key}}"
"?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0"
f"&LAYER={layer}&TILEMATRIXSET=PopularWebMercator512"
"&TILEMATRIX={z}&TILECOL={x}&TILEROW={y}&FORMAT=image/jpeg"
+ f"&MAXCC={int(maxcc)}"
)
if start and end:
url += f"&TIME={start}/{end}"
@@ -117,43 +135,56 @@ def wmts_url(layer: str = DEFAULT_LAYER, start: str | None = None, end: str | No
def variant_id(base_id: str, layer: str | None = None, start: str | None = None,
- end: str | None = None) -> str:
- """Pack a layer + window into a provider id. Mirror of ``parse_variant``.
+ end: str | None = None, maxcc: int | None = None) -> str:
+ """Pack a layer + window + cloud ceiling into a provider id. Mirror of
+ ``parse_variant``.
- The default layer with no window is just the base id: the plain basemap must
- not get a second name, or it would cache twice and read as two providers in
- provenance.
+ The default layer with no window and no ceiling is just the base id: the
+ plain basemap must not get a second name, or it would cache twice and read
+ as two providers in provenance.
"""
layer = layer or DEFAULT_LAYER
- if layer == DEFAULT_LAYER and not (start and end):
+ ceiling = DEFAULT_MAXCC if maxcc is None else int(maxcc)
+ windowed = bool(start and end)
+ if layer == DEFAULT_LAYER and not windowed and ceiling == DEFAULT_MAXCC:
return base_id
parts = [base_id, layer]
- if start and end:
- parts += [start, end]
+ if windowed:
+ parts += [str(start), str(end)]
+ if ceiling != DEFAULT_MAXCC:
+ parts.append(f"CC{ceiling}")
return VARIANT_SEP.join(parts)
-def parse_variant(spec: str) -> tuple[str, str | None, str | None]:
- """``"SWIR~2026-05-01~2026-05-31"`` → ``("SWIR", "2026-05-01", "2026-05-31")``.
+def parse_variant(spec: str) -> tuple[str, str | None, str | None, int]:
+ """``"SWIR~2026-05-01~2026-05-31~CC20"`` → ``("SWIR", "2026-05-01", "2026-05-31", 20)``.
- Raises ValueError on anything that isn't a layer-shaped name and a pair of
- ISO dates in order. This is the validation boundary for a string that
- arrives from a URL path and ends up as a directory name, so the *shape* is
- an allowlist: no separators, no traversal, no free-form text, no reversed
- windows. Membership of LAYERS deliberately isn't checked — an instance
- serves whatever its configuration says (capabilities_layers), and a layer
- the catalogue never heard of is the user's to ask for. A wrong one comes
- back as Sentinel Hub's own 400, which says more than we could.
+ Raises ValueError on anything that isn't a layer-shaped name, an optional
+ pair of ISO dates in order and an optional ``CCnn`` ceiling. This is the
+ validation boundary for a string that arrives from a URL path and ends up as
+ a directory name, so the *shape* is an allowlist: no separators, no
+ traversal, no free-form text, no reversed windows. Membership of LAYERS
+ deliberately isn't checked — an instance serves whatever its configuration
+ says (capabilities_layers), and a layer the catalogue never heard of is the
+ user's to ask for. A wrong one comes back as Sentinel Hub's own 400, which
+ says more than we could.
"""
parts = spec.split(VARIANT_SEP)
- if len(parts) not in (1, 3):
+ if not 1 <= len(parts) <= 4:
raise ValueError(f"malformed Sentinel-2 variant '{spec}'")
layer = parts[0]
if not _LAYER_RE.match(layer):
raise ValueError(f"malformed Sentinel-2 layer '{layer}'")
- if len(parts) == 1:
- return layer, None, None
- start, end = parts[1], parts[2]
+ rest = parts[1:]
+ maxcc = DEFAULT_MAXCC
+ # a ceiling only ever sits last, and no ISO date can be read as one
+ if rest and _MAXCC_RE.match(rest[-1]):
+ maxcc = int(rest.pop()[2:])
+ if not rest:
+ return layer, None, None, maxcc
+ if len(rest) != 2:
+ raise ValueError(f"malformed Sentinel-2 variant '{spec}'")
+ start, end = rest
for value in (start, end):
if not _DATE_RE.match(value):
raise ValueError(f"malformed date '{value}' (expected YYYY-MM-DD)")
@@ -163,16 +194,22 @@ def parse_variant(spec: str) -> tuple[str, str | None, str | None]:
raise ValueError(f"impossible date '{value}'") from exc
if start > end:
raise ValueError(f"window ends before it starts ({start} → {end})")
- return layer, start, end
+ return layer, start, end, maxcc
-def variant_label(layer: str, start: str | None, end: str | None) -> str:
- """How a variant reads to a human: "SWIR · 2026-05-01 → 2026-05-31"."""
+def variant_label(
+ layer: str, start: str | None, end: str | None, maxcc: int = DEFAULT_MAXCC
+) -> str:
+ """How a variant reads to a human: "SWIR · 2026-05-01 → 2026-05-31 · ≤20% cloud"."""
known = next((entry.label for entry in LAYERS if entry.id == layer), layer)
if start and end:
window = start if start == end else f"{start} → {end}"
- return f"{known} · {window}"
- return f"{known} · most recent"
+ label = f"{known} · {window}"
+ else:
+ label = f"{known} · most recent"
+ if maxcc != DEFAULT_MAXCC:
+ label += f" · ≤{int(maxcc)}% cloud"
+ return label
# -- date discovery (WFS) ------------------------------------------------------
@@ -308,6 +345,10 @@ def dates(
"BBOX": f"{lat - _BBOX_PAD},{lon - _BBOX_PAD},{lat + _BBOX_PAD},{lon + _BBOX_PAD}",
"TIME": f"{start}/{end}",
"MAXFEATURES": str(_MAX_FEATURES),
+ # every pass, cloudy ones included: the calendar shows cover per day and
+ # the user's own ceiling decides what to grey out. A list already cut by
+ # the instance's filter would hide passes we never said we hid.
+ "MAXCC": str(DEFAULT_MAXCC),
}
response = fetch(
f"{BASE}/wfs/{instance}", params=params,
@@ -340,6 +381,7 @@ def coverage(
lon: float,
layer: str,
day: str,
+ maxcc: int = DEFAULT_MAXCC,
*,
get: Callable[..., Any] | None = None,
) -> dict[str, Any]:
@@ -348,13 +390,15 @@ def coverage(
WFS supplies candidate acquisition dates. This WMS dataMask probe is the
final authority before the UI replaces a working map with a dated layer.
It uses the configured layer, so a custom layer is checked against its own
- collection rather than the date catalogue's L2A assumption.
+ collection rather than the date catalogue's L2A assumption, and the same
+ cloud ceiling the tiles will carry — the probe has to be answering the
+ question the map is about to ask.
"""
if not (-90 <= lat <= 90 and -180 <= lon <= 180):
raise ValueError("coordinates are outside WGS84 bounds")
- # Reuse the variant parser as the validation boundary for both URL values.
- checked_layer, checked_day, _ = parse_variant(
- f"{layer}{VARIANT_SEP}{day}{VARIANT_SEP}{day}"
+ # Reuse the variant parser as the validation boundary for all three values.
+ checked_layer, checked_day, _, checked_maxcc = parse_variant(
+ f"{layer}{VARIANT_SEP}{day}{VARIANT_SEP}{day}{VARIANT_SEP}CC{int(maxcc)}"
)
earth_radius = 6_378_137.0
@@ -373,6 +417,7 @@ def coverage(
"HEIGHT": str(_COVERAGE_SIZE),
"FORMAT": "image/png",
"TIME": f"{checked_day}/{checked_day}",
+ "MAXCC": str(checked_maxcc),
"EVALSCRIPT": _COVERAGE_EVALSCRIPT,
}
fetch = get or httpx.get
@@ -398,6 +443,7 @@ def coverage(
"coverage": round(valid / len(values), 3),
"date": checked_day,
"layer": checked_layer,
+ "maxcc": checked_maxcc,
}
diff --git a/src/azimut/engine/tiles.py b/src/azimut/engine/tiles.py
index 8fc608d..69d94d8 100644
--- a/src/azimut/engine/tiles.py
+++ b/src/azimut/engine/tiles.py
@@ -92,9 +92,10 @@ GOOGLE_SATELLITE_URL = "https://tile.googleapis.com/v1/2dtiles/{z}/{x}/{y}?sessi
GOOGLE_JS_LOADER_URL = "https://maps.googleapis.com/maps/api/js?key={key}&v=weekly"
# Sentinel Hub OGC WMTS (docs/IMAGERY_PROVIDERS.md): {key} is the user's
# configuration-instance UUID, which is the whole credential — no token to mint.
-# The layer and the mosaicking window are choices, not constants, so the
-# template is built per variant in engine/sentinel.py; this is the plain one
-# (TRUE_COLOR, the layer's own default window = most recent).
+# The layer, the mosaicking window and the cloud ceiling are choices, not
+# constants, so the template is built per variant in engine/sentinel.py; this is
+# the plain one (TRUE_COLOR, the layer's own default window = most recent, and
+# no cloud filter — the instance's own would silently drop cloudy passes).
SENTINELHUB_WMTS_URL = sentinel.wmts_url()
BUILTIN_PROVIDERS: tuple[Provider, ...] = (
@@ -291,14 +292,14 @@ def get_provider(provider_id: str) -> Provider:
if provider.id != "sentinel2":
raise KeyError(f"provider '{base_id}' has no variants")
try:
- layer, start, end = sentinel.parse_variant(spec)
+ layer, start, end, maxcc = sentinel.parse_variant(spec)
except ValueError as exc:
raise KeyError(str(exc)) from exc
return replace(
provider,
id=provider_id,
- label=f"{provider.label} · {sentinel.variant_label(layer, start, end)}",
- url=sentinel.wmts_url(layer, start, end).replace(
+ label=f"{provider.label} · {sentinel.variant_label(layer, start, end, maxcc)}",
+ url=sentinel.wmts_url(layer, start, end, maxcc).replace(
"{key}", _sentinel_key_from(provider.url)
),
)
diff --git a/tests/test_sentinel.py b/tests/test_sentinel.py
index 19155a5..8d4beac 100644
--- a/tests/test_sentinel.py
+++ b/tests/test_sentinel.py
@@ -44,6 +44,13 @@ def test_wmts_url_ignores_a_half_open_window():
assert "TIME=" not in sentinel.wmts_url("SWIR", "2026-05-01", None)
+def test_wmts_url_always_states_the_cloud_ceiling():
+ # left unsaid, the instance's own filter applies (20% in the standard
+ # template) and cloudy passes come back empty rather than cloudy
+ assert "MAXCC=100" in sentinel.wmts_url()
+ assert "MAXCC=20" in sentinel.wmts_url("TRUE_COLOR", None, None, 20)
+
+
# -- variant ids ---------------------------------------------------------------
@@ -59,7 +66,7 @@ def test_variant_id_round_trips_through_parse_variant():
assert packed == "sentinel2~SWIR~2026-05-01~2026-05-31"
base, _, spec = packed.partition("~")
assert base == "sentinel2"
- assert sentinel.parse_variant(spec) == ("SWIR", "2026-05-01", "2026-05-31")
+ assert sentinel.parse_variant(spec) == ("SWIR", "2026-05-01", "2026-05-31", 100)
def test_variant_id_keeps_a_windowed_default_layer():
@@ -68,13 +75,13 @@ def test_variant_id_keeps_a_windowed_default_layer():
def test_parse_variant_takes_a_bare_layer():
- assert sentinel.parse_variant("FALSE_COLOR") == ("FALSE_COLOR", None, None)
+ assert sentinel.parse_variant("FALSE_COLOR") == ("FALSE_COLOR", None, None, 100)
def test_parse_variant_accepts_a_layer_the_catalogue_never_heard_of():
# an instance serves whatever its configuration says; the catalogue is a
# default, not a gate (a wrong one comes back as Sentinel Hub's own 400)
- assert sentinel.parse_variant("MY_CUSTOM_SCRIPT") == ("MY_CUSTOM_SCRIPT", None, None)
+ assert sentinel.parse_variant("MY_CUSTOM_SCRIPT") == ("MY_CUSTOM_SCRIPT", None, None, 100)
@pytest.mark.parametrize(
@@ -96,11 +103,40 @@ def test_parse_variant_refuses_anything_ill_shaped(spec):
sentinel.parse_variant(spec)
+def test_variant_id_carries_a_cloud_ceiling():
+ packed = sentinel.variant_id("sentinel2", "SWIR", "2026-05-01", "2026-05-31", 20)
+ assert packed == "sentinel2~SWIR~2026-05-01~2026-05-31~CC20"
+ assert sentinel.parse_variant(packed.partition("~")[2]) == (
+ "SWIR", "2026-05-01", "2026-05-31", 20
+ )
+
+
+def test_variant_id_carries_a_ceiling_without_a_window():
+ packed = sentinel.variant_id("sentinel2", "TRUE_COLOR", None, None, 0)
+ assert packed == "sentinel2~TRUE_COLOR~CC0"
+ assert sentinel.parse_variant(packed.partition("~")[2]) == ("TRUE_COLOR", None, None, 0)
+
+
+def test_variant_id_leaves_the_default_ceiling_off_the_id():
+ # 100 is "no filter", which is the plain basemap: naming it would cache the
+ # same tiles twice under two ids
+ assert sentinel.variant_id("sentinel2", "TRUE_COLOR", None, None, 100) == "sentinel2"
+
+
[email protected]("spec", ["SWIR~CC101", "SWIR~CC-5", "SWIR~CC", "SWIR~CC20~CC20"])
+def test_parse_variant_refuses_an_impossible_ceiling(spec):
+ with pytest.raises(ValueError):
+ sentinel.parse_variant(spec)
+
+
def test_variant_label_reads_like_a_human_wrote_it():
assert sentinel.variant_label("SWIR", None, None).endswith("most recent")
assert "2026-05-01 → 2026-05-31" in sentinel.variant_label("SWIR", "2026-05-01", "2026-05-31")
# a single-day window is a day, not a range from a day to itself
assert sentinel.variant_label("SWIR", "2026-05-01", "2026-05-01").endswith("2026-05-01")
+ # a ceiling changes the pixels, so it is part of what the capture was from
+ assert sentinel.variant_label("SWIR", None, None, 20).endswith("≤20% cloud")
+ assert "cloud" not in sentinel.variant_label("SWIR", None, None, 100)
# -- date discovery ------------------------------------------------------------
@@ -213,6 +249,19 @@ def test_dates_sends_a_latitude_first_bbox():
assert lon_min < 2.0 < lon_max
+def test_dates_asks_for_every_pass_however_cloudy():
+ captured = {}
+
+ def get(url, params=None, **kwargs):
+ captured.update(params)
+ return _response(url, {"features": []})
+
+ sentinel.dates("inst-uuid", 48.0, 2.0, "2026-05-01", "2026-05-31", get=get)
+ # the calendar colours days by cloud and the user's own ceiling greys them
+ # out; a list already cut upstream would hide passes we never said we hid
+ assert captured["MAXCC"] == "100"
+
+
def test_dates_reports_a_day_the_service_gave_no_cloud_figure_for():
def get(url, params=None, **kwargs):
return _response(url, {"features": [{"properties": {"date": "2026-05-01"}}]})
@@ -261,6 +310,7 @@ def test_coverage_uses_the_selected_layer_and_day():
"coverage": 0.016,
"date": "2026-05-11",
"layer": "SWIR",
+ "maxcc": 100,
}
assert captured["url"].endswith("/ogc/wms/inst-uuid")
assert captured["params"]["LAYERS"] == "SWIR"
@@ -269,6 +319,28 @@ def test_coverage_uses_the_selected_layer_and_day():
assert captured["params"]["EVALSCRIPT"]
+def test_coverage_probes_at_the_ceiling_the_map_will_render_with():
+ captured = {}
+
+ def get(url, params=None, **kwargs):
+ captured.update(params)
+ return _mask_response(url, [0] * 64)
+
+ result = sentinel.coverage(
+ "inst-uuid", 48.0, 2.0, "TRUE_COLOR", "2026-05-11", 20, get=get
+ )
+ # above the ceiling Sentinel Hub renders nothing, so a probe at 100% would
+ # promise imagery the tiles are not going to show
+ assert captured["MAXCC"] == "20"
+ assert result["maxcc"] == 20
+
+
[email protected]("maxcc", [101, -1])
+def test_coverage_rejects_an_impossible_ceiling(maxcc):
+ with pytest.raises(ValueError):
+ sentinel.coverage("inst-uuid", 48.0, 2.0, "TRUE_COLOR", "2026-05-11", maxcc)
+
+
def test_coverage_reports_no_source_pixels():
result = sentinel.coverage(
"inst-uuid", 48.8584, 2.2945, "TRUE_COLOR", "2026-05-11",
diff --git a/tests/test_settings_api.py b/tests/test_settings_api.py
index 2d97c29..b01bfa4 100644
--- a/tests/test_settings_api.py
+++ b/tests/test_settings_api.py
@@ -529,27 +529,55 @@ def test_sentinel_coverage_checks_the_layer_and_counts_the_request(client, monke
client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
calls = []
- def check(instance, lat, lon, layer, day):
- calls.append((instance, lat, lon, layer, day))
+ def check(instance, lat, lon, layer, day, maxcc):
+ calls.append((instance, lat, lon, layer, day, maxcc))
return {
"available": False,
"coverage": 0.0,
"date": day,
"layer": layer,
+ "maxcc": maxcc,
}
monkeypatch.setattr(sentinel, "coverage", check)
body = client.get(
"/api/satellite/sentinel/coverage"
- "?lat=48.8584&lon=2.2945&layer=SWIR&date=2026-05-11"
+ "?lat=48.8584&lon=2.2945&layer=SWIR&date=2026-05-11&maxcc=20"
).json()
assert body["available"] is False
- assert calls == [("inst-uuid", 48.8584, 2.2945, "SWIR", "2026-05-11")]
+ # the probe answers for the ceiling the tiles will carry, not for 100%
+ assert calls == [("inst-uuid", 48.8584, 2.2945, "SWIR", "2026-05-11", 20)]
settings = client.get("/api/settings").json()
assert settings["usage"]["sentinelhub"][settings["month"]] == 1
+def test_sentinel_coverage_defaults_to_no_cloud_filter(client, monkeypatch):
+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
+ calls = []
+
+ def check(instance, lat, lon, layer, day, maxcc):
+ calls.append(maxcc)
+ return {"available": True, "coverage": 1.0, "date": day, "layer": layer, "maxcc": maxcc}
+
+ monkeypatch.setattr(sentinel, "coverage", check)
+ client.get(
+ "/api/satellite/sentinel/coverage?lat=48&lon=2&layer=SWIR&date=2026-05-11"
+ )
+ assert calls == [100]
+
+
+def test_sentinel_coverage_refuses_a_ceiling_outside_the_scale(client):
+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
+ # refused before anything is sent: no request, no charge
+ response = client.get(
+ "/api/satellite/sentinel/coverage"
+ "?lat=48&lon=2&layer=SWIR&date=2026-05-11&maxcc=150"
+ )
+ assert response.status_code == 422
+ assert client.get("/api/settings").json()["usage"] == {}
+
+
def test_sentinel_coverage_rejects_bad_input_without_counting(client, monkeypatch):
client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
diff --git a/tests/test_tiles.py b/tests/test_tiles.py
index bdefa23..baebce3 100644
--- a/tests/test_tiles.py
+++ b/tests/test_tiles.py
@@ -282,9 +282,24 @@ def test_get_provider_variant_without_a_window_keeps_the_default_time(monkeypatc
assert "TIME=" not in p.url
+def test_get_provider_carries_the_cloud_ceiling_into_the_url(monkeypatch, tmp_path):
+ provider = _sentinel(monkeypatch, tmp_path)
+ # the plain basemap states the default explicitly: without it the instance's
+ # own filter applies and cloudy passes render as nothing
+ assert "MAXCC=100" in provider.url
+ p = tiles.get_provider("sentinel2~TRUE_COLOR~2026-05-01~2026-05-01~CC20")
+ assert "MAXCC=20" in p.url
+ assert "TIME=2026-05-01/2026-05-01" in p.url
+ # the ceiling changes the pixels, so it is in the id the cache and a
+ # capture's provenance key on
+ assert p.id == "sentinel2~TRUE_COLOR~2026-05-01~2026-05-01~CC20"
+ assert "≤20% cloud" in p.label
+
+
def test_get_provider_refuses_a_malformed_variant(monkeypatch, tmp_path):
_sentinel(monkeypatch, tmp_path)
- for bad in ("sentinel2~../etc", "sentinel2~SWIR~2026-99-01~2026-05-31", "sentinel2~a b"):
+ for bad in ("sentinel2~../etc", "sentinel2~SWIR~2026-99-01~2026-05-31", "sentinel2~a b",
+ "sentinel2~SWIR~CC101"):
with pytest.raises(KeyError):
tiles.get_provider(bad)