The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.
JavaScript
Speak failures in one clause, open the running Azimut, ship ffmpeg's licences, and harden imports and the job queue (#99)
OsintMeThat7c95b289edc9
diff --git a/README.md b/README.mdindex 40cd7d4..70bea5f 100644--- a/README.md+++ b/README.md@@ -31,6 +31,10 @@ pipx install azimut # isolated app install; plain `pip install azimut` also woazimut # starts on http://127.0.0.1:8477 and opens a browser tab```+Starting Azimut a second time opens the one already running. If another program+holds port 8477, Azimut takes the next free port, and the capture extension needs+that address in its options. Settings → Capture extension shows which.+No Python? Every release attaches a self-contained binary for Windows, macOS(Apple Silicon) and Linux on the[Releases page](https://github.com/OsintMeThat/azimut/releases). Download it, run@@ -52,21 +56,21 @@ to fix a point on the map.*| Tool | What it does ||------|--------------|-| **Timeline** | The case on a time axis, and where events are noted: one line with a date, a sentence and `@` mentions. A point is an instant, a bracket a date known to the day or month, a bar a period; the ruler reads in any zone or at a saved place, the list copies out as a table, and a picked file plays in place. |-| **Board** | The case as an index: people, accounts, places and things first, each with how many events name it and when, then the files and work folded under. One filter bar whose values are all taken from the case, Details beside the list, and a ticked selection deleted as one recoverable act. |-| **Graph** | The same case drawn. Lenses pick what a reading is about, nodes cluster, edges carry their verb, and a click opens what a node connects to without losing the picture you were reading. Graph and Timeline both export a reading as an SVG or PNG plate carrying its question, period and legend. |-| **Sheet** | The case's own CSVs in a plain grid: a comparison table, a worklist with its own state, or the half-facts too soft to be entities. Columns can be typed, a workbook arrives one sheet per tab, and a declared sheet promotes into entities, places and dated statements. A worklist can also be built back out of what the case holds. |-| **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. |+| **Timeline** | The case on a time axis, where an event is one dated line with `@` mentions and the ruler reads in any zone or at a saved place. |+| **Board** | The case as an index of people, accounts, places and things, each with how many events name it and when, filtered by values taken from the case. |+| **Graph** | The same case drawn as clustered nodes and verb-labelled edges, exported with its question, period and legend as an SVG or PNG plate. |+| **Sheet** | The case's CSVs in a plain grid, where typed columns, worklists and declared sheets promote into entities, places and dated statements. |+| **Media** | Import local files or download by URL (X, Telegram, TikTok, YouTube, Instagram and more via yt-dlp and gallery-dl), each kept as a clean local file with metadata and a SHA-256. || **Files** | Every saved artifact in one Finder-style view of your folders, not just media: select several, drag them into a folder, search across the lot. |-| **Reverse Search** | Prepare an image or a video frame for keyless reverse-image services. With the capture extension, pressing an engine opens it with the picture already in it. Nothing leaves the machine until you press one. |-| **Inspect** | Reads any photo or video closely: sharpest-frame capture onto a strip, frame adjustments, editable crop and ELA hints. Frames and edits are kept with the file as you make them; a frame or an adjusted video enters the Media Library only when you save it to the case. |-| **Collage** | Lays out frames and images from any number of files on one canvas, with per-piece warp, scale, rotate and crop, and auto-stitch to solve a panorama's layout. Saved as you go; the picture it exports is case media. |-| **Satellite** | Coordinates or a place name become an imagery crop. The search bar proposes matches as you type: saved work, coordinates and a bundled city list answer offline, and the geocoder fills in the rest once you pause. Select-area capture with an optional scale bar and north arrow, map rotation, measurement tools, a right-click menu on any point, stacked overlays (borders, village names, roads, railways, power lines, fires, night lights), your own KML, KMZ, GeoJSON, GPX or My Maps layers, GeoConfirmed conflicts narrowed to a period, and editable AOI grids for area review. Esri/OSM by default, plus the Esri Wayback archive, Sentinel-2 with a date calendar and a cloud-ceiling slider, and Sentinel-1 radar passes; add a Mapbox or Google key for more basemaps. Open it in several tabs and they stay in sync. |-| **Compare** | Links two dated map views for side-by-side, swipe, fade or blink, with Difference highlights laid over any of them. All dates lists every picture of a point, oldest first, to set on either side. Ground-anchored notes, shapes, numbered markers and measurements follow both maps. Editable sessions and rendered previews stay in the case; attributed PNG/GIF copies go to exports. |-| **Detect** | Sweeps drawn areas of Sentinel-2 for vessels, fires, construction, burn scars and other changes, and of Sentinel-1 radar for vessels, razed buildings, new structures and floods through cloud, once or as a saved routine. Only a candidate you keep becomes a case pin, dated by the passes that found it. |-| **Coords & Sky** | Convert common coordinate formats, copy the result, open map or geocoding links, and read the sun and moon at that point on a date: rise, set, azimuth, altitude, twilights, moon phase and bright-limb angle, in local time and UTC, computed offline. |-| **Geo Proof** | Start a named proof from a reusable house style, or from a published post whose pictures become its panels. Compose case panels in a grid or free layout, turn or crop them, annotate with colored shapes, fills, symbols, numbered markers, blur boxes, freehand and text, state every place and every source the proof argues, and export `proof.png` plus a re-editable spec. |-| **Geo Report** | Turn a proof into a prepared thread for X or Bluesky: coordinates, plus code, attribution, target-specific character counts, media, and a structured Markdown case note with linked evidence. |+| **Reverse Search** | Prepare an image or a video frame for keyless reverse-image services, which the capture extension opens with the picture already in them. |+| **Inspect** | Reads any photo or video closely with sharpest-frame capture, frame adjustments, editable crop and ELA hints, all kept with the file as you work. |+| **Collage** | Lays out frames and images from any number of files on one canvas, with per-piece warp and crop and auto-stitch for panoramas. |+| **Satellite** | Coordinates or a place name become an imagery crop over Esri, OSM, the Wayback archive, Sentinel-2 or Sentinel-1 radar, with measurement tools, stacked overlays, your own KML, GeoJSON or GPX layers, and AOI grids for area review. |+| **Compare** | Links two dated map views for side-by-side, swipe, fade or blink, with Difference highlights and ground-anchored notes that follow both maps. |+| **Detect** | Sweeps drawn areas of Sentinel-2 and Sentinel-1 radar for vessels, fires, construction, burn scars, floods and other changes, and only a candidate you keep becomes a case pin. |+| **Coords & Sky** | Converts coordinate formats, opens map links, and reads the sun and moon at that point on a date, computed offline. |+| **Geo Proof** | Composes annotated case panels into a proof, from a house style or a published post, and exports `proof.png` plus a re-editable spec. |+| **Geo Report** | Turns a proof into a prepared thread for X or Bluesky, with coordinates, attribution, character counts, media and a Markdown case note. || **Notebook** | Tabbed Markdown notes with local media, Mermaid diagrams, linked case evidence, broken-reference markers, and PDF export of one note or a whole selection. |Under the hood: reusable proof and thread templates, per-case SQLite with a@@ -99,8 +103,8 @@ Detect sweeps an area for what appeared, and the map takes layers made elsewherea GeoConfirmed conflict. A dated layer narrows to a period.- Proofs turn and crop their images, stamp numbered markers and blur boxes, andcarry a sentence and the date their material was taken.-- To-do lists on Home, one date field across the app, a claim filed from where- you are, and Reverse Search from a Media Library row or an Inspect frame.+- To-do lists on Home, every date typed day-first in the same field, a claim filed+ from where you are, and Reverse Search from a Media row or an Inspect frame.- Existing cases open as they are, with 0.3.0 Inspect sessions merged into onework per file, and older bundles still import.@@ -170,8 +174,8 @@ The downloadable binaries bundle a static **ffmpeg** (and ffprobe), so videothumbnails, frame scans, video enhancement, and downloads that merge separateaudio+video streams work out of the box. If you `pip install azimut` instead,put ffmpeg on your `PATH` for those features. Everything else works without it.-The bundled ffmpeg is redistributed under its own license; see-[ffmpeg.org/legal.html](https://ffmpeg.org/legal.html).+The binaries carry the bundled build's license notice and texts, readable from+**Settings → System**; see also [ffmpeg.org/legal.html](https://ffmpeg.org/legal.html).### From source@@ -234,12 +238,16 @@ Frontend development (hot reload, proxied API):cd frontend && npm run dev # UI on :5173```-Checks (CI runs these on every push):+Checks (CI fails a pull request on any of these). A fresh clone runs+`uv sync --extra dev` first, which installs pytest, ruff and mypy:```bash-uv run ruff check src tests scripts packaging # lint-uv run mypy # type-check the package, scripts and packaging-cd frontend && npm run check # svelte-check (blocks on errors)+uv run pytest -q -n auto # backend tests+cd frontend && npx vitest run # frontend tests+cd frontend && npm run check # svelte-check+uv run ruff check src tests scripts packaging # lint+uv run mypy # type-check+cd frontend && npm run test:e2e # Playwright, for changes seen in the browser```### Capture extension (optional)@@ -401,11 +409,10 @@ One-time setup: register the repo as a2. A case contains the investigation's files and SQLite graph. A closed casefolder is complete and portable; bundle export carries both Azimut's filesand anything kept beside them.-3. One tab = one tool, useful in 30 seconds.-4. Azimut integrates specialized services instead of recreating them.-5. The analyst decides; tools do not produce automated verdicts.-6. Every artifact records how it was produced.-7. Free and open source. No paid key is ever required; bring your own for+3. Azimut integrates specialized services instead of recreating them.+4. The analyst decides; tools do not produce automated verdicts.+5. Every artifact records how it was produced.+6. Free and open source. No paid key is ever required; bring your own formore basemaps.Full spec: [docs/SPEC.md](docs/SPEC.md).diff --git a/docs/IMAGERY_PROVIDERS.md b/docs/IMAGERY_PROVIDERS.mdindex e1a5789..9c76264 100644--- a/docs/IMAGERY_PROVIDERS.md+++ b/docs/IMAGERY_PROVIDERS.md@@ -54,7 +54,7 @@ is still the user's quota identity, so it lives in `api_keys` like any other key⁴ A Maps JS key is client-side **by design** (referrer-restricted, not secret), soshipping it to the browser in the loader URL is intended. Every-tile key, which stays server-side behind the proxy.+other key is a tile key, and stays server-side behind the proxy.## Google in the EEA since 2025-07-08@@ -213,7 +213,7 @@ window and file under another. `tiles.get_provider()` parses the variant;| Choice | UI | Notes ||--------|----|-------|-| 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 |+| Layer | picker populated from **GetCapabilities** on a user request | `LAYERS` in `engine/sentinel.py` is a four-entry catalogue; the instance is authoritative. Analyzer checks keep missing products visible but disabled and use actual IDs such as `VEGETATION_INDEX`. An unverified catalogue cannot start check imagery. || 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 |diff --git a/docs/SPEC.md b/docs/SPEC.mdindex 503a622..fb398b6 100644--- a/docs/SPEC.md+++ b/docs/SPEC.md@@ -150,18 +150,18 @@ proof for publication.| ✅ **Timeline readings** | Builds coloured tracks from presets or Search+, then saves a changing Live view or a fixed Snapshot. || ✅ **Shared analysis views** | Shares one filter, saved-view family and fact-time window between Board and Graph, while Timeline keeps readings built for tracks and the Map only exchanges a window with them. || ✅ **Analysis view export** | Writes the Graph or the Timeline out as a vector plate carrying its lens, question, window, clock and legend, or copies it as an image. |-| ✅ **Case Sheet** | Opens and builds case CSVs in a plain grid: keyed rows, sorts, filters, row colour, clipboard both ways, bulk fill, undo, cells that point at case entities, and a reading handed out as CSV or Markdown. |-| ✅ **Typed columns** | Types a column in the sidecar as a state, a list, a yes/no, a number, a point, a date or a picture, and lets the sort, the filters, the vocabulary, the map, the Timeline, the progress and the link check read it. |+| ✅ **Case Sheet** | Opens and builds case CSVs in a plain grid: keyed rows, sorts, filters, row colour, clipboard both ways, bulk fill, undo and cells that point at case entities. |+| ✅ **Typed columns** | Types a column as a state, a list, a yes/no, a number, a point, a date or a picture, read by the sort, the filters, the map, the Timeline and the progress. || ✅ **A family of sheets** | Files a workbook one sheet per tab, forks a sheet, moves ticked rows under a column mapping, and confirms a reload or an overwrite when the file changed on disk. |-| ✅ **A sheet into the case, both ways** | Promotes a declared sheet into entities, places, bookmarks, vocabularies, row edges and dated Claims in one transaction, read as a plan first, and builds a worklist back out of what the case holds. |+| ✅ **A sheet into the case, both ways** | Promotes a declared sheet into entities, places, vocabularies, row edges and dated Claims in one planned transaction, and builds a worklist back out of the case. || ✅ **Geolocation index** | Lays the case's proofs out one per row with their media, place and coordinates, and builds one proof per row back out of two address columns and a coordinate column, as a stoppable job. |-| ✅ **Imported proofs** | Turns a published post into a composed proof: every picture a panel, its text read for a position, the addresses it points at fetched as material, and nothing filed before the preview is approved. |+| ✅ **Imported proofs** | Turns a published post into a composed proof, every picture a panel and its text read for a position, with nothing filed before the preview is approved. || ✅ **Import origin** | States one origin for a whole import, offers it to a batch that landed without one, and corrects any file later from Details. || ✅ **Drawing on a proof** | Stamps a fixed set of marks, fills boxes and ellipses at a chosen opacity, keeps every shape tool in hand, and recolours, restyles, nudges, drags or deletes a picked family at once. || ✅ **Proof image transforms** | Turns or crops a panel or proof-owned overlay without changing its source, while keeping attached annotations on the same pixels. |-| ✅ **A proof of several points** | States every place a proof argues — each panel's own included, none of them overwritten — optionally named, one of them the camera's, any of them moved on a map rather than typed; files them as places under one title and carries them into the tweet and onto the exported picture. |-| ✅ **What a proof says about itself** | Carries an optional sentence, which is its notes and what a post is written from, and an optional date for when its material was taken — never pre-filled, cleared in one press, and shown on the Timeline. |-| ✅ **A date that reaches the footage** | A dated proof states that date for the sources it rests on — the original, never the frame cut from it or a capture — as one cited statement per proof, restated on every save and never written over the file's own clock. |+| ✅ **A proof of several points** | States every place a proof argues, each optionally named and moved on a map, files them under one title and carries them into the post and the exported picture. |+| ✅ **What a proof says about itself** | Carries an optional sentence, which is its notes and what a post is written from, and an optional date for its material, never pre-filled and shown on the Timeline. |+| ✅ **A date that reaches the footage** | A dated proof states that date for the original sources it rests on, as one cited statement restated on every save and never written over the file's own clock. |### v3 GEOINT expansion (shipped as GitHub `v0.3.0+`)@@ -170,18 +170,18 @@ proof for publication.| ✅ **Map engine** | Draws the map on MapLibre GL behind the `lib/map` façade, with the same providers, captures and bearing. || ✅ **Map chrome** | Puts modes in one rail, map layers in their tool panel or popup, imagery in the map corner and position in a status line, each tool declared once. || ✅ **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, opens it in the other map tabs, 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, place names, 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. |-| ✅ **Added map layers** | Opens a KML, KMZ, GeoJSON or GPX file, or follows a public My Maps or map URL refreshed only while enabled, and draws it with its own colours, optionally its own icons composed once at import, a legend that filters and a search that goes to one feature — read, cited and never adopted into the case. |+| ✅ **Map windows** | Opens the map in several tabs with the view in the URL, links them and extension panels to one camera, and syncs saved points, grids and sweeps live. |+| ✅ **Map layers** | Stacks key-less overlays (borders, place names, roads, railways, power lines, sea marks, GPS traces), FIRMS fires and VIIRS night lights, and filters pins by kind and folder. |+| ✅ **Added map layers** | Draws a KML, KMZ, GeoJSON or GPX file or a public My Maps URL in its own colours and icons, with a legend that filters, cited but never adopted into the case. || ✅ **Added layer rows** | Folds each row to one line with icon acts, drags the rows into the order the map stacks them and refreshes every followed layer at once. || ✅ **Dates on a layer** | Narrows a dated added layer (GeoConfirmed, KML timestamps, GPX waypoints) to a period dragged on a strip of its events over time or picked on a calendar, kept with the legend. |-| ✅ **GeoConfirmed layer** | Adds one GeoConfirmed conflict over a window of days or dates or its whole history, optionally only the view, in GeoConfirmed's own icons, grouped by faction with each event's sources and geolocation one click away. |-| ✅ **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. |+| ✅ **GeoConfirmed layer** | Adds one GeoConfirmed conflict over a window of days or its whole history, in its own icons, grouped by faction with each event's sources one click away. |+| ✅ **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. || ✅ **Imagery Wayback** | Browses every Esri World Imagery release, narrowed on request 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. || ✅ **Detect sweep** | Native Sentinel-2 detectors, mask footprints, manual candidates and Keep / Dismiss / Pin review with PNG evidence stamped with its dates and point. |-| ✅ **Passes over an area** | Picks Detect's Copernicus dates from the passes the drawn areas really have, up to a year back or between two days picked in a calendar, 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, 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. |+| ✅ **Passes over an area** | Picks Detect's Copernicus dates from the passes the drawn areas really have, each with the share its swath reached, and reports what a finished run swept. |+| ✅ **Cloud & shadow filter** | One click in Difference and Detect on Sentinel-2's scene classification, taking unsure edges, dropping cloud specks and masking shadows cast away from the sun. || ✅ **Difference over any view** | A switch beside Compare's four views, offered on a matched pair only, laying its highlights on A, B or both (the default). || ✅ **Detect** | Map-first tab, resizable dock, shared case areas in ordered groups, live A/B preview with per-area dates, one-off and routine runs grouped in Saved, repeat notices and explicit SAT layer snapshots. || ✅ **Capture scale & north** | Adds a scale bar and true-north needle to app and extension captures when resolution and heading are known. |@@ -194,32 +194,32 @@ proof for publication.| ✅ **Compare from the ground** | Right-clicking a point opens Compare on the last two Esri Wayback pictures of it, its last two Copernicus passes, or its last two radar passes of one track. || ✅ **Marks that number and hide** | Stamps numbered markers counting a series per colour, and blur boxes that redraw the picture under them, on a proof's panels and on a comparison's ground alike. || ✅ **A date in one field** | Reads a day, a month, a year, a time or a range from one line of text, or builds one from a calendar with its marks of doubt, and says what it understood. |-| ✅ **Words that hold still** | One name for a Claim on every surface, a tooltip on every icon, a stated reason on a layer that cannot be switched on, the recent work first on Home, and Coords & Sky opening on the point the map is on. |+| ✅ **Words that hold still** | One name for a Claim everywhere, a tooltip on every icon, a reason on a layer that cannot be switched on, and recent work first on Home. || ✅ **A picture sent to Reverse Search** | Opens Reverse Search on a Media Library file, from a row's Open in… menu, or on an Inspect frame as it is cropped, saved or not. |-| ✅ **Add event from anywhere** | One line for an event under the Timeline axis, atop Details and over any tool (Alt+N), with `@` mentions that can file a new subject, what the tool shows already cited, and a date only the analyst gives. |+| ✅ **Add event from anywhere** | One line for an event under the Timeline axis, atop Details and over any tool (Alt+N), with `@` mentions, the tool's view already cited, and a date only the analyst gives. || ✅ **Radar Detect** | Five Sentinel-1 analyzers (vessels, any change, razed buildings, new structures, floods) through the user's own radar layer, calibrated on real scenes, held to one track. || ✅ **Sentinel-1 basemap** | Radar passes as a dated basemap in Satellite, Compare and Detect, named by day, UTC time and direction. || ✅ **All dates** | Lists every dated picture of the point in Compare, oldest first, to set on either side. || ✅ **Copernicus where it is needed** | Detect and Compare say in the middle of the tool what Copernicus still lacks, with the free account, the Sentinel-2 configuration and the Sentinel-1 layer form field by field. || ✅ **A candidate in Compare** | Opens a Detect candidate in Compare on the passes that found it, or against high-resolution imagery for a thing present on one pass. |-| ✅ **Sizes in Detect** | Right-clicks Detect's map for its own point menu, measures a hull with a ruler, sizes each candidate along its footprint, walks the largest first, and hides the drawing or blinks A against B from the review. |-| ✅ **Analyzers of your own** | Builds a Detect analyzer for one satellite and one date or two, fixed when it is made, from up to six rules on any band, index, ground class or radar polarisation, read before, after or as the change; proved on checks made on the map (two passes on a split map and pins), tested on the ground under the pins with its cost said first, each rule painted and its effect on the pins read; five calibrated examples ship with theirs; also opened from a built-in or a Difference reading, with a shape filter for every analyzer. |-| ✅ **Examine: Inspect and Collage** | Keeps one work per file, saved as it is made, with its frames on a strip; lays collages out of frames and images from any file, listed as cards with a preview and exported at full resolution; merges a case's 0.3.0 sessions on open. |+| ✅ **Sizes in Detect** | Right-clicks Detect's map for its point menu, sizes each candidate along its footprint, walks the largest first, and blinks A against B from the review. |+| ✅ **Analyzers of your own** | Builds a Detect analyzer for one satellite from up to six rules on any band, index, ground class or radar polarisation, proved on checks drawn on the map; five calibrated examples ship. |+| ✅ **Examine: Inspect and Collage** | Keeps one autosaved work per file with its frames on a strip, lays collages out of any file's frames and images, and merges a case's 0.3.0 sessions on open. || ✅ **One camera for the map tabs** | Satellite, Compare and Detect show the same ground, and the link carries it to other windows; a Detect review keeps its own, and Settings turns it off. |-| ✅ **Comparisons in Saved work** | A saved comparison stands on the map with the captures, at its frame's centre with the frame outlined, dated A → B, and reopens in Compare; an export can also be kept in the case under it. |-| ✅ **Dated pins and pictures** | A kept Detect candidate files a claim at its pin (a change between two passes, or a thing seen on one); comparisons and pinned evidence carry each picture's date, estimates marked; Detect layers filter a change by its span; exports are named by their pictures' dates. |-| ✅ **An evolution of one point** | Exports Sentinel-2 passes or Wayback pictures ticked by hand on their previews, back to 2015, as one GIF or one sheet drawn from the tile proxy on the same ground, repeats and empty pictures left out and counted. |+| ✅ **Comparisons in Saved work** | A saved comparison stands on the map with the captures, its frame outlined and dated A → B, and reopens in Compare; an export can be kept under it. |+| ✅ **Dated pins and pictures** | A kept Detect candidate files a claim at its pin, comparisons and pinned evidence carry each picture's date, and exports are named by their pictures' dates. |+| ✅ **An evolution of one point** | Exports hand-ticked Sentinel-2 passes or Wayback pictures, back to 2015, as one GIF or one sheet on the same ground, empty pictures left out and counted. || ✅ **Signed exports, marks in their colours** | Compare exports close their credits line with the Azimut logo and name unless unticked, and a GIF keeps every mark's colour exact. |-| ✅ **One turn on every map** | A middle-drag turns any map or Inspect frame like a wheel about the grabbed point, settling on north, in 15° steps with Ctrl; a middle click or Shift+↑ puts north back, Shift+← / → steps. |+| ✅ **One turn on every map** | A middle-drag turns any map or Inspect frame about the grabbed point, settling on north, in 15° steps with Ctrl; a middle click or Shift+↑ puts north back. || ✅ **Checked proof points** | A proof point taken from a capture's centre reads greyed until checked; Save and To post show each one on the map first, and one saved for later stays off the case map. || ✅ **Compare and Detect full screen** | Both take the whole screen with their bars and panel, as Satellite does, and any change of tab gives it back. |-| ✅ **A Timeline that reads at a glance** | A point is an instant, a bracket a date known to the day, month or year, a bar a period; it opens on the files where the analyst dated them over the events, imagery on a lane of its own, on the clock of the case's places, under one bar; reads axis and list as one, copies out as a table, and shows the file an entry is about. |-| ✅ **Names in any script** | Search folds case and accents in Latin, Greek and Cyrillic and vowel marks in Arabic and Hebrew, reads month names in the browser's languages, and keeps right-to-left text in its own direction. |+| ✅ **A Timeline that reads at a glance** | A point is an instant, a bracket a date known to the day, month or year, a bar a period, with imagery on its own lane and axis and list read as one. |+| ✅ **Names in any script** | Search folds case and accents in Latin, Greek and Cyrillic and vowel marks in Arabic and Hebrew, and keeps right-to-left text in its own direction. || ✅ **Subjects corrected safely** | Changes a subject's type without losing a field or a link, and merges two duplicates with a preview, redirects for the absorbed id and an Undo. |-| ✅ **The Board as an index** | Groups the case by family, people, places and things first with how many events name each and when, the files folded under; Most noted first, Details beside the list, walked with the arrow keys. |+| ✅ **The Board as an index** | Groups the case by family, people, places and things first, with how many events name each and when, files folded under and Details beside the list. || ✅ **Every date on a clock** | One Clock chip wherever a date is typed: a day or a time reads on its place's zone, UTC, this computer or any zone in the world, and the Timeline spans that zone's day. |-| ✅ **Dates in posts, better templates** | A `#date` token carries the proof's date into a post only where a template asks; templates start from a layout, duplicate, preview on the open post with each platform's count, flag a misspelled token and set the default. |-| ✅ **A work folder, and Files that acts** | New files and saved work land in the folder being worked in; folders rename with their items and files; Files and the sidebar act on a right-click, Files filters by type or by what is linked to nothing, and the sidebar also shows the case's to-do lists and recent work. |+| ✅ **Dates in posts, better templates** | A `#date` token carries the proof's date into a post where a template asks; templates start from a layout, preview on the open post and flag a misspelled token. |+| ✅ **A work folder, and Files that acts** | New files and saved work land in the folder being worked in, Files and the sidebar act on a right-click, and Files filters by type or by what is linked to nothing. || ✅ **Links the case proposes** | Proposes the account a post's address names and joins points under 300 m apart as one site, reviewed in one list from the Graph; a dropped proposal does not come back. || ✅ **A Sheet home** | The Sheet tab opens on the recent sheets and the ones the case could start, counted; Close saves and comes back to it; a status chip opens its words. || ✅ **Files to geolocate** | One row per imported picture or video, done once a proof answers it, opened from the Sheet home or the Media Library and kept level by Refresh. |@@ -381,8 +381,9 @@ stops making sense.decimal degrees + metres on disk.- **Distribution:** `pip install azimut` plus PyInstaller single-file binariesfor Windows x86_64, Linux x86_64 and Apple Silicon macOS. Binaries bundle a- static ffmpeg/ffprobe; pip installs still want ffmpeg on `PATH`. Intel macOS- uses the Python package.+ static ffmpeg/ffprobe with its licence notice and texts (Settings → System →+ licence); pip installs still want ffmpeg on `PATH`. Intel macOS uses the Python+ package.- **Dependencies:** ranges in `pyproject.toml`, exact pins in `uv.lock`; yt-dlp+ gallery-dl unbounded on purpose; scraper self-update keeps an old binary useful.- **Storage:** per-case SQLite `case.db` is the authoritative graph (files for@@ -421,7 +422,10 @@ stops making sense.one fixed workspace path and takes nothing off the request — no path, nopayload — so it sits on the settings router rather than in the ingest island,where the extension-origin CORS would have reached it; the message that then- restarts the extension is only reachable from the app's own localhost page,+ restarts the extension is only reachable from the page on the port the extension+ is paired with (any other localhost port is refused, told which address to set,+ and may only ask which copy is loaded; hand-offs open only the posting sites and+ image engines the app offers),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 — one position's points without theirdiff --git a/docs/STORAGE_AND_PERFORMANCE.md b/docs/STORAGE_AND_PERFORMANCE.mdindex ef4cf69..ba24a2c 100644--- a/docs/STORAGE_AND_PERFORMANCE.md+++ b/docs/STORAGE_AND_PERFORMANCE.md@@ -511,7 +511,9 @@ after each hash matches. There is no small fixed case-size cap: preview andimport compare the required temporary space with current filesystem capacity,keep a safety reserve, and warn for imports above 10 GiB. Work is staged under`<workspace>/<id>.incoming/`; the existing shell and completed staging directory are-swapped by rename for Windows compatibility. Every import creates a new case and+swapped by rename for Windows compatibility. Both carry an `.azimut-importing` mark+until the swap, so the switcher leaves them out and the next start removes any a+crash left behind. Every import creates a new case andrecords `origin_case_id` plus `imported_at` in database metadata.Entities, links and entity photo galleries keep their original ids and state.diff --git a/docs/UI.md b/docs/UI.mdindex 50a36d7..d9c02ff 100644--- a/docs/UI.md+++ b/docs/UI.md@@ -2206,7 +2206,7 @@ ground. Between two moves the field is yours — what you typed, or the point yopicked out of the case, stands.The saved-work layer answers two questions under its own switch: **what kind**-(all, places, captures, proofs, media) and **which folder**, offered only where the+(Media, Places or Captures) and **which folder**, offered only where thecase has more than one to choose between. They are the Saved panel's ownfilter, so a map read here and the panel beside it can never disagree aboutwhat the case holds, and the layer's count is what is drawn rather than what is@@ -2218,11 +2218,7 @@ files as white-ringed ones, items at the same spot collapseinto one counted mark, and clicking a mark of saved work opens a cardwith its preview, provider, dates and note. A mark of files has no card: it playsthem in the panel. A mark whose capture carries proofs-wears a dot up-left; its card names the count and offers **Show proofs**, which-switches the panel and the layer to the proofs view. In that view the card opens-the proof in Geo Proof and lists the saved posts written from it. Two post titles-fit directly in the card; additional posts expand in place, and selecting one-opens its draft in Geo Report. Hovering a card, a tree row or a search result+wears a dot up-left, and its card names the count. Hovering a card, a tree row or a search resultlights the others.A card also holds the point's relations. The Saved index carries their count only,@@ -2231,7 +2227,7 @@ straight away — clicking a place to see which photos claim it is the point ofgesture — and a stack waits to be asked. A point enrichment proposed from a file'smetadata is marked `suggested` in both the card and the tree, so a camera's readingnever passes for analyst work. The Save-place dialog carries the matching write:-one **Relate to…** field says why the point is being saved while the analyst still+one **Relations** field says why the point is being saved while the analyst stillknows.**A place's card traces its footprint.** A pin dropped on a guess is what this@@ -2249,7 +2245,7 @@ a radius typed back over a traced shape asks in Details before dropping it: themap draws one of the two, so a place states its precision once.**The place dialog hands over to the full editor.** Title, folder, note and-*Relate to…* are what an analyst fills at the moment of saving; how precise the+*Relations* are what an analyst fills at the moment of saving; how precise thepoint is, the source's own wording and how the point was found are edited in thepanel every other surface opens. **Edit more details** on an existing place opensthat panel — the same body as the case sidebar — and asks first if the short form@@ -2677,8 +2673,8 @@ or **Two dates**. That is fixed for good, so its rules and checks always fit it:the builder shows it as a locked chip, offers only the measures and dates thatfit, and another satellite or number of dates is a new analyzer. A saved onethat never declared it gets it from its rules, once. The same screen offers-**Blank**, with one rule to begin with, and the ready examples that read the-same thing: a fresh burn (Lahaina, August 2023), a forest cleared (Grünheide,+**Blank**, starting on brightness in True colour for optical data, and the ready+examples that read the same thing: a fresh burn (Lahaina, August 2023), a forest cleared (Grünheide,2019 → 2020), water drained (the Kakhovka reservoir, June 2023) and a solar farmbuilt (Dubai, 2019 → 2023) on two dates, ships at anchor (Fujairah, one pass) onone, each with its checks. A press copies an example into the library at once,@@ -2697,7 +2693,8 @@ Over the rules a strip names the check on the map, says how it last came out andcarries **Test**. A rule reads as the sentence it says (*NDVI dropped by 0.25 ormore*); its dot carries its number and its map colour and hides or shows itspixels, and ★ ranks the candidates by it. A rule names a quantity, when it is-read, and the line. The quantity is one of the six indices, **My index** (a+read, and the line; its data label names the bands or classification it reads.+The quantity is one of the six indices, **My index** (anormalised difference of any two Level-2A bands, with NDMI, NDSI, NDRE, NBR2 andGNDVI one pick away), one band's reflectance, brightness, a colour change,Sentinel-2's own ground class, or radar backscatter in VV, VH or VV − VH. On two@@ -2724,8 +2721,16 @@ passes: the before pass on the left and the after pass on the right, each on itsown map with the two cameras held together and a handle to drag the cut, and**Before**, **Split** and **After** switch between the whole map on one and thecut. A check of one date shows its pass on one map. An eye puts the basemap in-the passes' place and back, and the layer menu picks the Copernicus layer they-are shown in, with the one that reads rule ★ best marked.+the passes' place and back. **Display** picks their Copernicus layer, with the+one that reads rule ★ best marked; it changes the picture, not the rule's bands.+Opening or selecting a check verifies the configuration's layers, without a+network check on builder mount. The menu shows their actual IDs, including+`VEGETATION_INDEX` where that is the configured NDVI display. Missing products+stay grey with a reason. The menu offers **Refresh layers** and setup instructions;+the same help appears in Settings → Imagery. A saved display resolves to its configured alias+or an available display, with a notice. If verification fails, the basemap+stays on. Tile errors on either pass name the layer and date and offer+**Retry imagery** or **Use basemap**.**Checks** are how an analyzer is proved, and one is needed to save it, with apin where something should be found; the others may be traps, where nothing maydiff --git a/extension/background.js b/extension/background.jsindex 8f271dd..7948f69 100644--- a/extension/background.js+++ b/extension/background.js@@ -17,6 +17,51 @@ const api = typeof browser !== "undefined" ? browser : chrome;const APP_ORIGINS = ["http://127.0.0.1", "http://localhost"];const isAppUrl = (url) => APP_ORIGINS.some((o) => url === o || url?.startsWith(o + ":") || url?.startsWith(o + "/"));+/**+ * Whether a tab is the paired Azimut, not merely something on localhost.+ *+ * The bridge runs on every loopback port, so a dev server or any other local page+ * can post to it. The routes that open tabs, capture the screen or stream case files+ * answer only the page served from the port this extension is paired with.+ * `localhost` and `127.0.0.1` are the same machine, so either name passes.+ */+async function isPairedApp(url) {+ if (!isAppUrl(url)) return false;+ const { backendUrl } = await settings();+ try {+ const tab = new URL(url);+ const app = new URL(backendUrl);+ return isAppUrl(app.origin) && tab.port === app.port && tab.protocol === app.protocol;+ } catch {+ return false;+ }+}++/**+ * Why a tab may not use the routes only the app may ask for, or null when it may.+ *+ * A loopback page on another port is most often this same Azimut, started while+ * another program held its port and moved to the next free one. "Not the app" would+ * leave the analyst nowhere, so the answer says what to change.+ */+async function notTheApp(tab) {+ if (!tab || !isAppUrl(tab.url)) return "not the Azimut app";+ if (await isPairedApp(tab.url)) return null;+ return `this extension is paired with another address. In its options, set the Azimut URL to ${new URL(tab.url).origin}`;+}++// Where the app's hand-offs may take a tab: the posting sites and the reverse image+// engines it offers. Anything else in a hand-off is refused, whoever asked.+const HANDOFF_HOSTS = new Set(["x.com", "bsky.app", "lens.google.com", "yandex.com", "www.bing.com", "tineye.com"]);+const handOffAllowed = (url) => {+ try {+ const parsed = new URL(url);+ return parsed.protocol === "https:" && HANDOFF_HOSTS.has(parsed.hostname);+ } catch {+ return false;+ }+};+function settings() {return api.storage.local.get({ backendUrl: "http://127.0.0.1:8477", token: "", lastCaseId: "" })@@ -212,6 +257,7 @@ function tabLoaded(tabId, timeoutMs = 20000) {async function handOff(payload) {const { backendUrl, token } = await settings();if (!token) throw new Error("not paired");+ if (!handOffAllowed(payload.url)) throw new Error("not a site Azimut posts to");fillComposer(payload, backendUrl, token).catch((e) =>notify("Azimut hand-off", `${e.message} The thread is on your clipboard.`));@@ -300,6 +346,7 @@ async function handOffReverse(payload) {if (!image.data) throw new Error("no image");if (image.data.length > MAX_REVERSE_DATA) throw new Error("that image is too large to hand over");if (!payload.url) throw new Error("no engine");+ if (!handOffAllowed(payload.url)) throw new Error("not an engine Azimut searches with");fillEngine(payload.url, image).catch((e) => {if (!LEFT.test(e.message || "")) trouble(e.message);});@@ -1101,7 +1148,8 @@ async function handle(msg, sender) {// frame — the app does its own registration, cropping and filing. Only the// app's localhost origin may ask for it.if (msg.type === "capture-tab") {- if (!sender.tab || !isAppUrl(sender.tab.url)) return { ok: false, error: "not the Azimut app" };+ const refused = await notTheApp(sender.tab);+ if (refused) return { ok: false, error: refused };try {const dataUrl = await withoutPanel(sender.tab.id, () => captureActiveTab(sender.tab.windowId));return { ok: true, dataUrl };@@ -1148,7 +1196,8 @@ async function handle(msg, sender) {// The app's Publish button, relayed by bridge.js: open the composer and fill// the thread. Same origin check as the capture route — only the app may ask.if (msg.type === "post-handoff") {- if (!sender.tab || !isAppUrl(sender.tab.url)) return { ok: false, error: "not the Azimut app" };+ const refused = await notTheApp(sender.tab);+ if (refused) return { ok: false, error: refused };try {return await handOff(msg.payload ?? {});} catch (e) {@@ -1159,7 +1208,8 @@ async function handle(msg, sender) {// The app's Reverse Search buttons, relayed by bridge.js: open the engine and// give it the image. Same origin check as every other app route.if (msg.type === "reverse-handoff") {- if (!sender.tab || !isAppUrl(sender.tab.url)) return { ok: false, error: "not the Azimut app" };+ const refused = await notTheApp(sender.tab);+ if (refused) return { ok: false, error: refused };try {return await handOffReverse(msg.payload ?? {});} catch (e) {@@ -1207,13 +1257,16 @@ async function handle(msg, sender) {}}- // Settings asking what this copy is: the version the browser parsed, and the- // folder stamp this code was loaded from. Only the app's own origin may ask —- // same rule as every other route relayed by the bridge.+ // Settings asking what this copy is: the version the browser parsed, the folder+ // stamp this code was loaded from, and whether the asking tab is the address this+ // copy is paired with. Identification only, so any loopback page may ask: an app+ // that moved to a free port must still find its extension, and be told why it+ // refuses to act for it.if (msg.type === "ext-state") {if (!sender.tab || !isAppUrl(sender.tab.url)) return { ok: false, error: "not the Azimut app" };return {ok: true,+ paired: await isPairedApp(sender.tab.url),version: api.runtime.getManifest().version,// Not `id`: the bridge spreads this answer next to the message's own// correlation id, and a collision there would break the pairing silently.@@ -1231,7 +1284,8 @@ async function handle(msg, sender) {// holding a rejected port. And the reply is only "taken", never "worked": what// proves the code moved is the stamp read back afterwards.if (msg.type === "ext-reload") {- if (!sender.tab || !isAppUrl(sender.tab.url)) return { ok: false, error: "not the Azimut app" };+ const refused = await notTheApp(sender.tab);+ if (refused) return { ok: false, error: refused };const stamp = await loadedStamp();// Two copies of this extension can be loaded at once on Chrome, which// derives the extension id from the folder path (see the app's Settingsdiff --git a/extension/mapref.js b/extension/mapref.jsindex 071a1ea..d3c2fa3 100644--- a/extension/mapref.js+++ b/extension/mapref.js@@ -623,7 +623,7 @@const total = answer.total ?? picker.items.length;picker.hint.textContent =total > picker.items.length- ? `${picker.items.length} of ${total} — search to narrow it down`+ ? `${picker.items.length} of ${total}. Search to narrow it down`: `${total} file${total === 1 ? "" : "s"}`;paintThumbs();}diff --git a/extension/maptools.js b/extension/maptools.jsindex 1d18aeb..e5be1a2 100644--- a/extension/maptools.js+++ b/extension/maptools.js@@ -1120,11 +1120,11 @@if (drawing === "polygon") {return vertices.length < 3? `Click the corners of the area (${vertices.length})`- : `${vertices.length} corners — close the shape when it fits`;+ : `${vertices.length} corners. Close the shape when it fits`;}if (!grid) return "No grid open";const seen = coverage(grid);- if (marking) return `${seen.percent}% swept — click cells to mark them`;+ if (marking) return `${seen.percent}% swept. Click cells to mark them`;return `${seen.percent}% swept · ${seen.cleared} cleared · ${seen.flagged} flagged`;},};diff --git a/extension/popup.js b/extension/popup.jsindex 852fcf5..38a98e6 100644--- a/extension/popup.js+++ b/extension/popup.js@@ -28,6 +28,32 @@ const numOrNull = (id) => {return Number.isFinite(v) ? v : null;};+// The ranges the app accepts, checked here where the field can still be fixed: past+// this the server answers with a list of objects no message can be made of.+const RANGES = {+ lat: [-90, 90, "Latitude runs from -90 to 90."],+ lon: [-180, 180, "Longitude runs from -180 to 180."],+ zoom: [0, 23, "Zoom runs from 0 to 23."],+ bearing: [0, 359.999, "Bearing runs from 0 to 359."],+};++const outOfRange = () => {+ for (const [id, [low, high, said]] of Object.entries(RANGES)) {+ const v = numOrNull(id);+ if (v !== null && (v < low || v > high)) return said;+ }+ return "";+};++// What the app said, as one line: a refusal is a sentence, a schema rejection was a+// list of objects, and `new Error(list)` printed "[object Object]".+const reason = async (r) => {+ const detail = (await r.json().catch(() => ({}))).detail;+ if (typeof detail === "string" && detail) return detail;+ if (Array.isArray(detail)) return detail.map((item) => item?.msg || "").filter(Boolean).join("; ") || `HTTP ${r.status}`;+ return `HTTP ${r.status}`;+};+const origin = (url) => {try {return new URL(url).origin;@@ -169,7 +195,7 @@ async function init() {headers: { "X-Azimut-Token": stored.token },body,});- if (!r.ok) throw new Error((await r.json().catch(() => ({}))).detail || `HTTP ${r.status}`);+ if (!r.ok) throw new Error(await reason(r));status("Bookmark saved.", "ok");setTimeout(() => window.close(), 700);} catch (e) {@@ -220,6 +246,11 @@ async function init() {syncPlaceButton();placeBtn.addEventListener("click", async () => {+ const wrong = outOfRange();+ if (wrong) {+ status(wrong, "error");+ return;+ }placeBtn.disabled = true;const body = new FormData();body.append("url", tab.url);@@ -236,7 +267,7 @@ async function init() {headers: { "X-Azimut-Token": stored.token },body,});- if (!r.ok) throw new Error((await r.json().catch(() => ({}))).detail || `HTTP ${r.status}`);+ if (!r.ok) throw new Error(await reason(r));// reuse whatever case this landed in, including a freshly minted scratchconst saved = await r.json().catch(() => ({}));if (saved.case_id) api.storage.local.set({ lastCaseId: saved.case_id });@@ -257,6 +288,10 @@ async function init() {status("Latitude and longitude go together. Fill both or neither.", "error");return;}+ if (outOfRange()) {+ status(outOfRange(), "error");+ return;+ }const r = await api.runtime.sendMessage({type: "start-area-select",tabId: tab.id,diff --git a/frontend/e2e/bundle-trash.spec.js b/frontend/e2e/bundle-trash.spec.jsindex 0054798..735031c 100644--- a/frontend/e2e/bundle-trash.spec.js+++ b/frontend/e2e/bundle-trash.spec.js@@ -3,7 +3,7 @@ import { CASE_ID, installAppFixture } from './app.fixture.js';test('keeps a failed export visible after its dialog closes', async ({ page }) => {const fixture = await installAppFixture(page, {- bundleJob: { state: 'failed', error: 'Export failed safely' },+ bundleJob: { state: 'failed', error: 'the disk is full' },});await page.goto('/#files');@@ -11,7 +11,8 @@ test('keeps a failed export visible after its dialog closes', async ({ page }) =await page.getByRole('button', { name: 'Export this case…' }).click();await page.getByRole('button', { name: 'Export', exact: true }).click();- await expect(page.getByText('Export failed safely', { exact: true })).toBeVisible();+ // The job's error is a clause; the toast says what it stopped.+ await expect(page.getByText('Could not export the case: the disk is full', { exact: true })).toBeVisible();await expect(page.getByRole('heading', { name: 'Export case' })).toHaveCount(0);expect(fixture.bundleCalls.map((call) => call.kind)).toEqual(['export', 'job']);fixture.expectNoUnexpectedRequests();diff --git a/frontend/e2e/detect.spec.js b/frontend/e2e/detect.spec.jsindex 23dca7f..18358d3 100644--- a/frontend/e2e/detect.spec.js+++ b/frontend/e2e/detect.spec.js@@ -422,7 +422,8 @@ async function answerBuilder(page) {log.lookups.push(route.request().postDataJSON());return route.fulfill({ json: { dates: [{ date: '2026-09-10', cloud: 4, coverage: 1 }, { date: '2026-09-01', cloud: 2, coverage: 1 }], truncated: false } });});- await page.route('**/api/satellite/sentinel/layers', (route) => route.fulfill({ json: { source: 'catalogue', layers: [+ await page.route('**/api/satellite/sentinel/layers**', (route) => route.fulfill({ json: {+ source: new URL(route.request().url()).searchParams.get('check') === 'true' ? 'instance' : 'catalogue', layers: [{ id: 'TRUE_COLOR', label: 'True colour' }, { id: 'FALSE_COLOR', label: 'False colour (infrared)' },{ id: 'SWIR', label: 'SWIR (short-wave infrared)' }, { id: 'NDVI', label: 'NDVI (vegetation index)' }] } }));await page.route('**/api/compare/analyzers/check/plan', (route) => {@@ -500,6 +501,8 @@ test('an analyzer of your own is proved on a check made on the map: two passes,await page.getByRole('button', { name: /^Blank/ }).click();await expect(page.getByRole('heading', { name: 'Build an analyzer' })).toBeVisible();await expect(page.locator('.reads')).toHaveText('Sentinel-2 · two dates');+ await expect(page.getByLabel('Rule 1 measures')).toHaveValue('brightness');+ await page.getByLabel('Rule 1 measures').selectOption('index');await page.getByRole('button', { name: 'Add a rule', exact: true }).click();await expect(page.getByLabel('Rule 2 says')).toHaveText('NDVI before is at least 0.40');// nothing has been asked of Copernicus, and there is no check to test on@@ -670,7 +673,8 @@ test('an analyzer of one date is tried on one map, with no split and no before oawait page.getByRole('group', { name: 'Dates' }).getByRole('button', { name: 'One date' }).click();await page.getByRole('button', { name: /^Blank/ }).click();await expect(page.locator('.reads')).toHaveText('Sentinel-2 · one date');- await expect(page.getByLabel('Rule 1 says')).toHaveText('NDVI is at least 0.40');+ await expect(page.getByLabel('Rule 1 measures')).toHaveValue('brightness');+ await expect(page.getByLabel('Rule 1 says')).toContainText('brightness is at least');await expect(page.getByLabel('Rule 1 reads')).toHaveCount(0);const deck = page.locator('.console');@@ -686,6 +690,125 @@ test('an analyzer of one date is tried on one map, with no split and no before oexpect(errors).toEqual([]);});+test('check displays use verified configuration layers and grey missing products with setup help', async ({ page }) => {+ const { errors } = await openDetect(page);+ await answerBuilder(page);+ const checks = [], tiles = [];+ await page.route('**/api/satellite/sentinel/layers**', (route) => {+ const checked = new URL(route.request().url()).searchParams.get('check') === 'true';+ if (checked) checks.push(route.request().url());+ return route.fulfill({ json: { source: checked ? 'instance' : 'catalogue', layers: checked+ ? [{ id: 'TRUE_COLOR', label: 'True colour' }, { id: 'VEGETATION_INDEX', label: 'Vegetation Index - NDVI' }]+ : [{ id: 'TRUE_COLOR', label: 'True colour' }, { id: 'NDVI', label: 'NDVI' }] } });+ });+ page.on('request', (request) => {+ const path = new URL(request.url()).pathname;+ if (path.startsWith('/api/tiles/sentinel2')) tiles.push(path);+ });+ await page.getByRole('button', { name: 'Analyzers', exact: true }).click();+ await page.getByRole('button', { name: 'New analyzer', exact: true }).click();+ await page.getByRole('button', { name: /^Blank/ }).click();+ await expect(page.getByLabel('Rule 1 measures')).toHaveValue('brightness');+ await expect(page.getByLabel('Rule 1 data')).toHaveText('Sentinel-2 bands · B02 · B03 · B04');+ expect(checks).toHaveLength(0);+ expect(tiles).toHaveLength(0);+ const deck = page.getByRole('region', { name: 'Checks on the map' });+ await deck.getByRole('button', { name: 'New check' }).click();+ await expect.poll(() => checks.length).toBe(1);+ await deck.getByRole('button', { name: 'Find passes', exact: true }).click();+ await page.getByLabel('Use 2026-09-01').getByRole('button', { name: 'Before', exact: true }).click();+ await page.getByLabel('Use 2026-09-10').getByRole('button', { name: 'After', exact: true }).click();+ await deck.getByRole('button', { name: 'Place the pins' }).click();+ await expect.poll(() => tiles.some((path) => path.includes('~TRUE_COLOR~2026-09-01'))).toBe(true);+ await expect.poll(() => tiles.some((path) => path.includes('~TRUE_COLOR~2026-09-10'))).toBe(true);+ await deck.getByRole('button', { name: 'Copernicus layer', exact: true }).click();+ const menu = page.getByRole('menu', { name: 'Copernicus layer' });+ const swir = menu.getByRole('menuitemradio', { name: /^SWIR/ });+ await expect(swir).toBeDisabled();+ await expect(swir).toContainText('Not in your Copernicus configuration.');+ await menu.getByText('Set up Copernicus layers', { exact: true }).click();+ await expect(menu.getByRole('link', { name: 'Configuration Utility', exact: true })).toBeVisible();+ await menu.getByRole('menuitemradio', { name: /VEGETATION_INDEX/ }).click();+ await expect.poll(() => tiles.some((path) => path.includes('~VEGETATION_INDEX~'))).toBe(true);+ expect(tiles.some((path) => path.includes('~NDVI~'))).toBe(false);+ await expect(page.getByLabel('Rule 1 measures')).toHaveValue('brightness');+ await deck.getByRole('button', { name: 'Copernicus layer', exact: true }).click();+ await page.getByRole('menu', { name: 'Copernicus layer' }).getByRole('button', { name: 'Refresh layers', exact: true }).click();+ await expect.poll(() => checks.length).toBe(2);+ for (const width of ['Home', 'End']) {+ await page.getByRole('button', { name: 'Resize Detect panel' }).focus();+ await page.keyboard.press(width);+ await expect.poll(async () => {+ const menuBox = await menu.boundingBox();+ const mapBox = await page.locator('.detect-tool .map').first().boundingBox();+ return menuBox.x >= mapBox.x && menuBox.x + menuBox.width <= mapBox.x + mapBox.width;+ }).toBe(true);+ }+ await page.screenshot({ path: test.info().outputPath('verified-check-layers.png') });+ expect(errors).toEqual([]);+});++test('a failed layer check keeps the basemap and explains how to recover', async ({ page }) => {+ const { errors } = await openDetect(page);+ await answerBuilder(page);+ await page.route('**/api/satellite/sentinel/layers**', (route) => route.fulfill({ json: {+ source: 'catalogue', layers: [{ id: 'TRUE_COLOR', label: 'True colour' }, { id: 'NDVI', label: 'NDVI' }],+ } }));+ const tiles = [];+ page.on('request', (request) => {+ const path = new URL(request.url()).pathname;+ if (path.startsWith('/api/tiles/sentinel2')) tiles.push(path);+ });+ await page.getByRole('button', { name: 'Analyzers', exact: true }).click();+ await page.getByRole('button', { name: 'New analyzer', exact: true }).click();+ await page.getByRole('button', { name: /^Blank/ }).click();+ const deck = page.getByRole('region', { name: 'Checks on the map' });+ await deck.getByRole('button', { name: 'New check' }).click();+ await deck.getByRole('button', { name: 'Find passes', exact: true }).click();+ await page.getByLabel('Use 2026-09-01').getByRole('button', { name: 'Before', exact: true }).click();+ await page.getByLabel('Use 2026-09-10').getByRole('button', { name: 'After', exact: true }).click();+ await deck.getByRole('button', { name: 'Place the pins' }).click();+ await expect(deck.getByText('Could not check your Copernicus layers; the basemap stays on.')).toBeVisible();+ await expect(page.locator('.detect-tool .map')).toHaveCount(1);+ await expect(deck.getByRole('button', { name: 'Copernicus layer', exact: true })).toContainText('Choose a layer');+ await expect(deck.getByRole('button', { name: 'Refresh layers', exact: true })).toBeEnabled();+ expect(tiles).toEqual([]);+ expect(errors).toEqual([]);+});++test('failed check imagery says why on both maps and can be retried or replaced by the basemap', async ({ page }) => {+ const { errors } = await openDetect(page);+ await answerBuilder(page);+ let failing = true;+ await page.route('**/api/tiles/sentinel2*/**', (route) => failing+ ? route.fulfill({ status: 400, contentType: 'application/xml', body: '<ServiceException>Layer not found</ServiceException>' })+ : route.fallback());+ await page.getByRole('button', { name: 'Analyzers', exact: true }).click();+ await page.getByRole('button', { name: 'New analyzer', exact: true }).click();+ await page.getByRole('button', { name: /^Blank/ }).click();+ const deck = page.getByRole('region', { name: 'Checks on the map' });+ await deck.getByRole('button', { name: 'New check' }).click();+ await deck.getByRole('button', { name: 'Find passes', exact: true }).click();+ await page.getByLabel('Use 2026-09-01').getByRole('button', { name: 'Before', exact: true }).click();+ await page.getByLabel('Use 2026-09-10').getByRole('button', { name: 'After', exact: true }).click();+ await deck.getByRole('button', { name: 'Place the pins' }).click();+ const notices = page.getByRole('status', { name: 'Imagery loading error' });+ await expect(notices).toHaveCount(2);+ await expect(notices.first()).toContainText('The imagery service refused this display layer.');+ await expect(notices.first()).toContainText('TRUE_COLOR');+ await expect(notices.first()).toContainText('2026-09-01');+ await expect(notices.last()).toContainText('2026-09-10');+ await page.screenshot({ path: test.info().outputPath('check-imagery-error.png') });+ failing = false;+ await notices.first().getByRole('button', { name: 'Retry imagery' }).click();+ await expect(notices).toHaveCount(1);+ await notices.first().getByRole('button', { name: 'Use basemap' }).click();+ await expect(notices).toHaveCount(0);+ await expect(page.locator('.detect-tool .map')).toHaveCount(1);+ await expect(deck.getByRole('button', { name: 'Passes on the map' })).toHaveAttribute('aria-pressed', 'false');+ expect(errors).toEqual([]);+});+test('takes the whole screen with its panel, folds it there, and gives it up to Compare', async ({ page }) => {const { errors } = await openDetect(page);const held = () => page.evaluate(() => document.fullscreenElement?.classList.contains('detect-tool') ?? false);diff --git a/frontend/e2e/media-download.spec.js b/frontend/e2e/media-download.spec.jsindex a805be9..01b186f 100644--- a/frontend/e2e/media-download.spec.js+++ b/frontend/e2e/media-download.spec.js@@ -14,7 +14,7 @@ test('explains when a large video must be saved from Telegram', async ({ page })});await page.goto('/#media');- await expect(page.getByRole('heading', { name: 'Media Library' })).toBeVisible();+ await expect(page.getByRole('heading', { name: 'Media', exact: true })).toBeVisible();await page.getByPlaceholder('Paste a link (X, Telegram, YouTube…)').fill(target);await page.getByRole('button', { name: 'Download', exact: true }).click();diff --git a/frontend/e2e/paste.spec.js b/frontend/e2e/paste.spec.jsindex 00ef17d..cd66519 100644--- a/frontend/e2e/paste.spec.js+++ b/frontend/e2e/paste.spec.js@@ -112,7 +112,7 @@ test('takes a copied address as a bookmark', async ({ page }) => {test('a link in Media is refused, and told where it does work', async ({ page }) => {const fixture = await installAppFixture(page, { catalog });await page.goto('/#media');- await expect(page.getByRole('heading', { name: 'Media Library' })).toBeVisible();+ await expect(page.getByRole('heading', { name: 'Media', exact: true })).toBeVisible();await paste(page, { text: 'https://leak.example.test/thread/1' });@@ -133,7 +133,7 @@ test('one Ctrl+V opens one dialog, however many tabs have been visited', async (// ungated listeners would answer one paste four times over.const fixture = await installAppFixture(page, { catalog });await page.goto('/#media');- await expect(page.getByRole('heading', { name: 'Media Library' })).toBeVisible();+ await expect(page.getByRole('heading', { name: 'Media', exact: true })).toBeVisible();// switched by the tabs, not by the hash: a deep link is read once, at mount, and// the point here is to leave three tools mounted at the same timeawait page.getByRole('button', { name: 'Files', exact: true }).click();@@ -177,7 +177,7 @@ test('a paste in Proof stays the composer\'s own', async ({ page }) => {// the boundary between them is worth a test rather than an argument.const fixture = await installAppFixture(page, { catalog });await page.goto('/#media');- await expect(page.getByRole('heading', { name: 'Media Library' })).toBeVisible();+ await expect(page.getByRole('heading', { name: 'Media', exact: true })).toBeVisible();await page.getByRole('navigation').first().getByRole('button', { name: 'Case' }).click();await page.locator('.tabstrip').getByRole('button', { name: 'Board', exact: true }).click();await expect(page.getByRole('heading', { name: 'Board' })).toBeVisible();diff --git a/frontend/e2e/satellite-added-layers.spec.js b/frontend/e2e/satellite-added-layers.spec.jsindex fc38c34..71af27f 100644--- a/frontend/e2e/satellite-added-layers.spec.js+++ b/frontend/e2e/satellite-added-layers.spec.js@@ -107,7 +107,7 @@ test("the pin's card states its point and copies it", async ({ page, context, brtest.skip(browserName !== 'chromium', 'only Chromium lets a test grant the clipboard');await context.grantPermissions(['clipboard-read', 'clipboard-write']);await where.click();- await expect(page.getByText('Coordinates copied')).toBeVisible();+ await expect(page.getByText('Copied', { exact: true })).toBeVisible();expect(await page.evaluate(() => navigator.clipboard.readText())).toBe('48.850000, 2.350000');});diff --git a/frontend/src/App.svelte b/frontend/src/App.svelteindex 838d426..8c12d39 100644--- a/frontend/src/App.svelte+++ b/frontend/src/App.svelte@@ -168,7 +168,7 @@(uiState.tool === 'timeline' && Boolean(analysisSearch.timeline.snapshotId)));const noteTitle = $derived(- noteFrozen ? 'A frozen snapshot takes no new event. Leave it to add one.' : 'Add an event about what is on screen (Alt+N)'+ noteFrozen ? 'A frozen snapshot takes no new event. Leave it to add one.' : 'Add event about what is on screen (Alt+N)');function toggleNote() {if (!caseState.current || noteFrozen) return;@@ -309,7 +309,7 @@since amber is kept for the main action and the selection. -->{#if caseState.current && !solo}<button- class="note-btn"+ class="btn btn-ghost btn-sm note-btn"class:on={uiState.noting}title={noteTitle}aria-label="Add an event"@@ -317,9 +317,7 @@disabled={noteFrozen}onclick={toggleNote}>- <Icon name="eventAdd" size={15} />- <span class="note-label">Add event</span>- <kbd>Alt N</kbd>+ <Icon name="eventAdd" size={16} /></button>{/if}{#if uiState.tool !== 'guide'}@@ -495,62 +493,10 @@color: var(--text-1);background: var(--bg-2);}- /* Add event: one outlined pill among the icon marks, since it is the one of them- that makes something; amber only while its bar is open. */- .note-btn {- display: inline-flex;- align-items: center;- gap: 7px;- height: 28px;- padding: 0 6px 0 9px;- border: 1px solid var(--border-strong);- border-radius: 999px;- background: transparent;- color: var(--text-2);- font-size: var(--fs-xs);- font-weight: 600;- cursor: pointer;- transition: color 0.15s var(--ease), background 0.15s var(--ease), border-color 0.15s var(--ease);- }- .note-btn:hover:not(:disabled) {- border-color: color-mix(in srgb, var(--text-1) 35%, transparent);- background: var(--bg-2);- color: var(--text-1);- }+ /* Add event sits with the other icon marks; amber only while its bar is open. */.note-btn.on {- border-color: color-mix(in srgb, var(--accent) 60%, transparent);- background: var(--accent-soft);- color: var(--accent);- }- .note-btn:disabled {- opacity: 0.45;- cursor: default;- }- .note-btn kbd {- padding: 1px 5px;- border: 1px solid var(--border);- border-radius: 999px;- background: var(--bg-2);- color: var(--text-3);- font-family: var(--font-mono);- font-size: 10px;- font-weight: 500;- line-height: 1.4;- }- .note-btn.on kbd {- border-color: transparent;- background: color-mix(in srgb, var(--accent) 18%, transparent);color: var(--accent);- }- /* A narrow window keeps the mark and drops the words, which the tooltip says. */- @media (max-width: 1100px) {- .note-btn {- padding: 0 7px;- }- .note-label,- .note-btn kbd {- display: none;- }+ background: var(--accent-soft);}.main {flex: 1;diff --git a/frontend/src/App.test.js b/frontend/src/App.test.jsindex bc41767..04ab7c6 100644--- a/frontend/src/App.test.js+++ b/frontend/src/App.test.js@@ -25,13 +25,14 @@ describe('the case on the rail', () => {});describe('Add event, from every tool', () => {- it('is one labelled button in the topbar, just before the guide mark', () => {+ it('is one icon button in the topbar, just before the guide mark', () => {const button = markup.indexOf('aria-label="Add an event"');const guide = markup.indexOf('onclick={() => openGuide(uiState.tool)}');expect(button).toBeGreaterThan(-1);expect(button).toBeLessThan(guide);- expect(markup).toContain('<Icon name="eventAdd" size={15} />');- expect(markup).toContain('<kbd>Alt N</kbd>');+ expect(markup).toContain('<Icon name="eventAdd" size={16} />');+ // the words live in the tooltip, not beside the icon+ expect(markup).not.toContain('note-label');// shown only with a case, since there is nowhere to add an event without oneexpect(markup).toMatch(/\{#if caseState\.current && !solo\}\s*<button[\s\S]{0,200}class:on=\{uiState\.noting\}/);});diff --git a/frontend/src/components/CaseSidebar.svelte b/frontend/src/components/CaseSidebar.svelteindex f98688c..7448c03 100644--- a/frontend/src/components/CaseSidebar.svelte+++ b/frontend/src/components/CaseSidebar.svelte@@ -668,7 +668,7 @@<Icon name="pushpin" size={13} /><buttonclass="work-name"- title="New files and saved work land in this folder. Press to show it."+ title="Show the folder new work lands in"onclick={revealWorkFolder}>{working}diff --git a/frontend/src/components/CaseSwitcher.svelte b/frontend/src/components/CaseSwitcher.svelteindex e205852..1a06223 100644--- a/frontend/src/components/CaseSwitcher.svelte+++ b/frontend/src/components/CaseSwitcher.svelte@@ -172,7 +172,7 @@triggerBundleDownload(current.id, started.job_id);toast('Download started', 'ok', 4000);} else {- toast(job.error || 'Could not export the case', 'danger', 7000);+ toast(job.error ? `Could not export the case: ${job.error}` : 'Could not export the case', 'danger', 7000);}} catch (error) {if (error.name !== 'AbortError') {@@ -238,7 +238,7 @@signal: bundleJobController.signal,});if (job.state !== 'ready') {- toast(job.error || 'Could not import the case', 'danger', 7000);+ toast(job.error ? `Could not import the case: ${job.error}` : 'Could not import the case', 'danger', 7000);return;}await refreshCaseList();diff --git a/frontend/src/components/CopernicusLayersHelp.svelte b/frontend/src/components/CopernicusLayersHelp.sveltenew file mode 100644index 0000000..9a197ab--- /dev/null+++ b/frontend/src/components/CopernicusLayersHelp.svelte@@ -0,0 +1,27 @@+<script>+ import { COPERNICUS_CONFIGURATIONS, DISPLAY_FORM, DISPLAY_STEPS } from '../lib/copernicusSetup.js';+ import { openCopernicusSettings } from '../lib/navigate.js';+</script>++<details class="layer-help">+ <summary>Set up Copernicus layers</summary>+ <p>The free Copernicus configuration controls which display layers are available.</p>+ <ol>{#each DISPLAY_STEPS as step (step)}<li>{step}</li>{/each}</ol>+ <dl>{#each DISPLAY_FORM as [field, value] (field)}<dt>{field}</dt><dd>{value}</dd>{/each}</dl>+ <p>Optical rules read Sentinel-2 L2A bands through TRUE_COLOR; each index needs no separate display layer.</p>+ <div class="actions">+ <a href={COPERNICUS_CONFIGURATIONS} target="_blank" rel="noreferrer">Configuration Utility</a>+ <button class="btn btn-sm" onclick={openCopernicusSettings}>Settings → Imagery</button>+ </div>+</details>++<style>+ .layer-help { font-size: var(--fs-xs); line-height: 1.5; color: var(--text-2); }+ summary { cursor: pointer; color: var(--text-1); }+ p { margin: 8px 0; }+ ol { margin: 8px 0; padding-left: 20px; }+ dl { display: grid; grid-template-columns: auto 1fr; gap: 4px 10px; margin: 8px 0; }+ dt { color: var(--text-1); }+ dd { margin: 0; }+ .actions { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }+</style>diff --git a/frontend/src/components/EntryLine.render.test.js b/frontend/src/components/EntryLine.render.test.jsindex ea6d60c..5b05707 100644--- a/frontend/src/components/EntryLine.render.test.js+++ b/frontend/src/components/EntryLine.render.test.js@@ -182,6 +182,22 @@ describe('filed from a model', () => {expect(onsaved).toHaveBeenCalled();});+ it('stays saved when only the redraw after it fails, so a retry files nothing twice', async () => {+ const onsaved = vi.fn();+ await open(MODEL, { onsaved });+ type(count(), '2');+ choose(conditionSelect(), 'destroyed');+ reloadCase.mockRejectedValueOnce(new Error('Azimut is not running. Start it again, then reload this tab.'));++ addButton().click();+ await settle();++ expect(post).toHaveBeenCalledTimes(1);+ expect(target.querySelector('.error, [role="alert"]')?.textContent ?? '').not.toContain('not running');+ expect(onsaved).toHaveBeenCalled();+ expect(toast).toHaveBeenCalledWith('Added', 'ok', 8000, expect.objectContaining({ label: 'Undo' }));+ });+it('keeps a sentence the analyst wrote when a field changes under it', async () => {await open(MODEL);type(sentence(), 'Two tanks burning near the bridge');diff --git a/frontend/src/components/EntryLine.svelte b/frontend/src/components/EntryLine.svelteindex f0f3879..66e26b8 100644--- a/frontend/src/components/EntryLine.svelte+++ b/frontend/src/components/EntryLine.svelte@@ -77,6 +77,7 @@import Icon from './Icon.svelte';import Modal from './Modal.svelte';import TemporalClaimEditor from './TemporalClaimEditor.svelte';+ import { shortcut } from '../lib/keys.js';let {caseId,@@ -296,21 +297,29 @@saving = true;error = '';refused = {};+ let saved;try {- const saved = await api.post(`/api/cases/${caseId}/timeline/claims`, body());- clear();- if (announce) toast('Added', 'ok', 8000, { label: 'Undo', onClick: () => undo(saved) });- sentence?.focus();- await reloadCase();- onsaved?.(saved, { undo: () => undo(saved) });+ saved = await api.post(`/api/cases/${caseId}/timeline/claims`, body());} catch (failure) {error = failure.message;// A mention the case lost since it was picked is marked where it sits.const gone = /entity '([^']+)' not found/.exec(failure.message)?.[1];if (gone) refused = { [gone]: 'no longer in the case' };- } finally {saving = false;+ return;}+ // Saved. What follows only redraws the case, so a failure there is not this line's:+ // reported as one, a retry would file the claim twice.+ clear();+ if (announce) toast('Added', 'ok', 8000, { label: 'Undo', onClick: () => undo(saved) });+ sentence?.focus();+ saving = false;+ try {+ await reloadCase();+ } catch {+ // the case list catches up on its next reload+ }+ onsaved?.(saved, { undo: () => undo(saved) });}/** Put a date on the line, as a click on the axis does, and go to the sentence. */@@ -695,13 +704,13 @@class:on={panel === 'sources'}aria-expanded={panel === 'sources'}aria-label="Cite a source"- title="Cite a source: a file, a capture, a proof, a page, a note. Or drop a file on the line"+ title="Cite a source, or drop a file here"onclick={() => togglePanel('sources')}><Icon name="paperclip" size={16} /><span class="attach-label">Source</span></button>{#if oncancel}<button class="btn btn-ghost" onclick={oncancel}>Cancel</button>{/if}- <button class="btn btn-primary" disabled={!ready} title={refusal || 'Enter · Ctrl+Enter from any field'} onclick={save}>+ <button class="btn btn-primary" disabled={!ready} title={refusal || shortcut('Enter · Ctrl+Enter from any field')} onclick={save}>{saving ? 'Adding…' : 'Add'}</button></div>@@ -846,7 +855,7 @@Rewrite from the mentions</button>{/if}- <button class="btn btn-ghost btn-sm" title="The role of the date, how it was worked out, and the source's own wording" onclick={openFull}>+ <button class="btn btn-ghost btn-sm" title="Edit the date's role, method and wording" onclick={openFull}><Icon name="edit" size={11} /> Full editor</button></div>diff --git a/frontend/src/components/FilterBar.svelte b/frontend/src/components/FilterBar.svelteindex 1fd5926..9d0d4e9 100644--- a/frontend/src/components/FilterBar.svelte+++ b/frontend/src/components/FilterBar.svelte@@ -37,6 +37,7 @@toggleValue,} from '../lib/entityFilter.js';import Icon from './Icon.svelte';+ import DateField from './DateField.svelte';let {filter = $bindable(),@@ -287,7 +288,7 @@class="btn btn-sm add"aria-expanded={open === '+'}{disabled}- title="Narrow the case: a stored field such as kind = video, a type, a folder, a date"+ title="Filter the case"onclick={() => (open = open === '+' ? '' : '+')}><Icon name="plus" size={12} /> Filter@@ -320,7 +321,7 @@knowing what to click is the fault this menu exists to fix. --><buttondisabled={state.off}- title={state.off ? `${axis.hint} — ${state.note}` : axis.hint}+ title={state.off ? `${axis.hint} (${state.note})` : axis.hint}onclick={() => chose(axis.key)}><span class="what">@@ -450,7 +451,7 @@<buttonclass:on={filter.folder === row.path}style="padding-left: {8 + row.depth * 12}px"- title="{row.path} — {row.direct} here, {row.under} with everything under it"+ title="{row.path}: {row.direct} here, {row.under} with everything under it"onclick={() => pickFolder(row)}><span>{row.name}</span>@@ -578,24 +579,16 @@<!-- A range typed by hand is absolute and stays where it is put, where a presetre-resolves against today on every request. Setting one drops the other. --><div class="dates">- <label>- From- <input- type="date"- value={filter.since}- onchange={(event) =>- (filter = { ...filter, since: event.currentTarget.value, added: '' })}- />- </label>- <label>- To- <input- type="date"- value={filter.until}- onchange={(event) =>- (filter = { ...filter, until: event.currentTarget.value, added: '' })}- />- </label>+ <div class="date-end">+ <span>From</span>+ <DateField day reading={false} label="From" value={filter.since}+ onchange={(value) => (filter = { ...filter, since: value || '', added: '' })} />+ </div>+ <div class="date-end">+ <span>To</span>+ <DateField day reading={false} label="To" value={filter.until}+ onchange={(value) => (filter = { ...filter, until: value || '', added: '' })} />+ </div></div>{:else if axis === 'by'}<ul class="scroll">@@ -803,7 +796,7 @@cursor: default;}.check,- .dates label {+ .dates .date-end {display: flex;align-items: center;gap: 6px;@@ -815,14 +808,7 @@display: flex;flex-direction: column;}- .dates input {+ .dates .date-end :global(.date-field) {flex: 1;- padding: 2px 5px;- border: 1px solid var(--border);- border-radius: var(--r-sm);- background: var(--bg-1);- color: var(--text-1);- font: inherit;- font-size: var(--fs-xs);}</style>diff --git a/frontend/src/components/FilterBar.test.js b/frontend/src/components/FilterBar.test.jsindex 5863cc9..3071299 100644--- a/frontend/src/components/FilterBar.test.js+++ b/frontend/src/components/FilterBar.test.js@@ -23,7 +23,7 @@ describe('a bar that never changes shape', () => {// a control you can see and cannot use teaches something; one that is not there// teaches nothing, which is how the field filter stayed invisibleexpect(markup).toContain('disabled={state.off}');- expect(markup).toContain('title={state.off ? `${axis.hint} — ${state.note}` : axis.hint}');+ expect(markup).toContain('title={state.off ? `${axis.hint} (${state.note})` : axis.hint}');expect(source).toContain("{ off: true, note: 'no stored fields here' }");expect(source).toContain("{ off: true, note: 'nothing is linked yet' }");});@@ -128,9 +128,11 @@ describe('every term is chosen from what the case holds', () => {});it('lets a date range be typed when a preset is the wrong shape', () => {- expect(markup).toContain('type="date"');+ // typed day-first like every other date, not in the browser's own order+ expect(markup).toContain('<DateField day reading={false} label="From"');+ expect(markup).not.toContain('type="date"');// and the two spellings of the same axis never both apply- expect(markup).toContain("since: event.currentTarget.value, added: ''");+ expect(markup).toContain("since: value || '', added: ''");});});diff --git a/frontend/src/components/Modal.render.test.js b/frontend/src/components/Modal.render.test.jsnew file mode 100644index 0000000..8dade5d--- /dev/null+++ b/frontend/src/components/Modal.render.test.js@@ -0,0 +1,50 @@+// @vitest-environment happy-dom+import { afterEach, describe, expect, it } from 'vitest';+import { createRawSnippet, flushSync, mount, unmount } from 'svelte';+import Modal from './Modal.svelte';++let live;+let opener;+afterEach(() => {+ if (live) unmount(live);+ live = null;+ document.body.innerHTML = '';+});++const body = createRawSnippet(() => ({ render: () => '<div><input id="first"><button id="last">Go</button></div>' }));++async function openModal() {+ opener = document.createElement('button');+ document.body.append(opener);+ opener.focus();+ const target = document.createElement('div');+ document.body.append(target);+ live = mount(Modal, { target, props: { title: 'Name it', onclose: () => {}, children: body } });+ flushSync();+ await Promise.resolve();+ await Promise.resolve();+}++describe('a modal and the keyboard', () => {+ it('takes the focus in, says it is modal, and gives it back on close', async () => {+ await openModal();+ const dialog = document.querySelector('[role="dialog"]');+ expect(dialog.getAttribute('aria-modal')).toBe('true');+ expect(dialog.contains(document.activeElement)).toBe(true);++ unmount(live);+ live = null;+ expect(document.activeElement).toBe(opener);+ });++ it('wraps Tab inside the dialog', async () => {+ await openModal();+ const dialog = document.querySelector('[role="dialog"]');+ const close = dialog.querySelector('button[aria-label="Close"]');+ document.getElementById('last').focus();+ dialog.dispatchEvent(new KeyboardEvent('keydown', { key: 'Tab', bubbles: true }));+ expect(document.activeElement).toBe(close);+ dialog.dispatchEvent(new KeyboardEvent('keydown', { key: 'Tab', shiftKey: true, bubbles: true }));+ expect(document.activeElement).toBe(document.getElementById('last'));+ });+});diff --git a/frontend/src/components/Modal.svelte b/frontend/src/components/Modal.svelteindex e1e2eb6..25a6e3f 100644--- a/frontend/src/components/Modal.svelte+++ b/frontend/src/components/Modal.svelte@@ -8,6 +8,38 @@const self = {};$effect(() => joinOverlays(self));+ let dialogEl = $state(null);++ // Keyboard focus moves in when the dialog opens and goes back where it was when it+ // closes; left behind the veil, Tab would walk a page nobody can see. A field the+ // dialog autofocuses keeps the focus: that runs first, in the same microtask queue.+ $effect(() => {+ const returnTo = document.activeElement;+ queueMicrotask(() => {+ if (dialogEl && !dialogEl.contains(document.activeElement)) dialogEl.focus();+ });+ return () => {+ if (returnTo?.isConnected) returnTo.focus?.();+ };+ });++ const FOCUSABLE = 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';++ /** Tab wraps inside the dialog rather than leaving it for the page behind. */+ function trap(e) {+ if (e.key !== 'Tab' || !dialogEl) return;+ const items = [...dialogEl.querySelectorAll(FOCUSABLE)];+ if (!items.length) return;+ const [first, last] = [items[0], items[items.length - 1]];+ if (e.shiftKey && (document.activeElement === first || document.activeElement === dialogEl)) {+ e.preventDefault();+ last.focus();+ } else if (!e.shiftKey && document.activeElement === last) {+ e.preventDefault();+ first.focus();+ }+ }+function onkeydown(e) {if (e.key === 'Escape' && isTopOverlay(self)) onclose?.();}@@ -21,7 +53,8 @@onclick={(e) => e.target === e.currentTarget && onclose?.()}role="presentation">- <div class="modal" style:width role="dialog" aria-label={title}>+ <div class="modal" style:width role="dialog" aria-modal="true" aria-label={title} tabindex="-1"+ bind:this={dialogEl} onkeydown={trap}><header><h3>{title}</h3><button class="btn btn-ghost btn-sm" onclick={onclose} aria-label="Close" title="Close">diff --git a/frontend/src/components/NoCase.svelte b/frontend/src/components/NoCase.sveltenew file mode 100644index 0000000..8d33422--- /dev/null+++ b/frontend/src/components/NoCase.svelte@@ -0,0 +1,50 @@+<script>+ /**+ * What a tool shows with no case open: what it would do with one, and a way in+ * that needs none. The scratch session is the README's "no setup" road, the same+ * one Media and the map take on their own; it can be kept as a case later.+ */+ import Icon from './Icon.svelte';+ import { ensureCase, toast } from '../lib/state.svelte.js';++ let { icon = 'folder', what } = $props();+ let starting = $state(false);++ async function start() {+ starting = true;+ try {+ await ensureCase();+ } catch (error) {+ toast(error.message, 'danger');+ } finally {+ starting = false;+ }+ }+</script>++<div class="no-case">+ <Icon name={icon} size={36} />+ <p>Open a case to {what}.</p>+ <button class="btn btn-sm" disabled={starting} onclick={start}>+ <Icon name="plus" size={14} /> {starting ? 'Starting…' : 'Start a scratch session'}+ </button>+</div>++<style>+ .no-case {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 10px;+ height: 100%;+ min-height: 220px;+ padding: 24px;+ color: var(--text-3);+ text-align: center;+ }+ p {+ margin: 0;+ color: var(--text-2);+ }+</style>diff --git a/frontend/src/components/NoCase.test.js b/frontend/src/components/NoCase.test.jsnew file mode 100644index 0000000..692f1eb--- /dev/null+++ b/frontend/src/components/NoCase.test.js@@ -0,0 +1,28 @@+// @vitest-environment happy-dom+import { afterEach, describe, expect, it, vi } from 'vitest';+import { flushSync, mount, unmount } from 'svelte';++const ensureCase = vi.fn(async () => ({ id: 'scratch' }));+vi.mock('../lib/state.svelte.js', () => ({ ensureCase, toast: vi.fn() }));+const { default: NoCase } = await import('./NoCase.svelte');++let live;+let target;+afterEach(() => {+ if (live) unmount(live);+ target?.remove();+});++describe('a tool with no case open', () => {+ it('says what it would do and starts a scratch session from where it is', async () => {+ target = document.createElement('div');+ document.body.append(target);+ live = mount(NoCase, { target, props: { what: 'write notes' } });+ flushSync();++ expect(target.textContent).toContain('Open a case to write notes.');+ target.querySelector('button').click();+ await Promise.resolve();+ expect(ensureCase).toHaveBeenCalledTimes(1);+ });+});diff --git a/frontend/src/components/ProposalReview.render.test.js b/frontend/src/components/ProposalReview.render.test.jsindex d0a39fa..aac35d7 100644--- a/frontend/src/components/ProposalReview.render.test.js+++ b/frontend/src/components/ProposalReview.render.test.js@@ -137,3 +137,18 @@ describe('the proposed links', () => {expect(uiState.openGraphEntity).toBe('e_b');});});++describe('closing the panel', () => {+ it('closes on Escape like every other panel', async () => {+ get.mockResolvedValue(SOME);+ await open();+ button('2 proposed').click();+ flushSync();+ expect(target.querySelector('[aria-label="Proposed links"]')).not.toBeNull();++ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));+ flushSync();++ expect(target.querySelector('[aria-label="Proposed links"]')).toBeNull();+ });+});diff --git a/frontend/src/components/ProposalReview.svelte b/frontend/src/components/ProposalReview.svelteindex 59b4698..ced3b82 100644--- a/frontend/src/components/ProposalReview.svelte+++ b/frontend/src/components/ProposalReview.svelte@@ -15,6 +15,7 @@import Icon from './Icon.svelte';import { api } from '../lib/api.js';import { closeOnOutsidePointer } from '../lib/dismiss.js';+ import { isTopOverlay, joinOverlays } from '../lib/overlayStack.js';import { filedWords, proposalSentence, waitingCount } from '../lib/proposalReview.js';import { caseState, reloadCase, toast, uiState } from '../lib/state.svelte.js';@@ -39,6 +40,13 @@$effect(() => (open && box ? closeOnOutsidePointer(box, () => (open = false)) : undefined));+ // Escape closes it like every other panel, and only when nothing sits above it.+ const self = {};+ $effect(() => (open ? joinOverlays(self) : undefined));+ function onkeydown(e) {+ if (open && e.key === 'Escape' && isTopOverlay(self)) open = false;+ }+const waiting = $derived(waitingCount(data?.pending));/** Never read for links yet: a case filed before the pass existed. */const unread = $derived(Boolean(data) && !data.through);@@ -53,7 +61,7 @@if (waitingCount(answer.pending)) open = true;await reloadCase();} catch (error) {- toast(error.message || 'The case could not be read for links.', 'error');+ toast(error.message || 'The case could not be read for links.', 'danger');} finally {busy = false;}@@ -67,7 +75,7 @@data = await api.get(`/api/cases/${caseId}/proposals`);await reloadCase();} catch (error) {- toast(error.message || 'This link could not be confirmed.', 'error');+ toast(error.message || 'This link could not be confirmed.', 'danger');} finally {busy = false;}@@ -80,7 +88,7 @@data = await api.del(`/api/cases/${caseId}/proposals/${item.id}`);await reloadCase();} catch (error) {- toast(error.message || 'This link could not be dropped.', 'error');+ toast(error.message || 'This link could not be dropped.', 'danger');} finally {busy = false;}@@ -91,6 +99,8 @@}</script>+<svelte:window {onkeydown} />+<div class="review" bind:this={box}>{#if waiting}<button class="count proposed" class:on={open} aria-expanded={open}diff --git a/frontend/src/components/SheetAppend.svelte b/frontend/src/components/SheetAppend.svelteindex c9e03b5..7e8901d 100644--- a/frontend/src/components/SheetAppend.svelte+++ b/frontend/src/components/SheetAppend.svelte@@ -101,7 +101,7 @@<Icon name="arrowRight" size={11} /><select class="input" value={mapping[name] ?? ''} aria-label="Where {name} lands"onchange={(event) => pick(name, event.currentTarget.value)}>- <option value="">— leave it out</option>+ <option value="">Leave it out</option>{#each columns as onto (onto)}<option value={onto}>{onto}</option>{/each}</select></label>diff --git a/frontend/src/components/SheetDate.svelte b/frontend/src/components/SheetDate.svelteindex 264f1cb..f14cd3a 100644--- a/frontend/src/components/SheetDate.svelte+++ b/frontend/src/components/SheetDate.svelte@@ -18,6 +18,7 @@*/import { ID_COLUMN } from '../lib/sheet.js';import { parseWhen, whenShape } from '../lib/sheetRoles.js';+ import DateField from './DateField.svelte';let { table, meta, subject = '', onchoices, onanchors } = $props();@@ -162,8 +163,8 @@{#if needsDay}<label class="row"><span>The day it belongs to</span>- <input class="input" type="date" aria-label="The day these hours belong to"- bind:value={day} />+ <DateField day reading={false} label="The day these hours belong to" value={day}+ onchange={(value) => (day = value || '')} /></label><p class="note">These cells hold clocks with no day.</p>{/if}diff --git a/frontend/src/components/SheetFromCase.svelte b/frontend/src/components/SheetFromCase.svelteindex 01b4a63..12cf8de 100644--- a/frontend/src/components/SheetFromCase.svelte+++ b/frontend/src/components/SheetFromCase.svelte@@ -174,10 +174,9 @@</p><p class="note">{#if filesShape && files?.sheet}- This case already has this worklist. Its Refresh brings it level, and building here- makes a second one.+ This case already has this worklist, so building here makes a second one.{:else if fixed}- The case writes those columns and Refresh keeps them level with it. Status, Notes and any+ The case writes those columns and Refresh keeps them level, while Status, Notes and anycolumn you add are yours.{:else}Each row points back at what it came from, so promoting it later updates that entitydiff --git a/frontend/src/components/SheetGeocode.svelte b/frontend/src/components/SheetGeocode.svelteindex 4be1cd6..b5226ed 100644--- a/frontend/src/components/SheetGeocode.svelte+++ b/frontend/src/components/SheetGeocode.svelte@@ -188,7 +188,7 @@</p>{#if !targets.length}- <p class="note">This sheet has no other column to write into. Add one first.</p>+ <p class="note">Add a column to write into first.</p>{:else}<label class="row"><span>Write the {forward ? 'coordinates' : 'place name'} into</span>@@ -203,7 +203,7 @@<Icon name="pin" size={11} /><strong>{fromCase.length}</strong>{fromCase.length === 1 ? 'row is' : 'rows are'} answered by the case itself, from the- entity the cell points at. No lookup for those.+ entity the cell points at.{#if linkable.length === MAX_CASE_POINTS}Only the first {MAX_CASE_POINTS} linked rows are read; run it again for the rest.{/if}@@ -222,8 +222,8 @@{#if work.length}<p class="note"><Icon name="globe" size={11} />- Uses OpenStreetMap's geocoder, about one lookup a second, so its servers see what is- looked for. Nothing is written until you press again.+ Pressing again asks OpenStreetMap's geocoder, about one lookup a second, and its+ servers see what is looked for.</p>{/if}diff --git a/frontend/src/components/SheetHelp.svelte b/frontend/src/components/SheetHelp.svelteindex e9dbd90..4a584e4 100644--- a/frontend/src/components/SheetHelp.svelte+++ b/frontend/src/components/SheetHelp.svelte@@ -15,6 +15,7 @@* which is the honest failure mode for a legend.*/import Icon from './Icon.svelte';+ import { shortcut } from '../lib/keys.js';let { onclose } = $props();@@ -62,7 +63,7 @@<section><p class="what">Keys</p>{#each KEYS as [key, what] (key)}- <p class="line"><kbd>{key}</kbd><span>{what}</span></p>+ <p class="line"><kbd>{shortcut(key)}</kbd><span>{what}</span></p>{/each}</section><section>diff --git a/frontend/src/components/SheetRoleEditor.svelte b/frontend/src/components/SheetRoleEditor.svelteindex d9e8384..b15bd7f 100644--- a/frontend/src/components/SheetRoleEditor.svelte+++ b/frontend/src/components/SheetRoleEditor.svelte@@ -453,8 +453,8 @@</label>{/if}<p class="menu-note">- A name that reaches no single row is left as written. Sending the rows to the case- draws real <code>part-of</code> edges from this column.+ Sending the rows to the case draws <code>part-of</code> edges from this column, and+ a name that reaches no single row stays as written.</p>{/if}@@ -474,21 +474,21 @@</button>{/if}<p class="menu-note">- A moment visible in several rows, used to line them up. <code>-00:01:50</code> is before- it, <code>00:04:04</code> after. Dating the sync point dates every row.+ A moment seen in several rows that lines them up (<code>-00:01:50</code> is before it,+ <code>00:04:04</code> after), so dating it dates every row.</p>{/if}{#if kind === 'stamped'}<p class="menu-note">- Every empty cell is dated on the next save, including rows already in the sheet, and never- rewritten after that. It goes into the file.+ Every empty cell, old rows included, is dated in the file on the next save and never+ rewritten after that.</p>{/if}{#if kind === 'locked'}<p class="menu-note">- The case holds this column. Refresh rewrites it, so typing here would be overwritten. The- cell still opens what it points at.+ The case holds this column and Refresh rewrites it, but the cell still opens what it+ points at.</p>{/if}{#if kind === 'computed'}@@ -559,16 +559,16 @@{#if !role.from}Nothing is written until a column is chosen.{:else if role.of === 'point'}- The point the case holds for what <code>{role.from}</code> points at. Blank when- it has none, or when two different points reach it.+ The point the case holds for what <code>{role.from}</code> points at, blank when+ it has none or two different points reach it.{:else}What the case has joined <code>{role.from}</code>'s entity to, one hop out.{/if}</p>{:else if role.of === 'in_case'}<p class="menu-note">- NO once the case stops holding what the row was built from. Rows you typed yourself- stay blank: they were never built from anything.+ NO once the case stops holding what the row was built from, and blank on rows you+ typed yourself.</p>{:else}<p class="menu-note">YES when the row points at something with a place.</p>diff --git a/frontend/src/components/TemporalInput.svelte b/frontend/src/components/TemporalInput.svelteindex 03762ad..bde9d23 100644--- a/frontend/src/components/TemporalInput.svelte+++ b/frontend/src/components/TemporalInput.svelte@@ -12,6 +12,7 @@import { axisZone, learnAxisZone } from '../lib/caseAxis.svelte.js';import { caseState } from '../lib/state.svelte.js';import ClockField from './ClockField.svelte';+ import DateField from './DateField.svelte';let {id,@@ -199,24 +200,13 @@<div class="parts range-parts"><label class="field"><span>Start</span>- <input- {id}- class="input input-sm mono"- aria-label="Start date"- type="date"- value={state.start}- oninput={(event) => { typed = true; emit({ start: event.currentTarget.value }); }}- />+ <DateField {id} day reading={false} label="Start date" value={state.start}+ onchange={(value) => { typed = true; emit({ start: value || '' }); }} /></label><label class="field"><span>End</span>- <input- class="input input-sm mono"- aria-label="End date"- type="date"- value={state.end}- oninput={(event) => { typed = true; emit({ end: event.currentTarget.value }); }}- />+ <DateField day reading={false} label="End date" value={state.end}+ onchange={(value) => { typed = true; emit({ end: value || '' }); }} /></label></div>{:else if state.mode === 'time-range'}diff --git a/frontend/src/components/Toasts.svelte b/frontend/src/components/Toasts.svelteindex 3d4f4e4..af34309 100644--- a/frontend/src/components/Toasts.svelte+++ b/frontend/src/components/Toasts.svelte@@ -15,9 +15,11 @@}</script>-<div class="toasts" use:portal>+<!-- Announced as they come: a failure interrupts a screen reader, anything else waits+ for it to finish. -->+<div class="toasts" use:portal role="status" aria-live="polite">{#each uiState.toasts as t (t.id)}- <div class="toast {t.kind}">+ <div class="toast {t.kind}" role={t.kind === 'danger' ? 'alert' : undefined}><Icon name={icons[t.kind] ?? 'compass'} size={15} /><span>{t.message}</span>{#if t.action}diff --git a/frontend/src/components/Toasts.test.js b/frontend/src/components/Toasts.test.jsindex c1969a4..cac8365 100644--- a/frontend/src/components/Toasts.test.js+++ b/frontend/src/components/Toasts.test.js@@ -23,3 +23,16 @@ describe('Toasts', () => {expect(body).toContain('toast-action');});});++describe('Toasts and a screen reader', () => {+ it('announces toasts politely and a failure at once', () => {+ uiState.toasts = [+ { id: 1, message: 'Copied', kind: 'ok' },+ { id: 2, message: 'Not saved', kind: 'danger' },+ ];+ const { body } = render(Toasts);+ expect(body).toContain('role="status"');+ expect(body).toContain('aria-live="polite"');+ expect(body.match(/role="alert"/g)).toHaveLength(1);+ });+});diff --git a/frontend/src/lib/api.js b/frontend/src/lib/api.jsindex 2540066..5d55fb1 100644--- a/frontend/src/lib/api.js+++ b/frontend/src/lib/api.js@@ -7,7 +7,7 @@* with the validator's list of objects, and handing that straight to `Error`* stringified every validation failure in the app as "[object Object]".*/-function detailLine(detail) {+export function detailLine(detail) {if (typeof detail === 'string') return detail;if (!Array.isArray(detail)) return '';return detail@@ -21,6 +21,9 @@ function detailLine(detail) {.join('; ');}+/** What any request says when the app behind the tab is gone. */+export const NOT_RUNNING = 'Azimut is not running. Start it again, then reload this tab.';+/** What a failure says when its body gave no reason: a crash on the server* answers with a bare "Internal Server Error". */function fallback(status) {@@ -42,7 +45,17 @@ async function request(method, path, body, opts = {}) {init.headers['Content-Type'] = 'application/json';init.body = JSON.stringify(body);}- const res = await fetch(path, { ...init, ...opts });+ let res;+ try {+ res = await fetch(path, { ...init, ...opts });+ } catch (error) {+ // A cancelled request is the caller's own doing and says nothing to anyone.+ if (error?.name === 'AbortError') throw error;+ // Otherwise the request never reached a server: the app was stopped, its window+ // closed, or the machine went to sleep under it. The browser's own words for that+ // ("Failed to fetch", "NetworkError when attempting…") name none of those.+ throw new ApiError(0, NOT_RUNNING);+ }if (!res.ok) {let detail = '';try {diff --git a/frontend/src/lib/api.test.js b/frontend/src/lib/api.test.jsindex de6a791..289ddc6 100644--- a/frontend/src/lib/api.test.js+++ b/frontend/src/lib/api.test.js@@ -63,3 +63,19 @@ describe('API errors', () => {});});});++describe('a request that reaches no server', () => {+ it('says the app is not running, not the browser’s “Failed to fetch”', async () => {+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new TypeError('Failed to fetch')));+ const failure = await api.put('/api/cases/c/notes/n', { text: 'x' }).catch((error) => error);+ expect(failure).toBeInstanceOf(ApiError);+ expect(failure.status).toBe(0);+ expect(failure.message).toBe('Azimut is not running. Start it again, then reload this tab.');+ });++ it('lets a cancelled request stay a cancellation', async () => {+ const aborted = Object.assign(new Error('The operation was aborted.'), { name: 'AbortError' });+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(aborted));+ await expect(api.get('/api/cases')).rejects.toBe(aborted);+ });+});diff --git a/frontend/src/lib/autosave.svelte.js b/frontend/src/lib/autosave.svelte.jsindex 570bba6..269e27f 100644--- a/frontend/src/lib/autosave.svelte.js+++ b/frontend/src/lib/autosave.svelte.js@@ -11,7 +11,9 @@* when nothing changed since the last save.** `flush()` writes whatever is pending and waits for it. A tool calls it before it- * lets go of the document: switching file, closing the case, leaving the tool.+ * lets go of the document: switching file, closing the case, leaving the tool. After+ * a failed write the document is still unsaved, so `flush()` tries it again: that is+ * what a Retry button calls. `unsaved` says whether it is still unsaved afterwards.*/export function createAutosave({ write, delay = 800 }) {const state = $state({ status: 'idle', error: '' });@@ -57,7 +59,7 @@ export function createAutosave({ write, delay = 800 }) {timer = setTimeout(run, delay);},async flush() {- if (timer) await run();+ if (timer || (state.status === 'error' && !running)) await run();else if (running) await running;},/** Forget a pending write, for a document that is being thrown away. */@@ -68,9 +70,13 @@ export function createAutosave({ write, delay = 800 }) {state.status = 'idle';state.error = '';},- /** Whether a write is scheduled or running, so a page closing can send it. */+ /** Whether a write is scheduled, running or failed, so a page closing can send it. */get pending() {- return timer !== null || running !== null;+ return timer !== null || running !== null || state.status === 'error';+ },+ /** Whether the last write failed and the document holds edits no write has kept. */+ get unsaved() {+ return state.status === 'error';},};}diff --git a/frontend/src/lib/autosave.svelte.test.js b/frontend/src/lib/autosave.svelte.test.jsindex 5f5f4e5..1b1dbe0 100644--- a/frontend/src/lib/autosave.svelte.test.js+++ b/frontend/src/lib/autosave.svelte.test.js@@ -151,7 +151,7 @@ describe('createAutosave', () => {saver.schedule();await saver.flush();expect(saver.state.status).toBe('error');- expect(saver.pending).toBe(false);+ expect(saver.unsaved).toBe(true); // failed, not stuck: the next write goes outwrite.mockResolvedValue();saver.schedule();@@ -174,6 +174,31 @@ describe('createAutosave', () => {expect(saver.state.error).toBe('');});+ it('retries a failed write when flushed alone, which is what Retry does', async () => {+ const write = vi.fn().mockRejectedValueOnce(new Error('disk full')).mockResolvedValue();+ const saver = createAutosave({ write, delay: 10 });++ saver.schedule();+ await vi.advanceTimersByTimeAsync(10);+ expect(saver.unsaved).toBe(true);+ expect(saver.pending).toBe(true); // a page closing now still has something to send++ await saver.flush();+ expect(write).toHaveBeenCalledTimes(2);+ expect(saver.state.status).toBe('saved');+ expect(saver.unsaved).toBe(false);+ });++ it('stays unsaved when the retry fails too, so the tool can refuse to let go', async () => {+ const write = vi.fn().mockRejectedValue(new Error('too large'));+ const saver = createAutosave({ write, delay: 10 });+ saver.schedule();+ await saver.flush();+ await saver.flush();+ expect(write).toHaveBeenCalledTimes(2);+ expect(saver.unsaved).toBe(true);+ });+it('forgets a pending write for a document being thrown away', async () => {const write = vi.fn(async () => {});const saver = createAutosave({ write, delay: 50 });diff --git a/frontend/src/lib/boardGroups.js b/frontend/src/lib/boardGroups.jsindex cb57b42..0fc67dd 100644--- a/frontend/src/lib/boardGroups.js+++ b/frontend/src/lib/boardGroups.js@@ -33,7 +33,7 @@ export const BOARD_GROUPS = [label: 'Files',families: ['collected'],kind: 'material',- reads: { tool: 'media', label: 'Media Library' },+ reads: { tool: 'media', label: 'Media' },},{ id: 'document', label: 'Work', families: ['document'], kind: 'material' },// A free type the registry has never heard of has no family, and still belongs@@ -59,16 +59,6 @@ export function typesOfGroup(group, caseTypes, familyOf) {return caseTypes.filter((type) => groupOfType(type, familyOf).id === group.id).sort();}-/**- * The types a group's own page asks for: its types, narrowed by the ones the question- * already picked. Empty means the group cannot hold an answer, so it sends nothing.- */-export function groupRequestTypes(group, caseTypes, wantedTypes, familyOf) {- const own = typesOfGroup(group, caseTypes, familyOf);- if (!wantedTypes?.length) return own;- return own.filter((type) => wantedTypes.includes(type));-}-/** How many of the answer each group holds, from a per-type count. */export function groupCounts(byType, familyOf) {const counts = Object.fromEntries(BOARD_GROUPS.map((group) => [group.id, 0]));diff --git a/frontend/src/lib/boardGroups.test.js b/frontend/src/lib/boardGroups.test.jsindex e02802c..26c2e26 100644--- a/frontend/src/lib/boardGroups.test.js+++ b/frontend/src/lib/boardGroups.test.js@@ -7,7 +7,6 @@ import {groupCounts,groupOfType,groupOpen,- groupRequestTypes,holdsSubjects,loadLayout,normalizeLayout,@@ -76,15 +75,6 @@ describe('board groups', () => {expect(typesOfGroup(boardGroup('asset'), caseTypes, familyOf)).toEqual([]);});- it('narrows a group’s request by the types the question picked', () => {- const caseTypes = ['person', 'organization', 'media'];- const actor = boardGroup('actor');- expect(groupRequestTypes(actor, caseTypes, [], familyOf)).toEqual(['organization', 'person']);- expect(groupRequestTypes(actor, caseTypes, ['person'], familyOf)).toEqual(['person']);- // a question about media leaves the people group nothing to ask- expect(groupRequestTypes(actor, caseTypes, ['media'], familyOf)).toEqual([]);- });-it('adds a per-type count up per group', () => {const counts = groupCounts({ person: 2, organization: 1, media: 20, mystery: 1 }, familyOf);expect(counts.actor).toBe(3);diff --git a/frontend/src/lib/clipboard.js b/frontend/src/lib/clipboard.jsnew file mode 100644index 0000000..d163670--- /dev/null+++ b/frontend/src/lib/clipboard.js@@ -0,0 +1,20 @@+import { toast } from './state.svelte.js';++/** Said when the browser keeps the clipboard shut: the page lost focus, or a+ * permission was refused. */+export const REFUSED = 'The browser refused the clipboard';++/**+ * Put text on the clipboard and say so, or say the browser refused. Returns whether+ * it landed, so a caller with more to do (Publish) carries on either way.+ */+export async function copyText(text, { said = 'Copied', quiet = false } = {}) {+ try {+ await navigator.clipboard.writeText(text);+ } catch {+ toast(REFUSED, 'warn');+ return false;+ }+ if (!quiet) toast(said, 'ok', 1600);+ return true;+}diff --git a/frontend/src/lib/clipboard.test.js b/frontend/src/lib/clipboard.test.jsnew file mode 100644index 0000000..6167c55--- /dev/null+++ b/frontend/src/lib/clipboard.test.js@@ -0,0 +1,32 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { uiState } from './state.svelte.js';+import { copyText, REFUSED } from './clipboard.js';++afterEach(() => {+ uiState.toasts = [];+ vi.unstubAllGlobals();+});++const clipboard = (writeText) => vi.stubGlobal('navigator', { clipboard: { writeText } });++describe('copyText', () => {+ it('copies and says so', async () => {+ const writeText = vi.fn().mockResolvedValue();+ clipboard(writeText);+ expect(await copyText('47.1, 2.3')).toBe(true);+ expect(writeText).toHaveBeenCalledWith('47.1, 2.3');+ expect(uiState.toasts.map((t) => [t.message, t.kind])).toEqual([['Copied', 'ok']]);+ });++ it('says the browser refused, and reports it rather than throwing', async () => {+ clipboard(vi.fn().mockRejectedValue(new DOMException('Document is not focused', 'NotAllowedError')));+ expect(await copyText('x')).toBe(false);+ expect(uiState.toasts.map((t) => [t.message, t.kind])).toEqual([[REFUSED, 'warn']]);+ });++ it('stays quiet on success when asked, never on a refusal', async () => {+ clipboard(vi.fn().mockResolvedValue());+ await copyText('x', { quiet: true });+ expect(uiState.toasts).toEqual([]);+ });+});diff --git a/frontend/src/lib/copernicusSetup.js b/frontend/src/lib/copernicusSetup.jsindex 2a83555..400d5aa 100644--- a/frontend/src/lib/copernicusSetup.js+++ b/frontend/src/lib/copernicusSetup.js@@ -20,6 +20,20 @@ export const ACCOUNT_STEPS = Object.freeze(['Copy the ID under "Service endpoints" and paste it in Settings → Imagery → Sentinel Hub.',]);+export const DISPLAY_STEPS = Object.freeze([+ 'Open the configuration whose ID is saved in Azimut, then press Add new layer.',+ 'Fill the form below for each display product you need, then Save.',+ 'Back in the check, press Refresh layers.',+]);++export const DISPLAY_FORM = Object.freeze([+ ['Layer name', 'TRUE_COLOR, FALSE_COLOR, SWIR or NDVI'],+ ['Source', 'Sentinel-2 L2A'],+ ['Data processing', 'Use the pencil to choose the matching predefined product.'],+ ['Time range', 'Leave both boxes unticked.'],+ ['Mosaic order', 'Most recent'],+]);+/** The Sentinel-1 layer, added to that same configuration. */export const RADAR_STEPS = Object.freeze(['In the Configuration Utility, open the configuration whose ID Azimut has, and press Add new layer.',diff --git a/frontend/src/lib/entityFilter.js b/frontend/src/lib/entityFilter.jsindex 9fa83a0..9c0d51c 100644--- a/frontend/src/lib/entityFilter.js+++ b/frontend/src/lib/entityFilter.js@@ -367,7 +367,7 @@ export function chipsOf(filter, names = {}) {if (filter.attrKey) {// A field with no value yet is a term still being built, and it says so rather// than reading as a filter that matches everything.- const value = filter.attrValue ? ` = ${filter.attrValue}` : ' — pick a value';+ const value = filter.attrValue ? ` = ${filter.attrValue}` : ': pick a value';chips.push({ axis: 'field', text: `${filter.attrKey}${value}` });}if (filter.linked) {diff --git a/frontend/src/lib/extBridge.js b/frontend/src/lib/extBridge.jsindex 91fa1d6..cfbafb8 100644--- a/frontend/src/lib/extBridge.js+++ b/frontend/src/lib/extBridge.js@@ -303,6 +303,9 @@ export function extensionState({ timeoutMs = 700, win = window } = {}) {// "development" for a folder or a temporary add-on, "normal" for a// packaged copy the browser manages. Null from a copy predating it.installType: msg.installType ?? null,+ // False when this tab is not the address the copy is paired with: it then+ // refuses to capture or hand off for it. Null from a copy predating it.+ paired: msg.paired ?? null,});}}diff --git a/frontend/src/lib/extBridge.test.js b/frontend/src/lib/extBridge.test.jsindex 82195b3..0556a38 100644--- a/frontend/src/lib/extBridge.test.js+++ b/frontend/src/lib/extBridge.test.js@@ -254,6 +254,15 @@ describe('extensionState', () => {off();});+ it('says whether this tab is the address the copy is paired with', async () => {+ const off = fakeRelay('ext-state', 'ext-state-result', () => ({+ ok: true, version: '0.3.1', extensionId: 'ext-a', loaded: null, paired: false,+ }));+ const [found] = await extensionState({ timeoutMs: 60 });+ expect(found.paired).toBe(false);+ off();+ });+it('drops a copy that refused', async () => {const off = fakeRelay('ext-state', 'ext-state-result', () => ({ ok: false, error: 'nope' }));await expect(extensionState({ timeoutMs: 60 })).resolves.toEqual([]);diff --git a/frontend/src/lib/extInstall.js b/frontend/src/lib/extInstall.jsindex 8ff0120..7df687f 100644--- a/frontend/src/lib/extInstall.js+++ b/frontend/src/lib/extInstall.js@@ -102,6 +102,10 @@ export function classify(server, { bridges, managed } = {}) {// distinguishable from one that never wrote anything.folderCurrent: Boolean(folder && bundledPayload && folder.payload === bundledPayload),installId: folder?.install_id ?? null,+ // A copy answered but is paired with another address, most often this Azimut+ // before it moved to a free port. It refuses to capture or hand off until its+ // options name this one.+ unpaired: answered.some((r) => r.paired === false),};}diff --git a/frontend/src/lib/extInstall.test.js b/frontend/src/lib/extInstall.test.jsindex 3003b8e..9ecf935 100644--- a/frontend/src/lib/extInstall.test.js+++ b/frontend/src/lib/extInstall.test.js@@ -174,6 +174,15 @@ describe('classify', () => {expect(v.unnamed).toBe(1);});+ it('names a copy paired with another address, which refuses to act for this one', () => {+ // Azimut moved to the next free port, the extension still points at the old one.+ const moved = { ...responder('mine', 'new'), paired: false };+ expect(classify(server(), probes([moved])).unpaired).toBe(true);+ expect(classify(server(), probes([{ ...moved, paired: true }])).unpaired).toBe(false);+ // A copy too old to say is not accused of anything.+ expect(classify(server(), probes([responder('mine', 'new')])).unpaired).toBe(false);+ });+it('survives a server read that failed and a probe that never ran', () => {expect(classify(null, {}).status).toBe('absent');expect(classify(null, {}).path).toBe('');diff --git a/frontend/src/lib/extension.test.js b/frontend/src/lib/extension.test.jsindex 432697b..89c34df 100644--- a/frontend/src/lib/extension.test.js+++ b/frontend/src/lib/extension.test.js@@ -181,6 +181,39 @@ describe('handle: capture-tab (the app relay)', () => {expect(res.ok).toBe(false);});+ it('refuses another program on localhost, answering only the paired port', async () => {+ const chrome = makeChrome();+ const { handle } = load({ chrome });+ for (const url of ['http://127.0.0.1:9999/', 'http://localhost:3000/dev']) {+ const res = await handle({ type: 'capture-tab' }, { tab: { id: 3, url, windowId: 7 } });+ // Most often this same Azimut on the next free port: the refusal says what to change.+ expect(res).toEqual({+ ok: false,+ error: `this extension is paired with another address. In its options, set the Azimut URL to ${new URL(url).origin}`,+ });+ }+ expect(chrome.tabs.captureVisibleTab).not.toHaveBeenCalled();+ // the same machine under its other name is still the app+ const res = await handle({ type: 'capture-tab' }, { tab: { id: 3, url: 'http://localhost:8477/', windowId: 7 } });+ expect(res.ok).toBe(true);+ expect(chrome.tabs.captureVisibleTab).toHaveBeenCalledTimes(1);+ });++ it('opens no hand-off tab on a site the app does not post or search with', async () => {+ const chrome = makeChrome();+ chrome.tabs.create = vi.fn(async () => ({ id: 9 }));+ const { handle } = load({ chrome });+ const app = { tab: { id: 3, url: 'http://127.0.0.1:8477/' } };+ const post = await handle({ type: 'post-handoff', payload: { url: 'https://evil.example/compose', posts: [] } }, app);+ const reverse = await handle(+ { type: 'reverse-handoff', payload: { url: 'http://lens.google.com/', image: { data: 'eA==' } } },+ app,+ );+ expect(post.ok).toBe(false);+ expect(reverse.ok).toBe(false);+ expect(chrome.tabs.create).not.toHaveBeenCalled();+ });+it('captures for the localhost app tab', async () => {const chrome = makeChrome();const { handle } = load({ chrome });@@ -673,6 +706,7 @@ describe('handle: ext-state', () => {const res = await handle({ type: 'ext-state' }, APP_TAB);expect(res).toEqual({ok: true,+ paired: true,version: '0.3.0',extensionId: 'theid',loaded: STAMP,@@ -683,6 +717,16 @@ describe('handle: ext-state', () => {expect(res.id).toBeUndefined();});+ it('answers an app on another port, saying it is not the paired one', async () => {+ // Started while another program held 8477, Azimut moved to the next free port.+ // Settings must still find its extension, and say why it will not act.+ const { chrome, fetchImpl } = stampChrome();+ const { handle } = load({ chrome, fetchImpl });+ const res = await handle({ type: 'ext-state' }, { tab: { url: 'http://127.0.0.1:8478/' } });+ expect(res.ok).toBe(true);+ expect(res.paired).toBe(false);+ });+it('names a packaged copy as one the browser manages', async () => {// Firefox's permanent install is a signed XPI: no install.json to read, and// sealed. Without this the app would read it as a stale unzip and offer todiff --git a/frontend/src/lib/extensionMapRefs.test.js b/frontend/src/lib/extensionMapRefs.test.jsindex 3b3b523..8a98dc4 100644--- a/frontend/src/lib/extensionMapRefs.test.js+++ b/frontend/src/lib/extensionMapRefs.test.js@@ -291,7 +291,7 @@ describe('choosing what to open', () => {mount({ search: () => Promise.resolve({ items: [PICTURE, PICTURE], total: 214 }) });layer.openPicker();await settle();- expect(picker().querySelector('.hint').textContent).toBe('2 of 214 — search to narrow it down');+ expect(picker().querySelector('.hint').textContent).toBe('2 of 214. Search to narrow it down');});it('says when a case has nothing to offer', async () => {diff --git a/frontend/src/lib/extensionPopup.test.js b/frontend/src/lib/extensionPopup.test.jsindex 1e8941e..815dcf3 100644--- a/frontend/src/lib/extensionPopup.test.js+++ b/frontend/src/lib/extensionPopup.test.js@@ -226,3 +226,41 @@ describe('the scale bar and north arrow tick', () => {expect($('marks-note').hidden).toBe(true);});});++describe('a place the app would refuse', () => {+ const mapPage = (extra = {}) => ({+ tabUrl: 'https://www.google.fr/maps/@48.85,2.29,17z',+ answers: {+ '/parse': ok({ site: 'google-maps', label: 'Google Maps', lat: 48.85, lon: 2.29, zoom: 17 }),+ '/cases': ok([{ id: 'c1', name: 'Case one' }]),+ ...extra,+ },+ });+ const posted = () => globalThis.fetch.mock.calls.filter(([url]) => String(url).includes('/ingest/place'));++ it('says which field is out of range, before sending anything', async () => {+ await runPopup(mapPage());+ $('lat').value = '95';+ $('lat').dispatchEvent(new Event('input'));+ $('save-place').click();+ await new Promise((resolve) => setTimeout(resolve, 0));++ expect($('status').textContent).toBe('Latitude runs from -90 to 90.');+ expect(posted()).toEqual([]);+ });++ it('reads a refusal the app sent as a list, never as [object Object]', async () => {+ await runPopup(mapPage({+ '/ingest/place': () => ({+ ok: false,+ status: 422,+ json: async () => ({ detail: [{ loc: ['body', 'title'], msg: 'String should have at most 300 characters' }] }),+ }),+ }));+ $('save-place').click();+ await new Promise((resolve) => setTimeout(resolve, 0));+ await new Promise((resolve) => setTimeout(resolve, 0));++ expect($('status').textContent).toBe('Could not save: String should have at most 300 characters');+ });+});diff --git a/frontend/src/lib/guide.js b/frontend/src/lib/guide.jsindex 6bdb10e..e838d97 100644--- a/frontend/src/lib/guide.js+++ b/frontend/src/lib/guide.js@@ -56,7 +56,7 @@ export const GUIDE = [},{label: 'The network waits for you',- text: 'Network access follows an action that needs it, such as a map tile or a download. The one check made on its own asks GitHub and PyPI for new versions when the app opens, and Settings turns it off.',+ text: 'Network access follows an action that needs it, such as a download. Two things reach out on their own: a check of GitHub and PyPI for new versions when the app opens, which Settings turns off, and the basemap tiles of the case map on the home page.',},{label: 'The rail is a sequence',@@ -114,7 +114,7 @@ export const GUIDE = [steps: [{ tool: 'media', text: 'Import the photo, or paste the URL of the post it came from to pull it down with its origin already written.' },{ tool: 'inspect', text: 'Crop and adjust what is hard to read, and run the error-level view over anything that looks composited.' },- { tool: 'reverse', text: 'Prepare the image and press an engine. Nothing is sent until you do.' },+ { tool: 'reverse', text: 'Prepare the image and press an engine.' },{ tool: 'satellite', text: 'Search the area, switch providers and dates until the ground matches, and capture the view.' },{ tool: 'proof', text: 'Put the photo beside the capture, mark what agrees, and name the point. It is filed as a place.' },],@@ -123,7 +123,7 @@ export const GUIDE = [title: 'Source a video from a post',lead: 'From a URL to a dated claim the case can argue with.',steps: [- { tool: 'media', text: 'Paste the post URL. The first attempt is made without cookies, and only an "unavailable" answer offers your saved browser session.' },+ { tool: 'media', text: 'Paste the post URL, and pick your signed-in browser if it answers "This link needs a login".' },{ tool: 'inspect', text: 'Step the video frame by frame and capture the stills the argument rests on, then save them to the case as media made here.' },{ tool: 'board', text: 'Confirm what the import proposed, then link the frames to the place, the account and the people.' },{ tool: 'timeline', text: 'Date the claim; the axis reads it in the local time of the place, UTC one pick away.' },@@ -134,7 +134,7 @@ export const GUIDE = [lead: 'From work in the case to something somebody else can check.',steps: [{ tool: 'proof', text: 'Export the panels as a PNG. The spec is saved beside it, so next week the same proof reopens and edits.' },- { tool: 'post', text: 'Build the sourced thread. With the extension it fills the composer on X or Bluesky box by box, and stops before Post.' },+ { tool: 'post', text: 'Build the sourced thread. With the extension it fills the composer on X or Bluesky box by box.' },{ tool: 'notebook', text: 'Write the note around it, embed the case media and a diagram, and export the PDF.' },],},@@ -148,7 +148,7 @@ export const GUIDE = [points: [{label: 'Import or download',- text: 'The Media Library takes files off your disk and pulls posts from a URL. The first attempt is always made without cookies, and only a download that answers "unavailable" is retried with the browser session you saved.',+ text: 'Media takes files off your disk and pulls posts from a URL. The first attempt is always made without cookies, and only a link that answers "This link needs a login" is retried with your browser session.',},{label: 'State the origin once',@@ -164,7 +164,7 @@ export const GUIDE = [},{label: 'Send a picture from where you are looking at it',- text: 'Open in… on a Media Library row sends the file, and a frame in Inspect goes as you cropped it, saved or not.',+ text: 'Open in… on a Media row sends the file, and a frame in Inspect goes as you cropped it, saved or not.',},],},@@ -344,7 +344,7 @@ export const GUIDE = [id: 'shortcuts',title: 'Shortcuts',icon: 'keyboard',- lead: 'Every key the app listens for, by where it is pressed.',+ lead: 'The keys worth knowing, by where they are pressed.',tools: [],keymap: [{@@ -366,6 +366,31 @@ export const GUIDE = [{ combo: 'Shift+↑', does: 'puts north back up' },],},+ {+ where: 'Satellite',+ keys: [+ { combo: 'C or Space', does: 'clears the grid cell under review and flies to the next' },+ { combo: 'F', does: 'flags the cell under review' },+ { combo: 'S', does: 'skips to the next unchecked cell' },+ { combo: 'P', does: 'flags the cell and saves it as a place' },+ { combo: 'Enter', does: 'confirms a polygon grid area' },+ { combo: 'Escape', does: 'stops the review, or the area being drawn' },+ ],+ },+ {+ where: 'Compare',+ keys: [+ { combo: '1 / 2 / 3 / 4', does: 'side by side, swipe, fade or blink' },+ { combo: '5', does: 'lays Difference over the view, or lifts it' },+ { combo: 'Space', does: 'pauses the blink, or resumes it' },+ { combo: '[', does: 'folds the column to a rail and back' },+ { combo: 'V A R E P M L D T N S', does: 'picks select, arrow, box, ellipse, area, measure, line, freehand, note, numbered marker and symbol' },+ { combo: '← / →, Home / End', does: 'moves the focused swipe divider, or sends it to an edge' },+ { combo: 'Delete', does: 'removes the selected mark' },+ { combo: 'Ctrl+Z', does: 'undoes the last mark' },+ { combo: 'Ctrl+Shift+Z or Ctrl+Y', does: 'redoes it' },+ ],+ },{where: 'Graph',keys: [@@ -443,7 +468,7 @@ export const GUIDE = [{ combo: 'H', does: 'hides the candidates and areas, or shows them again' },{ combo: 'B', does: 'blinks A and B on the map, when the run read two passes' },{ combo: 'M', does: 'picks up the ruler, or puts it down' },- { combo: 'Delete', does: 'removes the selected measure' },+ { combo: 'Delete or Backspace', does: 'removes the selected measure' },],},{@@ -472,6 +497,13 @@ export const GUIDE = [{ combo: '← / →', does: 'walks the preview through the folder' },],},+ {+ where: 'Files',+ keys: [+ { combo: 'F2', does: 'renames the selected item' },+ { combo: 'Delete', does: 'deletes the selected items, after asking' },+ ],+ },],},{@@ -482,8 +514,8 @@ export const GUIDE = [tools: [],fixes: [{- symptom: 'A download answers "unavailable"',- fix: 'The site wants a session. The Media Library offers your browser cookies at that point, and only at that point: the first attempt is always made without them.',+ symptom: 'A download answers "This link needs a login"',+ fix: 'The site wants a session. Pick a browser you are signed in to there, or give an exported cookies.txt.',},{symptom: 'A video has no thumbnail, and frames will not export',@@ -498,8 +530,8 @@ export const GUIDE = [fix: 'Four providers need no key. The rest use yours, entered in Settings, Imagery, and the tab says which ones are missing one.',},{- symptom: 'The app opens on "this workspace is in use"',- fix: 'Another Azimut holds the folder. Close it, or take the lock from the screen offering it. Two copies writing one workspace is the one thing the app refuses.',+ symptom: 'The app opens on "Another Azimut has this workspace"',+ fix: 'Close the other Azimut and reload, or press "Take it anyway" if it is already gone.',},{symptom: 'The tab is closed and the app seems gone',diff --git a/frontend/src/lib/guide.test.js b/frontend/src/lib/guide.test.jsindex bb2deb9..d194125 100644--- a/frontend/src/lib/guide.test.js+++ b/frontend/src/lib/guide.test.js@@ -1,3 +1,6 @@+import { readdirSync, readFileSync } from 'node:fs';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';import { describe, expect, it } from 'vitest';import { GUIDE, guideFor, guideSection, readingSection } from './guide.js';import { CASE_WORKSPACE, TOOL_LABELS, WORKSPACES } from './workspaces.js';@@ -160,6 +163,30 @@ describe('the register the guide is written in', () => {}});+ it('quotes only words the app puts on screen', () => {+ // a quoted label is what the reader searches the screen for, so a renamed+ // dialog or button has to fail here rather than send them looking for nothing+ const root = fileURLToPath(new URL('../', import.meta.url));+ const sources = [];+ const walk = (dir) => {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const at = join(dir, entry.name);+ if (entry.isDirectory()) {+ if (entry.name !== 'node_modules') walk(at);+ } else if (/\.(svelte|js)$/.test(entry.name) && !entry.name.endsWith('.test.js') && entry.name !== 'guide.js') {+ sources.push(readFileSync(at, 'utf8'));+ }+ }+ };+ walk(root);+ const app = sources.join('\n');+ const quoted = prose().flatMap((line) => [...line.matchAll(/"([^"]+)"/g)].map((match) => match[1]));+ expect(quoted.length).toBeGreaterThan(0);+ for (const label of quoted) {+ expect(app.includes(label), `the guide quotes "${label}", which no screen shows`).toBe(true);+ }+ });+it('walks a recipe through tools that exist, in the words the tabs use', () => {const real = new Set([...RAIL_AND_CASE.flatMap((ws) => ws.tools)]);for (const section of GUIDE) {diff --git a/frontend/src/lib/keys.js b/frontend/src/lib/keys.jsnew file mode 100644index 0000000..2214624--- /dev/null+++ b/frontend/src/lib/keys.js@@ -0,0 +1,14 @@+/**+ * A shortcut as this machine spells it.+ *+ * The app listens for Ctrl or ⌘ alike (`ctrlKey || metaKey`), but the labels said+ * Ctrl everywhere, and on the macOS binary that is the key that does something else.+ */+export const IS_MAC =+ typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent || '');++/** `shortcut('Undo (Ctrl+Z)')` reads `Undo (⌘Z)` on a Mac and is left alone elsewhere. */+export function shortcut(label, mac = IS_MAC) {+ if (!mac) return label;+ return label.replace(/\bCtrl\+/g, '⌘').replace(/\bShift\+/g, '⇧').replace(/\bCtrl\b/g, '⌘');+}diff --git a/frontend/src/lib/keys.test.js b/frontend/src/lib/keys.test.jsnew file mode 100644index 0000000..c3c16a6--- /dev/null+++ b/frontend/src/lib/keys.test.js@@ -0,0 +1,14 @@+import { describe, expect, it } from 'vitest';+import { shortcut } from './keys.js';++describe('shortcut', () => {+ it('spells the modifier the way the machine labels its keys', () => {+ expect(shortcut('Undo (Ctrl+Z)', true)).toBe('Undo (⌘Z)');+ expect(shortcut('Ctrl+Shift+Z or Ctrl+Y', true)).toBe('⌘⇧Z or ⌘Y');+ expect(shortcut('Ctrl-click a second entry', true)).toBe('⌘-click a second entry');+ });++ it('leaves the label alone elsewhere', () => {+ expect(shortcut('Redo (Ctrl+Shift+Z)', false)).toBe('Redo (Ctrl+Shift+Z)');+ });+});diff --git a/frontend/src/lib/map/analyzerRules.js b/frontend/src/lib/map/analyzerRules.jsindex cdaaf34..e3b3e1a 100644--- a/frontend/src/lib/map/analyzerRules.js+++ b/frontend/src/lib/map/analyzerRules.js@@ -488,7 +488,7 @@ export function newRecipe(methods = [], { sensor = 'sentinel2', dates = 'two' }const radar = sensor === 'sentinel1';const sizes = methods.find((entry) => entry.id === (radar ? 'sar-change' : 'rules'))?.sizes;const two = dates === 'two';- const first = radar ? newRule('radar', two ? 'change' : 'b') : newRule('index', two ? 'change' : 'b');+ const first = newRule(radar ? 'radar' : 'brightness', two ? 'change' : 'b');return {id: 'custom', name: '', description: '', phenomenon: 'Candidate', method: 'rules', sensor, dates,parameters: { ...DEFAULT_PARAMETERS, ...(sizes?.all ?? {}) },@@ -755,7 +755,7 @@ const firstOf = (wanted, ids) => wanted.find((id) => ids.includes(id));* the layers the configuration offers.*/export function suggestedLayer(rule, layers = []) {- const ids = layers.map((layer) => layer.id);+ const ids = layers.filter((layer) => layer.enabled !== false).map((layer) => layer.id);const fallback = ids.includes('TRUE_COLOR') ? 'TRUE_COLOR' : ids[0] ?? 'TRUE_COLOR';if (!rule) return fallback;const swir = ['B11', 'B12'];@@ -763,13 +763,13 @@ export function suggestedLayer(rule, layers = []) {let wanted = ['TRUE_COLOR'];if (rule.measure === 'index') {wanted = {- ndvi: ['NDVI', 'FALSE_COLOR'], nbr: ['SWIR', 'MOISTURE_INDEX'], ndwi: ['NDWI', 'FALSE_COLOR'],- mndwi: ['NDWI', 'FALSE_COLOR'], ndbi: ['FALSE_COLOR_URBAN', 'SWIR'], bsi: ['SWIR', 'FALSE_COLOR_URBAN'],+ ndvi: ['NDVI', 'VEGETATION_INDEX', 'FALSE_COLOR', 'COLOR_INFRARED'], nbr: ['SWIR', 'MOISTURE_INDEX'], ndwi: ['NDWI', 'FALSE_COLOR', 'COLOR_INFRARED'],+ mndwi: ['NDWI', 'FALSE_COLOR', 'COLOR_INFRARED'], ndbi: ['FALSE_COLOR_URBAN', 'COLOR_INFRARED__URBAN_', 'SWIR'], bsi: ['SWIR', 'FALSE_COLOR_URBAN', 'COLOR_INFRARED__URBAN_'],}[rule.index] ?? wanted;} else if (rule.measure === 'nd' || rule.measure === 'band') {const bands = ruleBands(rule);- wanted = bands.some((band) => swir.includes(band)) ? ['SWIR', 'FALSE_COLOR']- : bands.some((band) => nir.includes(band)) ? ['FALSE_COLOR', 'NDVI'] : ['TRUE_COLOR'];+ wanted = bands.some((band) => swir.includes(band)) ? ['SWIR', 'FALSE_COLOR', 'COLOR_INFRARED']+ : bands.some((band) => nir.includes(band)) ? ['FALSE_COLOR', 'COLOR_INFRARED', 'NDVI', 'VEGETATION_INDEX'] : ['TRUE_COLOR'];} else if (rule.measure === 'class') {wanted = ['SCENE_CLASSIFICATION', 'TRUE_COLOR'];}diff --git a/frontend/src/lib/map/analyzerRules.test.js b/frontend/src/lib/map/analyzerRules.test.jsindex 35967d9..1169ea0 100644--- a/frontend/src/lib/map/analyzerRules.test.js+++ b/frontend/src/lib/map/analyzerRules.test.js@@ -4,7 +4,7 @@ import {describeWithout, directionOf, directionsFor, lineScale, shortRule, withAmount, withDirection,formatShare, formatValue, fromDifference, measuresFor, newRecipe, newRule, paintMask, passSource,pinTicks, productCount, readingRecipe, recipeBands, recipeCapability, recipeProblem, retarget, savingProblem,- scaleOf, sideOf, signalOf, toEngine, whensFor,+ scaleOf, sideOf, signalOf, suggestedLayer, toEngine, whensFor,checkDated, checkKey, checkState, checksSummary, describeChecks, describeOutcome, marksBounds, markOutcomes,newCheck, signature, testedCheck, withFlippedMark, withMark, withoutMark,} from './analyzerRules.js';@@ -176,6 +176,20 @@ describe('what a recipe reads', () => {expect(newRecipe(radarSizes, { sensor: 'sentinel1' }).parameters.smoothing).toBe(2);});+ it('starts blank optical analyzers on brightness and true colour', () => {+ const two = newRecipe(METHODS);+ expect(two.rules[0]).toMatchObject({ measure: 'brightness', on: 'change', op: 'moved', value: 0.05 });+ expect(newRecipe(METHODS, { dates: 'one' }).rules[0]).toMatchObject({ measure: 'brightness', on: 'b', op: 'ge', value: 0.2 });+ expect(suggestedLayer(two.rules[0], [{ id: 'TRUE_COLOR' }, { id: 'NDVI' }])).toBe('TRUE_COLOR');+ });++ it('suggests actual configuration identifiers and skips disabled display products', () => {+ expect(suggestedLayer(newRule('index'), [{ id: 'TRUE_COLOR' }, { id: 'NDVI', enabled: false },+ { id: 'VEGETATION_INDEX' }])).toBe('VEGETATION_INDEX');+ expect(suggestedLayer(newRule('index'), [{ id: 'TRUE_COLOR' }, { id: 'NDVI', enabled: false }])).toBe('TRUE_COLOR');+ expect(suggestedLayer(newRule('index', 'b', { index: 'ndwi' }), [{ id: 'COLOR_INFRARED' }])).toBe('COLOR_INFRARED');+ });+it('says why it cannot run before the engine has to', () => {expect(recipeProblem(recipe())).toMatch(/Add a rule/);expect(recipeProblem(recipe(newRule('index', 'change'), newRule('radar', 'change')))).toMatch(/two satellites/);diff --git a/frontend/src/lib/map/basemap.js b/frontend/src/lib/map/basemap.jsindex 3fe29dc..d3797ae 100644--- a/frontend/src/lib/map/basemap.js+++ b/frontend/src/lib/map/basemap.js@@ -274,6 +274,15 @@ export function rasterSource(provider, providerId, cell) {};}+export function imageryError(error) {+ const status = error?.status;+ if (status === 404) return 'No imagery is available here for this pass.';+ if (status === 400 || status === 422) return 'The imagery service refused this display layer.';+ if (status === 401 || status === 403) return 'The imagery service refused the key; check Settings → Imagery.';+ if (status === 429) return 'The imagery allowance is exhausted; check Settings → Imagery.';+ return 'The imagery could not be loaded; try again.';+}+/*** Own the layers of one map.*@@ -297,6 +306,7 @@ export function createBasemaps(engine, hooks = {}) {* it, so the tool that owns the layer can ask why (FIRMS: a spent* allowance, a refused key). */onOverlayTrouble = () => {},+ onImageryTrouble = () => {},} = hooks;const map = engine.impl;@@ -353,6 +363,8 @@ export function createBasemaps(engine, hooks = {}) {function onError(event) {const source = event?.sourceId;+ const key = source === IMAGERY ? live : source === ALTERNATE ? alternate : null;+ if (key) onImageryTrouble({ id: key.slice(0, key.lastIndexOf('@')), error: event.error });const overlay = source && OVERLAYS.find((entry) => overlaySourceIds(entry).includes(source));if (overlay) onOverlayTrouble(overlay.id);}@@ -486,6 +498,10 @@ export function createBasemaps(engine, hooks = {}) {showTiles(provider, providerId, cell);},+ retry(provider, providerId, cell) {+ if (provider && !provider.widget) showTiles(provider, providerId, cell);+ },+/*** Lay one overlay over the imagery, or take it off (`OVERLAY_IDS`).*diff --git a/frontend/src/lib/map/basemap.test.js b/frontend/src/lib/map/basemap.test.jsindex 266e6be..6196e04 100644--- a/frontend/src/lib/map/basemap.test.js+++ b/frontend/src/lib/map/basemap.test.js@@ -1,6 +1,6 @@// @vitest-environment happy-domimport { describe, expect, it, vi } from 'vitest';-import { OVERLAY_IDS, rasterSource, sourceMaxZoom, tileTemplate, tileUrls } from './basemap.js';+import { OVERLAY_IDS, imageryError, rasterSource, sourceMaxZoom, tileTemplate, tileUrls } from './basemap.js';/*** The provider shapes are the ones `/api/satellite/providers` really answers@@ -50,6 +50,14 @@ const WIDGET = {meter: 'google_js',};+it('explains imagery failures without exposing the upstream URL or response', () => {+ expect(imageryError({ status: 400, message: 'private upstream URL' })).toContain('display layer');+ expect(imageryError({ status: 404 })).toContain('No imagery');+ expect(imageryError({ status: 403 })).toContain('key');+ expect(imageryError({ status: 429 })).toContain('allowance');+ expect(imageryError(new Error('private upstream URL'))).toBe('The imagery could not be loaded; try again.');+});+describe('where a provider’s tiles are fetched from', () => {it('sends every provider it can through the backend proxy', () => {// keys and session tokens stay server-side, and a billed tile is counted@@ -434,6 +442,29 @@ describe('the layers on a map', () => {});});+ it('reports the failed imagery variant and rebuilds it only when Retry is pressed', async () => {+ await withStubbedGoogle(async ({ createBasemaps }) => {+ const map = stubMap();+ const trouble = vi.fn();+ const basemaps = createBasemaps(stubEngine(map), { onImageryTrouble: trouble });+ const id = 'sentinel2~TRUE_COLOR~2026-09-25~2026-09-25';+ basemaps.show(SENTINEL, id, 512);+ basemaps.setAlternate(SENTINEL, 'sentinel2~SWIR', 512);+ const [, onError] = map.calls.on.find(([name]) => name === 'error');+ const error = { status: 400 };+ onError({ sourceId: 'basemap-imagery', error });+ onError({ sourceId: 'basemap-alternate', error });+ onError({ sourceId: 'basemap-roads', error });+ expect(trouble.mock.calls).toEqual([[{ id, error }], [{ id: 'sentinel2~SWIR', error }]]);+ const source = map.sources.get('basemap-imagery');+ basemaps.show(SENTINEL, id, 512);+ expect(map.sources.get('basemap-imagery')).toBe(source);+ basemaps.retry(SENTINEL, id, 512);+ expect(map.sources.get('basemap-imagery')).not.toBe(source);+ expect(map.sources.get('basemap-imagery').tiles[0]).toContain(id);+ });+ });+it('adds an overlay once and takes it off when asked', async () => {await withStubbedGoogle(async ({ createBasemaps }) => {const map = stubMap();diff --git a/frontend/src/lib/map/bench.svelte.js b/frontend/src/lib/map/bench.svelte.jsindex 34855c9..9b68614 100644--- a/frontend/src/lib/map/bench.svelte.js+++ b/frontend/src/lib/map/bench.svelte.js@@ -22,18 +22,13 @@ import { acquisitionQuery, olderSpan, withOlder } from './acquisitions.js';import { clone, viewZone } from './analyzers.js';import { canPickPass } from './detectWhen.js';import { isoDay } from '../sentinel.js';+import { availableDisplayLayer, displayLayers, DISPLAY_LAYERS } from '../sentinelLayers.js';import {RULE_COLOURS, checkDated, checkKey, datesOf, markOutcomes, marksBounds, newCheck, passSource, readingRecipe,readsOneDate, readsRadar, recipeBands, recipeProblem, sensorOf, signalOf, signature, suggestedLayer, testedCheck,withFlippedMark, withMark, withoutMark,} from './analyzerRules.js';-/** What a configuration that has not answered yet still offers. */-const STANDARD_LAYERS = Object.freeze([- { id: 'TRUE_COLOR', label: 'True colour' }, { id: 'FALSE_COLOR', label: 'False colour (infrared)' },- { id: 'SWIR', label: 'SWIR (short-wave infrared)' }, { id: 'NDVI', label: 'NDVI (vegetation index)' },-]);-/** A lookup looks at the ground round the middle of the map, never a whole country. */const LOOKUP_REACH = 0.15;@@ -53,6 +48,8 @@ export class Bench {#recipe;#limits;#layers;+ #layerState;+ #radarLayer;#viewBounds;#fly;#say;@@ -75,6 +72,7 @@ export class Bench {/** The basemap instead of the passes, for a check that has them. */basemap = $state(false);layer = $state('TRUE_COLOR');+ displayNotice = $state('');/** Where the split sits, as a percentage of the map from its left edge. */divider = $state(50);/** What the map paints: each rule's pixels, or the detections alone. */@@ -95,11 +93,14 @@ export class Bench {/** How much of the map's bottom edge the console covers, in pixels, for a card to keep clear of it. */reach = $state(0);- constructor({ api, recipe, limits = {}, layers = () => [], viewBounds = () => null, fly = () => {}, say = () => {} }) {+ constructor({ api, recipe, limits = {}, layers = () => [], layerState = () => null, radarLayer = () => '',+ viewBounds = () => null, fly = () => {}, say = () => {} }) {this.#api = api;this.#recipe = recipe;this.#limits = limits;this.#layers = layers;+ this.#layerState = layerState;+ this.#radarLayer = radarLayer;this.#viewBounds = viewBounds;this.#fly = fly;this.#say = say;@@ -107,6 +108,17 @@ export class Bench {// The cost of the next test follows what it would read, and nothing else:// a line moved on a slider costs no request and asks no question.this.#dispose = $effect.root(() => {+ $effect(() => {+ const offered = this.offered;+ const layer = this.layer;+ if (this.radar || !offered.some((entry) => entry.enabled !== false)) return;+ const next = availableDisplayLayer(layer, offered);+ if (next === layer) return;+ untrack(() => {+ this.layer = next;+ this.displayNotice = `${layer} is unavailable; showing ${next}.`;+ });+ });$effect(() => {const keys = this.planKeys;const timer = setTimeout(() => untrack(() => void this.#refreshPlans(keys)), 250);@@ -128,10 +140,33 @@ export class Bench {get problem() { return recipeProblem(this.#recipe, this.#limits); }get current() { return signature(this.#recipe); }get colours() { return RULE_COLOURS; }- /** The Copernicus layers the configuration offers, or the standard four. */+ /** Available display layers, with missing standard products kept disabled. */get offered() {+ const state = this.#layerState();+ if (state) return displayLayers(state.layers, state.layersSource === 'instance', this.#radarLayer());const layers = this.#layers();- return layers.length ? layers : STANDARD_LAYERS;+ return layers.length ? layers : DISPLAY_LAYERS;+ }+ get layersBusy() { return this.#layerState()?.layersBusy ?? false; }+ get layersNote() {+ const state = this.#layerState();+ if (!state || this.radar) return '';+ if (state.layersBusy) return 'Checking your Copernicus layers…';+ if (state.layersNote) return state.layersNote;+ if (state.layersSource !== 'instance') return 'Check your Copernicus layers to show a pass.';+ if (!this.offered.some((entry) => entry.enabled)) return 'No optical display layer is available; the basemap stays on.';+ return this.displayNotice;+ }+ get dataProblem() {+ const state = this.#layerState();+ if (!state || this.radar) return '';+ if (state.layersSource !== 'instance') return 'Check your Copernicus layers before testing.';+ return state.layers.some((entry) => entry.id === 'TRUE_COLOR') ? ''+ : 'Optical rules need a Sentinel-2 L2A layer named TRUE_COLOR.';+ }+ checkLayers(force = false) {+ if (this.radar) return Promise.resolve(true);+ return this.#layerState()?.loadLayers(true, true, force) ?? Promise.resolve(true);}/** The panel waits while a check is being made: nothing else is touched until it is valid. */@@ -162,6 +197,7 @@ export class Bench {this.basemap = false;const check = this.#recipe.checks.find((entry) => entry.id === id);if (!check) return;+ void this.checkLayers();this.#adoptLayer(check);if (frame) this.#frame(check);}@@ -169,6 +205,7 @@ export class Bench {/** A new check, where the map is: passes first, then the pins. */startDraft() {if (this.draft || this.atMostChecks) return;+ void this.checkLayers();this.#returnTo = this.selected;this.selected = null;this.pinning = null;@@ -309,6 +346,7 @@ export class Bench {get imagery() {const check = this.check;if (!check || this.basemap || !check.b?.date) return { mode: 'basemap' };+ if (!this.radar && !this.offered.some((entry) => entry.id === this.layer && entry.enabled !== false)) return { mode: 'basemap' };const after = { ...check.b, layer: this.layer };const before = this.single || !check.a?.date ? null : { ...check.a, layer: this.layer };const shape = (source) => (this.radar ? { provider: 'sentinel1', date: source.date, time: source.time ?? '' }@@ -322,7 +360,9 @@ export class Bench {setBasemap(on) { this.basemap = on; }setLayer(id) {+ if (!this.offered.some((entry) => entry.id === id && entry.enabled !== false)) return;this.layer = id;+ this.displayNotice = '';this.basemap = false;if (this.radar) return;this.#patch((check) => ({ ...check, a: check.a?.date ? { ...check.a, layer: id } : check.a,@@ -336,7 +376,8 @@ export class Bench {#adoptLayer(check) {const own = check.b?.layer;- this.layer = own && this.offered.some((entry) => entry.id === own) ? own : this.#suggested();+ this.layer = availableDisplayLayer(own || this.#suggested(), this.offered) || own || this.#suggested();+ this.displayNotice = own && own !== this.layer ? `${own} is unavailable; showing ${this.layer}.` : '';}get suggestion() { return this.#suggested(); }@@ -438,6 +479,7 @@ export class Bench {if (!this.dated) return this.single ? 'Pick the pass this check is read on.' : 'Pick the before and after passes.';if (!check.marks.length) return 'Drop a pin to choose what this check reads.';if (this.problem) return this.problem;+ if (this.dataProblem) return this.dataProblem;if (this.plan?.error) return this.plan.error;return '';}@@ -479,8 +521,12 @@ export class Bench {/** Test every check that has its passes and a pin, one after the other. */async testAll() {if (this.running || this.problem) return;- const list = this.#recipe.checks.filter((check) => check.marks.length && checkDated(this.#recipe, check));+ this.running = 'Checking layers…';try {+ await this.checkLayers();+ if (this.#gone) return;+ if (this.dataProblem) { this.#say(this.dataProblem, 'warn'); return; }+ const list = this.#recipe.checks.filter((check) => check.marks.length && checkDated(this.#recipe, check));for (const [i, check] of list.entries()) {this.running = `Testing ${i + 1} of ${list.length}…`;await this.#run(check, { detail: check.id === this.check?.id });diff --git a/frontend/src/lib/map/bench.svelte.test.js b/frontend/src/lib/map/bench.svelte.test.jsindex 5034565..bc8ee19 100644--- a/frontend/src/lib/map/bench.svelte.test.js+++ b/frontend/src/lib/map/bench.svelte.test.js@@ -14,7 +14,8 @@ const settle = async () => {};/** A bench on a recipe of two dates, with an engine that answers what a real one would. */-function make({ dates = 'two', sensor = 'sentinel2', checks = [], answers = {}, limits = { max_checks: 12, max_marks: 20 } } = {}) {+function make({ dates = 'two', sensor = 'sentinel2', checks = [], answers = {}, layerState = null,+ limits = { max_checks: 12, max_marks: 20 } } = {}) {const recipe = $state({ ...newRecipe(METHODS, { sensor, dates }), name: 'Mine', checks });const calls = [];const api = {@@ -36,7 +37,7 @@ function make({ dates = 'two', sensor = 'sentinel2', checks = [], answers = {},};const fly = vi.fn();const say = vi.fn();- const bench = new Bench({ api, recipe, limits, layers: () => [], viewBounds: () => VIEW, fly, say });+ const bench = new Bench({ api, recipe, limits, layers: () => [], layerState: () => layerState, viewBounds: () => VIEW, fly, say });return { recipe, api, calls, bench, fly, say };}@@ -192,13 +193,53 @@ describe('choosing a check', () => {});describe('the imagery under the pins', () => {+ it('checks layers only on a check action and keeps the basemap until availability is known', async () => {+ const state = $state({ layers: [{ id: 'TRUE_COLOR' }], layersSource: 'catalogue', layersBusy: false, layersNote: '',+ loadLayers: vi.fn(async () => {}) });+ const { bench } = open({ layerState: state });+ flushSync();+ expect(state.loadLayers).not.toHaveBeenCalled();+ bench.startDraft();+ expect(state.loadLayers).toHaveBeenCalledWith(true, true, false);+ bench.setPass('b', { date: '2023-08-13' });+ expect(bench.imagery.mode).toBe('basemap');+ state.layersSource = 'instance'; flushSync();+ expect(bench.imagery.b.layer).toBe('TRUE_COLOR');+ });++ it('repairs an unavailable saved display using its actual alias, without changing the rules', () => {+ const state = $state({ layers: [{ id: 'TRUE_COLOR' }, { id: 'VEGETATION_INDEX' }], layersSource: 'instance',+ loadLayers: vi.fn(async () => true) });+ const kept = made('Plot'); kept.b.layer = 'NDVI';+ const { bench, recipe } = open({ checks: [kept], layerState: state });+ bench.select(kept.id); flushSync();+ expect(bench.imagery.b.layer).toBe('VEGETATION_INDEX');+ expect(bench.layersNote).toContain('NDVI is unavailable; showing VEGETATION_INDEX');+ expect(recipe.rules[0].measure).toBe('brightness');+ bench.setLayer('SWIR');+ expect(bench.layer).toBe('VEGETATION_INDEX');+ });++ it('keeps NDVI rules testable without an NDVI display, but blocks a missing optical data source', async () => {+ const state = $state({ layers: [{ id: 'TRUE_COLOR' }], layersSource: 'instance', loadLayers: vi.fn(async () => true) });+ const { bench, recipe, api } = open({ checks: [made('Plot')], layerState: state });+ recipe.rules = [newRule('index', 'change')];+ bench.select(bench.checks[0].id); await settle();+ expect(bench.canTest).toBe(true);+ expect(bench.offered.find((entry) => entry.id === 'NDVI').enabled).toBe(false);+ state.layers = [{ id: 'SWIR' }]; flushSync();+ expect(bench.canTest).toBe(false);+ expect(bench.dataProblem).toContain('TRUE_COLOR');+ await bench.testAll();+ expect(api.post.mock.calls.some(([path]) => path.endsWith('/check'))).toBe(false);+ });it('is the basemap until a check has a pass, then each pass as it is picked', () => {const { bench } = open();expect(bench.imagery).toEqual({ mode: 'basemap' });bench.startDraft();expect(bench.imagery).toEqual({ mode: 'basemap' });bench.setPass('b', { date: '2023-08-13' });- expect(bench.imagery).toEqual({ mode: 'single', b: { provider: 'sentinel2', date: '2023-08-13', layer: 'NDVI' } });+ expect(bench.imagery).toEqual({ mode: 'single', b: { provider: 'sentinel2', date: '2023-08-13', layer: 'TRUE_COLOR' } });bench.setPass('a', { date: '2023-08-08' });expect(bench.imagery).toEqual({ mode: 'swipe', a: expect.objectContaining({ date: '2023-08-08' }),b: expect.objectContaining({ date: '2023-08-13' }) });@@ -233,7 +274,7 @@ describe('the imagery under the pins', () => {it('starts on the layer that shows what the ranking rule reads, and the layer is not what is read', () => {const kept = made('Plot');const { bench, recipe } = open({ checks: [kept] });- expect(bench.layer).toBe('NDVI'); // the first rule is NDVI+ expect(bench.layer).toBe('TRUE_COLOR');bench.select(kept.id);bench.setLayer('SWIR');expect(recipe.checks[0].b.layer).toBe('SWIR');@@ -270,7 +311,7 @@ describe('what a test would cost', () => {bench.dropPin({ lon: REEF[0], lat: REEF[1] });await settle();expect(calls).toHaveLength(2);- recipe.rules[0].index = 'nbr';+ recipe.rules[0] = newRule('index', 'change', { index: 'nbr' });await settle();expect(calls).toHaveLength(3);});@@ -411,6 +452,7 @@ describe('testing', () => {bench.select(one.id);await settle();const all = bench.testAll();+ await Promise.resolve();expect(bench.running).toBe('Testing 1 of 2…');await all;expect(bench.running).toBe('');@@ -419,6 +461,21 @@ describe('testing', () => {expect(recipe.checks.map((check) => check.result?.signature)).toEqual([signature(recipe), signature(recipe)]);expect(bench.detail).not.toBe(null);});++ it('holds Test all while layers are checked and explains a missing data source', async () => {+ let release;+ const state = $state({ layers: [{ id: 'SWIR' }], layersSource: 'instance',+ loadLayers: vi.fn(() => new Promise((resolve) => { release = resolve; })) });+ const { bench, calls, say } = open({ checks: [made('Plot')], layerState: state });+ const pending = bench.testAll();+ expect(bench.running).toBe('Checking layers…');+ await bench.testAll();+ expect(state.loadLayers).toHaveBeenCalledTimes(1);+ release(true); await pending;+ expect(bench.running).toBe('');+ expect(say).toHaveBeenCalledWith(expect.stringContaining('TRUE_COLOR'), 'warn');+ expect(calls.filter(([url]) => url.endsWith('/check'))).toHaveLength(0);+ });});describe('a point of the ground', () => {diff --git a/frontend/src/lib/map/detectWhen.js b/frontend/src/lib/map/detectWhen.jsindex f422c6e..f7fbc4c 100644--- a/frontend/src/lib/map/detectWhen.js+++ b/frontend/src/lib/map/detectWhen.js@@ -151,15 +151,6 @@ export function whenNeed({ single, routine, against, pairs, chooseB, lastPassesreturn '';}-/** One area's days, for the list shown when the areas differ. */-export function areaLine(pair, { single, routine, radar = false }) {- const newest = newestLabel({ maxcc: pair?.b?.maxcc, radar });- const a = sideLine(pair?.a, radar) || 'not chosen';- const b = sideLine(pair?.b, radar) || newest;- if (single) return routine ? newest : b;- return routine ? `A ${a}` : `A ${a} → B ${b}`;-}-/** The step as one line, for the recap before the start. */export function whenSummary({ single, routine, against, pairs, radar = false, maxcc = 100 }) {if (pairs.length > 1 && !uniform(pairs)) return 'Its own days for each area';diff --git a/frontend/src/lib/map/detectWhen.test.js b/frontend/src/lib/map/detectWhen.test.jsindex 9c3d0f9..c4fb17c 100644--- a/frontend/src/lib/map/detectWhen.test.js+++ b/frontend/src/lib/map/detectWhen.test.js@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';import {- ADVISED_MAXCC, areaLine, canPickPass, ceilingWarning, newestLabel, newestLine, newestPick, passBefore, setSide, shadowLength, shadowWarning, sharedSide, sideLine, uniform,+ ADVISED_MAXCC, canPickPass, ceilingWarning, newestLabel, newestLine, newestPick, passBefore, setSide, shadowLength, shadowWarning, sharedSide, sideLine, uniform,whenNeed, whenSummary, withRule,} from './detectWhen.js';@@ -97,16 +97,6 @@ describe('the When step of a detection', () => {expect(whenNeed({ ...base, single: true, against: 'previous', followupId: null })).toBe('');});- it('lists one area\'s days when the areas differ', () => {- const once = { single: false, routine: false };- // "newest" is the newest the ceiling allows, and says so- expect(areaLine(pair('x', '2026-08-01'), once)).toBe('A 2026-08-01 → B newest pass under 30% cloud');- expect(areaLine(pair('x', '', '2026-09-06'), once)).toBe('A not chosen → B 2026-09-06');- expect(areaLine(pair('x', '', '2026-09-06'), { ...once, single: true })).toBe('2026-09-06');- expect(areaLine(pair('x', '2026-08-01'), { ...once, routine: true })).toBe('A 2026-08-01');- expect(areaLine(pair('x'), { single: true, routine: true })).toBe('newest pass under 30% cloud');- });-it('sums the step up in one line', () => {const once = { single: false, routine: false, against: 'previous' };expect(whenSummary({ ...once, pairs: [pair('x', '2026-08-01')] })).toBe('2026-08-01 → newest pass');diff --git a/frontend/src/lib/map/firePoints.js b/frontend/src/lib/map/firePoints.jsindex 41022fd..5fe489b 100644--- a/frontend/src/lib/map/firePoints.js+++ b/frontend/src/lib/map/firePoints.js@@ -16,9 +16,7 @@* close in gives each one a square of the sensor's footprint.*/-/** The shallowest zoom whose tiles carry the detections themselves, and the- * deepest tile there is, as the backend serves them. */-export const POINTS_MIN_ZOOM = 8;+/** The deepest tile the backend serves the detections in. */export const POINTS_MAX_ZOOM = 13;/** The smallest a detection is drawn, on screen: the size FIRMS's pictures use. */export const MARK_PX = 7;diff --git a/frontend/src/lib/map/firePoints.test.js b/frontend/src/lib/map/firePoints.test.jsindex 040d987..a4c7eff 100644--- a/frontend/src/lib/map/firePoints.test.js+++ b/frontend/src/lib/map/firePoints.test.js@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';import {- FIRE_MARKS, HANDOVER, MARK_PX, POINT_LAYERS, POINTS_MAX_ZOOM, POINTS_MIN_ZOOM, SQUARE,+ FIRE_MARKS, HANDOVER, MARK_PX, POINT_LAYERS, POINTS_MAX_ZOOM, SQUARE,markSize, marksUrl, squareImage, TILE_REVISION,} from './firePoints.js';@@ -39,7 +39,7 @@ describe('FIRMS marks, drawn by the map', () => {});it('asks the zooms the backend serves', () => {- expect([POINTS_MIN_ZOOM, POINTS_MAX_ZOOM]).toEqual([8, 13]);+ expect(POINTS_MAX_ZOOM).toBe(13);});it('keeps a mark the same size on screen until its footprint is bigger', () => {diff --git a/frontend/src/lib/sentinelLayers.js b/frontend/src/lib/sentinelLayers.jsnew file mode 100644index 0000000..83c819b--- /dev/null+++ b/frontend/src/lib/sentinelLayers.js@@ -0,0 +1,32 @@+/** Display layers are configuration entries; rule quantities are computed from bands. */+export const DISPLAY_LAYERS = Object.freeze([+ { id: 'TRUE_COLOR', label: 'True colour', aliases: [] },+ { id: 'FALSE_COLOR', label: 'False colour (infrared)', aliases: ['COLOR_INFRARED'] },+ { id: 'SWIR', label: 'SWIR (short-wave infrared)', aliases: [] },+ { id: 'NDVI', label: 'NDVI (vegetation index)', aliases: ['VEGETATION_INDEX'] },+]);++export function displayLayerFamily(id) {+ return DISPLAY_LAYERS.find((entry) => entry.id === id || entry.aliases.includes(id))?.id ?? id;+}++export function displayLayers(layers, verified, radarLayer = '') {+ const offered = layers.filter((entry) => entry.id !== radarLayer).map((entry) => ({+ ...entry, enabled: verified,+ reason: verified ? '' : 'Check your Copernicus layers first.',+ }));+ for (const { id, label } of DISPLAY_LAYERS) {+ if (offered.some((entry) => displayLayerFamily(entry.id) === id)) continue;+ offered.push({ id, label, enabled: false,+ reason: verified ? 'Not in your Copernicus configuration.' : 'Check your Copernicus layers first.' });+ }+ return offered;+}++export function availableDisplayLayer(wanted, offered) {+ const available = offered.filter((entry) => entry.enabled !== false);+ return available.find((entry) => entry.id === wanted)?.id+ ?? available.find((entry) => displayLayerFamily(entry.id) === displayLayerFamily(wanted))?.id+ ?? available.find((entry) => entry.id === 'TRUE_COLOR')?.id+ ?? available[0]?.id ?? '';+}diff --git a/frontend/src/lib/sentinelLayers.test.js b/frontend/src/lib/sentinelLayers.test.jsnew file mode 100644index 0000000..0c150bb--- /dev/null+++ b/frontend/src/lib/sentinelLayers.test.js@@ -0,0 +1,26 @@+import { expect, it } from 'vitest';+import { availableDisplayLayer, displayLayers } from './sentinelLayers.js';++const configured = [{ id: 'TRUE_COLOR', label: 'True colour' }, { id: 'VEGETATION_INDEX', label: 'Vegetation Index - NDVI' },+ { id: 'RADAR', label: 'Radar' }];++it('keeps actual identifiers, excludes the radar layer and greys missing displays', () => {+ const options = displayLayers(configured, true, 'RADAR');+ expect(options.find((entry) => entry.id === 'VEGETATION_INDEX').enabled).toBe(true);+ expect(options.some((entry) => ['NDVI', 'RADAR'].includes(entry.id))).toBe(false);+ expect(options.find((entry) => entry.id === 'SWIR')).toMatchObject({ enabled: false, reason: 'Not in your Copernicus configuration.' });+ expect(availableDisplayLayer('NDVI', options)).toBe('VEGETATION_INDEX');+ expect(availableDisplayLayer('SWIR', options)).toBe('TRUE_COLOR');+});++it('never treats the fallback catalogue as verified availability', () => {+ const options = displayLayers(configured, false);+ expect(options.every((entry) => !entry.enabled)).toBe(true);+ expect(availableDisplayLayer('TRUE_COLOR', options)).toBe('');+});++it('keeps a custom configured display and handles an empty configuration', () => {+ const options = displayLayers([{ id: 'MY_GROUND', label: 'My ground' }], true);+ expect(availableDisplayLayer('NDVI', options)).toBe('MY_GROUND');+ expect(displayLayers([], true).every((entry) => !entry.enabled)).toBe(true);+});diff --git a/frontend/src/lib/state.svelte.js b/frontend/src/lib/state.svelte.jsindex 1e9f808..8ac5fb9 100644--- a/frontend/src/lib/state.svelte.js+++ b/frontend/src/lib/state.svelte.js@@ -384,9 +384,15 @@ let toastSeq = 0;* A timeout of 0 holds it up until `dismissToast` takes it down, which is how a* wait of unknown length is said: the message has to outlast the work rather* than a guess at how long the work takes. Returns the id either way.+ *+ * Without a timeout, a failure or a toast offering an action stays long enough to+ * be read and pressed; a plain confirmation goes quickly. `error` is taken as+ * `danger`, the one kind the toast styles as a failure.*/-export function toast(message, kind = 'info', timeout = 3800, action = null) {+export function toast(message, kind = 'info', timeout = null, action = null) {const id = ++toastSeq;+ if (kind === 'error') kind = 'danger';+ if (timeout == null) timeout = kind === 'danger' || action ? 8000 : 3800;uiState.toasts.push({ id, message, kind, action });if (timeout > 0) setTimeout(() => dismissToast(id), timeout);return id;diff --git a/frontend/src/lib/toast.test.js b/frontend/src/lib/toast.test.jsindex 19e065e..26e26db 100644--- a/frontend/src/lib/toast.test.js+++ b/frontend/src/lib/toast.test.js@@ -26,3 +26,21 @@ describe('toast actions', () => {expect(uiState.toasts).toHaveLength(0);});});++describe('toast kinds and how long they stay', () => {+ it('takes error as danger, the kind the toast styles as a failure', () => {+ toast('This sheet could not be saved.', 'error');+ expect(uiState.toasts[0].kind).toBe('danger');+ });++ it('keeps a failure, or a toast with an action, up long enough to read and press', () => {+ vi.useFakeTimers();+ toast('Not saved', 'danger');+ toast('Removed', 'ok', undefined, { label: 'Undo', onClick: vi.fn() });+ toast('Copied', 'ok');+ vi.advanceTimersByTime(3800);+ expect(uiState.toasts.map((t) => t.message)).toEqual(['Not saved', 'Removed']);+ vi.advanceTimersByTime(4200);+ expect(uiState.toasts).toHaveLength(0);+ });+});diff --git a/frontend/src/tools/Board.svelte b/frontend/src/tools/Board.svelteindex 9689937..c10485e 100644--- a/frontend/src/tools/Board.svelte+++ b/frontend/src/tools/Board.svelte@@ -97,6 +97,7 @@import { loadRelationTypes } from '../lib/relations.svelte.js';import { fetchEventRows } from '../lib/catalog.js';import { offerNote } from '../lib/noteHere.svelte.js';+ import NoCase from '../components/NoCase.svelte';import {BOARD_GROUPS,GROUPINGS,@@ -1388,7 +1389,7 @@/><buttonclass="btn"- title="Take a file into the case: a document, a scan, a plan, an image"+ title="Add a file to the case"disabled={!caseState.current || importing || snapshotReading}onclick={() => fileInput?.click()}>@@ -1560,7 +1561,7 @@</div>{/if}{#if !caseState.current}- <p class="empty">Open a case to see what it holds.</p>+ <NoCase icon="grid" what="see what it holds" />{:else if totalling}<!-- The addition. One row per subject the statements point at, and every numberbeside what it left out: a sum that hid its uncounted and its ruled-outdiff --git a/frontend/src/tools/Collage.render.svelte.test.js b/frontend/src/tools/Collage.render.svelte.test.jsindex 587d95c..56d1bc5 100644--- a/frontend/src/tools/Collage.render.svelte.test.js+++ b/frontend/src/tools/Collage.render.svelte.test.js@@ -464,6 +464,53 @@ describe('finding and leaving a collage', () => {expect(target.querySelector('.tool-header')).not.toBeNull();expect(toast).toHaveBeenCalledWith('The collage could not be saved, so it stays open', 'warn');});++ it('writes again on Retry after a failed save', async () => {+ post.mockImplementationOnce(async () => {+ throw new Error('disk full');+ });+ await start();+ button('New collage').click();+ await settle();+ button('Images').click();+ flushSync();+ target.querySelector('.picker .thumb').click();+ await settle(20);+ button('Close').click(); // the save runs, and fails+ await settle(20);+ expect(target.querySelector('.status.error')).not.toBeNull();+ const before = collagePosts().length;++ button('Retry').click();+ await settle(20);++ expect(collagePosts().length).toBe(before + 1);+ expect(target.querySelector('.status.error')).toBeNull();+ });++ it('keeps an unsaved collage open when another is asked for', async () => {+ post.mockImplementation(async () => {+ throw new Error('disk full');+ });+ await start();+ button('New collage').click();+ await settle();+ button('Images').click();+ flushSync();+ target.querySelector('.picker .thumb').click();+ await settle(20);+ button('Close').click();+ await settle(20);+ toast.mockClear();++ [...document.querySelectorAll('button')].find((el) => el.title === 'Start an empty canvas').click();+ await settle(20);++ expect(toast).toHaveBeenCalledWith('The collage could not be saved, so it stays open', 'warn');+ expect(target.querySelector('.status.error')).not.toBeNull();+ post.mockReset();+ post.mockImplementation(async (path, body) => (path === '/api/cases/case-a/collages' ? { name: body.title, title: body.title } : {}));+ });});describe('the piece picker', () => {diff --git a/frontend/src/tools/Collage.svelte b/frontend/src/tools/Collage.svelteindex 27a4dcf..71989f9 100644--- a/frontend/src/tools/Collage.svelte+++ b/frontend/src/tools/Collage.svelte@@ -1,5 +1,5 @@<script>- import { api } from '../lib/api.js';+ import { api, detailLine } from '../lib/api.js';import { fileUrl } from '../lib/fileUrl.js';import { caseState, uiState, reloadCase, toast } from '../lib/state.svelte.js';import {@@ -24,6 +24,8 @@import PiecePicker from './inspect/PiecePicker.svelte';import PieceCropModal from './inspect/PieceCropModal.svelte';import SaveToCase from './inspect/SaveToCase.svelte';+ import NoCase from '../components/NoCase.svelte';+ import { shortcut } from '../lib/keys.js';// A collage lays out pieces from any number of files on one canvas: frames cut// in Inspect, or images already in the case. It is a document of its own, saved@@ -365,9 +367,18 @@cropPieceNode = null;}+ /** A collage whose save failed is held open, where the header says so and offers+ * Retry, rather than dropped by whatever was about to replace it. */+ function heldUnsaved() {+ if (!autosave.unsaved) return false;+ toast('The collage could not be saved, so it stays open', 'warn');+ return true;+ }+async function newCollage() {listOpen = false;await autosave.flush();+ if (heldUnsaved()) return;await refreshList();closeDoc();doc.open = true;@@ -380,6 +391,7 @@async function openCollage(name) {listOpen = false;await autosave.flush();+ if (heldUnsaved()) return;await ensureOps();closeDoc();const run = docRun;@@ -457,7 +469,7 @@if (!res.ok) {let detail = 'render failed';try {- detail = (await res.json()).detail;+ detail = detailLine((await res.json()).detail) || detail;} catch {/* non-json */}@@ -588,10 +600,7 @@async function closeCollage() {await renaming;await autosave.flush();- if (autosave.state.status === 'error') {- toast('The collage could not be saved, so it stays open', 'warn');- return;- }+ if (heldUnsaved()) return;closeDoc();query = '';await refreshList();@@ -722,10 +731,10 @@<button class="btn btn-ghost btn-xs" onclick={() => autosave.flush()}>Retry</button>{/if}<div class="spacer"></div>- <button class="btn btn-ghost btn-sm" title="Undo (Ctrl+Z)" disabled={!canUndo} onclick={undo}>+ <button class="btn btn-ghost btn-sm" title={shortcut('Undo (Ctrl+Z)')} disabled={!canUndo} onclick={undo}><Icon name="undo" size={15} /></button>- <button class="btn btn-ghost btn-sm" title="Redo (Ctrl+Shift+Z / Ctrl+Y)" disabled={!canRedo} onclick={redo}>+ <button class="btn btn-ghost btn-sm" title={shortcut('Redo (Ctrl+Shift+Z / Ctrl+Y)')} disabled={!canRedo} onclick={redo}><Icon name="redo" size={15} /></button><button class="btn btn-sm" onclick={() => { query = ''; refreshList(); listOpen = true; }} title="Open another collage">@@ -741,10 +750,7 @@{/if}{#if !caseState.current}- <div class="empty">- <Icon name="grid" size={40} />- <p>Open a case to lay out a collage.</p>- </div>+ <NoCase icon="grid" what="lay out a collage" />{:else if !doc.open}<div class="start"><div class="start-col">@@ -828,7 +834,7 @@<ConfirmDialogtitle="Delete this collage?"message={`“${deleting.title}” goes to the Trash.`}- detail="A picture already saved from it stays in the Media Library."+ detail="A picture already saved from it stays in Media."confirmLabel="Delete"tone="danger"icon="trash"@@ -868,16 +874,6 @@.spacer {flex: 1;}- .empty {- flex: 1;- display: flex;- flex-direction: column;- align-items: center;- justify-content: center;- gap: 12px;- color: var(--text-3);- text-align: center;- }/* The whole panel scrolls and the column sits centred in it, so the wheel worksover the margins and the scrollbar stays on the edge. */.start {diff --git a/frontend/src/tools/Compare.svelte b/frontend/src/tools/Compare.svelteindex fc0fcf8..7fe44ba 100644--- a/frontend/src/tools/Compare.svelte+++ b/frontend/src/tools/Compare.svelte@@ -19,6 +19,7 @@toast,uiState,} from '../lib/state.svelte.js';+ import { copyText } from '../lib/clipboard.js';import { saveRelation } from '../lib/relations.svelte.js';import { actionsFor, otherMapTools } from '../lib/map/contextMenu.js';import { openMapAt } from '../lib/navigate.js';@@ -1691,12 +1692,7 @@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');- }+ await copyText(value);} else if (id === 'place') {openNewPlaceAt(point);} else if (id === 'measure') {diff --git a/frontend/src/tools/Coordinates.svelte b/frontend/src/tools/Coordinates.svelteindex d06f50c..2b1a6b7 100644--- a/frontend/src/tools/Coordinates.svelte+++ b/frontend/src/tools/Coordinates.svelte@@ -8,6 +8,7 @@// sky panel below is pure local computation and never goes out.import { api } from '../lib/api.js';import { caseState, toast, uiState } from '../lib/state.svelte.js';+ import { copyText } from '../lib/clipboard.js';import { mapLinks } from '../lib/maplinks.js';import { bidiSafe } from '../lib/bidi.js';import Icon from '../components/Icon.svelte';@@ -53,8 +54,7 @@}async function copy(value) {- await navigator.clipboard.writeText(bidiSafe(value));- toast('Copied', 'ok', 1400);+ await copyText(bidiSafe(value));}async function lookupPlace() {diff --git a/frontend/src/tools/Detect.svelte b/frontend/src/tools/Detect.svelteindex 789ba3e..7a91be3 100644--- a/frontend/src/tools/Detect.svelte+++ b/frontend/src/tools/Detect.svelte@@ -18,6 +18,7 @@import { onMount, tick, untrack } from 'svelte';import { api } from '../lib/api.js';import { caseState, dismissToast, prefs, prefsReady, toast, uiState } from '../lib/state.svelte.js';+ import { copyText } from '../lib/clipboard.js';import { marksToZones, sourceLabel, viewZone, zoneMarks, zoneRing } from '../lib/map/analyzers.js';import { blinkable } from '../lib/map/detectReview.js';import { ADVISED_MAXCC } from '../lib/map/detectWhen.js';@@ -411,12 +412,7 @@if (id === 'lookup') return lookUpPoint(point);closePointMenu();if (id === 'copy') {- try {- await navigator.clipboard.writeText(value);- toast('Coordinates copied', 'ok', 1600);- } catch {- toast('The browser refused the clipboard', 'warn');- }+ await copyText(value);} else if (id === 'candidate') {await panel?.addCandidate(at.areaId, { type: 'Point', coordinates: [point.lon, point.lat] });} else if (id === 'measure') {@@ -701,13 +697,14 @@onusage={() => imagery.refreshUsage()}onviewsettled={onSettled}oncontextmenu={onMapContextMenu}+ onimageryfallback={() => builder ? builder.setBasemap(true) : leavePass()}/>{#if builder?.split}<SecondPass {imagery} primary={engine} source={builder.imagery.b} {view} {bearing} {home} {overlays}imperial={prefs.units === 'imperial'} armed={measuring ? 'measuring' : builder.pinning ? 'selecting' : null}divider={builder.divider} bind:engine={secondEngine} bind:element={secondElement}onsplit={(percent) => builder.setDivider(percent)} onclick={onMapClick} oncontextmenu={onMapContextMenu}- onusage={() => imagery.refreshUsage()} />+ onusage={() => imagery.refreshUsage()} onimageryfallback={() => builder.setBasemap(true)} />{/if}{#if builder}<RuleLayers {engine} {element} detail={builder.detail} rules={builder.recipe.rules} shown={paintedRules}@@ -827,6 +824,7 @@bind:builderviewBounds={() => engine?.viewBounds?.() ?? null}passLayers={s2.layers}+ passLayerState={s2}onfly={({ lon, lat, zoom, bounds }) => (bounds ? engine?.fitBounds(bounds, { padding: 40 }) : engine?.setView({ lon, lat }, zoom))}/></div>diff --git a/frontend/src/tools/Files.svelte b/frontend/src/tools/Files.svelteindex c2bd498..f0178b6 100644--- a/frontend/src/tools/Files.svelte+++ b/frontend/src/tools/Files.svelte@@ -72,6 +72,7 @@import FolderSelect from '../components/FolderSelect.svelte';import PasteDialog from '../components/PasteDialog.svelte';import SourceDialog from '../components/SourceDialog.svelte';+ import NoCase from '../components/NoCase.svelte';const TYPE_ICON = {media: 'image', capture: 'satellite', note: 'note', proof: 'proof',@@ -1126,11 +1127,7 @@</div>{#if !caseState.current}- <div class="empty" style="height: 100%">- <div class="empty-icon"><Icon name="folder" size={42} /></div>- <h3>No case open</h3>- <p>Create or open a case to organize its files.</p>- </div>+ <NoCase icon="folder" what="organize its files" />{:else}<div class="workbench"><!-- left: folder tree (navigation + drop targets) -->diff --git a/frontend/src/tools/Graph.svelte b/frontend/src/tools/Graph.svelteindex a916587..c87d075 100644--- a/frontend/src/tools/Graph.svelte+++ b/frontend/src/tools/Graph.svelte@@ -162,6 +162,7 @@import EntityDetails from '../components/EntityDetails.svelte';import PasteDialog from '../components/PasteDialog.svelte';import SnapshotDetails from '../components/SnapshotDetails.svelte';+ import { shortcut } from '../lib/keys.js';loadEntityTypes();loadRelationTypes();@@ -2376,6 +2377,15 @@record();}+ /** The page is going away and no timer will run: send the moves still waiting with+ * `keepalive`, which outlives the page. */+ function onpagehide() {+ if (!savingCase || !pending.size) return;+ const pins = [...pending.entries()].map(([id, at]) => ({ id, x: at.x, y: at.y }));+ api.put(`/api/cases/${savingCase}/graph/pins`, { lens: savingFor ?? lens, pins }, { keepalive: true })+ .catch(() => {});+ }+/*** Send the moves nobody has filed yet.*@@ -4773,7 +4783,8 @@$effect(() => () => {if (frame) cancelAnimationFrame(frame);frame = 0;- // A drag inside the debounce window would otherwise be lost to the tab closing.+ // A drag inside the debounce window would otherwise be lost to the tool unmounting.+ // The tab closing runs no teardown: `onpagehide` below sends it then.flushPins();stage?.destroy();stage = null;@@ -4787,6 +4798,7 @@onpointermove={onPointerMove}onpointerup={onPointerUp}onpointercancel={onPointerUp}+ {onpagehide}/><div class="graph-tool" bind:this={toolElement}>@@ -4810,7 +4822,7 @@<!-- Named for what it decides rather than for what it does to the survivors:*Keep* read as a verb the analyst was pressing, and the drawing has a listof nodes kept by name that this control has nothing to do with. -->- <label class="control" title="Which nodes this view keeps, now that the case is too large to draw whole">+ <label class="control" title="Which nodes to keep when the case is too large">Ranking<select class="select pick" bind:value={order}>{#each orders as entry (entry.value)}@@ -4932,7 +4944,7 @@cases where this number matters it would always have read zero. --><spanclass="count isolated"- title="Nothing in this lens connects to them, counted across the case"+ title="Connected to nothing in this lens">{payload.isolated} unconnected</span>@@ -5011,7 +5023,7 @@<buttonclass="btn btn-ghost btn-sm placed"onclick={undo}- title="Undo the last change to the drawing (Ctrl+Z)"+ title={shortcut('Undo the last change to the drawing (Ctrl+Z)')}><Icon name="undo" size={14} stroke={1.7} />Undo@@ -5021,7 +5033,7 @@<buttonclass="btn btn-ghost btn-sm placed"onclick={redo}- title="Do it again (Ctrl+Shift+Z)"+ title={shortcut('Do it again (Ctrl+Shift+Z)')}><Icon name="redo" size={14} stroke={1.7} />Redo@@ -5349,14 +5361,14 @@class:set={onlyThis}aria-pressed={onlyThis}onclick={toggleOnly}- title="Take the rest of the case off the screen and frame what is left"+ title="Hide the rest of the case">Only this</button><buttonclass="step wide"onclick={() => askWayFrom(chosen.id)}- title="Find how this reaches another entity: click the other end, or name it"+ title="Find a path to another entity">Path to…</button>diff --git a/frontend/src/tools/Graph.test.js b/frontend/src/tools/Graph.test.jsindex 7e259e6..f9a73f2 100644--- a/frontend/src/tools/Graph.test.js+++ b/frontend/src/tools/Graph.test.js@@ -2153,3 +2153,10 @@ describe('Graph offers what is open to the Add event bar', () => {expect(source).toContain("onDestroy(() => withdrawNote('graph'))");});});++describe('a drag and a closing tab', () => {+ it('sends the moves still waiting with keepalive when the page goes', () => {+ expect(source).toMatch(/<svelte:window[^>]*\{onpagehide\}/s);+ expect(source).toContain('{ lens: savingFor ?? lens, pins }, { keepalive: true }');+ });+});diff --git a/frontend/src/tools/Guide.svelte b/frontend/src/tools/Guide.svelteindex f25507b..f34a27a 100644--- a/frontend/src/tools/Guide.svelte+++ b/frontend/src/tools/Guide.svelte@@ -17,6 +17,7 @@import { ALL_WORKSPACES, TOOL_LABELS } from '../lib/workspaces.js';import { uiState } from '../lib/state.svelte.js';import Icon from '../components/Icon.svelte';+ import { shortcut } from '../lib/keys.js';/** Where the whole picture lives, for a reader who downloaded a binary and has no* repository in front of them. */@@ -203,7 +204,7 @@<h3>{group.where}</h3><ul class="keys">{#each group.keys as key (key.combo)}- <li><kbd>{key.combo}</kbd><span>{key.does}</span></li>+ <li><kbd>{shortcut(key.combo)}</kbd><span>{shortcut(key.does)}</span></li>{/each}</ul></div>diff --git a/frontend/src/tools/Inspector.svelte b/frontend/src/tools/Inspector.svelteindex ae96e1b..e5d8530 100644--- a/frontend/src/tools/Inspector.svelte+++ b/frontend/src/tools/Inspector.svelte@@ -1,6 +1,6 @@<script>import { onDestroy } from 'svelte';- import { api } from '../lib/api.js';+ import { api, detailLine } from '../lib/api.js';import { fileUrl } from '../lib/fileUrl.js';import { caseState, uiState, reloadCase, toast } from '../lib/state.svelte.js';import { workFolder } from '../lib/folders.js';@@ -24,6 +24,7 @@import FrameMenu from './inspect/FrameMenu.svelte';import VideoMenu from './inspect/VideoMenu.svelte';import VideoPlayer from './inspect/VideoPlayer.svelte';+ import NoCase from '../components/NoCase.svelte';// Inspect works on one file at a time: a video to cut frames from, or an image// to read closely. What is done to it is its work, one per file, kept as it is@@ -245,9 +246,18 @@frameAspect = null;}+ /** A work whose save failed is held open, where the header says so and offers Retry,+ * rather than dropped by whatever was about to replace it. */+ function heldUnsaved() {+ if (!autosave.unsaved) return false;+ toast('The work could not be saved, so it stays open', 'warn');+ return true;+ }+async function open(item) {pickerOpen = false;await autosave.flush();+ if (heldUnsaved()) return;await ensureOps();closeFile();const run = openRun;@@ -275,9 +285,11 @@}}- /** Back to the file list. Nothing is lost: what is pending is written first. */+ /** Back to the file list. Nothing is lost: what is pending is written first, and a+ * work that cannot be saved stays open. */async function leave() {await autosave.flush();+ if (heldUnsaved()) return;closeFile();refreshWorks();}@@ -420,7 +432,7 @@if (!res.ok) {let detail = 'render failed';try {- detail = (await res.json()).detail;+ detail = detailLine((await res.json()).detail) || detail;} catch {/* non-json */}@@ -741,17 +753,13 @@{/if}{#if !caseState.current}- <div class="empty">- <Icon name="inspect" size={40} />- <p>Open a case and add media to start inspecting.</p>- <button class="btn" onclick={() => (uiState.tool = 'media')}>Go to Media Library</button>- </div>+ <NoCase icon="inspect" what="inspect its pictures and videos" />{:else if !work.source}{#if inspectable.length === 0}<div class="empty"><Icon name="inspect" size={40} /><p>Add an image or a video to the case to inspect it.</p>- <button class="btn" onclick={() => (uiState.tool = 'media')}>Go to Media Library</button>+ <button class="btn" onclick={() => (uiState.tool = 'media')}>Go to Media</button></div>{:else}<div class="start">diff --git a/frontend/src/tools/MediaLibrary.svelte b/frontend/src/tools/MediaLibrary.svelteindex bbd8ae2..5111417 100644--- a/frontend/src/tools/MediaLibrary.svelte+++ b/frontend/src/tools/MediaLibrary.svelte@@ -594,7 +594,7 @@uiState.openSheet = sheetId;uiState.tool = 'sheet';} catch (error) {- toast(error.message || 'The worklist could not be opened.', 'error');+ toast(error.message || 'The worklist could not be opened.', 'danger');} finally {worklistBusy = false;}@@ -903,7 +903,7 @@<divclass="tool"role="region"- aria-label="Media Library"+ aria-label="Media"ondragover={(e) => {e.preventDefault();dragOver = true;@@ -914,7 +914,7 @@ondrop={onDrop}><div class="tool-header">- <h2>Media Library</h2>+ <h2>Media</h2><div class="spacer"></div><formclass="dl-form"@@ -937,7 +937,7 @@</button><!-- The pictures and videos brought in here, as the sheet they are worked down in. --><button class="btn" onclick={openWorklist} disabled={!items.length || worklistBusy}- title="The imported pictures and videos as a sheet, each marked done once a proof answers it">+ title="Open as a worklist sheet"><Icon name="table" size={15} /> Worklist</button><!-- The two upkeep sweeps, behind one door. The door stays put on an emptydiff --git a/frontend/src/tools/Notebook.svelte b/frontend/src/tools/Notebook.svelteindex 405335c..cb3278e 100644--- a/frontend/src/tools/Notebook.svelte+++ b/frontend/src/tools/Notebook.svelte@@ -26,6 +26,7 @@import ExportFolderPicker from '../components/ExportFolderPicker.svelte';import Modal from '../components/Modal.svelte';import FolderSelect from '../components/FolderSelect.svelte';+ import NoCase from '../components/NoCase.svelte';let tabs = $state([]); // [{ id: 'case' | entity id, noteId }]let activeId = $state('case');@@ -376,18 +377,28 @@// the ones captured here, not the live fields: by the time this is flushed// the analyst may be on another note.pendingSave = () => save(target, targetKey, contents, version);+ unsent = targetKey ? { target, contents } : null;saveTimer = setTimeout(() => {pendingSave = null;+ unsent = null;save(target, targetKey, contents, version);}, 700);}+ // The edit still waiting for its timer, as a body. A tab closing runs no timer and no+ // teardown, so it is sent from here with `keepalive`, which outlives the page.+ let unsent = null;+ function onpagehide() {+ if (unsent) api.put(unsent.target, { text: unsent.contents }, { keepalive: true }).catch(() => {});+ }+/** Write a debounced edit immediately, if one is still waiting. */async function flushPendingSave() {const write = pendingSave;clearTimeout(saveTimer);saveTimer = undefined;pendingSave = null;+ unsent = null;if (write) await write();}@@ -642,10 +653,10 @@}</script>-<svelte:window onkeydown={onWindowKeydown} />+<svelte:window onkeydown={onWindowKeydown} {onpagehide} />{#if !caseState.current}- <div class="empty"><h2>No case open</h2><p>Open a case to write notes.</p></div>+ <NoCase icon="note" what="write notes" />{:else}<section bind:this={notebookEl} class="notebook"><header class="notebook-bar">@@ -1105,7 +1116,5 @@ flowchart LR.markdown :global(.mermaid-error) { margin: 0 0 8px; color: var(--warn); font-size: var(--fs-xs); text-align: left; }.preview-only { grid-template-columns: 1fr !important; }.preview-only .writer, .preview-only .splitter { display: none; }- .empty { padding: 28px; color: var(--text-2); }- .empty h2 { color: var(--text-1); }@media (max-width: 800px) { .panes { grid-template-columns: 1fr !important; } .splitter { display: none; } .writer { min-height: 52%; border-bottom: 1px solid var(--border); } .preview-only .writer { display: none; } }</style>diff --git a/frontend/src/tools/Notebook.test.js b/frontend/src/tools/Notebook.test.jsindex 9d276e8..c6fc94c 100644--- a/frontend/src/tools/Notebook.test.js+++ b/frontend/src/tools/Notebook.test.js@@ -15,7 +15,7 @@ describe('Notebook notes menu', () => {it('closes on a click outside and on Escape', () => {expect(source).toContain('class="menu-backdrop" onclick={closeNotesMenu}');expect(source).toContain("if (event.key === 'Escape' && menuOpen) closeNotesMenu();");- expect(source).toContain('<svelte:window onkeydown={onWindowKeydown} />');+ expect(source).toContain('<svelte:window onkeydown={onWindowKeydown} {onpagehide} />');});it('searches and browses note folders once the case has more than six notes', () => {@@ -102,3 +102,13 @@ describe('Notebook offers what is open to the Add event bar', () => {expect(source).toContain("onDestroy(() => withdrawNote('notebook'))");});});++describe('Notebook and a closing tab', () => {+ it('sends the edit still waiting for its timer with keepalive when the page goes', () => {+ // A tab closing runs no timer and no teardown, so only pagehide can still send it.+ expect(source).toContain('<svelte:window onkeydown={onWindowKeydown} {onpagehide} />');+ expect(source).toContain("api.put(unsent.target, { text: unsent.contents }, { keepalive: true })");+ // Sent once: the timer and a flush both forget it when they write it.+ expect(source.match(/(?<!let )unsent = null;/g)).toHaveLength(2);+ });+});diff --git a/frontend/src/tools/PostComposer.defaultTemplate.render.test.js b/frontend/src/tools/PostComposer.defaultTemplate.render.test.jsindex f6bba29..0b6a3a5 100644--- a/frontend/src/tools/PostComposer.defaultTemplate.render.test.js+++ b/frontend/src/tools/PostComposer.defaultTemplate.render.test.js@@ -236,3 +236,29 @@ describe('the draft the template editor previews with', () => {expect(postDraftState.fields).toBeNull();});});++describe('Publish', () => {+ afterEach(() => vi.unstubAllGlobals());++ it('still opens the site when the browser refuses the clipboard, and says what is left to do', async () => {+ vi.stubGlobal('navigator', { ...navigator, clipboard: { writeText: vi.fn().mockRejectedValue(new Error('denied')) } });+ const open = vi.fn();+ vi.stubGlobal('open', open);+ mountComposer();+ await settle();+ const first = target.querySelector('.tweet-block textarea');+ first.value = 'Convoy on the coast road';+ first.dispatchEvent(new Event('input', { bubbles: true }));+ flushSync();+ const publish = [...target.querySelectorAll('button')].find((b) => b.title.startsWith('Copy posts and open'));+ expect(publish.disabled).toBe(false);++ publish.click();+ publish.click(); // a second press while the first runs opens nothing more+ await settle();++ expect(open).toHaveBeenCalledTimes(1);+ expect(toasts()).toContain('The browser refused the clipboard');+ expect(toasts().some((t) => t.endsWith('Copy the replies from here.'))).toBe(true);+ });+});diff --git a/frontend/src/tools/PostComposer.svelte b/frontend/src/tools/PostComposer.svelteindex 97f49d2..1e05ce3 100644--- a/frontend/src/tools/PostComposer.svelte+++ b/frontend/src/tools/PostComposer.svelte@@ -4,6 +4,7 @@import { fileUrl } from '../lib/fileUrl.js';import { fetchAllEntities, lookupEntity, fetchDerivation } from '../lib/catalog.js';import { caseState, uiState, toast, reloadCase, prefs, updatesState } from '../lib/state.svelte.js';+ import { copyText } from '../lib/clipboard.js';import { templatesState, postDraftState } from '../lib/state.svelte.js';import { createNote } from '../lib/notes.js';import { openNotebook } from '../lib/navigate.js';@@ -454,8 +455,7 @@// Copies go through bidiSafe so coordinates, plus codes, mentions and URLs// keep reading left-to-right in Arabic or Hebrew posts (see lib/bidi).async function copy(value) {- await navigator.clipboard.writeText(bidiSafe(value));- toast('Copied to clipboard', 'ok', 1600);+ await copyText(bidiSafe(value));}function threadParts() {@@ -471,8 +471,7 @@async function copyAll(showToast = true) {const parts = threadParts();- await navigator.clipboard.writeText(parts.map(bidiSafe).join('\n\n---\n\n'));- if (showToast) toast('All posts copied', 'ok', 1800);+ return copyText(parts.map(bidiSafe).join('\n\n---\n\n'), { said: 'All posts copied', quiet: !showToast });}// ---- media picker -------------------------------------------------------@@ -1118,13 +1117,26 @@}}+ let publishing = $state(false);+async function publish() {- // Social intents prefill the first post only. The rest is copied as replies.- await copyAll(false);- if (await tryHandOff()) return;- const url = postComposeUrl(target, bidiSafe(tweet1));- window.open(url, '_blank', 'noopener,noreferrer');- toast(`Opened ${targetInfo.label}. Posts copied for replies.`, 'info', 3200);+ if (publishing) return;+ publishing = true;+ try {+ // Social intents prefill the first post only. The rest is copied as replies, and a+ // clipboard the browser keeps shut costs the replies, never the hand-off itself.+ const copied = await copyAll(false);+ if (await tryHandOff()) return;+ const url = postComposeUrl(target, bidiSafe(tweet1));+ window.open(url, '_blank', 'noopener,noreferrer');+ toast(+ copied ? `Opened ${targetInfo.label}. Posts copied for replies.` : `Opened ${targetInfo.label}. Copy the replies from here.`,+ 'info',+ 3200,+ );+ } finally {+ publishing = false;+ }}</script>@@ -1150,7 +1162,7 @@<button class="btn btn-ok btn-sm" onclick={openSaveReport} disabled={!hasContent || reportSaving} title="Write the finding up as a Notebook note"><Icon name="file" size={14} /> Save report</button>- <button class="btn btn-info btn-sm" onclick={publish} disabled={!tweet1.trim()} title={`Copy posts and open ${targetInfo.label}`}>+ <button class="btn btn-info btn-sm" onclick={publish} disabled={!tweet1.trim() || publishing} title={`Copy posts and open ${targetInfo.label}`}><Icon name="post" size={14} /> Publish on {targetInfo.label}</button></div>diff --git a/frontend/src/tools/ReverseSearch.render.test.js b/frontend/src/tools/ReverseSearch.render.test.jsindex 765205f..6f71c3f 100644--- a/frontend/src/tools/ReverseSearch.render.test.js+++ b/frontend/src/tools/ReverseSearch.render.test.js@@ -171,7 +171,7 @@ describe('the landing', () => {await land([MEDIA[2]]);expect(target.textContent).toContain('Add an image or a video to the case to search it.');- buttonNamed('Go to Media Library').click();+ buttonNamed('Go to Media').click();expect(uiState.tool).toBe('media');expect(target.querySelectorAll('.engine-link')).toHaveLength(4);});diff --git a/frontend/src/tools/ReverseSearch.svelte b/frontend/src/tools/ReverseSearch.svelteindex aaba8cf..0d01ba3 100644--- a/frontend/src/tools/ReverseSearch.svelte+++ b/frontend/src/tools/ReverseSearch.svelte@@ -24,6 +24,7 @@import Modal from '../components/Modal.svelte';import Icon from '../components/Icon.svelte';import SourcePicker from '../components/SourcePicker.svelte';+ import { shortcut } from '../lib/keys.js';const PASTE = UPLOAD_PAGES.filter((e) => e.paste);const DRAG = UPLOAD_PAGES.filter((e) => !e.paste);@@ -210,7 +211,7 @@}async function copySelection() {- await copyPng(pngBlob(), `Copied the ${frameLabel}. Paste it in the tab with Ctrl+V`);+ await copyPng(pngBlob(), `Copied the ${frameLabel}. Paste it in the tab with ${shortcut('Ctrl+V')}`);}async function saveSelection() {@@ -267,7 +268,7 @@}}window.open(engine.url, '_blank', 'noopener,noreferrer');- if (engine.paste) toast(`Opened ${engine.label}. Paste the ${frameLabel} with Ctrl+V`, 'info', 4500);+ if (engine.paste) toast(`Opened ${engine.label}. Paste the ${frameLabel} with ${shortcut('Ctrl+V')}`, 'info', 4500);else savePng(blob, `Opened ${engine.label}. Drag the saved ${frameLabel} in`);}@@ -336,7 +337,7 @@<div class="empty"><Icon name="search" size={40} /><p>Add an image or a video to the case to search it.</p>- <button class="btn" onclick={() => (uiState.tool = 'media')}>Go to Media Library</button>+ <button class="btn" onclick={() => (uiState.tool = 'media')}>Go to Media</button>{@render engineLinks()}</div>{:else}@@ -428,7 +429,7 @@{/if}{#if pasteLeft.length}<div class="eg-group">- <span class="eg-head">Copy, then paste (Ctrl+V) in the tab</span>+ <span class="eg-head">{shortcut('Copy, then paste (Ctrl+V) in the tab')}</span><div class="eg-list">{#each pasteLeft as e (e.id)}<adiff --git a/frontend/src/tools/ReverseSearch.test.js b/frontend/src/tools/ReverseSearch.test.jsindex e7f98fb..6a788bb 100644--- a/frontend/src/tools/ReverseSearch.test.js+++ b/frontend/src/tools/ReverseSearch.test.js@@ -36,7 +36,7 @@ describe('Reverse Search case picker', () => {// one fallback, and it is the road that always worked.expect(source).toContain('blob.size <= MAX_HANDOFF_BYTES');expect(source).toContain("window.open(engine.url, '_blank', 'noopener,noreferrer');");- expect(source).toContain('if (engine.paste) toast(`Opened ${engine.label}. Paste the ${frameLabel} with Ctrl+V`');+ expect(source).toContain("if (engine.paste) toast(`Opened ${engine.label}. Paste the ${frameLabel} with ${shortcut('Ctrl+V')}`");expect(source).toContain('else savePng(blob, `Opened ${engine.label}. Drag the saved ${frameLabel} in`);');});diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelteindex 8252993..0b33bde 100644--- a/frontend/src/tools/Satellite.svelte+++ b/frontend/src/tools/Satellite.svelte@@ -31,6 +31,7 @@import {caseState, uiState, ensureCase, reloadCase, toast, dismissToast, prefs, fmtCoords, prefsReady,} from '../lib/state.svelte.js';+ import { copyText } from '../lib/clipboard.js';import { markerGeometry, markerSvg } from '../lib/mapMarkers.js';import { startRectDrag, turnFromKey, turnFromPress } from '../lib/map/gestures.js';import { panelWidth } from '../lib/panelWidth.js';@@ -943,12 +944,7 @@if (id === 'lookup') return lookUpPoint(point);closePointMenu();if (id === 'copy') {- try {- await navigator.clipboard.writeText(value);- toast('Coordinates copied', 'ok', 1600);- } catch {- toast('The browser refused the clipboard', 'warn');- }+ await copyText(value);} else if (id === 'place') {openNewPlaceAt(point);} else if (id === 'centre') {@@ -1948,8 +1944,7 @@const readout = $derived(fmtCoords(displayCoords.lat, displayCoords.lon));async function copyCoords() {- await navigator.clipboard.writeText(readout);- toast('Coordinates copied', 'ok', 1600);+ await copyText(readout);}async function toggleCaptures() {diff --git a/frontend/src/tools/Settings.render.test.js b/frontend/src/tools/Settings.render.test.jsindex e6e7eae..54964c6 100644--- a/frontend/src/tools/Settings.render.test.js+++ b/frontend/src/tools/Settings.render.test.js@@ -305,3 +305,28 @@ describe('post templates', () => {expect(prefs.postTemplate).toBe('po_2');});});++describe('settings that could not be read', () => {+ it('says so in the pane and reads them again on Reload', async () => {+ unmount(live);+ document.body.innerHTML = '';+ const real = api.get.getMockImplementation();+ api.get.mockImplementation(async (path) => {+ if (path === '/api/settings') throw new Error('Azimut is not running. Start it again, then reload this tab.');+ return real(path);+ });+ const target = document.createElement('div');+ document.body.append(target);+ live = mount(Settings, { target });+ for (let i = 0; i < 10; i += 1) await Promise.resolve();+ flushSync();++ const alert = document.querySelector('.load-error');+ expect(alert?.textContent).toContain('Settings could not be read');+ api.get.mockImplementation(real);+ [...alert.querySelectorAll('button')].find((b) => b.textContent.trim() === 'Reload').click();+ for (let i = 0; i < 10; i += 1) await Promise.resolve();+ flushSync();+ expect(document.querySelector('.load-error')).toBeNull();+ });+});diff --git a/frontend/src/tools/Settings.svelte b/frontend/src/tools/Settings.svelteindex 833e295..19b1493 100644--- a/frontend/src/tools/Settings.svelte+++ b/frontend/src/tools/Settings.svelte@@ -263,7 +263,7 @@toast('Folder written. Load it in your browser to finish', 'ok', 8000);}} catch (e) {- toast(e.message || 'Could not write the extension folder', 'error');+ toast(e.message || 'Could not write the extension folder', 'danger');} finally {extBusy = '';}@@ -304,7 +304,7 @@adoptExtState(classify(server, { bridges, managed }));toast('Folder updated. Reload the extension in your browser', 'warn', 8000);} catch (e) {- toast(e.message || 'Could not update the extension', 'error');+ toast(e.message || 'Could not update the extension', 'danger');} finally {extBusy = '';}@@ -324,7 +324,7 @@try {await api.post('/api/settings/extension/reveal');} catch (e) {- toast(e.message || 'Could not open the folder', 'error');+ toast(e.message || 'Could not open the folder', 'danger');}}// Keep home-view fields as text until change so partial numbers remain editable.@@ -671,8 +671,21 @@formatCoords(Number(home.lat) || 43, Number(home.lon) || 25, prefs.coordFormat));+ // Read once on open. A failure stays on the page with a way to try again: the panes+ // underneath would otherwise read as "no key set" and an empty home view, which looks+ // like settings that were lost rather than settings that were not read.+ let loadError = $state('');+ async function readSettings() {+ loadError = '';+ try {+ await load();+ } catch (e) {+ loadError = e.message;+ }+ }+onMount(() => {- load().catch((e) => toast(`Could not load settings: ${e.message}`, 'danger'));+ readSettings();loadTemplates();});@@ -858,6 +871,13 @@</nav><div class="pane settings-pane">+ {#if loadError}+ <div class="load-error" role="alert">+ <Icon name="alert" size={15} />+ <span>Settings could not be read: {loadError}</span>+ <button class="btn btn-sm" onclick={readSettings}>Reload</button>+ </div>+ {/if}{#if tab === 'general'}<GeneralTab{prefs}@@ -1164,4 +1184,17 @@padding: 12px 14px;border-top: 1px solid var(--border);}+ .load-error {+ display: flex;+ align-items: center;+ gap: 8px;+ margin-bottom: 14px;+ padding: 9px 12px;+ border: 1px solid var(--danger);+ border-radius: var(--r-md);+ color: var(--danger);+ }+ .load-error span {+ flex: 1;+ }</style>diff --git a/frontend/src/tools/Settings.test.js b/frontend/src/tools/Settings.test.jsindex 17723fe..1e8e92f 100644--- a/frontend/src/tools/Settings.test.js+++ b/frontend/src/tools/Settings.test.js@@ -40,6 +40,17 @@ describe('Report an issue', () => {expect(shell).toContain('navigator.clipboard.writeText(report.report)');});+ it('names both update hosts and the home map wherever the network is described', () => {+ expect(system).toContain('(GitHub and PyPI)');+ expect(system).toContain("home map's tiles");+ expect(system).not.toContain('automatic GitHub update check');+ });++ it('links the bundled ffmpeg licence notice', () => {+ expect(system).toContain('{#if ffmpeg.notice}');+ expect(system).toContain('href="/api/settings/ffmpeg/notice"');+ });+it('warns that the tracker is public', () => {expect(system).toContain('public GitHub tracker; anyone can read it');});diff --git a/frontend/src/tools/Sheet.render.test.js b/frontend/src/tools/Sheet.render.test.jsindex 2c55ba2..ef754a4 100644--- a/frontend/src/tools/Sheet.render.test.js+++ b/frontend/src/tools/Sheet.render.test.js@@ -4070,6 +4070,78 @@ describe('the home the tab lands on', () => {expect(put.mock.calls[0][1].rows[0]).toEqual(['r1', 'Quai nord', 'ruled out']);});+ it('asks before closing onto the home when the save keeps failing', async () => {+ withHome();+ await open();+ put.mockClear();+ put.mockRejectedValue(new Error('disk full'));+ const cell = rows()[0].querySelectorAll('.cell:not(.gutter)')[1];+ cell.dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));+ flushSync();+ const editor = target.querySelector('.editor');+ editor.value = 'Quai nord';+ editor.dispatchEvent(new Event('input', { bubbles: true }));+ editor.dispatchEvent(new Event('blur', { bubbles: true }));+ flushSync();++ button('Close').click();+ await settle();++ // Tried, failed: the grid stays, and leaving now would drop the edit, so it asks.+ expect(put).toHaveBeenCalled();+ expect(target.querySelector('.rows')).not.toBeNull();+ expect(document.body.textContent).toContain('Leave and lose your edits');+ inDialog('Cancel').click();+ flushSync();+ expect(target.querySelector('.rows')).not.toBeNull();+ put.mockReset();+ put.mockImplementation(async (_path, body) => ({ status: 'saved', stamp: '2000-64', ...body }));+ });++ it('sends an edit still waiting for its timer when the tab closes', async () => {+ withHome();+ await open();+ put.mockClear();+ const cell = rows()[0].querySelectorAll('.cell:not(.gutter)')[1];+ cell.dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));+ flushSync();+ const editor = target.querySelector('.editor');+ editor.value = 'Quai est';+ editor.dispatchEvent(new Event('input', { bubbles: true }));+ editor.dispatchEvent(new Event('blur', { bubbles: true }));+ flushSync();+ await Promise.resolve();+ expect(put).not.toHaveBeenCalled();++ window.dispatchEvent(new Event('pagehide'));++ expect(put).toHaveBeenCalledTimes(1);+ const [, body, opts] = put.mock.calls[0];+ expect(body.rows[0][1]).toBe('Quai est');+ expect(opts).toEqual({ keepalive: true });+ });++ it('counts the keepalive cap in bytes, which Arabic text fills twice as fast', async () => {+ // The browser refuses a keepalive body over 64 KB of bytes. 35 000 Arabic letters+ // are 70 KB: under the cap counted in characters, over it on the wire.+ withHome();+ await open();+ put.mockClear();+ const cell = rows()[0].querySelectorAll('.cell:not(.gutter)')[1];+ cell.dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));+ flushSync();+ const editor = target.querySelector('.editor');+ editor.value = 'ع'.repeat(35_000);+ editor.dispatchEvent(new Event('input', { bubbles: true }));+ editor.dispatchEvent(new Event('blur', { bubbles: true }));+ flushSync();+ await Promise.resolve();++ window.dispatchEvent(new Event('pagehide'));++ expect(put).not.toHaveBeenCalled();+ });+it('opens straight onto a sheet another tool asked for', async () => {uiState.openSheet = SHEET.id;withHome();diff --git a/frontend/src/tools/Sheet.svelte b/frontend/src/tools/Sheet.svelteindex 56effd6..584d81a 100644--- a/frontend/src/tools/Sheet.svelte+++ b/frontend/src/tools/Sheet.svelte@@ -163,6 +163,7 @@import SheetMove from '../components/SheetMove.svelte';import SheetRowMenu from '../components/SheetRowMenu.svelte';import SheetRowPanel from '../components/SheetRowPanel.svelte';+ import { shortcut } from '../lib/keys.js';const HEAD_H = 32;/** How long the two lines above the grid may be. Mirrors `engine/sheets.MAX_DESCRIPTION`,@@ -518,12 +519,22 @@});});- /** Back to the home. Whatever is unsaved is written first, as on any other switch, so- * closing never loses an edit. */+ /** Back to the home. Whatever is unsaved is written first, as on any other switch, and+ * a grid that still holds what no write kept asks before it is dropped. */async function goHome() {+ await release(async () => {+ close();+ await list(caseId);+ });+ }++ /** Write what is pending, then let go of the sheet. A failed or conflicting save leaves+ * edits only the grid holds, and leaving drops them as surely as Reload does, so it asks+ * the same way. */+ async function release(then) {await flush();- close();- await list(caseId);+ if (!unsaved) return then();+ confirming = { kind: 'leave', then };}/** Which sheet this case was last left on. Kept in the browser rather than in the case:@@ -550,7 +561,10 @@async function open(id) {if (id === openId) return;- await flush();+ await release(() => openNow(id));+ }++ async function openNow(id) {loading = true;picker = null;try {@@ -558,7 +572,7 @@openId = id;rememberOpened(caseId, id);} catch (error) {- toast(error.message || 'This sheet could not be opened.', 'error');+ toast(error.message || 'This sheet could not be opened.', 'danger');} finally {loading = false;}@@ -790,6 +804,20 @@}}+ // A tab closing runs no timer and no teardown, so an edit still waiting for its timer+ // goes out from here with `keepalive`, which outlives the page. The browser caps such+ // a request at 64 KB, so a big sheet's last edit cannot be sent this way.+ const KEEPALIVE_BYTES = 60_000;+ function onpagehide() {+ if (saveState !== 'dirty' || conflict || !openId) return;+ const [path, body] = pendingTable+ ? [`/api/cases/${caseId}/sheets/${openId}`, { columns: table.columns, rows: table.rows, meta, stamp }]+ : [`/api/cases/${caseId}/sheets/${openId}/meta`, { meta }];+ // Bytes, not characters: Arabic or Cyrillic text takes two of them per character.+ if (new TextEncoder().encode(JSON.stringify(body)).length > KEEPALIVE_BYTES) return;+ api.put(path, body, { keepalive: true }).catch(() => {});+ }+/*** One write, down whichever of the two roads the change needs.*@@ -847,7 +875,7 @@conflict = true;return;}- toast(error.message || 'This sheet could not be saved.', 'error');+ toast(error.message || 'This sheet could not be saved.', 'danger');}}@@ -866,13 +894,14 @@try {adopt(await api.get(`/api/cases/${caseId}/sheets/${openId}`), { reset: true });} catch (error) {- toast(error.message || 'This sheet could not be opened.', 'error');+ toast(error.message || 'This sheet could not be opened.', 'danger');}}- /** Write anything pending before leaving the sheet, so switching never drops an edit. */+ /** Write anything pending before leaving the sheet, so switching never drops an edit.+ * A save that failed is tried once more; a conflict is not, it needs the analyst. */async function flush() {- if (saveState === 'dirty') await save();+ if (saveState === 'dirty' || (saveState === 'failed' && !conflict)) await save();}$effect(() => () => {@@ -927,7 +956,7 @@if (conflict) conflict = true;stale = { diff };} catch (error) {- toast(error.message || 'That file could not be read.', 'error');+ toast(error.message || 'That file could not be read.', 'danger');} finally {comparing = false;}@@ -967,7 +996,7 @@await save();}} catch (error) {- toast(error.message || 'This sheet could not be created.', 'error');+ toast(error.message || 'This sheet could not be created.', 'danger');}}@@ -979,7 +1008,7 @@await api.patch(`/api/cases/${caseId}/entities/${openId}`, { label: name });await list(caseId);} catch (error) {- toast(error.message || 'This sheet could not be renamed.', 'error');+ toast(error.message || 'This sheet could not be renamed.', 'danger');title = current?.title ?? title;}}@@ -991,7 +1020,7 @@close();await list(caseId);} catch (error) {- toast(error.message || 'This sheet could not be deleted.', 'error');+ toast(error.message || 'This sheet could not be deleted.', 'danger');}}@@ -1029,7 +1058,7 @@: `“${made.label ?? 'Sheet'}” created, with the rows and everything the grid knows.`,);} catch (error) {- toast(error.message || 'This sheet could not be copied.', 'error');+ toast(error.message || 'This sheet could not be copied.', 'danger');}}@@ -1046,7 +1075,7 @@const grown = appendRows(table, incoming, mapping);appending = false;if (!grown.added) {- toast('No column of that table matches this sheet.', 'error');+ toast('No column of that table matches this sheet.', 'danger');return;}structural(() => {@@ -1087,7 +1116,7 @@onClick: () => showExports(),});} catch (error) {- toast(error.message || 'This sheet could not be exported.', 'error');+ toast(error.message || 'This sheet could not be exported.', 'danger');} finally {exporting = false;}@@ -1099,7 +1128,7 @@try {await revealSheetExports(caseId);} catch (error) {- toast(error.message || 'That folder could not be opened.', 'error');+ toast(error.message || 'That folder could not be opened.', 'danger');}}@@ -1176,7 +1205,7 @@dropped || cut ? 'warn' : 'info',);} catch (error) {- toast(error.message || 'This workbook could not be read.', 'error');+ toast(error.message || 'This workbook could not be read.', 'danger');} finally {building = false;}@@ -1219,7 +1248,7 @@async function bringIn(file, rowIndex, columnIndex) {const at = pictureColumn(columnIndex);if (at === -1) {- toast('Declare a column a picture first, then drop the image on it.', 'error');+ toast('Declare a column a picture first, then drop the image on it.', 'danger');return;}try {@@ -1238,7 +1267,7 @@await reloadCase();toast(made.duplicate ? 'Already in the case. The cell now cites it.' : 'Picture added to the case.');} catch (error) {- toast(error.message || 'That picture could not be brought in.', 'error');+ toast(error.message || 'That picture could not be brought in.', 'danger');}}@@ -2085,7 +2114,7 @@]);toast(`${found.length} ${found.length === 1 ? 'file' : 'files'} attached to this row.`);} catch (error) {- toast(error.message || 'The library could not be searched.', 'error');+ toast(error.message || 'The library could not be searched.', 'danger');}}@@ -2170,7 +2199,7 @@await reloadCase();} catch (error) {if (error?.status === 409) conflict = true;- else toast(error.message || 'Those rows could not be moved.', 'error');+ else toast(error.message || 'Those rows could not be moved.', 'danger');} finally {promoting = false;}@@ -2207,7 +2236,7 @@await reloadCase();} catch (error) {if (error?.status === 409) conflict = true;- else toast(error.message || 'That move could not be put back.', 'error');+ else toast(error.message || 'That move could not be put back.', 'danger');} finally {promoting = false;}@@ -2253,7 +2282,7 @@await reloadCase();} catch (error) {if (error?.status === 409) conflict = true;- else toast(error.message || 'These rows could not be sent to the case.', 'error');+ else toast(error.message || 'These rows could not be sent to the case.', 'danger');} finally {promoting = false;}@@ -2304,7 +2333,7 @@].filter(Boolean);toast(said.length ? `${said.join(', ')}.` : 'Already level with the case.');} catch (error) {- toast(error.message || 'This sheet could not be refreshed.', 'error');+ toast(error.message || 'This sheet could not be refreshed.', 'danger');} finally {refreshing = false;}@@ -2341,7 +2370,7 @@await watchBuild(job_id);} catch (error) {buildJob = null;- toast(error.message || 'That build could not be started.', 'error');+ toast(error.message || 'That build could not be started.', 'danger');}}@@ -2355,7 +2384,7 @@}buildJob = null;if (status.status !== 'done') {- toast(status.error || 'That build stopped.', 'error');+ toast(status.error ? `That build stopped: ${status.error}.` : 'That build stopped.', 'danger');return;}buildReport = status.result ?? null;@@ -2542,7 +2571,7 @@*/function room(growth) {const full = tooBigBy(table, growth);- if (full) toast(full, 'error');+ if (full) toast(full, 'danger');return !full;}@@ -2754,7 +2783,7 @@function cleanTable(next, said) {const full = tooBigBy(next.table);if (full) {- toast(full, 'error');+ toast(full, 'danger');return;}structural(() => {@@ -2878,7 +2907,7 @@}reading = { kind: 'links', column: name, ...readVerdicts(entries, verdicts) };} catch (error) {- toast(error.message || 'Those links could not be checked.', 'error');+ toast(error.message || 'Those links could not be checked.', 'danger');} finally {checking = null;}@@ -2907,7 +2936,7 @@: `${sheet.taken} ${sheet.taken === 1 ? 'row' : 'rows'} taken into the sheet.`,);} catch (error) {- toast(error.message || 'This sheet could not be built.', 'error');+ toast(error.message || 'This sheet could not be built.', 'danger');} finally {building = false;}@@ -2939,9 +2968,9 @@);try {await navigator.clipboard.writeText(text);- toast(`${shown.length} ${shown.length === 1 ? 'row' : 'rows'} copied as a table.`);+ toast(`${shown.length} ${shown.length === 1 ? 'row' : 'rows'} copied as a table`);} catch {- toast('Copying failed. Export the CSV instead.', 'error');+ toast('Copying failed. Export the CSV instead.', 'danger');}}@@ -3077,7 +3106,7 @@const at = table.columns.indexOf(name);const points = rows.map((index) => pointOf(index, at)).filter(Boolean);if (!points.length) {- toast('No coordinates could be read in this column.', 'error');+ toast('No coordinates could be read in this column.', 'danger');return;}uiState.mapSheetPoints = { points, sheet: title, column: name };@@ -3101,7 +3130,7 @@function batchToMap() {const name = firstOfKind('latlon');if (!name) {- toast('No column is set to coordinates.', 'error');+ toast('No column is set to coordinates.', 'danger');return;}toMap(name, batchIndices);@@ -3110,7 +3139,7 @@function batchToTimeline() {const name = firstOfKind('when');if (!name) {- toast('No column is set to dates.', 'error');+ toast('No column is set to dates.', 'danger');return;}toTimeline(name, batchIndices);@@ -3170,7 +3199,7 @@.filter((read) => read?.shape === 'moment').map((read) => read.key);if (!moments.length) {- toast('No date in this column could be read.', 'error');+ toast('No date in this column could be read.', 'danger');return;}const day = 86_400_000;@@ -3651,7 +3680,7 @@<!-- The focus listener is what turns "the file moved on" from a refusal into a warning:the stamp is a stat, so asking on every return is cheap, and hearing it now beatshearing it at the save. -->-<svelte:window onkeydown={onKey} oncopy={onCopy} onpaste={onPaste} onfocus={checkStamp} />+<svelte:window onkeydown={onKey} oncopy={onCopy} onpaste={onPaste} onfocus={checkStamp} {onpagehide} /><div class="tool"><header class="tool-header">@@ -3904,10 +3933,10 @@<strong>{shown.length}</strong> of {table.rows.length}</span><div class="spacer"></div>- <button class="btn btn-ghost btn-sm" title="Undo (Ctrl+Z)" disabled={!canUndo} onclick={undo}>+ <button class="btn btn-ghost btn-sm" title={shortcut('Undo (Ctrl+Z)')} disabled={!canUndo} onclick={undo}><Icon name="undo" size={13} /></button>- <button class="btn btn-ghost btn-sm" title="Redo (Ctrl+Shift+Z)" disabled={!canRedo} onclick={redo}>+ <button class="btn btn-ghost btn-sm" title={shortcut('Redo (Ctrl+Shift+Z)')} disabled={!canRedo} onclick={redo}><Icon name="redo" size={13} /></button><!-- Thirty pixels is right for a worklist and wrong for the column the reasoning is@@ -4063,7 +4092,7 @@{#if reading.bad.length}<div class="found">{#each reading.bad.slice(0, 12) as entry (entry.url)}- <button class="chip" title="{entry.url} — {entry.state}{entry.code ? ` (${entry.code})` : ''}"+ <button class="chip" title="{entry.url}: {entry.state}{entry.code ? ` (${entry.code})` : ''}"onclick={() => paintReading(entry.rows, 'red')}>{linkLabel(entry.url)} <small>×{entry.rows.length}</small></button>@@ -5082,6 +5111,14 @@confirmLabel="Reload"onconfirm={() => { confirming = null; reload(); }}oncancel={() => (confirming = null)} />+{:else if confirming?.kind === 'leave'}+ <ConfirmDialog+ title="Leave and lose your edits"+ message="This grid is holding changes that could not be written. Leaving drops them."+ detail="Stay to save them again or copy them out."+ confirmLabel="Leave"+ onconfirm={() => { const then = confirming.then; confirming = null; then(); }}+ oncancel={() => (confirming = null)} />{:else if confirming?.kind === 'overwrite'}<ConfirmDialogtitle="Write over the file"diff --git a/frontend/src/tools/Timeline.svelte b/frontend/src/tools/Timeline.svelteindex 98f1644..73a81c4 100644--- a/frontend/src/tools/Timeline.svelte+++ b/frontend/src/tools/Timeline.svelte@@ -95,6 +95,8 @@import TemporalClaimEditor from '../components/TemporalClaimEditor.svelte';import TimelineTrackEditor from '../components/TimelineTrackEditor.svelte';import ZonePicker from '../components/ZonePicker.svelte';+ import NoCase from '../components/NoCase.svelte';+ import { shortcut } from '../lib/keys.js';const PAGE = 200;loadEntityTypes();@@ -1899,7 +1901,7 @@: chronologyBlock(rows);await navigator.clipboard.writeText(text);const count = `${rows.length} ${rows.length === 1 ? 'entry' : 'entries'}`;- toast(read.truncated ? `The first ${count} copied.` : `${count} copied.`, 'ok', 1800);+ toast(read.truncated ? `The first ${count} copied` : `${count} copied`, 'ok', 1800);} catch (error) {toast(error?.message || 'Copying failed.', 'danger');} finally {@@ -2150,7 +2152,7 @@{/if}{/snippet}{#if !caseState.current}- <div class="blank-state"><Icon name="clock" size={24} /><h2>Open a case to build its timeline.</h2></div>+ <NoCase icon="clock" what="build its timeline" />{:else if !extent?.from && !loading}<div class="blank-state"><Icon name="clock" size={24} />@@ -2587,7 +2589,7 @@label={previewEntity?.label ?? selected.label}/>{#if previewEntity && !snapshotReading}- <button class="btn btn-ghost btn-sm from-file" title="Write an event on the line that cites this file, its dates one press away" onclick={focusLine}>+ <button class="btn btn-ghost btn-sm from-file" title="Cite this file in a new event" onclick={focusLine}><Icon name="plus" size={12} /> Add event from this file</button>{/if}@@ -2654,7 +2656,7 @@<buttonclass="btn btn-sm date-change"disabled={!inspectorChain?.entity}- title="The file keeps its own date; this files a sourced correction beside it"+ title="File a sourced correction to this date"onclick={addMediaCorrection}><Icon name="edit" size={12} /> Correct this date@@ -2729,7 +2731,7 @@{#if selected.confidence}<div><dt>Confidence</dt><dd>{selected.confidence}</dd></div>{/if}</dl>{#if canDragTemporal(selected) && !snapshotReading}<p class="axis-edit-help">{selected.shape === 'interval' ? 'Drag it on the axis to move it, or either edge to resize.' : 'Drag it on the axis to move it.'}</p>{/if}- {#if !pairReading}<p class="measure-hint">Ctrl-click a second entry to measure between them.</p>{/if}+ {#if !pairReading}<p class="measure-hint">{shortcut('Ctrl-click a second entry to measure between them.')}</p>{/if}</details><!-- Both acts are about a lane: pinning keeps an entry out of that lane'sdiff --git a/frontend/src/tools/compare/AnnotationToolbar.svelte b/frontend/src/tools/compare/AnnotationToolbar.svelteindex 1b356e5..356b02c 100644--- a/frontend/src/tools/compare/AnnotationToolbar.svelte+++ b/frontend/src/tools/compare/AnnotationToolbar.svelte@@ -3,6 +3,7 @@import ProofGlyph from '../../components/ProofGlyph.svelte';import { PROOF_ICONS, isSolidIcon } from '../../lib/proofIcons.js';import { STAMPED, canFill, ANNOTATION_TOOLS } from '../../lib/map/compareAnnotations.js';+ import { shortcut } from '../../lib/keys.js';let {tool = $bindable(),@@ -107,8 +108,8 @@</button>{:else}<aside class="annotation-toolbar" aria-label="Comparison annotation tools">- <button class="tool-button" title="Undo (Ctrl+Z)" disabled={!canUndo} onclick={undo}><Icon name="undo" size={18} /></button>- <button class="tool-button" title="Redo (Ctrl+Shift+Z)" disabled={!canRedo} onclick={redo}><Icon name="redo" size={18} /></button>+ <button class="tool-button" title={shortcut('Undo (Ctrl+Z)')} disabled={!canUndo} onclick={undo}><Icon name="undo" size={18} /></button>+ <button class="tool-button" title={shortcut('Redo (Ctrl+Shift+Z)')} disabled={!canRedo} onclick={redo}><Icon name="redo" size={18} /></button><div class="separator"></div><!-- Pressing the tool in hand puts it down: the way out of a drawing tool wasaiming at the cursor button, and the button you are already on is thediff --git a/frontend/src/tools/compare/DifferencePanel.svelte b/frontend/src/tools/compare/DifferencePanel.svelteindex 68fb346..feb4e08 100644--- a/frontend/src/tools/compare/DifferencePanel.svelte+++ b/frontend/src/tools/compare/DifferencePanel.svelte@@ -107,7 +107,7 @@<select bind:value={settings.index} onchange={chosen}>{#each CHANGE_INDICES as entry}<option value={entry.id}>{entry.label} · {entry.hint}</option>{/each}</select></label>{:else}- <label title="Adapt the threshold to this view, or follow the sensitivity.">Threshold+ <label title="Fit the threshold to this view, or set it by hand">Threshold<select bind:value={settings.threshold}><option value="auto">Automatic</option><option value="manual">Manual</option></select></label>{/if}diff --git a/frontend/src/tools/detect/AnalyzerBuilder.svelte b/frontend/src/tools/detect/AnalyzerBuilder.svelteindex af190e1..6033513 100644--- a/frontend/src/tools/detect/AnalyzerBuilder.svelte+++ b/frontend/src/tools/detect/AnalyzerBuilder.svelte@@ -41,6 +41,7 @@viewBounds = () => null,/** The Copernicus layers this configuration offers, `[{ id, label, hint }]`. */layers = [],+ layerState = null,/** Frame a place: `{ lon, lat, zoom }` or `{ bounds }`. */onfly = () => {},onsave = async () => {},@@ -49,7 +50,8 @@const limits = $derived(catalogue?.rules ?? {});const bench = untrack(() => new Bench({- api, recipe, limits: catalogue?.rules ?? {}, layers: () => layers, viewBounds: () => viewBounds(),+ api, recipe, limits: catalogue?.rules ?? {}, layers: () => layers, layerState: () => layerState,+ radarLayer: () => catalogue?.radar_layer ?? '', viewBounds: () => viewBounds(),fly: (target) => onfly(target), say: toast,}));builder = bench;@@ -172,7 +174,8 @@canRemove={recipe.rules.length > 1} onremove={() => remove(i)} onsignal={() => rank(i)}onhover={(index) => bench.hoverRule(index)} />{/each}- <button class="btn btn-sm" disabled={recipe.rules.length >= most} onclick={add}>+ <button class="btn btn-sm" disabled={recipe.rules.length >= most}+ title={recipe.rules.length >= most ? `At most ${most} rules per analyzer` : undefined} onclick={add}><Icon name="plus" size={13} /> Add a rule</button></section>diff --git a/frontend/src/tools/detect/AnalyzerChecks.svelte b/frontend/src/tools/detect/AnalyzerChecks.svelteindex b97ea4a..f4106ad 100644--- a/frontend/src/tools/detect/AnalyzerChecks.svelte+++ b/frontend/src/tools/detect/AnalyzerChecks.svelte@@ -37,7 +37,8 @@<section class="checks" aria-label="Checks"><p class="hint">A check is two passes and the pins that say where something should be found and where nothing may be.</p><div class="row actions">- <button class="btn btn-sm" disabled={bench.atMostChecks} onclick={() => bench.startDraft()}>+ <button class="btn btn-sm" disabled={bench.atMostChecks}+ title={bench.atMostChecks ? 'This analyzer holds all the checks it can' : undefined} onclick={() => bench.startDraft()}><Icon name="plus" size={12} /> New check</button>{#if bench.checks.length}diff --git a/frontend/src/tools/detect/AnalyzerLibrary.render.svelte.test.js b/frontend/src/tools/detect/AnalyzerLibrary.render.svelte.test.jsnew file mode 100644index 0000000..f9f255e--- /dev/null+++ b/frontend/src/tools/detect/AnalyzerLibrary.render.svelte.test.js@@ -0,0 +1,57 @@+// @vitest-environment happy-dom+import { afterEach, describe, expect, it, vi } from 'vitest';+import { flushSync, mount, unmount } from 'svelte';++const del = vi.fn(async () => ({}));+vi.mock('../../lib/api.js', () => ({ api: { get: vi.fn(async () => ({})), post: vi.fn(), put: vi.fn(), del } }));+const toast = vi.fn();+vi.mock('../../lib/state.svelte.js', async (importOriginal) => ({ ...(await importOriginal()), toast }));++const { default: AnalyzerLibrary } = await import('./AnalyzerLibrary.svelte');++const MINE = { id: 'an_1', name: 'Port watch', colour: '#22aa88', method: 'rules', rules: [], checks: [] };++let live;+let target;++afterEach(() => {+ if (live) unmount(live);+ live = null;+ target?.remove();+ del.mockClear();+});++function mountLibrary(onchanged = vi.fn(async () => {})) {+ target = document.createElement('div');+ document.body.append(target);+ live = mount(AnalyzerLibrary, { target, props: { catalogue: { builtins: [], custom: [MINE] }, onchanged } });+ flushSync();+ return onchanged;+}++const dialogButton = (label) =>+ [...document.querySelectorAll('[role="alertdialog"] button')].find((b) => b.textContent.trim().startsWith(label));++describe('deleting an analyzer of your own', () => {+ it('asks first, naming it, and deletes nothing on Cancel', () => {+ mountLibrary();+ target.querySelector('button[aria-label="Delete Port watch"]').click();+ flushSync();++ expect(document.body.textContent).toContain('Delete Port watch');+ dialogButton('Cancel').click();+ flushSync();+ expect(del).not.toHaveBeenCalled();+ });++ it('deletes once confirmed', async () => {+ const onchanged = mountLibrary();+ target.querySelector('button[aria-label="Delete Port watch"]').click();+ flushSync();+ dialogButton('Delete').click();+ await new Promise((resolve) => setTimeout(resolve, 0));++ expect(del).toHaveBeenCalledWith('/api/compare/analyzers/an_1');+ expect(onchanged).toHaveBeenCalled();+ });+});diff --git a/frontend/src/tools/detect/AnalyzerLibrary.svelte b/frontend/src/tools/detect/AnalyzerLibrary.svelteindex b4a529a..df1b8e5 100644--- a/frontend/src/tools/detect/AnalyzerLibrary.svelte+++ b/frontend/src/tools/detect/AnalyzerLibrary.svelte@@ -23,6 +23,7 @@import AnalyzerSettings from './AnalyzerSettings.svelte';import FoldGroup from './FoldGroup.svelte';import Icon from '../../components/Icon.svelte';+ import ConfirmDialog from '../../components/ConfirmDialog.svelte';let {catalogue,@@ -34,6 +35,7 @@/** The Copernicus layers on offer and a way to frame a place: what the* builder needs of the map. */layers = [],+ layerState = null,onfly = () => {},} = $props();@@ -51,6 +53,9 @@/** Built-in categories opened by hand; all start folded. */let openKinds = $state({});let busy = $state(false);+ // The analyzer whose deletion is being confirmed: its rules, checks and calibration+ // are app-wide and have no Trash to come back from.+ let deleting = $state(null);let error = $state('');// The map holds the builder's bench only while a builder is open, and this is what lets it go: on@@ -165,7 +170,7 @@<Icon name="edit" size={13} /></button><button class="cmp-icon" title="Delete" aria-label={`Delete ${entry.name}`} disabled={busy}- onclick={() => act(() => remove(entry))}><Icon name="trash" size={13} /></button>+ onclick={() => (deleting = entry)}><Icon name="trash" size={13} /></button></div>{/each}</section>@@ -245,7 +250,7 @@<div class="cmp-dock-foot"><button class="btn btn-sm" onclick={back}>Cancel</button></div>{:else if mode === 'build' && recipe}{#key session}- <AnalyzerBuilder {catalogue} bind:recipe isNew={isNew} {start} bind:builder {viewBounds} {layers} {onfly}+ <AnalyzerBuilder {catalogue} bind:recipe isNew={isNew} {start} bind:builder {viewBounds} {layers} {layerState} {onfly}onsave={(next) => save(next)} oncancel={back} />{/key}{:else if recipe}@@ -283,6 +288,17 @@</div>{/if}+{#if deleting}+ <ConfirmDialog+ title={`Delete ${deleting.name}`}+ message="It leaves the library for every case, with its rules and checks."+ detail="Nothing brings it back. A copy in a settings backup can."+ confirmLabel="Delete"+ tone="danger"+ onconfirm={() => { const entry = deleting; deleting = null; act(() => remove(entry)); }}+ oncancel={() => (deleting = null)} />+{/if}+<style>section { display: grid; gap: 4px; }section > strong {diff --git a/frontend/src/tools/detect/CheckBench.svelte b/frontend/src/tools/detect/CheckBench.svelteindex 88296c2..d870807 100644--- a/frontend/src/tools/detect/CheckBench.svelte+++ b/frontend/src/tools/detect/CheckBench.svelte@@ -17,6 +17,7 @@import AcquisitionPicker from './AcquisitionPicker.svelte';import PassDates from './PassDates.svelte';import Icon from '../../components/Icon.svelte';+ import CopernicusLayersHelp from '../../components/CopernicusLayersHelp.svelte';let { bench } = $props();@@ -37,7 +38,7 @@const side = $derived(bench.divider >= 99 ? 'before' : bench.divider <= 1 ? 'after' : 'split');const pinCount = $derived(bench.marks.length);/** The layer's name without its explanation: "NDVI (vegetation index)" is NDVI on a button. */- const layerLabel = $derived((bench.offered.find((entry) => entry.id === bench.layer)?.label ?? bench.layer).replace(/\s*\(.*$/, ''));+ const layerLabel = $derived((bench.offered.find((entry) => entry.id === bench.layer && entry.enabled !== false)?.label ?? 'Choose a layer').replace(/\s*\(.*$/, ''));const suggestion = $derived(bench.suggestion);/** How every pin came out, from the last test, with the count of what it found. */@@ -143,7 +144,7 @@</button>{/each}<hr />- <button role="menuitem" disabled={bench.atMostChecks} onclick={startNew}><Icon name="plus" size={12} /><span class="grow">New check</span></button>+ <button role="menuitem" disabled={bench.atMostChecks} title={bench.atMostChecks ? 'This analyzer holds all the checks it can' : undefined} onclick={startNew}><Icon name="plus" size={12} /><span class="grow">New check</span></button></div>{/if}</div>@@ -168,27 +169,38 @@title={bench.basemap ? 'Show the passes' : 'Show the basemap'} onclick={() => bench.setBasemap(!bench.basemap)}><Icon name={bench.basemap ? 'eyeOff' : 'eye'} size={15} /></button>{#if !bench.radar}- <div class="pick">+ <div class="pick look-pick"><button class="select look" class:off={bench.basemap} aria-haspopup="menu" aria-expanded={open === 'look'}- aria-label="Copernicus layer" title="How the passes are shown" onclick={() => (open = open === 'look' ? '' : 'look')}>- <Icon name="layers" size={14} /><span>{layerLabel}</span><Icon name="chevronDown" size={13} />+ aria-label="Copernicus layer" title="Display layer" onclick={() => {+ open = open === 'look' ? '' : 'look';+ if (open === 'look') void bench.checkLayers();+ }}>+ <Icon name="layers" size={14} /><span>Display: {layerLabel}</span><Icon name="chevronDown" size={13} /></button>{#if open === 'look'}<div class="menu look-menu cmp-glass" role="menu" aria-label="Copernicus layer">{#each bench.offered as entry (entry.id)}- <button role="menuitemradio" aria-checked={bench.layer === entry.id} title={entry.hint ?? ''}+ <button role="menuitemradio" aria-checked={bench.layer === entry.id} disabled={entry.enabled === false}+ title={entry.reason || entry.hint || undefined}onclick={() => { bench.setLayer(entry.id); open = ''; }}>- <span class="grow">{entry.label}</span>- {#if entry.id === suggestion}<small>best for rule ★</small>{/if}+ <span class="grow">{entry.label}<span class="layer-id cmp-mono">{entry.id}</span>+ {#if entry.reason}<span class="layer-reason">{entry.reason}</span>{/if}</span>+ {#if entry.enabled !== false && entry.id === suggestion}<small>for rule ★</small>{/if}</button>{/each}+ <hr />+ <div class="layer-setup">+ <button class="btn btn-sm" disabled={bench.layersBusy} onclick={() => bench.checkLayers(true)}>+ {bench.layersBusy ? 'Checking…' : 'Refresh layers'}</button>+ <CopernicusLayersHelp />+ </div></div>{/if}</div>{/if}{:else if !check}<span class="hint grow">Pick a check to try the rules on it.</span>- <button class="btn btn-sm" disabled={bench.atMostChecks} onclick={startNew}><Icon name="plus" size={12} /> New check</button>+ <button class="btn btn-sm" disabled={bench.atMostChecks} title={bench.atMostChecks ? 'This analyzer holds all the checks it can' : undefined} onclick={startNew}><Icon name="plus" size={12} /> New check</button>{/if}{#if bench.draft && !bench.choosingPasses}@@ -198,6 +210,16 @@{/if}</div>+ {#if !bench.radar && check && (bench.layersNote || bench.dataProblem)}+ <div class="layer-status" role="status">+ <span>{bench.layersNote || bench.dataProblem}</span>+ {#if !bench.layersBusy}+ <button class="btn btn-sm" onclick={() => bench.checkLayers(true)}>Refresh layers</button>+ <CopernicusLayersHelp />+ {/if}+ </div>+ {/if}+{#if check && !bench.choosingPasses}<div class="tools"><div class="pins" role="group" aria-label="Pin to drop on the map">@@ -259,6 +281,7 @@.console > .head, .console > .tools, .console > .result, .console > .note { padding: 7px 10px; }.console > * + * { border-top: 1px solid var(--glass-line); }.head, .tools, .result { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; min-width: 0; }+ .head { position: relative; }.grow { flex: 1; }/* Which check is on the map, which pass of it, and how the passes are shown. */@@ -309,7 +332,13 @@padding: 4px;box-shadow: var(--shadow-2);}- .look-menu { width: 280px; gap: 0; }+ .look-pick { position: static; }+ .look-menu { left: auto; right: 10px; width: 320px; max-width: calc(100% - 20px); gap: 0; }+ .layer-id, .layer-reason { display: block; font-size: var(--fs-xs); color: var(--glass-muted); }+ .layer-reason { white-space: normal; }+ .layer-setup, .layer-status { display: grid; gap: 7px; padding: 8px 10px; font-size: var(--fs-xs); }+ .layer-status { border-top: 1px solid var(--glass-line); color: var(--warn); }+ .layer-setup > .btn, .layer-status > .btn { justify-self: start; }.menu button {display: flex;align-items: center;diff --git a/frontend/src/tools/detect/CheckBench.svelte.test.js b/frontend/src/tools/detect/CheckBench.svelte.test.jsindex f2fdf19..35262fa 100644--- a/frontend/src/tools/detect/CheckBench.svelte.test.js+++ b/frontend/src/tools/detect/CheckBench.svelte.test.js@@ -21,7 +21,7 @@ afterEach(() => {vi.useRealTimers();});-function open({ dates = 'two', sensor = 'sentinel2', checks = [], layers } = {}) {+function open({ dates = 'two', sensor = 'sentinel2', checks = [], layers, layerState = null } = {}) {const recipe = $state({ ...newRecipe(METHODS, { sensor, dates }), name: 'Mine', checks });const api = { post: vi.fn(async (url, body) => {calls.push([url, body]);@@ -33,7 +33,8 @@ function open({ dates = 'two', sensor = 'sentinel2', checks = [], layers } = {})}return { dates: [{ date: '2026-05-11', cloud: 4, coverage: 1 }, { date: '2026-05-04', cloud: 2, coverage: 1 }], truncated: false };}) };- bench = new Bench({ api, recipe, limits: { max_checks: 12, max_marks: 20 }, layers: () => layers ?? [], viewBounds: () => VIEW });+ bench = new Bench({ api, recipe, limits: { max_checks: 12, max_marks: 20 }, layers: () => layers ?? [],+ layerState: () => layerState, viewBounds: () => VIEW });target = document.createElement('div');document.body.append(target);live = mount(CheckBench, { target, props: { bench } });@@ -150,17 +151,18 @@ it('says the rules changed, in place of the outcome, and what went wrong in the});it('shows the passes in the layer the rules read best, or the basemap in their place, from an eye', () => {- open({ checks: [made('The plot')], layers: [{ id: 'TRUE_COLOR', label: 'True colour' }, { id: 'NDVI', label: 'NDVI (vegetation index)', hint: 'Greens' }] });+ const { recipe } = open({ checks: [made('The plot')], layers: [{ id: 'TRUE_COLOR', label: 'True colour' }, { id: 'NDVI', label: 'NDVI (vegetation index)', hint: 'Greens' }] });+ recipe.rules = [newRule('index', 'change')];bench.select(bench.checks[0].id); flushSync();const look = query('[aria-label="Copernicus layer"][aria-haspopup]');- expect(look.textContent.trim()).toBe('True colour'); // the layer the check was saved in+ expect(look.textContent.trim()).toBe('Display: True colour');click(look);const menu = query('[role="menu"][aria-label="Copernicus layer"]');const rows = [...menu.querySelectorAll('[role="menuitemradio"]')];- expect(rows.map((row) => row.textContent.replace(/\s+/g, ' ').trim())).toEqual(['True colour', 'NDVI (vegetation index) best for rule ★']);+ expect(rows.map((row) => row.textContent.replace(/\s+/g, ' ').trim())).toEqual(['True colourTRUE_COLOR', 'NDVI (vegetation index)NDVI for rule ★']);click(rows[1]);expect(bench.layer).toBe('NDVI');- expect(look.textContent.trim()).toBe('NDVI');+ expect(look.textContent.trim()).toBe('Display: NDVI');expect(query('[role="menu"]')).toBe(null);// the eye puts the basemap where the passes were, and back@@ -190,6 +192,26 @@ it('has no layer to choose for radar, which has one picture, and still has the eexpect(query('button[aria-label="Passes on the map"]')).not.toBe(null);});+it('shows missing displays disabled with a reason and offers setup and refresh', () => {+ const layerState = { layers: [{ id: 'TRUE_COLOR', label: 'True colour' },+ { id: 'VEGETATION_INDEX', label: 'Vegetation Index - NDVI' }], layersSource: 'instance',+ loadLayers: vi.fn(async () => true) };+ open({ checks: [made('The plot')], layerState });+ bench.select(bench.checks[0].id); flushSync();+ click(query('[aria-label="Copernicus layer"][aria-haspopup]'));+ const menu = query('[role="menu"][aria-label="Copernicus layer"]');+ const rows = [...menu.querySelectorAll('[role="menuitemradio"]')];+ expect(rows.find((row) => row.textContent.includes('VEGETATION_INDEX')).disabled).toBe(false);+ const missing = rows.find((row) => row.textContent.includes('SWIR'));+ expect(missing.disabled).toBe(true);+ expect(missing.textContent).toContain('Not in your Copernicus configuration.');+ click(missing);+ expect(bench.layer).toBe('TRUE_COLOR');+ expect(menu.querySelector('summary').textContent).toBe('Set up Copernicus layers');+ click([...menu.querySelectorAll('button')].find((row) => row.textContent.trim() === 'Refresh layers'));+ expect(layerState.loadLayers).toHaveBeenLastCalledWith(true, true, true);+});+it('makes a new check in three steps: its passes, its pins, and Finish', async () => {const { recipe } = open();click(named('New check'));diff --git a/frontend/src/tools/detect/DetectPanel.svelte b/frontend/src/tools/detect/DetectPanel.svelteindex f4b85c4..7052bdc 100644--- a/frontend/src/tools/detect/DetectPanel.svelte+++ b/frontend/src/tools/detect/DetectPanel.svelte@@ -78,6 +78,7 @@viewBounds = () => null,/** The Copernicus layers on offer and a way to frame a place, which the builder uses. */passLayers = [],+ passLayerState = null,onfly = () => {},} = $props();@@ -815,7 +816,7 @@</div>{:else if view === 'library'}<AnalyzerLibrary bind:this={library} {catalogue} onchanged={loadCatalogue} bind:builder {viewBounds}- layers={passLayers} {onfly}+ layers={passLayers} layerState={passLayerState} {onfly}onsaved={(recipe) => { if (draft) offer = recipe.id; }} />{/if}{/if}diff --git a/frontend/src/tools/detect/DetectPanel.test.js b/frontend/src/tools/detect/DetectPanel.test.jsindex b0b5f15..5a24f5b 100644--- a/frontend/src/tools/detect/DetectPanel.test.js+++ b/frontend/src/tools/detect/DetectPanel.test.js@@ -1053,6 +1053,10 @@ it('edits and removes an analyzer of its own', async () => {expect(button('Save changes')).toBeDefined();button('Cancel').click(); await settle();labelled('Delete Weekly harbour').click(); await settle();+ // gone for every case, with no Trash to come back from: it asks first+ expect(del).not.toHaveBeenCalled();+ [...document.querySelectorAll('[role="alertdialog"] button')].find((b) => b.textContent.trim() === 'Delete').click();+ await settle();expect(del).toHaveBeenCalledWith('/api/compare/analyzers/custom-1');});@@ -1164,7 +1168,7 @@ it('builds an analyzer from rules, proves it on a check made on the map, and keeconst bench = await openBuilder();expect(heading()).toBe('Build an analyzer');expect(target.querySelector('.reads').textContent.trim()).toBe('Sentinel-2 · two dates');- expect(phrase()).toBe('Keeps ground where NDVI dropped by 0.25 or more, outside cloud.');+ expect(phrase()).toBe('Keeps ground where brightness moved by 5.0% or more either way, outside cloud.');expect(tab('Rules').getAttribute('aria-selected')).toBe('true');// building reads nothing, and with no check on the map there is nothing to testawait debounce(); await settle();@@ -1208,8 +1212,8 @@ it('builds an analyzer from rules, proves it on a check made on the map, and keebutton('Add to my analyzers').click(); await settle();expect(post).toHaveBeenCalledWith('/api/compare/analyzers', expect.objectContaining({id: 'custom', method: 'rules', name: 'Cleared ground', match: 'all', sensor: 'sentinel2', dates: 'two',- description: 'Keeps ground where NDVI dropped by 0.25 or more, outside cloud.',- rules: [expect.objectContaining({ measure: 'index', index: 'ndvi', on: 'change', op: 'le', value: -0.25 })],+ description: 'Keeps ground where brightness moved by 5.0% or more either way, outside cloud.',+ rules: [expect.objectContaining({ measure: 'brightness', on: 'change', op: 'moved', value: 0.05 })],checks: [expect.objectContaining({ name: 'Check 1', marks: [{ point: [2.01, 48.01], expect: 'found' }],result: expect.objectContaining({ count: 1, covered: [true] }) })] }));});@@ -1368,7 +1372,7 @@ it('reads a point on the map and drops a pin from it, and a stricter line turnscovered = false;const tests = () => post.mock.calls.filter(([path, body]) => path === '/api/compare/analyzers/check' && body.read).length;const before = tests();- type(target.querySelector('[aria-label="Rule 1 value"]'), '0.6', 'change'); await settle();+ type(target.querySelector('[aria-label="Rule 1 value"]'), '60', 'change'); await settle();await debounce(); await settle();expect(tests()).toBe(before);expect(post.mock.calls.filter(([path]) => path === '/api/compare/analyzers/check/plan')).toHaveLength(2);@@ -1376,7 +1380,7 @@ it('reads a point on the map and drops a pin from it, and a stricter line turnsexpect(tests()).toBe(before + 1);expect(target.querySelector('.strip').textContent).toContain('0 of 1 found');expect(tab('Checks').textContent.replace(/\s+/g, '')).toBe('Checks0/1');- expect(post.mock.calls.findLast(([path]) => path === '/api/compare/analyzers/check')[1].recipe.rules[0].value).toBe(-0.6);+ expect(post.mock.calls.findLast(([path]) => path === '/api/compare/analyzers/check')[1].recipe.rules[0].value).toBe(0.6);});it('shows the detections alone on the map, and keeps each eye for the way back', async () => {@@ -1404,11 +1408,11 @@ it('adds, ranks, rewrites and removes rules, and the sentence follows', async ()answer({ '/api/compare/analyzers': rulesCatalogue() });await openBuilder();button('Add a rule').click(); await settle();- expect(phrase()).toBe('Keeps ground where NDVI dropped by 0.25 or more and NDVI before is at least 0.40, outside cloud.');+ expect(phrase()).toBe('Keeps ground where brightness moved by 5.0% or more either way and NDVI before is at least 0.40, outside cloud.');button('any rule').click(); await settle();expect(phrase()).toContain('or NDVI before is at least 0.40');labelled('Rank candidates by rule 2').click(); await settle();- expect(phrase()).toMatch(/^Keeps ground where NDVI before is at least 0.40 or NDVI dropped/);+ expect(phrase()).toMatch(/^Keeps ground where NDVI before is at least 0.40 or brightness moved/);const measure = target.querySelector('[aria-label="Rule 2 measures"]');measure.value = 'band'; measure.dispatchEvent(new Event('change', { bubbles: true })); await settle();expect(phrase()).toContain('B08 (near infrared) moved by 5.0% or more either way');diff --git a/frontend/src/tools/detect/DetectWizard.svelte b/frontend/src/tools/detect/DetectWizard.svelteindex cd70155..118ae60 100644--- a/frontend/src/tools/detect/DetectWizard.svelte+++ b/frontend/src/tools/detect/DetectWizard.svelte@@ -33,6 +33,10 @@import AnalyzerSettings from './AnalyzerSettings.svelte';import AnalyzerSize from './AnalyzerSize.svelte';import WhenStep from './WhenStep.svelte';++ /** The areas one sweep holds, as the backend counts them (engine/analysis_models.py). */+ const MAX_AREAS = 32;+ const FULL = `At most ${MAX_AREAS} areas per sweep`;import FoldGroup from './FoldGroup.svelte';import Icon from '../../components/Icon.svelte';@@ -270,7 +274,10 @@return;}const additions = additionsOf(members);- if (zones.length + additions.length > 32) return;+ if (zones.length + additions.length > MAX_AREAS) {+ toast(`That group would pass the ${MAX_AREAS} areas a sweep holds`, 'warn');+ return;+ }zones = [...zones, ...additions];}@@ -373,7 +380,7 @@<button type="button" role="checkbox" class="tick" aria-checked={state}aria-label={`Use ${group.title}`}title={state === 'true' ? `Leave out ${group.title}` : `Look in all of ${group.title}`}- disabled={pending || !members.length || (state !== 'true' && zones.length + additionsOf(members).length > 32)}+ disabled={pending || !members.length || (state !== 'true' && zones.length + additionsOf(members).length > MAX_AREAS)}onclick={() => toggleGroup(group)}>{#if state === 'true'}<Icon name="check" size={11} />{:else if state === 'mixed'}<Icon name="minus" size={11} />{/if}</button>@@ -393,7 +400,7 @@{@const area = areas.find((item) => item.id === zone.id)}{@const on = isOn(zone.id)}<button type="button" class="area-item" class:on aria-pressed={on}- disabled={pending || (!on && zones.length >= 32)}+ disabled={pending || (!on && zones.length >= MAX_AREAS)}onclick={() => (on ? removeZone(zone.id) : area ? useArea(area) : (zones = [...zones, zone]))}><span class="tick" aria-hidden="true">{#if on}<Icon name="check" size={11} />{/if}</span><span class="swatch" style={`--tint: ${area?.colour ?? AREA_COLOUR}`}></span>{zone.name}@@ -411,7 +418,7 @@{#each loose as area (area.id)}{@const on = isOn(area.id)}<button type="button" class="area-item" class:on aria-pressed={on}- disabled={!on && zones.length >= 32}+ disabled={!on && zones.length >= MAX_AREAS}onclick={() => (on ? removeZone(area.id) : useArea(area))}><span class="tick" aria-hidden="true">{#if on}<Icon name="check" size={11} />{/if}</span><span class="swatch" style={`--tint: ${area.colour}`}></span>{area.name}@@ -427,12 +434,14 @@<div class="cmp-seg" role="group" aria-label="Draw an area">{#each [['rect', 'Rectangle'], ['polygon', 'Polygon'], ['ellipse', 'Circle']] as [shape, label]}<button type="button" class:on={drawing === shape} aria-pressed={drawing === shape}- disabled={zones.length >= 32}+ disabled={zones.length >= MAX_AREAS} title={zones.length >= MAX_AREAS ? FULL : undefined}onclick={() => { drawing = drawing === shape ? 'select' : shape; showZones = true; }}>{label}</button>{/each}</div>- <button class="btn btn-sm" disabled={zones.length >= 32} onclick={onusecurrentview}>Use current view</button>+ <button class="btn btn-sm" disabled={zones.length >= MAX_AREAS}+ title={zones.length >= MAX_AREAS ? FULL : undefined} onclick={onusecurrentview}>Use current view</button></div>+ {#if zones.length >= MAX_AREAS}<p class="hint">{FULL}.</p>{/if}{#if drawing !== 'select'}<p class="hint">{drawing === 'polygon' ? 'Click corners on the map; Enter finishes, Escape cancels.' : 'Drag on the map. Escape cancels.'}</p>{:else if !zones.length}diff --git a/frontend/src/tools/detect/DetectWizard.test.js b/frontend/src/tools/detect/DetectWizard.test.jsnew file mode 100644index 0000000..63b5219--- /dev/null+++ b/frontend/src/tools/detect/DetectWizard.test.js@@ -0,0 +1,22 @@+import { describe, expect, it } from 'vitest';+import { readFileSync } from 'node:fs';++const wizard = readFileSync(new URL('./DetectWizard.svelte', import.meta.url), 'utf8');+const builder = readFileSync(new URL('./AnalyzerBuilder.svelte', import.meta.url), 'utf8');+const checks = readFileSync(new URL('./AnalyzerChecks.svelte', import.meta.url), 'utf8');++describe('a cap says why a control went grey', () => {+ it('holds one area cap, the backend\'s, and says it where drawing stops', () => {+ expect(wizard).toContain('const MAX_AREAS = 32;');+ expect(wizard).not.toMatch(/>= 32|> 32/);+ expect(wizard).toContain('{#if zones.length >= MAX_AREAS}<p class="hint">{FULL}.</p>{/if}');+ expect(wizard).toContain('title={zones.length >= MAX_AREAS ? FULL : undefined}');+ // ticking a group that would overflow says so instead of doing nothing+ expect(wizard).toContain('would pass the ${MAX_AREAS} areas a sweep holds');+ });++ it('names the rule and check limits on the buttons they disable', () => {+ expect(builder).toContain('`At most ${most} rules per analyzer`');+ expect(checks).toContain("'This analyzer holds all the checks it can'");+ });+});diff --git a/frontend/src/tools/detect/RuleRow.svelte b/frontend/src/tools/detect/RuleRow.svelteindex 4ef40d9..81f6b96 100644--- a/frontend/src/tools/detect/RuleRow.svelte+++ b/frontend/src/tools/detect/RuleRow.svelte@@ -11,7 +11,7 @@import {BAND_NAMES, CLASS_NAMES, INDICES, L2A_BANDS, PAIRS, POLARISATIONS, amountOf, describeRule, directionOf,directionsFor, formatShare, lineScale, measuresFor, readsOneDate, retarget, ruleProblem, toEngine, whensFor,- withAmount, withDirection,+ withAmount, withDirection, ruleBands,} from '../../lib/map/analyzerRules.js';import Icon from '../../components/Icon.svelte';@@ -50,6 +50,9 @@const between = $derived(rule.op === 'between');const problem = $derived(ruleProblem(rule));const measures = $derived(measuresFor(recipe));+ const dataLabel = $derived(rule.measure === 'class' ? 'Sentinel-2 scene classification (SCL)'+ : rule.measure === 'radar' ? `Sentinel-1 · ${rule.polarisation === 'vv' ? 'VV' : rule.polarisation === 'vh' ? 'VH' : 'VV · VH'}`+ : `Sentinel-2 bands · ${ruleBands(rule).join(' · ')}`);const whens = $derived(whensFor(recipe, rule));const pair = $derived(PAIRS.find((entry) => entry.bands[0] === rule.bands[0] && entry.bands[1] === rule.bands[1])?.id ?? '');const shownAmount = $derived(Number((amountOf(rule) * scale.factor).toFixed(4)));@@ -157,6 +160,7 @@{/each}</div>{/if}+ <span class="data-source" aria-label={`Rule ${n} data`}>{dataLabel}</span></div></div>@@ -306,7 +310,7 @@.control :global(.cmp-seg.fill > button) { padding: 0 5px; }}.pair { display: grid; grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr); align-items: center; gap: 5px; }- .note { color: var(--text-3); font-size: 10.5px; line-height: 1.4; }+ .note, .data-source { color: var(--text-3); font-size: 10.5px; line-height: 1.4; }.value { display: flex; align-items: center; gap: 6px; }.value input[type='number'] { width: 84px; }.minus, .unit { color: var(--text-3); font-size: var(--fs-xs); }diff --git a/frontend/src/tools/detect/RuleRow.svelte.test.js b/frontend/src/tools/detect/RuleRow.svelte.test.jsindex ebe0503..17c9f63 100644--- a/frontend/src/tools/detect/RuleRow.svelte.test.js+++ b/frontend/src/tools/detect/RuleRow.svelte.test.js@@ -32,6 +32,17 @@ it('says the rule as the sentence it is, with the number and colour it wears onexpect(query('.rule').getAttribute('style')).toContain('--tint: #facc15');});+it('names the data each rule reads and follows a change of quantity', () => {+ const props = open(newRule('index', 'change'));+ expect(query('[aria-label="Rule 1 data"]').textContent).toBe('Sentinel-2 bands · B08 · B04');+ props.rule = newRule('brightness', 'change'); flushSync();+ expect(query('[aria-label="Rule 1 data"]').textContent).toBe('Sentinel-2 bands · B02 · B03 · B04');+ props.rule = newRule('class', 'b'); flushSync();+ expect(query('[aria-label="Rule 1 data"]').textContent).toContain('scene classification (SCL)');+ props.rule = newRule('radar', 'change', { polarisation: 'vh' }); flushSync();+ expect(query('[aria-label="Rule 1 data"]').textContent).toBe('Sentinel-1 · VH');+});+it('offers before, after and change on two dates, says where each is painted, and nothing on one date', () => {open(newRule('index', 'change'));expect([...query('[aria-label="Rule 1 reads"]').querySelectorAll('button')].map((b) => b.textContent)).toEqual(['Before', 'After', 'Change']);diff --git a/frontend/src/tools/detect/SecondPass.svelte b/frontend/src/tools/detect/SecondPass.svelteindex 2750bbc..325f2ff 100644--- a/frontend/src/tools/detect/SecondPass.svelte+++ b/frontend/src/tools/detect/SecondPass.svelte@@ -40,6 +40,7 @@onclick = () => {},oncontextmenu = () => {},onusage = () => {},+ onimageryfallback = () => {},} = $props();const place = () => ({ lat: view.lat, lon: view.lon });@@ -111,7 +112,8 @@<div class="second" bind:this={stage} style:--divider={`${divider}%`}><div class="clip"><MapSurface bind:engine bind:element bind:ready bind:providerId {imagery} s2={s2} s1={s1} {view} {bearing} {home}- resetToHome={false} {imperial} {overlays} {armed} chrome={false} controlsTop={108} {onclick} {oncontextmenu} {onusage} />+ resetToHome={false} {imperial} {overlays} {armed} chrome={false} controlsTop={108} {onclick} {oncontextmenu} {onusage}+ {onimageryfallback} errorSide="right" /></div><button type="button" class="line" class:dragging class:armed={!!armed} role="slider" aria-label="Split between the before and after passes"aria-valuemin="0" aria-valuemax="100" aria-valuenow={Math.round(divider)} tabindex="0"diff --git a/frontend/src/tools/inspect/CollageMenu.svelte b/frontend/src/tools/inspect/CollageMenu.svelteindex 3c83ed0..3184cd0 100644--- a/frontend/src/tools/inspect/CollageMenu.svelte+++ b/frontend/src/tools/inspect/CollageMenu.svelte@@ -236,7 +236,7 @@{/if}<div class="section">- <div class="section-head" title="Places the pieces from the imagery they share. You can still drag them after.">+ <div class="section-head" title="Place the pieces by the imagery they share"><span>Auto panorama</span></div><div class="modes">diff --git a/frontend/src/tools/inspect/FrameMenu.svelte b/frontend/src/tools/inspect/FrameMenu.svelteindex c08f7b0..012322d 100644--- a/frontend/src/tools/inspect/FrameMenu.svelte+++ b/frontend/src/tools/inspect/FrameMenu.svelte@@ -176,7 +176,7 @@class="btn btn-sm reverse"disabled={reversing}onclick={reverseActive}- title="Search the web for this image as it is adjusted and cropped here"+ title="Search the web for this frame as shown"><Icon name="search" size={14} /> {reversing ? 'Preparing…' : 'Reverse image search'}</button>diff --git a/frontend/src/tools/inspect/SaveToCase.svelte b/frontend/src/tools/inspect/SaveToCase.svelteindex 798143f..1aa4e59 100644--- a/frontend/src/tools/inspect/SaveToCase.svelte+++ b/frontend/src/tools/inspect/SaveToCase.svelte@@ -49,7 +49,7 @@<div class="head"><span><Icon name="save" size={14} /> Save to case</span>{#if filedPath}- <button class="btn btn-ghost btn-xs filed" onclick={showInLibrary} title="Show it in the Media Library">+ <button class="btn btn-ghost btn-xs filed" onclick={showInLibrary} title="Show it in Media"><Icon name="check" size={12} /> In the case</button>{/if}diff --git a/frontend/src/tools/proof/ImportProofDialog.svelte b/frontend/src/tools/proof/ImportProofDialog.svelteindex dbcfe9e..ba50de9 100644--- a/frontend/src/tools/proof/ImportProofDialog.svelte+++ b/frontend/src/tools/proof/ImportProofDialog.svelte@@ -482,7 +482,7 @@</div>{#if job}<p class="import-progress">- Downloading{job.progress?.percent != null ? ` — ${job.progress.percent}%` : '…'}+ Downloading{job.progress?.percent != null ? ` ${job.progress.percent}%` : '…'}</p>{/if}</div>@@ -685,7 +685,7 @@{#if phase === 'source'}<p class="import-progress">{job?.progress?.percent != null- ? `Downloading the footage — ${job.progress.percent}%`+ ? `Downloading the footage: ${job.progress.percent}%`: 'Reaching the footage…'}</p>{/if}diff --git a/frontend/src/tools/proof/ProofLayersPanel.svelte b/frontend/src/tools/proof/ProofLayersPanel.svelteindex 61d4e5f..d7ebae1 100644--- a/frontend/src/tools/proof/ProofLayersPanel.svelte+++ b/frontend/src/tools/proof/ProofLayersPanel.svelte@@ -3,6 +3,7 @@import ProofGlyph from '../../components/ProofGlyph.svelte';import { iconByName } from '../../lib/proofIcons.js';import { fileUrl } from '../../lib/fileUrl.js';+ import { shortcut } from '../../lib/keys.js';let {proof,@@ -299,7 +300,7 @@</div>{#if !collapsed.overlays}{#if !proof.pastes.length}- <div class="none">Paste a screenshot with Ctrl+V. It stays in this proof only.</div>+ <div class="none">{shortcut('Paste a screenshot with Ctrl+V. It stays in this proof only.')}</div>{/if}{#each proof.pastes as paste, index (paste.id)}<div class="panel-row paste-row card" class:selected={selectionLive && selectedPasteId === paste.id}>@@ -476,7 +477,7 @@{/if}<buttonclass="btn btn-ghost btn-sm"- title="Duplicate (Ctrl+D)"+ title={shortcut('Duplicate (Ctrl+D)')}onclick={(event) => { event.stopPropagation(); duplicateShape(shape.id); }}><Icon name="copy" size={13} /></button><buttondiff --git a/frontend/src/tools/proof/ProofToolbar.svelte b/frontend/src/tools/proof/ProofToolbar.svelteindex c4a1dae..3c6ff88 100644--- a/frontend/src/tools/proof/ProofToolbar.svelte+++ b/frontend/src/tools/proof/ProofToolbar.svelte@@ -3,6 +3,7 @@import ProofGlyph from '../../components/ProofGlyph.svelte';import { PROOF_ICONS } from '../../lib/proofIcons.js';import { canFill, fillPaint } from '../../lib/proofEdits.js';+ import { shortcut } from '../../lib/keys.js';let {canUndo,@@ -149,10 +150,10 @@</script><div class="toolbar">- <button class="tb-btn" title="Undo (Ctrl+Z)" disabled={!canUndo} onclick={undo}>+ <button class="tb-btn" title={shortcut('Undo (Ctrl+Z)')} disabled={!canUndo} onclick={undo}><Icon name="undo" size={18} /></button>- <button class="tb-btn" title="Redo (Ctrl+Shift+Z / Ctrl+Y)" disabled={!canRedo} onclick={redo}>+ <button class="tb-btn" title={shortcut('Redo (Ctrl+Shift+Z / Ctrl+Y)')} disabled={!canRedo} onclick={redo}><Icon name="redo" size={18} /></button><div class="tb-sep"></div>diff --git a/frontend/src/tools/satellite/AddedLayersOverlay.svelte b/frontend/src/tools/satellite/AddedLayersOverlay.svelteindex 94daabc..9d58ffc 100644--- a/frontend/src/tools/satellite/AddedLayersOverlay.svelte+++ b/frontend/src/tools/satellite/AddedLayersOverlay.svelte@@ -19,6 +19,7 @@import { attribution, UNNAMED } from '../../lib/map/addedLayers.js';import { layerCard } from '../../lib/map/layerCard.js';import { fmtCoords, toast } from '../../lib/state.svelte.js';+ import { copyText } from '../../lib/clipboard.js';let {engine = null,@@ -33,12 +34,7 @@} = $props();async function copy(text) {- try {- await navigator.clipboard.writeText(text);- toast('Coordinates copied', 'ok', 1600);- } catch {- toast('The browser refused the clipboard', 'warn');- }+ await copyText(text);}/** name → { layer, sha } so a refreshed snapshot redraws and nothing else does. */diff --git a/frontend/src/tools/satellite/ExtensionGate.svelte b/frontend/src/tools/satellite/ExtensionGate.svelteindex 025c73f..bd0b22b 100644--- a/frontend/src/tools/satellite/ExtensionGate.svelte+++ b/frontend/src/tools/satellite/ExtensionGate.svelte@@ -14,10 +14,9 @@<Modal title="Capture needs the browser extension" {onclose} width="460px"><p class="gate-hint">- Google's terms allow nothing programmatic out of this basemap. A capture- here is a <strong>screenshot of the tab</strong>, and the Azimut Capture- extension is what takes it (one grab per click, no screen-share prompt,- works in fullscreen). Other basemaps are not affected.+ Google's terms allow nothing programmatic out of this basemap, so a capture+ here is a <strong>screenshot of the tab</strong> taken by the Azimut Capture+ extension.</p><p class="gate-hint">Install it from <strong>Settings → Capture extension</strong>, then reloaddiff --git a/frontend/src/tools/satellite/ImageryChip.svelte b/frontend/src/tools/satellite/ImageryChip.svelteindex 9f1c149..67aed99 100644--- a/frontend/src/tools/satellite/ImageryChip.svelte+++ b/frontend/src/tools/satellite/ImageryChip.svelte@@ -165,7 +165,7 @@small caps and letterspaced, and it turned every basemap nameinto a heading three lines tall --><span class="name">{provider.label}</span>- {#if provider.needs_key}<span class="need">needs key</span>{/if}+ {#if provider.needs_key}<span class="need">Needs a key</span>{/if}</button></li>{/each}diff --git a/frontend/src/tools/satellite/MapSurface.svelte b/frontend/src/tools/satellite/MapSurface.svelteindex 94fd486..e149770 100644--- a/frontend/src/tools/satellite/MapSurface.svelte+++ b/frontend/src/tools/satellite/MapSurface.svelte@@ -25,7 +25,7 @@*/import { onMount, tick } from 'svelte';import { createMapEngine } from '../../lib/map/engine.js';- import { createBasemaps, OVERLAY_IDS } from '../../lib/map/basemap.js';+ import { createBasemaps, imageryError, OVERLAY_IDS } from '../../lib/map/basemap.js';import { DEFAULT_LAYER, DEFAULT_MAXCC, SENTINEL_ID } from '../../lib/sentinel.js';import { RADAR_ID, orbitMark } from '../../lib/radar.js';import { pictureDate } from '../../lib/map/pictureDate.js';@@ -99,6 +99,8 @@onwidgetfailed = () => {},/** A tile of an overlay failed, by overlay id, for the tool that offers it. */onoverlaytrouble = () => {},+ onimageryfallback = null,+ errorSide = 'left',/** The settled camera and the turn, for a parent that shares them. */onviewsettled = () => {},onbearingchange = () => {},@@ -109,6 +111,8 @@let mapEl = $state();let basemaps = null;+ let tileFailure = $state(null);+ let failureProvider = '';// Acquisition date of the imagery under the crosshair — Esri only.let imageryDate = $state(null); // { supported, date, source } | nulllet dateRequest = 0;@@ -127,6 +131,7 @@}));const radarPass = $derived(shown.provider?.id === RADAR_ID ? s1?.pass ?? null : null);+ const tileProblem = $derived(tileFailure?.id === shown.id ? tileFailure : null);/** A pinned Sentinel-2 day *is* the acquisition date — the one provider that* can answer "when was this taken?" without being asked. */@@ -198,6 +203,7 @@onWidgetAuthFailure: onwidgetauthfailure,onWidgetFailed: onwidgetfailed,onOverlayTrouble: (id) => onoverlaytrouble(id),+ onImageryTrouble: (failure) => { tileFailure = { id: failure.id, message: imageryError(failure.error) }; },});basemaps.setZoomCeiling(zoomCeiling);showBasemap();@@ -233,6 +239,22 @@basemaps.show(shown.provider, shown.id, shown.cell);}+ function retryImagery() {+ tileFailure = null;+ basemaps?.retry(shown.provider, shown.id, shown.cell);+ }++ function useBasemap() {+ tileFailure = null;+ if (onimageryfallback) onimageryfallback();+ else providerId = 'esri-world-imagery';+ }++ $effect(() => {+ const id = shown.id;+ if (failureProvider !== id) { failureProvider = id; tileFailure = null; }+ });+$effect(() => {const value = zoomCeiling;if (ready) basemaps?.setZoomCeiling(value);@@ -324,6 +346,20 @@<p class="map-refused">The map needs WebGL, which this browser does not have.</p>{/if}+ {#if tileProblem && !grabbing}+ <div class="tile-trouble" class:right={errorSide === 'right'} role="status" aria-label="Imagery loading error">+ <strong>Could not load imagery</strong>+ <span>{shown.provider?.label}{shown.provider?.id === SENTINEL_ID ? ` · ${s2?.layer ?? DEFAULT_LAYER}` : ''}{pinnedDay ? ` · ${pinnedDay}` : radarPass?.date ? ` · ${radarPass.date}` : ''}</span>+ <p>{tileProblem.message}</p>+ <div class="error-actions">+ <button class="btn btn-sm" onclick={retryImagery}>Retry imagery</button>+ {#if shown.provider?.id !== 'esri-world-imagery' && imagery.find('esri-world-imagery')}+ <button class="btn btn-sm" onclick={useBasemap}>Use basemap</button>+ {/if}+ </div>+ </div>+ {/if}+{@render children?.()}<!-- The picture this surface is showing, when it was taken, and the compass@@ -401,6 +437,15 @@</div><style>+ .tile-trouble {+ position: absolute; top: 154px; left: 12px; z-index: 600;+ display: grid; gap: 6px; max-width: min(330px, calc(100% - 24px));+ padding: 12px; border: 1px solid var(--warn); border-radius: var(--r-sm);+ background: var(--bg-1); color: var(--text-1); font-size: var(--fs-xs);+ }+ .tile-trouble.right { left: auto; right: 12px; }+ .tile-trouble span, .tile-trouble p { margin: 0; color: var(--text-2); }+ .error-actions { display: flex; flex-wrap: wrap; gap: 7px; }.map-wrap {position: relative;flex: 1;diff --git a/frontend/src/tools/satellite/PlaceDialog.svelte b/frontend/src/tools/satellite/PlaceDialog.svelteindex efeff56..eececd6 100644--- a/frontend/src/tools/satellite/PlaceDialog.svelte+++ b/frontend/src/tools/satellite/PlaceDialog.svelte@@ -112,7 +112,7 @@{#if draft.id && ondetails}<buttonclass="btn btn-ghost btn-sm"- title="Precision, the source's own wording, how the point was found"+ title="Edit precision, wording and method"onclick={() => (touched ? (discarding = true) : ondetails())}>Edit more details</button>{/if}diff --git a/frontend/src/tools/satellite/PlaceSearch.svelte b/frontend/src/tools/satellite/PlaceSearch.svelteindex 050067c..aa06b45 100644--- a/frontend/src/tools/satellite/PlaceSearch.svelte+++ b/frontend/src/tools/satellite/PlaceSearch.svelte@@ -186,7 +186,7 @@autocomplete="off"aria-label="Search a place or coordinates"placeholder={'A place, or 50.4501, 30.5234'}- title="A place name, or coordinates (decimal, DMS, MGRS, plus code)"+ title="Place name or coordinates (decimal, DMS, MGRS, plus code)"{value}{oninput}{onkeydown}diff --git a/frontend/src/tools/satellite/RefPicker.svelte b/frontend/src/tools/satellite/RefPicker.svelteindex f13b65e..0147790 100644--- a/frontend/src/tools/satellite/RefPicker.svelte+++ b/frontend/src/tools/satellite/RefPicker.svelte@@ -98,7 +98,7 @@<div class="ref-empty">Loading…</div>{:else if !media.length}<div class="ref-empty">- No images or videos in this case yet. Import one in the Media Library first.+ No images or videos in this case yet. Import one in Media first.</div>{:else}{#if narrowing}diff --git a/frontend/src/tools/satellite/ScreenshotDialog.svelte b/frontend/src/tools/satellite/ScreenshotDialog.svelteindex b77aa0b..ee86da1 100644--- a/frontend/src/tools/satellite/ScreenshotDialog.svelte+++ b/frontend/src/tools/satellite/ScreenshotDialog.svelte@@ -11,6 +11,7 @@*/import Icon from '../../components/Icon.svelte';import Modal from '../../components/Modal.svelte';+ import { shortcut } from '../../lib/keys.js';let {/** `{ lat, lon, zoom }` the map is on, which is what a pasted image is filed at. */@@ -93,15 +94,11 @@{#if !grabbing}<Modal title="File a screenshot" onclose={close} width="520px"><p class="shot-hint">- The <strong>Capture</strong> button already crops this basemap off the screen- through the usual frame. Use this when it can't:- grab the whole map view below, or paste- (<span class="mono">Ctrl+V</span>) / drop your own OS screenshot.- Unlike a framed capture, this is filed at the current <em>view</em>- (<span class="mono">{fmtCoords(view.lat, view.lon)}</span>, z{view.zoom}).- the coordinates describe the map, not a registered crop. The Google attribution- is burned into a footer either way; keep Google's on-screen credits inside the- frame too.+ <strong>Capture</strong> already crops this basemap. Use this when it can't: grab+ the whole view below, or paste (<span class="mono">{shortcut('Ctrl+V')}</span>) or drop your own+ screenshot. It is filed at the current view+ (<span class="mono">{fmtCoords(view.lat, view.lon)}</span>, z{view.zoom}), so the+ coordinates describe the map, not a crop.</p><div style="display:flex;justify-content:center;margin-bottom:10px"><button class="btn btn-primary" onclick={onGrab} disabled={grabbing}>@@ -123,7 +120,7 @@{#if preview}<img src={preview} alt="screenshot to file" />{:else}- <span>Paste (Ctrl+V) or drop the screenshot here</span>+ <span>{shortcut('Paste (Ctrl+V) or drop the screenshot here')}</span>{/if}</div><div style="display:flex;gap:8px;justify-content:flex-end;margin-top:12px">diff --git a/frontend/src/tools/satellite/SheetPointsOverlay.svelte b/frontend/src/tools/satellite/SheetPointsOverlay.svelteindex 91fd04c..62d3397 100644--- a/frontend/src/tools/satellite/SheetPointsOverlay.svelte+++ b/frontend/src/tools/satellite/SheetPointsOverlay.svelte@@ -53,7 +53,7 @@at: point,...mark(coarse),title: coarse- ? `${point.label} — written to ${point.decimals} decimals, about ${metres} m`+ ? `${point.label}, written to ${point.decimals} decimals (about ${metres} m)`: point.label,tip: { text: point.label, direction: 'top', offset: [0, -12] },};diff --git a/frontend/src/tools/satellite/SunPanel.svelte b/frontend/src/tools/satellite/SunPanel.svelteindex c01afe0..6fabc80 100644--- a/frontend/src/tools/satellite/SunPanel.svelte+++ b/frontend/src/tools/satellite/SunPanel.svelte@@ -8,6 +8,7 @@// backend again.import Icon from '../../components/Icon.svelte';import MoonGlyph from '../../components/MoonGlyph.svelte';+ import DateField from '../../components/DateField.svelte';let {sky = null,@@ -106,12 +107,12 @@title="Drag to move this panel"aria-label="Move panel"><Icon name="grip" size={14} /></button>- <input- class="input input-sm"- type="date"+ <DateField+ day+ reading={false}+ label="Local date at the anchored point"value={day}- onchange={(e) => ondate(e.currentTarget.value)}- title="Local date at the anchored point"+ onchange={(value) => value && ondate(value)}/><span class="zone">{sky?.zone?.abbreviation ?? ''}</span><button class="btn btn-ghost btn-sm" onclick={onclose} title="Close (Esc)">@@ -202,10 +203,8 @@.grip:active {cursor: grabbing;}- .line .input {+ .line :global(.date-field) {flex: 1;- font-family: var(--font-mono);- font-size: var(--fs-sm);}.zone {font-size: var(--fs-xs);diff --git a/frontend/src/tools/satellite/WaybackPicker.svelte b/frontend/src/tools/satellite/WaybackPicker.svelteindex 94c0d06..acdf105 100644--- a/frontend/src/tools/satellite/WaybackPicker.svelte+++ b/frontend/src/tools/satellite/WaybackPicker.svelte@@ -100,7 +100,7 @@class="chip-opt"class:on={wb.changesOnly}onclick={() => wb.setChangesOnly(true)}- title="Read which releases show a different picture at the crosshair"+ title="Find the releases that differ at the crosshair">Changes here</button></div>diff --git a/frontend/src/tools/satellite/state/capture.svelte.js b/frontend/src/tools/satellite/state/capture.svelte.jsindex 45d1ec5..81a5b91 100644--- a/frontend/src/tools/satellite/state/capture.svelte.js+++ b/frontend/src/tools/satellite/state/capture.svelte.js@@ -124,7 +124,7 @@ export function createCaptureState({} catch {// The capture still carries what is ticked; only the remembering failed,// and saying so is worth one line rather than undoing their click.- notify('That tick applies to this session — it could not be saved', 'warn');+ notify('That tick could not be saved, so it lasts this session only', 'warn');}}diff --git a/frontend/src/tools/satellite/state/sentinel.svelte.js b/frontend/src/tools/satellite/state/sentinel.svelte.jsindex 0d9f1cf..416054b 100644--- a/frontend/src/tools/satellite/state/sentinel.svelte.js+++ b/frontend/src/tools/satellite/state/sentinel.svelte.js@@ -56,6 +56,9 @@ export function createSentinelState({ place, onBilled, notify, api }) {let menuOpen = $state(false);let layers = $state([]); // [{id,label,hint}] — catalogue until the instance is askedlet layersSource = $state('');+ let layersBusy = $state(false);+ let layersNote = $state('');+ let layersPending = null;let layersAsked = false; // the instance is asked once per session, on first open// The month the calendar is showing, and the passes found in it:// { 'YYYY-MM-DD': {cloud, granules} }. A day with no entry has no imagery and@@ -88,20 +91,40 @@ export function createSentinelState({ place, onBilled, notify, api }) {* from its own list); `check` asks the user's instance what it really serves,* which is the only authority — a configuration can rename or drop any layer.*/- async function loadLayers(check = false, quiet = false) {+ async function loadLayers(check = false, quiet = false, force = false) {+ if (layersPending) {+ await layersPending;+ if (!check || layersSource === 'instance') return layersSource === 'instance';+ return loadLayers(check, quiet, force);+ }+ if (check && !force && layersSource === 'instance') return true;+ layersBusy = true;+ layersNote = '';+ layersPending = readLayers(check, quiet);+ try { return await layersPending; }+ finally { layersPending = null; layersBusy = false; }+ }++ async function readLayers(check, quiet) {try {const r = await api.get(`/api/satellite/sentinel/layers${check ? '?check=true' : ''}`);layers = r.layers ?? [];layersSource = r.source ?? '';+ layersNote = check && layersSource !== 'instance'+ ? 'Could not check your Copernicus layers; the basemap stays on.' : '';// a layer that vanished with the list can't stay selected- if (layers.length && !layers.some((l) => l.id === layer)) layer = layers[0].id;- if (quiet) return;+ if (layersSource === 'instance' && layers.length && !layers.some((l) => l.id === layer)) layer = layers[0].id;+ if (quiet) return layersSource === 'instance';if (check && r.detail) notify(r.detail, 'warn', 6000);else if (check && r.source === 'instance') {notify(`${r.layers.length} layers read from your instance`, 'ok');}+ return layersSource === 'instance';} catch (e) {+ layersSource = '';+ layersNote = 'Could not check your Copernicus layers; the basemap stays on.';notify(`Sentinel-2 layers: ${e.message}`, 'danger');+ return false;}}@@ -333,6 +356,8 @@ export function createSentinelState({ place, onBilled, notify, api }) {get layersSource() {return layersSource;},+ get layersBusy() { return layersBusy; },+ get layersNote() { return layersNote; },get month() {return month;},diff --git a/frontend/src/tools/satellite/state/sentinel.svelte.test.js b/frontend/src/tools/satellite/state/sentinel.svelte.test.jsindex c99f565..b1df247 100644--- a/frontend/src/tools/satellite/state/sentinel.svelte.test.js+++ b/frontend/src/tools/satellite/state/sentinel.svelte.test.js@@ -239,6 +239,42 @@ describe('what the pill can claim', () => {});describe('which layers are on offer', () => {+ it('does not mistake the local catalogue for a checked instance and shares concurrent checks', async () => {+ get = vi.fn(async (path) => ({ source: path.includes('?check=true') ? 'instance' : 'catalogue',+ layers: [{ id: 'TRUE_COLOR', label: 'True colour' }, { id: 'VEGETATION_INDEX', label: 'Vegetation index' }] }));+ const s2 = store();+ expect(get).not.toHaveBeenCalled();+ await s2.loadLayers();+ expect(s2.layersSource).toBe('catalogue');+ await Promise.all([s2.loadLayers(true, true), s2.loadLayers(true, true)]);+ expect(get.mock.calls.filter(([path]) => path.includes('?check=true'))).toHaveLength(1);+ expect(s2.layersSource).toBe('instance');+ expect(s2.layersBusy).toBe(false);+ await s2.loadLayers(true, true);+ expect(get).toHaveBeenCalledTimes(2);+ await s2.loadLayers(true, true, true);+ expect(get).toHaveBeenCalledTimes(3);+ });++ it('keeps a failed capabilities lookup unverified and lets the user retry', async () => {+ get = vi.fn(async () => ({ source: 'catalogue', layers: [{ id: 'NDVI' }], detail: 'offline' }));+ const s2 = store();+ expect(await s2.loadLayers(true, true)).toBe(false);+ expect(s2.layersNote).toContain('Could not check');+ expect(s2.layer).toBe('TRUE_COLOR');+ get.mockResolvedValue({ source: 'instance', layers: [{ id: 'TRUE_COLOR' }] });+ expect(await s2.loadLayers(true, true)).toBe(true);+ expect(s2.layersNote).toBe('');+ });++ it('reports a refused request and finishes the loading state', async () => {+ get = vi.fn(async () => { throw new Error('key refused'); });+ const s2 = store();+ expect(await s2.loadLayers(true, true)).toBe(false);+ expect(s2.layersSource).toBe('');+ expect(s2.layersBusy).toBe(false);+ expect(s2.layersNote).toContain('basemap stays on');+ });it('asks the instance once a session, quietly, and takes its answer', async () => {const s2 = store();s2.toggleMenu();diff --git a/frontend/src/tools/settings/ExtensionTab.render.test.js b/frontend/src/tools/settings/ExtensionTab.render.test.jsnew file mode 100644index 0000000..a6a42b2--- /dev/null+++ b/frontend/src/tools/settings/ExtensionTab.render.test.js@@ -0,0 +1,67 @@+// @vitest-environment happy-dom+/**+ * The Capture extension section, actually mounted.+ *+ * Azimut takes the next free port when another program holds its own, and an+ * extension paired with the old address then refuses to capture or post for it.+ * The section has to say so, and name the address to set.+ */+import { afterEach, describe, expect, it, vi } from 'vitest';+import { flushSync, mount, unmount } from 'svelte';+import ExtensionTab from './ExtensionTab.svelte';+import { classify } from '../../lib/extInstall.js';++let target;+let app;++function open(answer) {+ target = document.createElement('div');+ document.body.append(target);+ const server = {+ path: '/home/a/Azimut/.azimut/extension',+ bundled: { version: '0.3.1', payload: 'p' },+ folder: { install_id: 'mine', version: '0.3.1', payload: 'p' },+ };+ const copy = { version: '0.3.1', extensionId: 'ext-a', loaded: { install_id: 'mine', payload: 'p' }, ...answer };+ app = mount(ExtensionTab, {+ target,+ props: {+ badges: {},+ extDetected: '0.3.1',+ extOutdated: false,+ extState: classify(server, { bridges: [{ version: '0.3.1' }], managed: [copy] }),+ extBundled: '0.3.1',+ extBusy: null,+ installExtension: vi.fn(),+ updateExtension: vi.fn(),+ copyExtensionPath: vi.fn(),+ revealExtension: vi.fn(),+ ingestToken: '',+ copyToken: vi.fn(),+ ensureToken: vi.fn(),+ rotateToken: vi.fn(),+ tokenShown: false,+ },+ });+ flushSync();+}++afterEach(() => {+ if (app) unmount(app);+ target?.remove();+ app = null;+});++describe('ExtensionTab', () => {+ it('names the address to set when the extension is paired with another one', () => {+ open({ paired: false });+ const note = [...target.querySelectorAll('.note.warn')].find((p) => p.textContent.includes('paired with another address'));+ expect(note).toBeTruthy();+ expect(note.textContent).toContain(location.origin);+ });++ it('says nothing about pairing when this is the paired address', () => {+ open({ paired: true });+ expect(target.textContent).not.toContain('paired with another address');+ });+});diff --git a/frontend/src/tools/settings/ExtensionTab.svelte b/frontend/src/tools/settings/ExtensionTab.svelteindex e362682..0ea6457 100644--- a/frontend/src/tools/settings/ExtensionTab.svelte+++ b/frontend/src/tools/settings/ExtensionTab.svelte@@ -113,6 +113,13 @@</p>{/if}+ {#if extState?.unpaired}+ <p class="note warn">+ The extension is paired with another address, so it won't capture or post for+ this one. In its options, set the Azimut URL to <span class="mono">{location.origin}</span>.+ </p>+ {/if}+{#if status === 'duplicate'}<p class="note warn">Two copies are loaded. Remove@@ -156,7 +163,7 @@<li>{extState.folderCurrent ? 'The app copy is written (path below)' : 'Press Install to write the app copy'}</li><li>Remove the current extension in your browser's extensions page</li><li>Load the folder below unpacked</li>- <li>Paste the pairing token again — Chrome ties stored data to the folder</li>+ <li>Paste the pairing token again, since Chrome ties stored data to the folder</li></ol>{/if}diff --git a/frontend/src/tools/settings/ImageryTab.svelte b/frontend/src/tools/settings/ImageryTab.svelteindex 3cb1347..19c8c19 100644--- a/frontend/src/tools/settings/ImageryTab.svelte+++ b/frontend/src/tools/settings/ImageryTab.svelte@@ -15,6 +15,7 @@import { tick } from 'svelte';import Icon from '../../components/Icon.svelte';import RadarLayer from './RadarLayer.svelte';+ import CopernicusLayersHelp from '../../components/CopernicusLayersHelp.svelte';import { SENTINEL_ECO_MAX_ZOOM } from '../../lib/usage.js';import {monthCount,@@ -191,6 +192,7 @@{/if}{#if k.id === 'sentinelhub' && keys[k.id]}+ <CopernicusLayersHelp /><RadarLayer bind:layer={radarLayer} onchanged={load} />{/if}diff --git a/frontend/src/tools/settings/PublishingTab.svelte b/frontend/src/tools/settings/PublishingTab.svelteindex 4df2f18..d0969a1 100644--- a/frontend/src/tools/settings/PublishingTab.svelte+++ b/frontend/src/tools/settings/PublishingTab.svelte@@ -59,9 +59,8 @@<div class="row-label"><span>Let the extension fill the composer</span><span class="row-hint">- Publish types the thread and attaches the proof, then stops. Nothing is- ever posted. Needs the capture extension; without it, Publish opens the- page as usual.+ Publish types the thread and attaches the proof with the capture extension,+ and only opens the page without it.</span></div><inputdiff --git a/frontend/src/tools/settings/SystemTab.svelte b/frontend/src/tools/settings/SystemTab.svelteindex e982f3b..d7a9693 100644--- a/frontend/src/tools/settings/SystemTab.svelte+++ b/frontend/src/tools/settings/SystemTab.svelte@@ -51,6 +51,9 @@{#if ffmpeg.available}{ffmpeg.version || 'installed'}<span class="sub">· {ffmpeg.source === 'bundled' ? 'bundled' : 'system PATH'}</span>+ {#if ffmpeg.notice}+ <a class="sub" href="/api/settings/ffmpeg/notice" target="_blank" rel="noreferrer">· licence</a>+ {/if}{:else}not found <span class="sub">· install ffmpeg on your PATH</span>{/if}@@ -59,8 +62,8 @@<dd>AGPL-3.0-only</dd></dl><p class="note">- Case data stays in the workspace; network access is limited to requested features- and the automatic GitHub update check.+ Case data stays in the workspace. Besides what you ask for, only the update check+ (GitHub and PyPI) and the home map's tiles reach the network.</p><div class="links"><a class="btn btn-sm" href={REPO_URL} target="_blank" rel="noreferrer">diff --git a/packaging/azimut.spec b/packaging/azimut.specindex 202c8bf..90cf507 100644--- a/packaging/azimut.spec+++ b/packaging/azimut.spec@@ -12,7 +12,7 @@import sysfrom pathlib import Path-from PyInstaller.utils.hooks import collect_data_files, collect_submodules+from PyInstaller.utils.hooks import collect_data_files, collect_submodules, copy_metadatahiddenimports = (collect_submodules("uvicorn")@@ -46,6 +46,13 @@ if sys.platform == "linux":# faces or they are different documents.datas = collect_data_files("azimut")+# The scrapers' .dist-info, which collect_submodules leaves behind. It is how+# engine/scrapers.py reads the version this build ships without importing it, and+# so whether an older copy updated into the workspace must give way to it. Without+# the metadata the workspace copy always wins, and a release that ships a fixed+# yt-dlp fixes nothing for anyone who once pressed Update.+datas += copy_metadata("yt-dlp") + copy_metadata("gallery-dl")+# The IANA timezone database, which `zoneinfo` falls back to when the OS has none# — that is Windows. Nothing imports `tzdata` by name, so PyInstaller cannot# discover it, and a missing database would not crash: engine/localtime.py would@@ -71,6 +78,10 @@ binaries = [for p in [vendor / name]if p.is_file()]+# The bundled ffmpeg is a GPL build: its notice (build, source, stated licence) and the+# licence texts travel inside the binary, and Settings → System opens the notice.+if (vendor / "ffmpeg-licenses" / "NOTICE.txt").is_file():+ datas += [(str(vendor / "ffmpeg-licenses"), "ffmpeg-licenses")]a = Analysis(["entry.py"],diff --git a/packaging/licenses/GPL-2.0.txt b/packaging/licenses/GPL-2.0.txtnew file mode 100644index 0000000..d159169--- /dev/null+++ b/packaging/licenses/GPL-2.0.txt@@ -0,0 +1,339 @@+ GNU GENERAL PUBLIC LICENSE+ Version 2, June 1991++ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++ Preamble++ The licenses for most software are designed to take away your+freedom to share and change it. By contrast, the GNU General Public+License is intended to guarantee your freedom to share and change free+software--to make sure the software is free for all its users. This+General Public License applies to most of the Free Software+Foundation's software and to any other program whose authors commit to+using it. (Some other Free Software Foundation software is covered by+the GNU Lesser General Public License instead.) You can apply it to+your programs, too.++ When we speak of free software, we are referring to freedom, not+price. Our General Public Licenses are designed to make sure that you+have the freedom to distribute copies of free software (and charge for+this service if you wish), that you receive source code or can get it+if you want it, that you can change the software or use pieces of it+in new free programs; and that you know you can do these things.++ To protect your rights, we need to make restrictions that forbid+anyone to deny you these rights or to ask you to surrender the rights.+These restrictions translate to certain responsibilities for you if you+distribute copies of the software, or if you modify it.++ For example, if you distribute copies of such a program, whether+gratis or for a fee, you must give the recipients all the rights that+you have. You must make sure that they, too, receive or can get the+source code. And you must show them these terms so they know their+rights.++ We protect your rights with two steps: (1) copyright the software, and+(2) offer you this license which gives you legal permission to copy,+distribute and/or modify the software.++ Also, for each author's protection and ours, we want to make certain+that everyone understands that there is no warranty for this free+software. If the software is modified by someone else and passed on, we+want its recipients to know that what they have is not the original, so+that any problems introduced by others will not reflect on the original+authors' reputations.++ Finally, any free program is threatened constantly by software+patents. We wish to avoid the danger that redistributors of a free+program will individually obtain patent licenses, in effect making the+program proprietary. To prevent this, we have made it clear that any+patent must be licensed for everyone's free use or not licensed at all.++ The precise terms and conditions for copying, distribution and+modification follow.++ GNU GENERAL PUBLIC LICENSE+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION++ 0. This License applies to any program or other work which contains+a notice placed by the copyright holder saying it may be distributed+under the terms of this General Public License. The "Program", below,+refers to any such program or work, and a "work based on the Program"+means either the Program or any derivative work under copyright law:+that is to say, a work containing the Program or a portion of it,+either verbatim or with modifications and/or translated into another+language. (Hereinafter, translation is included without limitation in+the term "modification".) Each licensee is addressed as "you".++Activities other than copying, distribution and modification are not+covered by this License; they are outside its scope. The act of+running the Program is not restricted, and the output from the Program+is covered only if its contents constitute a work based on the+Program (independent of having been made by running the Program).+Whether that is true depends on what the Program does.++ 1. You may copy and distribute verbatim copies of the Program's+source code as you receive it, in any medium, provided that you+conspicuously and appropriately publish on each copy an appropriate+copyright notice and disclaimer of warranty; keep intact all the+notices that refer to this License and to the absence of any warranty;+and give any other recipients of the Program a copy of this License+along with the Program.++You may charge a fee for the physical act of transferring a copy, and+you may at your option offer warranty protection in exchange for a fee.++ 2. You may modify your copy or copies of the Program or any portion+of it, thus forming a work based on the Program, and copy and+distribute such modifications or work under the terms of Section 1+above, provided that you also meet all of these conditions:++ a) You must cause the modified files to carry prominent notices+ stating that you changed the files and the date of any change.++ b) You must cause any work that you distribute or publish, that in+ whole or in part contains or is derived from the Program or any+ part thereof, to be licensed as a whole at no charge to all third+ parties under the terms of this License.++ c) If the modified program normally reads commands interactively+ when run, you must cause it, when started running for such+ interactive use in the most ordinary way, to print or display an+ announcement including an appropriate copyright notice and a+ notice that there is no warranty (or else, saying that you provide+ a warranty) and that users may redistribute the program under+ these conditions, and telling the user how to view a copy of this+ License. (Exception: if the Program itself is interactive but+ does not normally print such an announcement, your work based on+ the Program is not required to print an announcement.)++These requirements apply to the modified work as a whole. If+identifiable sections of that work are not derived from the Program,+and can be reasonably considered independent and separate works in+themselves, then this License, and its terms, do not apply to those+sections when you distribute them as separate works. But when you+distribute the same sections as part of a whole which is a work based+on the Program, the distribution of the whole must be on the terms of+this License, whose permissions for other licensees extend to the+entire whole, and thus to each and every part regardless of who wrote it.++Thus, it is not the intent of this section to claim rights or contest+your rights to work written entirely by you; rather, the intent is to+exercise the right to control the distribution of derivative or+collective works based on the Program.++In addition, mere aggregation of another work not based on the Program+with the Program (or with a work based on the Program) on a volume of+a storage or distribution medium does not bring the other work under+the scope of this License.++ 3. You may copy and distribute the Program (or a work based on it,+under Section 2) in object code or executable form under the terms of+Sections 1 and 2 above provided that you also do one of the following:++ a) Accompany it with the complete corresponding machine-readable+ source code, which must be distributed under the terms of Sections+ 1 and 2 above on a medium customarily used for software interchange; or,++ b) Accompany it with a written offer, valid for at least three+ years, to give any third party, for a charge no more than your+ cost of physically performing source distribution, a complete+ machine-readable copy of the corresponding source code, to be+ distributed under the terms of Sections 1 and 2 above on a medium+ customarily used for software interchange; or,++ c) Accompany it with the information you received as to the offer+ to distribute corresponding source code. (This alternative is+ allowed only for noncommercial distribution and only if you+ received the program in object code or executable form with such+ an offer, in accord with Subsection b above.)++The source code for a work means the preferred form of the work for+making modifications to it. For an executable work, complete source+code means all the source code for all modules it contains, plus any+associated interface definition files, plus the scripts used to+control compilation and installation of the executable. However, as a+special exception, the source code distributed need not include+anything that is normally distributed (in either source or binary+form) with the major components (compiler, kernel, and so on) of the+operating system on which the executable runs, unless that component+itself accompanies the executable.++If distribution of executable or object code is made by offering+access to copy from a designated place, then offering equivalent+access to copy the source code from the same place counts as+distribution of the source code, even though third parties are not+compelled to copy the source along with the object code.++ 4. You may not copy, modify, sublicense, or distribute the Program+except as expressly provided under this License. Any attempt+otherwise to copy, modify, sublicense or distribute the Program is+void, and will automatically terminate your rights under this License.+However, parties who have received copies, or rights, from you under+this License will not have their licenses terminated so long as such+parties remain in full compliance.++ 5. You are not required to accept this License, since you have not+signed it. However, nothing else grants you permission to modify or+distribute the Program or its derivative works. These actions are+prohibited by law if you do not accept this License. Therefore, by+modifying or distributing the Program (or any work based on the+Program), you indicate your acceptance of this License to do so, and+all its terms and conditions for copying, distributing or modifying+the Program or works based on it.++ 6. Each time you redistribute the Program (or any work based on the+Program), the recipient automatically receives a license from the+original licensor to copy, distribute or modify the Program subject to+these terms and conditions. You may not impose any further+restrictions on the recipients' exercise of the rights granted herein.+You are not responsible for enforcing compliance by third parties to+this License.++ 7. If, as a consequence of a court judgment or allegation of patent+infringement or for any other reason (not limited to patent issues),+conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License. If you cannot+distribute so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you+may not distribute the Program at all. For example, if a patent+license would not permit royalty-free redistribution of the Program by+all those who receive copies directly or indirectly through you, then+the only way you could satisfy both it and this License would be to+refrain entirely from distribution of the Program.++If any portion of this section is held invalid or unenforceable under+any particular circumstance, the balance of the section is intended to+apply and the section as a whole is intended to apply in other+circumstances.++It is not the purpose of this section to induce you to infringe any+patents or other property right claims or to contest validity of any+such claims; this section has the sole purpose of protecting the+integrity of the free software distribution system, which is+implemented by public license practices. Many people have made+generous contributions to the wide range of software distributed+through that system in reliance on consistent application of that+system; it is up to the author/donor to decide if he or she is willing+to distribute software through any other system and a licensee cannot+impose that choice.++This section is intended to make thoroughly clear what is believed to+be a consequence of the rest of this License.++ 8. If the distribution and/or use of the Program is restricted in+certain countries either by patents or by copyrighted interfaces, the+original copyright holder who places the Program under this License+may add an explicit geographical distribution limitation excluding+those countries, so that distribution is permitted only in or among+countries not thus excluded. In such case, this License incorporates+the limitation as if written in the body of this License.++ 9. The Free Software Foundation may publish revised and/or new versions+of the General Public License from time to time. Such new versions will+be similar in spirit to the present version, but may differ in detail to+address new problems or concerns.++Each version is given a distinguishing version number. If the Program+specifies a version number of this License which applies to it and "any+later version", you have the option of following the terms and conditions+either of that version or of any later version published by the Free+Software Foundation. If the Program does not specify a version number of+this License, you may choose any version ever published by the Free Software+Foundation.++ 10. If you wish to incorporate parts of the Program into other free+programs whose distribution conditions are different, write to the author+to ask for permission. For software which is copyrighted by the Free+Software Foundation, write to the Free Software Foundation; we sometimes+make exceptions for this. Our decision will be guided by the two goals+of preserving the free status of all derivatives of our free software and+of promoting the sharing and reuse of software generally.++ NO WARRANTY++ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,+REPAIR OR CORRECTION.++ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE+POSSIBILITY OF SUCH DAMAGES.++ END OF TERMS AND CONDITIONS++ How to Apply These Terms to Your New Programs++ If you develop a new program, and you want it to be of the greatest+possible use to the public, the best way to achieve this is to make it+free software which everyone can redistribute and change under these terms.++ To do so, attach the following notices to the program. It is safest+to attach them to the start of each source file to most effectively+convey the exclusion of warranty; and each file should have at least+the "copyright" line and a pointer to where the full notice is found.++ <one line to give the program's name and a brief idea of what it does.>+ Copyright (C) <year> <name of author>++ This program is free software; you can redistribute it and/or modify+ it under the terms of the GNU General Public License as published by+ the Free Software Foundation; either version 2 of the License, or+ (at your option) any later version.++ This program is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ GNU General Public License for more details.++ You should have received a copy of the GNU General Public License along+ with this program; if not, write to the Free Software Foundation, Inc.,+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.++Also add information on how to contact you by electronic and paper mail.++If the program is interactive, make it output a short notice like this+when it starts in an interactive mode:++ Gnomovision version 69, Copyright (C) year name of author+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.+ This is free software, and you are welcome to redistribute it+ under certain conditions; type `show c' for details.++The hypothetical commands `show w' and `show c' should show the appropriate+parts of the General Public License. Of course, the commands you use may+be called something other than `show w' and `show c'; they could even be+mouse-clicks or menu items--whatever suits your program.++You should also get your employer (if you work as a programmer) or your+school, if any, to sign a "copyright disclaimer" for the program, if+necessary. Here is a sample; alter the names:++ Yoyodyne, Inc., hereby disclaims all copyright interest in the program+ `Gnomovision' (which makes passes at compilers) written by James Hacker.++ <signature of Ty Coon>, 1 April 1989+ Ty Coon, President of Vice++This General Public License does not permit incorporating your program into+proprietary programs. If your program is a subroutine library, you may+consider it more useful to permit linking proprietary applications with the+library. If this is what you want to do, use the GNU Lesser General+Public License instead of this License.diff --git a/packaging/licenses/GPL-3.0.txt b/packaging/licenses/GPL-3.0.txtnew file mode 100644index 0000000..f288702--- /dev/null+++ b/packaging/licenses/GPL-3.0.txt@@ -0,0 +1,674 @@+ GNU GENERAL PUBLIC LICENSE+ Version 3, 29 June 2007++ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++ Preamble++ The GNU General Public License is a free, copyleft license for+software and other kinds of works.++ The licenses for most software and other practical works are designed+to take away your freedom to share and change the works. By contrast,+the GNU General Public License is intended to guarantee your freedom to+share and change all versions of a program--to make sure it remains free+software for all its users. We, the Free Software Foundation, use the+GNU General Public License for most of our software; it applies also to+any other work released this way by its authors. You can apply it to+your programs, too.++ When we speak of free software, we are referring to freedom, not+price. Our General Public Licenses are designed to make sure that you+have the freedom to distribute copies of free software (and charge for+them if you wish), that you receive source code or can get it if you+want it, that you can change the software or use pieces of it in new+free programs, and that you know you can do these things.++ To protect your rights, we need to prevent others from denying you+these rights or asking you to surrender the rights. Therefore, you have+certain responsibilities if you distribute copies of the software, or if+you modify it: responsibilities to respect the freedom of others.++ For example, if you distribute copies of such a program, whether+gratis or for a fee, you must pass on to the recipients the same+freedoms that you received. You must make sure that they, too, receive+or can get the source code. And you must show them these terms so they+know their rights.++ Developers that use the GNU GPL protect your rights with two steps:+(1) assert copyright on the software, and (2) offer you this License+giving you legal permission to copy, distribute and/or modify it.++ For the developers' and authors' protection, the GPL clearly explains+that there is no warranty for this free software. For both users' and+authors' sake, the GPL requires that modified versions be marked as+changed, so that their problems will not be attributed erroneously to+authors of previous versions.++ Some devices are designed to deny users access to install or run+modified versions of the software inside them, although the manufacturer+can do so. This is fundamentally incompatible with the aim of+protecting users' freedom to change the software. The systematic+pattern of such abuse occurs in the area of products for individuals to+use, which is precisely where it is most unacceptable. Therefore, we+have designed this version of the GPL to prohibit the practice for those+products. If such problems arise substantially in other domains, we+stand ready to extend this provision to those domains in future versions+of the GPL, as needed to protect the freedom of users.++ Finally, every program is threatened constantly by software patents.+States should not allow patents to restrict development and use of+software on general-purpose computers, but in those that do, we wish to+avoid the special danger that patents applied to a free program could+make it effectively proprietary. To prevent this, the GPL assures that+patents cannot be used to render the program non-free.++ The precise terms and conditions for copying, distribution and+modification follow.++ TERMS AND CONDITIONS++ 0. Definitions.++ "This License" refers to version 3 of the GNU General Public License.++ "Copyright" also means copyright-like laws that apply to other kinds of+works, such as semiconductor masks.++ "The Program" refers to any copyrightable work licensed under this+License. Each licensee is addressed as "you". "Licensees" and+"recipients" may be individuals or organizations.++ To "modify" a work means to copy from or adapt all or part of the work+in a fashion requiring copyright permission, other than the making of an+exact copy. The resulting work is called a "modified version" of the+earlier work or a work "based on" the earlier work.++ A "covered work" means either the unmodified Program or a work based+on the Program.++ To "propagate" a work means to do anything with it that, without+permission, would make you directly or secondarily liable for+infringement under applicable copyright law, except executing it on a+computer or modifying a private copy. Propagation includes copying,+distribution (with or without modification), making available to the+public, and in some countries other activities as well.++ To "convey" a work means any kind of propagation that enables other+parties to make or receive copies. Mere interaction with a user through+a computer network, with no transfer of a copy, is not conveying.++ An interactive user interface displays "Appropriate Legal Notices"+to the extent that it includes a convenient and prominently visible+feature that (1) displays an appropriate copyright notice, and (2)+tells the user that there is no warranty for the work (except to the+extent that warranties are provided), that licensees may convey the+work under this License, and how to view a copy of this License. If+the interface presents a list of user commands or options, such as a+menu, a prominent item in the list meets this criterion.++ 1. Source Code.++ The "source code" for a work means the preferred form of the work+for making modifications to it. "Object code" means any non-source+form of a work.++ A "Standard Interface" means an interface that either is an official+standard defined by a recognized standards body, or, in the case of+interfaces specified for a particular programming language, one that+is widely used among developers working in that language.++ The "System Libraries" of an executable work include anything, other+than the work as a whole, that (a) is included in the normal form of+packaging a Major Component, but which is not part of that Major+Component, and (b) serves only to enable use of the work with that+Major Component, or to implement a Standard Interface for which an+implementation is available to the public in source code form. A+"Major Component", in this context, means a major essential component+(kernel, window system, and so on) of the specific operating system+(if any) on which the executable work runs, or a compiler used to+produce the work, or an object code interpreter used to run it.++ The "Corresponding Source" for a work in object code form means all+the source code needed to generate, install, and (for an executable+work) run the object code and to modify the work, including scripts to+control those activities. However, it does not include the work's+System Libraries, or general-purpose tools or generally available free+programs which are used unmodified in performing those activities but+which are not part of the work. For example, Corresponding Source+includes interface definition files associated with source files for+the work, and the source code for shared libraries and dynamically+linked subprograms that the work is specifically designed to require,+such as by intimate data communication or control flow between those+subprograms and other parts of the work.++ The Corresponding Source need not include anything that users+can regenerate automatically from other parts of the Corresponding+Source.++ The Corresponding Source for a work in source code form is that+same work.++ 2. Basic Permissions.++ All rights granted under this License are granted for the term of+copyright on the Program, and are irrevocable provided the stated+conditions are met. This License explicitly affirms your unlimited+permission to run the unmodified Program. The output from running a+covered work is covered by this License only if the output, given its+content, constitutes a covered work. This License acknowledges your+rights of fair use or other equivalent, as provided by copyright law.++ You may make, run and propagate covered works that you do not+convey, without conditions so long as your license otherwise remains+in force. You may convey covered works to others for the sole purpose+of having them make modifications exclusively for you, or provide you+with facilities for running those works, provided that you comply with+the terms of this License in conveying all material for which you do+not control copyright. Those thus making or running the covered works+for you must do so exclusively on your behalf, under your direction+and control, on terms that prohibit them from making any copies of+your copyrighted material outside their relationship with you.++ Conveying under any other circumstances is permitted solely under+the conditions stated below. Sublicensing is not allowed; section 10+makes it unnecessary.++ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.++ No covered work shall be deemed part of an effective technological+measure under any applicable law fulfilling obligations under article+11 of the WIPO copyright treaty adopted on 20 December 1996, or+similar laws prohibiting or restricting circumvention of such+measures.++ When you convey a covered work, you waive any legal power to forbid+circumvention of technological measures to the extent such circumvention+is effected by exercising rights under this License with respect to+the covered work, and you disclaim any intention to limit operation or+modification of the work as a means of enforcing, against the work's+users, your or third parties' legal rights to forbid circumvention of+technological measures.++ 4. Conveying Verbatim Copies.++ You may convey verbatim copies of the Program's source code as you+receive it, in any medium, provided that you conspicuously and+appropriately publish on each copy an appropriate copyright notice;+keep intact all notices stating that this License and any+non-permissive terms added in accord with section 7 apply to the code;+keep intact all notices of the absence of any warranty; and give all+recipients a copy of this License along with the Program.++ You may charge any price or no price for each copy that you convey,+and you may offer support or warranty protection for a fee.++ 5. Conveying Modified Source Versions.++ You may convey a work based on the Program, or the modifications to+produce it from the Program, in the form of source code under the+terms of section 4, provided that you also meet all of these conditions:++ a) The work must carry prominent notices stating that you modified+ it, and giving a relevant date.++ b) The work must carry prominent notices stating that it is+ released under this License and any conditions added under section+ 7. This requirement modifies the requirement in section 4 to+ "keep intact all notices".++ c) You must license the entire work, as a whole, under this+ License to anyone who comes into possession of a copy. This+ License will therefore apply, along with any applicable section 7+ additional terms, to the whole of the work, and all its parts,+ regardless of how they are packaged. This License gives no+ permission to license the work in any other way, but it does not+ invalidate such permission if you have separately received it.++ d) If the work has interactive user interfaces, each must display+ Appropriate Legal Notices; however, if the Program has interactive+ interfaces that do not display Appropriate Legal Notices, your+ work need not make them do so.++ A compilation of a covered work with other separate and independent+works, which are not by their nature extensions of the covered work,+and which are not combined with it such as to form a larger program,+in or on a volume of a storage or distribution medium, is called an+"aggregate" if the compilation and its resulting copyright are not+used to limit the access or legal rights of the compilation's users+beyond what the individual works permit. Inclusion of a covered work+in an aggregate does not cause this License to apply to the other+parts of the aggregate.++ 6. Conveying Non-Source Forms.++ You may convey a covered work in object code form under the terms+of sections 4 and 5, provided that you also convey the+machine-readable Corresponding Source under the terms of this License,+in one of these ways:++ a) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by the+ Corresponding Source fixed on a durable physical medium+ customarily used for software interchange.++ b) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by a+ written offer, valid for at least three years and valid for as+ long as you offer spare parts or customer support for that product+ model, to give anyone who possesses the object code either (1) a+ copy of the Corresponding Source for all the software in the+ product that is covered by this License, on a durable physical+ medium customarily used for software interchange, for a price no+ more than your reasonable cost of physically performing this+ conveying of source, or (2) access to copy the+ Corresponding Source from a network server at no charge.++ c) Convey individual copies of the object code with a copy of the+ written offer to provide the Corresponding Source. This+ alternative is allowed only occasionally and noncommercially, and+ only if you received the object code with such an offer, in accord+ with subsection 6b.++ d) Convey the object code by offering access from a designated+ place (gratis or for a charge), and offer equivalent access to the+ Corresponding Source in the same way through the same place at no+ further charge. You need not require recipients to copy the+ Corresponding Source along with the object code. If the place to+ copy the object code is a network server, the Corresponding Source+ may be on a different server (operated by you or a third party)+ that supports equivalent copying facilities, provided you maintain+ clear directions next to the object code saying where to find the+ Corresponding Source. Regardless of what server hosts the+ Corresponding Source, you remain obligated to ensure that it is+ available for as long as needed to satisfy these requirements.++ e) Convey the object code using peer-to-peer transmission, provided+ you inform other peers where the object code and Corresponding+ Source of the work are being offered to the general public at no+ charge under subsection 6d.++ A separable portion of the object code, whose source code is excluded+from the Corresponding Source as a System Library, need not be+included in conveying the object code work.++ A "User Product" is either (1) a "consumer product", which means any+tangible personal property which is normally used for personal, family,+or household purposes, or (2) anything designed or sold for incorporation+into a dwelling. In determining whether a product is a consumer product,+doubtful cases shall be resolved in favor of coverage. For a particular+product received by a particular user, "normally used" refers to a+typical or common use of that class of product, regardless of the status+of the particular user or of the way in which the particular user+actually uses, or expects or is expected to use, the product. A product+is a consumer product regardless of whether the product has substantial+commercial, industrial or non-consumer uses, unless such uses represent+the only significant mode of use of the product.++ "Installation Information" for a User Product means any methods,+procedures, authorization keys, or other information required to install+and execute modified versions of a covered work in that User Product from+a modified version of its Corresponding Source. The information must+suffice to ensure that the continued functioning of the modified object+code is in no case prevented or interfered with solely because+modification has been made.++ If you convey an object code work under this section in, or with, or+specifically for use in, a User Product, and the conveying occurs as+part of a transaction in which the right of possession and use of the+User Product is transferred to the recipient in perpetuity or for a+fixed term (regardless of how the transaction is characterized), the+Corresponding Source conveyed under this section must be accompanied+by the Installation Information. But this requirement does not apply+if neither you nor any third party retains the ability to install+modified object code on the User Product (for example, the work has+been installed in ROM).++ The requirement to provide Installation Information does not include a+requirement to continue to provide support service, warranty, or updates+for a work that has been modified or installed by the recipient, or for+the User Product in which it has been modified or installed. Access to a+network may be denied when the modification itself materially and+adversely affects the operation of the network or violates the rules and+protocols for communication across the network.++ Corresponding Source conveyed, and Installation Information provided,+in accord with this section must be in a format that is publicly+documented (and with an implementation available to the public in+source code form), and must require no special password or key for+unpacking, reading or copying.++ 7. Additional Terms.++ "Additional permissions" are terms that supplement the terms of this+License by making exceptions from one or more of its conditions.+Additional permissions that are applicable to the entire Program shall+be treated as though they were included in this License, to the extent+that they are valid under applicable law. If additional permissions+apply only to part of the Program, that part may be used separately+under those permissions, but the entire Program remains governed by+this License without regard to the additional permissions.++ When you convey a copy of a covered work, you may at your option+remove any additional permissions from that copy, or from any part of+it. (Additional permissions may be written to require their own+removal in certain cases when you modify the work.) You may place+additional permissions on material, added by you to a covered work,+for which you have or can give appropriate copyright permission.++ Notwithstanding any other provision of this License, for material you+add to a covered work, you may (if authorized by the copyright holders of+that material) supplement the terms of this License with terms:++ a) Disclaiming warranty or limiting liability differently from the+ terms of sections 15 and 16 of this License; or++ b) Requiring preservation of specified reasonable legal notices or+ author attributions in that material or in the Appropriate Legal+ Notices displayed by works containing it; or++ c) Prohibiting misrepresentation of the origin of that material, or+ requiring that modified versions of such material be marked in+ reasonable ways as different from the original version; or++ d) Limiting the use for publicity purposes of names of licensors or+ authors of the material; or++ e) Declining to grant rights under trademark law for use of some+ trade names, trademarks, or service marks; or++ f) Requiring indemnification of licensors and authors of that+ material by anyone who conveys the material (or modified versions of+ it) with contractual assumptions of liability to the recipient, for+ any liability that these contractual assumptions directly impose on+ those licensors and authors.++ All other non-permissive additional terms are considered "further+restrictions" within the meaning of section 10. If the Program as you+received it, or any part of it, contains a notice stating that it is+governed by this License along with a term that is a further+restriction, you may remove that term. If a license document contains+a further restriction but permits relicensing or conveying under this+License, you may add to a covered work material governed by the terms+of that license document, provided that the further restriction does+not survive such relicensing or conveying.++ If you add terms to a covered work in accord with this section, you+must place, in the relevant source files, a statement of the+additional terms that apply to those files, or a notice indicating+where to find the applicable terms.++ Additional terms, permissive or non-permissive, may be stated in the+form of a separately written license, or stated as exceptions;+the above requirements apply either way.++ 8. Termination.++ You may not propagate or modify a covered work except as expressly+provided under this License. Any attempt otherwise to propagate or+modify it is void, and will automatically terminate your rights under+this License (including any patent licenses granted under the third+paragraph of section 11).++ However, if you cease all violation of this License, then your+license from a particular copyright holder is reinstated (a)+provisionally, unless and until the copyright holder explicitly and+finally terminates your license, and (b) permanently, if the copyright+holder fails to notify you of the violation by some reasonable means+prior to 60 days after the cessation.++ Moreover, your license from a particular copyright holder is+reinstated permanently if the copyright holder notifies you of the+violation by some reasonable means, this is the first time you have+received notice of violation of this License (for any work) from that+copyright holder, and you cure the violation prior to 30 days after+your receipt of the notice.++ Termination of your rights under this section does not terminate the+licenses of parties who have received copies or rights from you under+this License. If your rights have been terminated and not permanently+reinstated, you do not qualify to receive new licenses for the same+material under section 10.++ 9. Acceptance Not Required for Having Copies.++ You are not required to accept this License in order to receive or+run a copy of the Program. Ancillary propagation of a covered work+occurring solely as a consequence of using peer-to-peer transmission+to receive a copy likewise does not require acceptance. However,+nothing other than this License grants you permission to propagate or+modify any covered work. These actions infringe copyright if you do+not accept this License. Therefore, by modifying or propagating a+covered work, you indicate your acceptance of this License to do so.++ 10. Automatic Licensing of Downstream Recipients.++ Each time you convey a covered work, the recipient automatically+receives a license from the original licensors, to run, modify and+propagate that work, subject to this License. You are not responsible+for enforcing compliance by third parties with this License.++ An "entity transaction" is a transaction transferring control of an+organization, or substantially all assets of one, or subdividing an+organization, or merging organizations. If propagation of a covered+work results from an entity transaction, each party to that+transaction who receives a copy of the work also receives whatever+licenses to the work the party's predecessor in interest had or could+give under the previous paragraph, plus a right to possession of the+Corresponding Source of the work from the predecessor in interest, if+the predecessor has it or can get it with reasonable efforts.++ You may not impose any further restrictions on the exercise of the+rights granted or affirmed under this License. For example, you may+not impose a license fee, royalty, or other charge for exercise of+rights granted under this License, and you may not initiate litigation+(including a cross-claim or counterclaim in a lawsuit) alleging that+any patent claim is infringed by making, using, selling, offering for+sale, or importing the Program or any portion of it.++ 11. Patents.++ A "contributor" is a copyright holder who authorizes use under this+License of the Program or a work on which the Program is based. The+work thus licensed is called the contributor's "contributor version".++ A contributor's "essential patent claims" are all patent claims+owned or controlled by the contributor, whether already acquired or+hereafter acquired, that would be infringed by some manner, permitted+by this License, of making, using, or selling its contributor version,+but do not include claims that would be infringed only as a+consequence of further modification of the contributor version. For+purposes of this definition, "control" includes the right to grant+patent sublicenses in a manner consistent with the requirements of+this License.++ Each contributor grants you a non-exclusive, worldwide, royalty-free+patent license under the contributor's essential patent claims, to+make, use, sell, offer for sale, import and otherwise run, modify and+propagate the contents of its contributor version.++ In the following three paragraphs, a "patent license" is any express+agreement or commitment, however denominated, not to enforce a patent+(such as an express permission to practice a patent or covenant not to+sue for patent infringement). To "grant" such a patent license to a+party means to make such an agreement or commitment not to enforce a+patent against the party.++ If you convey a covered work, knowingly relying on a patent license,+and the Corresponding Source of the work is not available for anyone+to copy, free of charge and under the terms of this License, through a+publicly available network server or other readily accessible means,+then you must either (1) cause the Corresponding Source to be so+available, or (2) arrange to deprive yourself of the benefit of the+patent license for this particular work, or (3) arrange, in a manner+consistent with the requirements of this License, to extend the patent+license to downstream recipients. "Knowingly relying" means you have+actual knowledge that, but for the patent license, your conveying the+covered work in a country, or your recipient's use of the covered work+in a country, would infringe one or more identifiable patents in that+country that you have reason to believe are valid.++ If, pursuant to or in connection with a single transaction or+arrangement, you convey, or propagate by procuring conveyance of, a+covered work, and grant a patent license to some of the parties+receiving the covered work authorizing them to use, propagate, modify+or convey a specific copy of the covered work, then the patent license+you grant is automatically extended to all recipients of the covered+work and works based on it.++ A patent license is "discriminatory" if it does not include within+the scope of its coverage, prohibits the exercise of, or is+conditioned on the non-exercise of one or more of the rights that are+specifically granted under this License. You may not convey a covered+work if you are a party to an arrangement with a third party that is+in the business of distributing software, under which you make payment+to the third party based on the extent of your activity of conveying+the work, and under which the third party grants, to any of the+parties who would receive the covered work from you, a discriminatory+patent license (a) in connection with copies of the covered work+conveyed by you (or copies made from those copies), or (b) primarily+for and in connection with specific products or compilations that+contain the covered work, unless you entered into that arrangement,+or that patent license was granted, prior to 28 March 2007.++ Nothing in this License shall be construed as excluding or limiting+any implied license or other defenses to infringement that may+otherwise be available to you under applicable patent law.++ 12. No Surrender of Others' Freedom.++ If conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License. If you cannot convey a+covered work so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you may+not convey it at all. For example, if you agree to terms that obligate you+to collect a royalty for further conveying from those to whom you convey+the Program, the only way you could satisfy both those terms and this+License would be to refrain entirely from conveying the Program.++ 13. Use with the GNU Affero General Public License.++ Notwithstanding any other provision of this License, you have+permission to link or combine any covered work with a work licensed+under version 3 of the GNU Affero General Public License into a single+combined work, and to convey the resulting work. The terms of this+License will continue to apply to the part which is the covered work,+but the special requirements of the GNU Affero General Public License,+section 13, concerning interaction through a network will apply to the+combination as such.++ 14. Revised Versions of this License.++ The Free Software Foundation may publish revised and/or new versions of+the GNU General Public License from time to time. Such new versions will+be similar in spirit to the present version, but may differ in detail to+address new problems or concerns.++ Each version is given a distinguishing version number. If the+Program specifies that a certain numbered version of the GNU General+Public License "or any later version" applies to it, you have the+option of following the terms and conditions either of that numbered+version or of any later version published by the Free Software+Foundation. If the Program does not specify a version number of the+GNU General Public License, you may choose any version ever published+by the Free Software Foundation.++ If the Program specifies that a proxy can decide which future+versions of the GNU General Public License can be used, that proxy's+public statement of acceptance of a version permanently authorizes you+to choose that version for the Program.++ Later license versions may give you additional or different+permissions. However, no additional obligations are imposed on any+author or copyright holder as a result of your choosing to follow a+later version.++ 15. Disclaimer of Warranty.++ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++ 16. Limitation of Liability.++ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF+SUCH DAMAGES.++ 17. Interpretation of Sections 15 and 16.++ If the disclaimer of warranty and limitation of liability provided+above cannot be given local legal effect according to their terms,+reviewing courts shall apply local law that most closely approximates+an absolute waiver of all civil liability in connection with the+Program, unless a warranty or assumption of liability accompanies a+copy of the Program in return for a fee.++ END OF TERMS AND CONDITIONS++ How to Apply These Terms to Your New Programs++ If you develop a new program, and you want it to be of the greatest+possible use to the public, the best way to achieve this is to make it+free software which everyone can redistribute and change under these terms.++ To do so, attach the following notices to the program. It is safest+to attach them to the start of each source file to most effectively+state the exclusion of warranty; and each file should have at least+the "copyright" line and a pointer to where the full notice is found.++ <one line to give the program's name and a brief idea of what it does.>+ Copyright (C) <year> <name of author>++ This program is free software: you can redistribute it and/or modify+ it under the terms of the GNU General Public License as published by+ the Free Software Foundation, either version 3 of the License, or+ (at your option) any later version.++ This program is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ GNU General Public License for more details.++ You should have received a copy of the GNU General Public License+ along with this program. If not, see <https://www.gnu.org/licenses/>.++Also add information on how to contact you by electronic and paper mail.++ If the program does terminal interaction, make it output a short+notice like this when it starts in an interactive mode:++ <program> Copyright (C) <year> <name of author>+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.+ This is free software, and you are welcome to redistribute it+ under certain conditions; type `show c' for details.++The hypothetical commands `show w' and `show c' should show the appropriate+parts of the General Public License. Of course, your program's commands+might be different; for a GUI interface, you would use an "about box".++ You should also get your employer (if you work as a programmer) or school,+if any, to sign a "copyright disclaimer" for the program, if necessary.+For more information on this, and how to apply and follow the GNU GPL, see+<https://www.gnu.org/licenses/>.++ The GNU General Public License does not permit incorporating your program+into proprietary programs. If your program is a subroutine library, you+may consider it more useful to permit linking proprietary applications with+the library. If this is what you want to do, use the GNU Lesser General+Public License instead of this License. But first, please read+<https://www.gnu.org/licenses/why-not-lgpl.html>.diff --git a/packaging/licenses/LGPL-2.1.txt b/packaging/licenses/LGPL-2.1.txtnew file mode 100644index 0000000..4362b49--- /dev/null+++ b/packaging/licenses/LGPL-2.1.txt@@ -0,0 +1,502 @@+ GNU LESSER GENERAL PUBLIC LICENSE+ Version 2.1, February 1999++ Copyright (C) 1991, 1999 Free Software Foundation, Inc.+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++[This is the first released version of the Lesser GPL. It also counts+ as the successor of the GNU Library Public License, version 2, hence+ the version number 2.1.]++ Preamble++ The licenses for most software are designed to take away your+freedom to share and change it. By contrast, the GNU General Public+Licenses are intended to guarantee your freedom to share and change+free software--to make sure the software is free for all its users.++ This license, the Lesser General Public License, applies to some+specially designated software packages--typically libraries--of the+Free Software Foundation and other authors who decide to use it. You+can use it too, but we suggest you first think carefully about whether+this license or the ordinary General Public License is the better+strategy to use in any particular case, based on the explanations below.++ When we speak of free software, we are referring to freedom of use,+not price. Our General Public Licenses are designed to make sure that+you have the freedom to distribute copies of free software (and charge+for this service if you wish); that you receive source code or can get+it if you want it; that you can change the software and use pieces of+it in new free programs; and that you are informed that you can do+these things.++ To protect your rights, we need to make restrictions that forbid+distributors to deny you these rights or to ask you to surrender these+rights. These restrictions translate to certain responsibilities for+you if you distribute copies of the library or if you modify it.++ For example, if you distribute copies of the library, whether gratis+or for a fee, you must give the recipients all the rights that we gave+you. You must make sure that they, too, receive or can get the source+code. If you link other code with the library, you must provide+complete object files to the recipients, so that they can relink them+with the library after making changes to the library and recompiling+it. And you must show them these terms so they know their rights.++ We protect your rights with a two-step method: (1) we copyright the+library, and (2) we offer you this license, which gives you legal+permission to copy, distribute and/or modify the library.++ To protect each distributor, we want to make it very clear that+there is no warranty for the free library. Also, if the library is+modified by someone else and passed on, the recipients should know+that what they have is not the original version, so that the original+author's reputation will not be affected by problems that might be+introduced by others.++ Finally, software patents pose a constant threat to the existence of+any free program. We wish to make sure that a company cannot+effectively restrict the users of a free program by obtaining a+restrictive license from a patent holder. Therefore, we insist that+any patent license obtained for a version of the library must be+consistent with the full freedom of use specified in this license.++ Most GNU software, including some libraries, is covered by the+ordinary GNU General Public License. This license, the GNU Lesser+General Public License, applies to certain designated libraries, and+is quite different from the ordinary General Public License. We use+this license for certain libraries in order to permit linking those+libraries into non-free programs.++ When a program is linked with a library, whether statically or using+a shared library, the combination of the two is legally speaking a+combined work, a derivative of the original library. The ordinary+General Public License therefore permits such linking only if the+entire combination fits its criteria of freedom. The Lesser General+Public License permits more lax criteria for linking other code with+the library.++ We call this license the "Lesser" General Public License because it+does Less to protect the user's freedom than the ordinary General+Public License. It also provides other free software developers Less+of an advantage over competing non-free programs. These disadvantages+are the reason we use the ordinary General Public License for many+libraries. However, the Lesser license provides advantages in certain+special circumstances.++ For example, on rare occasions, there may be a special need to+encourage the widest possible use of a certain library, so that it becomes+a de-facto standard. To achieve this, non-free programs must be+allowed to use the library. A more frequent case is that a free+library does the same job as widely used non-free libraries. In this+case, there is little to gain by limiting the free library to free+software only, so we use the Lesser General Public License.++ In other cases, permission to use a particular library in non-free+programs enables a greater number of people to use a large body of+free software. For example, permission to use the GNU C Library in+non-free programs enables many more people to use the whole GNU+operating system, as well as its variant, the GNU/Linux operating+system.++ Although the Lesser General Public License is Less protective of the+users' freedom, it does ensure that the user of a program that is+linked with the Library has the freedom and the wherewithal to run+that program using a modified version of the Library.++ The precise terms and conditions for copying, distribution and+modification follow. Pay close attention to the difference between a+"work based on the library" and a "work that uses the library". The+former contains code derived from the library, whereas the latter must+be combined with the library in order to run.++ GNU LESSER GENERAL PUBLIC LICENSE+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION++ 0. This License Agreement applies to any software library or other+program which contains a notice placed by the copyright holder or+other authorized party saying it may be distributed under the terms of+this Lesser General Public License (also called "this License").+Each licensee is addressed as "you".++ A "library" means a collection of software functions and/or data+prepared so as to be conveniently linked with application programs+(which use some of those functions and data) to form executables.++ The "Library", below, refers to any such software library or work+which has been distributed under these terms. A "work based on the+Library" means either the Library or any derivative work under+copyright law: that is to say, a work containing the Library or a+portion of it, either verbatim or with modifications and/or translated+straightforwardly into another language. (Hereinafter, translation is+included without limitation in the term "modification".)++ "Source code" for a work means the preferred form of the work for+making modifications to it. For a library, complete source code means+all the source code for all modules it contains, plus any associated+interface definition files, plus the scripts used to control compilation+and installation of the library.++ Activities other than copying, distribution and modification are not+covered by this License; they are outside its scope. The act of+running a program using the Library is not restricted, and output from+such a program is covered only if its contents constitute a work based+on the Library (independent of the use of the Library in a tool for+writing it). Whether that is true depends on what the Library does+and what the program that uses the Library does.++ 1. You may copy and distribute verbatim copies of the Library's+complete source code as you receive it, in any medium, provided that+you conspicuously and appropriately publish on each copy an+appropriate copyright notice and disclaimer of warranty; keep intact+all the notices that refer to this License and to the absence of any+warranty; and distribute a copy of this License along with the+Library.++ You may charge a fee for the physical act of transferring a copy,+and you may at your option offer warranty protection in exchange for a+fee.++ 2. You may modify your copy or copies of the Library or any portion+of it, thus forming a work based on the Library, and copy and+distribute such modifications or work under the terms of Section 1+above, provided that you also meet all of these conditions:++ a) The modified work must itself be a software library.++ b) You must cause the files modified to carry prominent notices+ stating that you changed the files and the date of any change.++ c) You must cause the whole of the work to be licensed at no+ charge to all third parties under the terms of this License.++ d) If a facility in the modified Library refers to a function or a+ table of data to be supplied by an application program that uses+ the facility, other than as an argument passed when the facility+ is invoked, then you must make a good faith effort to ensure that,+ in the event an application does not supply such function or+ table, the facility still operates, and performs whatever part of+ its purpose remains meaningful.++ (For example, a function in a library to compute square roots has+ a purpose that is entirely well-defined independent of the+ application. Therefore, Subsection 2d requires that any+ application-supplied function or table used by this function must+ be optional: if the application does not supply it, the square+ root function must still compute square roots.)++These requirements apply to the modified work as a whole. If+identifiable sections of that work are not derived from the Library,+and can be reasonably considered independent and separate works in+themselves, then this License, and its terms, do not apply to those+sections when you distribute them as separate works. But when you+distribute the same sections as part of a whole which is a work based+on the Library, the distribution of the whole must be on the terms of+this License, whose permissions for other licensees extend to the+entire whole, and thus to each and every part regardless of who wrote+it.++Thus, it is not the intent of this section to claim rights or contest+your rights to work written entirely by you; rather, the intent is to+exercise the right to control the distribution of derivative or+collective works based on the Library.++In addition, mere aggregation of another work not based on the Library+with the Library (or with a work based on the Library) on a volume of+a storage or distribution medium does not bring the other work under+the scope of this License.++ 3. You may opt to apply the terms of the ordinary GNU General Public+License instead of this License to a given copy of the Library. To do+this, you must alter all the notices that refer to this License, so+that they refer to the ordinary GNU General Public License, version 2,+instead of to this License. (If a newer version than version 2 of the+ordinary GNU General Public License has appeared, then you can specify+that version instead if you wish.) Do not make any other change in+these notices.++ Once this change is made in a given copy, it is irreversible for+that copy, so the ordinary GNU General Public License applies to all+subsequent copies and derivative works made from that copy.++ This option is useful when you wish to copy part of the code of+the Library into a program that is not a library.++ 4. You may copy and distribute the Library (or a portion or+derivative of it, under Section 2) in object code or executable form+under the terms of Sections 1 and 2 above provided that you accompany+it with the complete corresponding machine-readable source code, which+must be distributed under the terms of Sections 1 and 2 above on a+medium customarily used for software interchange.++ If distribution of object code is made by offering access to copy+from a designated place, then offering equivalent access to copy the+source code from the same place satisfies the requirement to+distribute the source code, even though third parties are not+compelled to copy the source along with the object code.++ 5. A program that contains no derivative of any portion of the+Library, but is designed to work with the Library by being compiled or+linked with it, is called a "work that uses the Library". Such a+work, in isolation, is not a derivative work of the Library, and+therefore falls outside the scope of this License.++ However, linking a "work that uses the Library" with the Library+creates an executable that is a derivative of the Library (because it+contains portions of the Library), rather than a "work that uses the+library". The executable is therefore covered by this License.+Section 6 states terms for distribution of such executables.++ When a "work that uses the Library" uses material from a header file+that is part of the Library, the object code for the work may be a+derivative work of the Library even though the source code is not.+Whether this is true is especially significant if the work can be+linked without the Library, or if the work is itself a library. The+threshold for this to be true is not precisely defined by law.++ If such an object file uses only numerical parameters, data+structure layouts and accessors, and small macros and small inline+functions (ten lines or less in length), then the use of the object+file is unrestricted, regardless of whether it is legally a derivative+work. (Executables containing this object code plus portions of the+Library will still fall under Section 6.)++ Otherwise, if the work is a derivative of the Library, you may+distribute the object code for the work under the terms of Section 6.+Any executables containing that work also fall under Section 6,+whether or not they are linked directly with the Library itself.++ 6. As an exception to the Sections above, you may also combine or+link a "work that uses the Library" with the Library to produce a+work containing portions of the Library, and distribute that work+under terms of your choice, provided that the terms permit+modification of the work for the customer's own use and reverse+engineering for debugging such modifications.++ You must give prominent notice with each copy of the work that the+Library is used in it and that the Library and its use are covered by+this License. You must supply a copy of this License. If the work+during execution displays copyright notices, you must include the+copyright notice for the Library among them, as well as a reference+directing the user to the copy of this License. Also, you must do one+of these things:++ a) Accompany the work with the complete corresponding+ machine-readable source code for the Library including whatever+ changes were used in the work (which must be distributed under+ Sections 1 and 2 above); and, if the work is an executable linked+ with the Library, with the complete machine-readable "work that+ uses the Library", as object code and/or source code, so that the+ user can modify the Library and then relink to produce a modified+ executable containing the modified Library. (It is understood+ that the user who changes the contents of definitions files in the+ Library will not necessarily be able to recompile the application+ to use the modified definitions.)++ b) Use a suitable shared library mechanism for linking with the+ Library. A suitable mechanism is one that (1) uses at run time a+ copy of the library already present on the user's computer system,+ rather than copying library functions into the executable, and (2)+ will operate properly with a modified version of the library, if+ the user installs one, as long as the modified version is+ interface-compatible with the version that the work was made with.++ c) Accompany the work with a written offer, valid for at+ least three years, to give the same user the materials+ specified in Subsection 6a, above, for a charge no more+ than the cost of performing this distribution.++ d) If distribution of the work is made by offering access to copy+ from a designated place, offer equivalent access to copy the above+ specified materials from the same place.++ e) Verify that the user has already received a copy of these+ materials or that you have already sent this user a copy.++ For an executable, the required form of the "work that uses the+Library" must include any data and utility programs needed for+reproducing the executable from it. However, as a special exception,+the materials to be distributed need not include anything that is+normally distributed (in either source or binary form) with the major+components (compiler, kernel, and so on) of the operating system on+which the executable runs, unless that component itself accompanies+the executable.++ It may happen that this requirement contradicts the license+restrictions of other proprietary libraries that do not normally+accompany the operating system. Such a contradiction means you cannot+use both them and the Library together in an executable that you+distribute.++ 7. You may place library facilities that are a work based on the+Library side-by-side in a single library together with other library+facilities not covered by this License, and distribute such a combined+library, provided that the separate distribution of the work based on+the Library and of the other library facilities is otherwise+permitted, and provided that you do these two things:++ a) Accompany the combined library with a copy of the same work+ based on the Library, uncombined with any other library+ facilities. This must be distributed under the terms of the+ Sections above.++ b) Give prominent notice with the combined library of the fact+ that part of it is a work based on the Library, and explaining+ where to find the accompanying uncombined form of the same work.++ 8. You may not copy, modify, sublicense, link with, or distribute+the Library except as expressly provided under this License. Any+attempt otherwise to copy, modify, sublicense, link with, or+distribute the Library is void, and will automatically terminate your+rights under this License. However, parties who have received copies,+or rights, from you under this License will not have their licenses+terminated so long as such parties remain in full compliance.++ 9. You are not required to accept this License, since you have not+signed it. However, nothing else grants you permission to modify or+distribute the Library or its derivative works. These actions are+prohibited by law if you do not accept this License. Therefore, by+modifying or distributing the Library (or any work based on the+Library), you indicate your acceptance of this License to do so, and+all its terms and conditions for copying, distributing or modifying+the Library or works based on it.++ 10. Each time you redistribute the Library (or any work based on the+Library), the recipient automatically receives a license from the+original licensor to copy, distribute, link with or modify the Library+subject to these terms and conditions. You may not impose any further+restrictions on the recipients' exercise of the rights granted herein.+You are not responsible for enforcing compliance by third parties with+this License.++ 11. If, as a consequence of a court judgment or allegation of patent+infringement or for any other reason (not limited to patent issues),+conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License. If you cannot+distribute so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you+may not distribute the Library at all. For example, if a patent+license would not permit royalty-free redistribution of the Library by+all those who receive copies directly or indirectly through you, then+the only way you could satisfy both it and this License would be to+refrain entirely from distribution of the Library.++If any portion of this section is held invalid or unenforceable under any+particular circumstance, the balance of the section is intended to apply,+and the section as a whole is intended to apply in other circumstances.++It is not the purpose of this section to induce you to infringe any+patents or other property right claims or to contest validity of any+such claims; this section has the sole purpose of protecting the+integrity of the free software distribution system which is+implemented by public license practices. Many people have made+generous contributions to the wide range of software distributed+through that system in reliance on consistent application of that+system; it is up to the author/donor to decide if he or she is willing+to distribute software through any other system and a licensee cannot+impose that choice.++This section is intended to make thoroughly clear what is believed to+be a consequence of the rest of this License.++ 12. If the distribution and/or use of the Library is restricted in+certain countries either by patents or by copyrighted interfaces, the+original copyright holder who places the Library under this License may add+an explicit geographical distribution limitation excluding those countries,+so that distribution is permitted only in or among countries not thus+excluded. In such case, this License incorporates the limitation as if+written in the body of this License.++ 13. The Free Software Foundation may publish revised and/or new+versions of the Lesser General Public License from time to time.+Such new versions will be similar in spirit to the present version,+but may differ in detail to address new problems or concerns.++Each version is given a distinguishing version number. If the Library+specifies a version number of this License which applies to it and+"any later version", you have the option of following the terms and+conditions either of that version or of any later version published by+the Free Software Foundation. If the Library does not specify a+license version number, you may choose any version ever published by+the Free Software Foundation.++ 14. If you wish to incorporate parts of the Library into other free+programs whose distribution conditions are incompatible with these,+write to the author to ask for permission. For software which is+copyrighted by the Free Software Foundation, write to the Free+Software Foundation; we sometimes make exceptions for this. Our+decision will be guided by the two goals of preserving the free status+of all derivatives of our free software and of promoting the sharing+and reuse of software generally.++ NO WARRANTY++ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH+DAMAGES.++ END OF TERMS AND CONDITIONS++ How to Apply These Terms to Your New Libraries++ If you develop a new library, and you want it to be of the greatest+possible use to the public, we recommend making it free software that+everyone can redistribute and change. You can do so by permitting+redistribution under these terms (or, alternatively, under the terms of the+ordinary General Public License).++ To apply these terms, attach the following notices to the library. It is+safest to attach them to the start of each source file to most effectively+convey the exclusion of warranty; and each file should have at least the+"copyright" line and a pointer to where the full notice is found.++ <one line to give the library's name and a brief idea of what it does.>+ Copyright (C) <year> <name of author>++ This library is free software; you can redistribute it and/or+ modify it under the terms of the GNU Lesser General Public+ License as published by the Free Software Foundation; either+ version 2.1 of the License, or (at your option) any later version.++ This library is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU+ Lesser General Public License for more details.++ You should have received a copy of the GNU Lesser General Public+ License along with this library; if not, write to the Free Software+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA++Also add information on how to contact you by electronic and paper mail.++You should also get your employer (if you work as a programmer) or your+school, if any, to sign a "copyright disclaimer" for the library, if+necessary. Here is a sample; alter the names:++ Yoyodyne, Inc., hereby disclaims all copyright interest in the+ library `Frob' (a library for tweaking knobs) written by James Random Hacker.++ <signature of Ty Coon>, 1 April 1990+ Ty Coon, President of Vice++That's all there is to it!diff --git a/scripts/smoke_binary.py b/scripts/smoke_binary.pyindex 9b5168e..daefe85 100644--- a/scripts/smoke_binary.py+++ b/scripts/smoke_binary.py@@ -49,6 +49,19 @@ def check_application(base_url: str) -> None:ffmpeg: dict[str, Any] = json.loads(body)if status != 200 or not ffmpeg.get("available") or ffmpeg.get("source") != "bundled":raise RuntimeError(f"bundled ffmpeg was not detected: {ffmpeg!r}")+ status, content_type, body = _request(f"{base_url}/api/settings/ffmpeg/notice")+ if status != 200 or "GNU" not in body or "SHA-256" not in body:+ raise RuntimeError("the bundled ffmpeg shipped without its licence notice")++ # What the frozen build drops without a word when the spec forgets it: the zone+ # database (local times silently read as UTC on Windows), the PDF fonts, the+ # capture extension the Settings install button and the zip route hand out, and+ # the scrapers' metadata (a stale workspace copy would shadow the shipped one).+ status, _content_type, body = _request(f"{base_url}/api/settings/bundled")+ smoke: dict[str, Any] = json.loads(body)+ missing = [name for name, ok in smoke.items() if not ok]+ if status != 200 or missing:+ raise RuntimeError(f"the binary is missing bundled parts: {missing or smoke!r}")def wait_until_ready(base_url: str, process: subprocess.Popen[bytes], timeout: float = 60) -> None:diff --git a/scripts/vendor_ffmpeg.py b/scripts/vendor_ffmpeg.pyindex 588b8b0..53bec73 100644--- a/scripts/vendor_ffmpeg.py+++ b/scripts/vendor_ffmpeg.py@@ -13,6 +13,7 @@ import jsonimport osimport shutilimport stat+import subprocessimport tempfileimport urllib.requestimport zipfile@@ -229,9 +230,72 @@ def vendor(target: str, output_dir: Path) -> dict[str, object]:encoding="utf-8",)os.replace(temporary_path, provenance_path)+ write_notice(output_dir, archives)return provenance+#: Where the source of each build lives: FFmpeg's own, and the scripts that built it.+BUILD_SOURCES = {+ "BtbN FFmpeg Builds": "https://github.com/BtbN/FFmpeg-Builds",+ "FFmpeg Build Server": "https://ffmpeg.martin-riedl.de",+}++LICENSE_TEXTS = Path(__file__).resolve().parent.parent / "packaging" / "licenses"+++def write_notice(output_dir: Path, archives: tuple[Archive, ...]) -> Path:+ """Write the notice the binaries carry beside ffmpeg: which build it is, where+ its source is, and the licence it states, with the licence texts beside it.++ Redistributing a GPL build means handing its licence and a way to its source to+ whoever gets the binary, and a link to ffmpeg.org/legal.html is neither. The+ licence statement is the build's own (``ffmpeg -L``), so a build that changes+ licence changes the notice with it.+ """+ licenses = output_dir / "ffmpeg-licenses"+ licenses.mkdir(parents=True, exist_ok=True)+ for text in sorted(LICENSE_TEXTS.glob("*.txt")):+ shutil.copyfile(text, licenses / text.name)+ lines = [+ "ffmpeg and ffprobe ship inside this Azimut binary as separate programs.",+ "Azimut runs them; it is not linked against them.",+ "",+ ]+ for archive in archives:+ lines += [+ f"Build: {archive.version} ({archive.source})",+ f"Downloaded from: {archive.url}",+ f"SHA-256: {archive.sha256}",+ f"Build scripts: {BUILD_SOURCES.get(archive.source, archive.source)}",+ "",+ ]+ lines += [+ "FFmpeg source code: https://ffmpeg.org/download.html#get-sources",+ "(the version above names the release or the git commit it was built from)",+ "",+ "Licence, as this build states it (ffmpeg -L):",+ "",+ _stated_license(output_dir),+ "",+ "The full licence texts are in this folder.",+ ]+ notice = licenses / "NOTICE.txt"+ notice.write_text("\n".join(lines) + "\n", encoding="utf-8")+ return notice+++def _stated_license(output_dir: Path) -> str:+ exe = next((output_dir / name for name in ("ffmpeg.exe", "ffmpeg") if (output_dir / name).is_file()), None)+ if exe is None:+ return "(ffmpeg missing)"+ try:+ answer = subprocess.run([str(exe), "-hide_banner", "-L"], capture_output=True, timeout=30, check=True)+ except (OSError, subprocess.SubprocessError):+ # Vendoring for another platform: the tool cannot run here.+ return "Run `ffmpeg -L` to read it. GPL builds are covered by the GPL texts in this folder."+ return answer.stdout.decode("utf-8", "replace").strip()++def main() -> None:parser = argparse.ArgumentParser()parser.add_argument("target", choices=sorted(ARTIFACTS))diff --git a/src/azimut/api/compare.py b/src/azimut/api/compare.pyindex e65d95b..3148f92 100644--- a/src/azimut/api/compare.py+++ b/src/azimut/api/compare.py@@ -42,7 +42,7 @@ from fastapi.responses import Responsefrom PIL import Imagefrom pydantic import BaseModel, Field, field_validator, model_validator-from .. import config, layout+from .. import config, errors, layoutfrom ..engine import artifacts as artifact_enginefrom ..engine import comparisons, exportdir, sentinel, tilesfrom ..engine import links as link_engine@@ -720,7 +720,7 @@ async def save_session_preview(delete_by_path(case, current)case.update_entity(entity["id"], {"attrs": {"preview": rel}})except (OSError, ValueError, CaseError) as exc:- raise HTTPException(status_code=409, detail=f"could not save the image: {exc}") from exc+ raise HTTPException(status_code=409, detail=f"could not save the image: {errors.explain(exc)}") from exc# the preview is the comparison's picture in the Saved panelsaved_changed(case)return {"path": rel, "format": format_, "replaced": replaced}@@ -798,7 +798,7 @@ async def keep_image(case, data, filename, suffix, source, by="compare", extra_attrs=attrs)except (OSError, ValueError, CaseError) as exc:- raise HTTPException(status_code=409, detail=f"could not keep the image: {exc}") from exc+ raise HTTPException(status_code=409, detail=f"could not keep the image: {errors.explain(exc)}") from excsaved_changed(case)return {"path": filed["item"]["path"], "entity": filed["entity"]["id"]}@@ -899,7 +899,7 @@ async def export_gif(export_destination = exportdir.destination("views", case.path)path = exportdir.write_out(data, export_destination, name)except (OSError, exportdir.ExportDirError) as exc:- raise HTTPException(status_code=409, detail=f"could not write the GIF: {exc}") from exc+ raise HTTPException(status_code=409, detail=f"could not write the GIF: {errors.explain(exc)}") from excreturn {"file": path.name, "path": str(export_destination), "animation": animation}@@ -960,7 +960,7 @@ async def export_sequence(export_destination = exportdir.destination("views", case.path)path = exportdir.write_out(data, export_destination, name)except (OSError, exportdir.ExportDirError) as exc:- raise HTTPException(status_code=409, detail=f"could not write the GIF: {exc}") from exc+ raise HTTPException(status_code=409, detail=f"could not write the GIF: {errors.explain(exc)}") from excreturn {"file": path.name, "path": str(export_destination), "frames": len(shown)}diff --git a/src/azimut/api/ingest.py b/src/azimut/api/ingest.pyindex 4f4babe..8c3a875 100644--- a/src/azimut/api/ingest.py+++ b/src/azimut/api/ingest.py@@ -51,7 +51,7 @@ from fastapi.responses import FileResponse, StreamingResponsefrom PIL import Imagefrom pydantic import BaseModel-from .. import __version__, config+from .. import __version__, config, errorsfrom ..engine import (extinstall,firms,@@ -281,7 +281,7 @@ async def ingest_screenshot(except (Image.DecompressionBombWarning, Image.DecompressionBombError) as exc:raise HTTPException(status_code=413, detail="image exceeds the 100 MP limit") from excexcept Exception as exc:- raise HTTPException(status_code=422, detail=f"not a readable image: {exc}") from exc+ raise HTTPException(status_code=422, detail=f"not a readable image: {errors.explain(exc)}") from excsite = parsed["site"]# Neither mark is invented for a map we did not draw: the bar needs thediff --git a/src/azimut/api/media.py b/src/azimut/api/media.pyindex f7941fe..8dc8fed 100644--- a/src/azimut/api/media.py+++ b/src/azimut/api/media.py@@ -11,7 +11,7 @@ from fastapi import APIRouter, Form, HTTPException, UploadFilefrom PIL import Imagefrom pydantic import BaseModel, Field, HttpUrl-from .. import config, jobs+from .. import config, errors, jobsfrom ..engine import enrich as enrich_enginefrom ..engine import exportdirfrom ..engine import media as media_engine@@ -313,7 +313,7 @@ async def paste(except (Image.DecompressionBombWarning, Image.DecompressionBombError) as exc:raise HTTPException(status_code=413, detail="image exceeds the 100 MP limit") from excexcept Exception as exc:- raise HTTPException(status_code=422, detail=f"not a readable image: {exc}") from exc+ raise HTTPException(status_code=422, detail=f"not a readable image: {errors.explain(exc)}") from excreturn media_engine.import_paste(get_case(case_id),diff --git a/src/azimut/api/notes.py b/src/azimut/api/notes.pyindex 3304f31..916fcb3 100644--- a/src/azimut/api/notes.py+++ b/src/azimut/api/notes.py@@ -25,7 +25,7 @@ from typing import Anyfrom fastapi import APIRouter, HTTPExceptionfrom pydantic import BaseModel, Field-from .. import layout+from .. import errors, layoutfrom ..engine import exportdirfrom ..engine import links as link_enginefrom ..engine import notes_pdf as pdf_engine@@ -248,7 +248,7 @@ def export_pdf(case_id: str, body: ExportIn) -> dict[str, Any]:else:path = exportdir.write_out(rendered.pdf, destination, filename)except (OSError, exportdir.ExportDirError) as exc:- raise HTTPException(status_code=409, detail=f"could not write the PDF: {exc}") from exc+ raise HTTPException(status_code=409, detail=f"could not write the PDF: {errors.explain(exc)}") from excwritten.append({"note": note_id, "title": title, "file": path.name})warnings.extend(f"{title}: {warning}" for warning in rendered.warnings)diff --git a/src/azimut/api/plates.py b/src/azimut/api/plates.pyindex 1b3b5b0..1bb2acf 100644--- a/src/azimut/api/plates.py+++ b/src/azimut/api/plates.py@@ -28,7 +28,7 @@ from typing import Anyfrom fastapi import APIRouter, HTTPExceptionfrom pydantic import BaseModel, Field-from .. import layout+from .. import errors, layoutfrom ..engine import exportdirfrom ..engine import reveal as reveal_enginefrom .cases import get_case@@ -137,7 +137,7 @@ def write_plate(case_id: str, body: PlateIn) -> dict[str, Any]:else:path = exportdir.write_out(data, destination, filename)except (OSError, exportdir.ExportDirError) as exc:- raise HTTPException(status_code=409, detail=f"could not write the plate: {exc}") from exc+ raise HTTPException(status_code=409, detail=f"could not write the plate: {errors.explain(exc)}") from excreturn {"file": path.name, "path": str(destination)}diff --git a/src/azimut/api/proposals.py b/src/azimut/api/proposals.pyindex 3678e04..c35712c 100644--- a/src/azimut/api/proposals.py+++ b/src/azimut/api/proposals.py@@ -25,8 +25,8 @@ MAX_LISTED = 200def _waiting(case: Any) -> dict[str, Any]:"""The proposals still waiting, with both ends named so a row reads as a sentence."""- waiting = [link for link in case.list_links() if proposal_engine.unreviewed(link)]- listed = waiting[:MAX_LISTED]+ suggestions = case.suggestions(proposal_engine.BY, limit=MAX_LISTED)+ listed = suggestions["items"]ends = {entity["id"]: entityfor entity in case.entities_by_ids(@@ -50,7 +50,7 @@ def _waiting(case: Any) -> dict[str, Any]:item["metres"] = round(proposal_engine.metres(a, b))items.append(item)return {- "pending": proposal_engine.pending(case),+ "pending": proposal_engine.counted(suggestions),"items": items,"listed": len(items),"through": (case.link_pass() or {}).get("at"),diff --git a/src/azimut/api/satellite.py b/src/azimut/api/satellite.pyindex fbebfc2..a1a1b56 100644--- a/src/azimut/api/satellite.py+++ b/src/azimut/api/satellite.py@@ -23,7 +23,7 @@ from fastapi.responses import Responsefrom PIL import Imagefrom pydantic import BaseModel, Field-from .. import config+from .. import config, errorsfrom ..engine.analysis_models import Zonefrom ..engine import (cities,@@ -1429,7 +1429,7 @@ async def capture_screenshot(try:img = Image.open(io.BytesIO(raw)).convert("RGB")except Exception as exc:- raise HTTPException(status_code=422, detail=f"not a readable image: {exc}") from exc+ raise HTTPException(status_code=422, detail=f"not a readable image: {errors.explain(exc)}") from exc# Only onto a registered crop. A pasted screenshot's coordinates describe# the map view at filing time rather than the picture itself, so nothingdiff --git a/src/azimut/api/settings.py b/src/azimut/api/settings.pyindex b0e1e34..873f80b 100644--- a/src/azimut/api/settings.py+++ b/src/azimut/api/settings.py@@ -14,10 +14,10 @@ from typing import Annotated, Any, Literalimport httpxfrom fastapi import APIRouter, HTTPException, Response, UploadFile-from fastapi.responses import FileResponse+from fastapi.responses import FileResponse, PlainTextResponsefrom pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator-from .. import __version__, config+from .. import __version__, config, errorsfrom ..engine import (diagnostics,exportdir,@@ -213,6 +213,25 @@ def ffmpeg_info() -> dict[str, Any]:return ffmpeg.info()[email protected]("/settings/bundled")+def bundled() -> dict[str, bool]:+ """Which of the parts a frozen build can silently lose are present."""+ return diagnostics.bundled_parts()++[email protected]("/settings/ffmpeg/notice")+def ffmpeg_notice() -> PlainTextResponse:+ """The bundled ffmpeg's notice and licence texts, as one page to read."""+ notice = ffmpeg.notice_path()+ if notice is None:+ raise HTTPException(status_code=404, detail="this ffmpeg is not bundled with Azimut")+ texts = [notice.read_text(encoding="utf-8")]+ for text in sorted(notice.parent.glob("*.txt")):+ if text != notice:+ texts.append(f"\n\n===== {text.name} =====\n\n" + text.read_text(encoding="utf-8"))+ return PlainTextResponse("".join(texts))++@router.put("/settings/prefs")def put_prefs(body: PrefsIn) -> dict[str, Any]:# validate before taking the settings lock — a 422 must not hold it@@ -389,7 +408,7 @@ def extension_install() -> dict[str, Any]:except LookupError as exc:raise HTTPException(status_code=404, detail=str(exc)) from excexcept OSError as exc:- raise HTTPException(status_code=409, detail=f"cannot write the extension folder: {exc}") from exc+ raise HTTPException(status_code=409, detail=f"cannot write the extension folder: {errors.explain(exc)}") from exc@router.post("/settings/extension/reveal")@@ -481,7 +500,7 @@ def discard_old_workspace() -> dict[str, str]:except workspacemove.MoveError as exc:raise HTTPException(status_code=409, detail=str(exc)) from excexcept OSError as exc:- raise HTTPException(status_code=409, detail=f"could not remove it: {exc}") from exc+ raise HTTPException(status_code=409, detail=f"could not remove it: {errors.explain(exc)}") from exc@router.post("/settings/ingest-token/rotate")@@ -539,6 +558,10 @@ def export_settings() -> Response:"""portable_settings = config.load_settings()portable_settings.pop("export_dirs", None)+ # A machine that never paired has no token to carry, and an empty one would+ # unpair the machine this backup is restored on.+ if not portable_settings.get("ingest_token"):+ portable_settings.pop("ingest_token", None)bundle = {"settings": portable_settings,"templates": config.load_templates(),@@ -762,6 +785,10 @@ class ImportIn(BaseModel):@router.post("/settings/import")def import_settings(body: ImportIn) -> dict[str, Any]:canonical = body.settings.model_dump(exclude_unset=True, by_alias=True)+ # Older backups wrote an empty token for a machine that never paired. Taking it+ # would unpair this one, and its extension would stop with no word why.+ if not canonical.get("ingest_token"):+ canonical.pop("ingest_token", None)applied = sorted(canonical)def apply(settings: dict[str, Any]) -> None:@@ -821,6 +848,9 @@ def test_key(provider: str) -> dict[str, Any]:raise HTTPException(status_code=404, detail=f"no {provider} key saved")def verdict(ok: bool, detail: str) -> dict[str, Any]:+ # A provider may quote the credential back ("Invalid instance id: <id>"),+ # and this sentence is shown, stored and carried by the settings backup.+ detail = detail.replace(key, "<key>")config.record_provider_status(provider, ok, detail)return {"ok": ok, "detail": detail}@@ -830,7 +860,7 @@ def test_key(provider: str) -> dict[str, Any]:google_tiles.session_token(key)return verdict(True, "session token created")except Exception as exc:- return verdict(False, str(exc))+ return verdict(False, tiles.upstream_failure(exc))if provider == "google_js":# A JS-API key only proves itself in a browser (gm_authFailure); the# Settings tab runs that test and reports through /status above.@@ -842,7 +872,7 @@ def test_key(provider: str) -> dict[str, Any]:response.raise_for_status()return verdict(True, "tile fetched")except Exception as exc:- return verdict(False, str(exc))+ return verdict(False, tiles.upstream_failure(exc))if provider == "firms":# The key is *asked about*, not used. A GetMap proves nothing here:# FIRMS answers a key it rejects with 200 and a 28 KB picture saying so@@ -860,7 +890,7 @@ def test_key(provider: str) -> dict[str, Any]:return verdict(False, firms.status_error(response.text))return verdict(True, "key accepted")except Exception as exc:- return verdict(False, str(exc))+ return verdict(False, tiles.upstream_failure(exc))if provider == "sentinelhub":# One real tile over Paris (grid level 13 → TILEMATRIX 14). This checks# the instance id *and* that the instance actually has a TRUE_COLOR@@ -876,7 +906,7 @@ def test_key(provider: str) -> dict[str, Any]:response.raise_for_status()return verdict(True, "tile fetched")except Exception as exc:- return verdict(False, str(exc))+ return verdict(False, tiles.upstream_failure(exc))raise HTTPException(status_code=404, detail=f"unknown keyed provider '{provider}'")diff --git a/src/azimut/api/sheets.py b/src/azimut/api/sheets.pyindex 0c1a200..a7efa8e 100644--- a/src/azimut/api/sheets.py+++ b/src/azimut/api/sheets.py@@ -39,7 +39,7 @@ from typing import Any, Literalfrom fastapi import APIRouter, HTTPException, UploadFilefrom pydantic import BaseModel, Field-from .. import layout+from .. import errors, layoutfrom ..engine import exportdirfrom ..engine import reveal as reveal_enginefrom ..engine import sheetfromcase as fromcase_engine@@ -632,7 +632,7 @@ def export_sheet(case_id: str, sheet_id: str, body: SheetExportIn) -> dict[str,else:path = exportdir.write_out(data, destination, written["filename"])except (OSError, exportdir.ExportDirError) as exc:- raise HTTPException(status_code=409, detail=f"could not write the CSV: {exc}") from exc+ raise HTTPException(status_code=409, detail=f"could not write the CSV: {errors.explain(exc)}") from excreturn {"file": path.name, "path": str(destination)}diff --git a/src/azimut/casestore.py b/src/azimut/casestore.pyindex 887c0df..11ca807 100644--- a/src/azimut/casestore.py+++ b/src/azimut/casestore.py@@ -105,6 +105,9 @@ class CaseStore:def list_links(self) -> list[dict[str, Any]]:return self._graph().list_links()+ def suggestions(self, by: str, *, limit: int) -> dict[str, Any]:+ return self._graph().suggestions(by, limit=limit)+def entity_images(self, entity_id: str) -> list[dict[str, Any]]:return self._graph().entity_images(entity_id)@@ -562,8 +565,8 @@ class CaseStore:def complete_job(self, job_id: str) -> None:self._graph().complete_job(job_id)- def fail_job(self, job_id: str, error: str) -> dict[str, Any]:- return self._graph().fail_job(job_id, error)+ def fail_job(self, job_id: str, error: str, *, final: bool = False) -> dict[str, Any]:+ return self._graph().fail_job(job_id, error, final=final)def cancel_job(self, job_id: str) -> None:self._graph().cancel_job(job_id)diff --git a/src/azimut/cli.py b/src/azimut/cli.pyindex 338ae4a..18f1918 100644--- a/src/azimut/cli.py+++ b/src/azimut/cli.py@@ -3,9 +3,10 @@from __future__ import annotationsimport argparse+import webbrowserfrom . import __version__-from .launcher import serve+from .launcher import choose_port, serveDEFAULT_PORT = 8477 # uncommon high port, clear of common dev ranges@@ -17,9 +18,18 @@ def main() -> None:parser.add_argument("--version", action="version", version=f"azimut {__version__}")args = parser.parse_args()- print(f"Azimut {__version__} · http://127.0.0.1:{args.port} (local only)")+ port, running = choose_port(args.port)+ url = f"http://127.0.0.1:{port}"+ if running:+ print(f"Azimut is already running at {url}.")+ if not args.no_browser:+ webbrowser.open(url)+ return+ if port != args.port:+ print(f"Port {args.port} is in use by another program, so Azimut takes {port}.")+ print(f"Azimut {__version__} · {url} (local only)")print("Runs in your browser tab. Close this window to stop Azimut.")- serve(args.port, open_browser=not args.no_browser)+ serve(port, open_browser=not args.no_browser)if __name__ == "__main__":diff --git a/src/azimut/engine/analysis_models.py b/src/azimut/engine/analysis_models.pyindex 886a19a..eddead4 100644--- a/src/azimut/engine/analysis_models.py+++ b/src/azimut/engine/analysis_models.py@@ -667,14 +667,6 @@ def recipe_products(recipe: Recipe | dict[str, Any]) -> list[str]:return [band_product(group) for group in groups]-def frames_for(recipe: Recipe | dict[str, Any]) -> int:- """Requests one tile costs: for each date read, the picture and every product."""- recipe = _as_recipe(recipe)- if recipe.method != "rules":- return frames_per_tile(recipe.method)- return (1 if is_single(recipe) else 2) * (1 + len(recipe_products(recipe)))--def _recipe(size: str = "all", **fields: Any) -> Recipe:parameters = {**SIZES[fields["method"]][size], **fields.pop("parameters", {})}return Recipe(parameters=Parameters(**parameters), **fields)diff --git a/src/azimut/engine/analyzers.py b/src/azimut/engine/analyzers.pyindex 524e29b..3ff372a 100644--- a/src/azimut/engine/analyzers.py+++ b/src/azimut/engine/analyzers.py@@ -483,6 +483,16 @@ def listing(case: Case, kind: str) -> list[dict[str, Any]]:rows.append(summary(kind, read(case, kind, path.stem.split("-", 1)[1])))except (OSError, ValueError, KeyError):continue+ if kind == "zones":+ # A deleted area stays named in its groups, so restoring it from the Trash+ # puts it back where it was. The list shows only the areas that exist now.+ live = {path.stem.split("-", 1)[1]+ for path in case.subdir(layout.ANALYSIS_DIR).glob("areas-*.json")}+ for row in rows:+ row["area_ids"] = [area_id for area_id in row["area_ids"] if area_id in live]+ row["areas"] = len(row["area_ids"])+ row["pending_review"] = [item for item in row.get("pending_review", [])+ if item.get("saved_area_id") in live]if kind in {"zones", "areas"}:ordered = sorted(rows, key=lambda row: (row.get("position") is None,row.get("position") or 0,diff --git a/src/azimut/engine/bundles.py b/src/azimut/engine/bundles.pyindex 456e685..da3836a 100644--- a/src/azimut/engine/bundles.py+++ b/src/azimut/engine/bundles.py@@ -18,7 +18,9 @@ from __future__ import annotationsimport hashlibimport json+import loggingimport os+import reimport shutilimport sqlite3import struct@@ -36,7 +38,7 @@ from typing import Any, BinaryIO, Callable, Iterable, Iteratorfrom cryptography.exceptions import InvalidTagfrom cryptography.hazmat.primitives.ciphers.aead import AESGCM-from .. import __version__, config, layout+from .. import __version__, config, errors, layoutfrom ..sqlite_backend import SQLITE_SCHEMA, SqliteCasefrom ..workspace import Case, CaseError, _now, _replace_with_retry, ensure_dirfrom . import workqueue@@ -123,6 +125,10 @@ _secret_lock = threading.Lock()_job_secrets: dict[str, str] = {}_removed_jobs: dict[str, dict[str, Any]] = {}_MAX_MEMORY_JOBS = 100+#: The cases an import of this process is still building, which a sweep leaves alone.+_building: set[str] = set()++logger = logging.getLogger(__name__)UPLOAD_MAX_AGE = 24 * 60 * 60_WINDOWS_RESERVED = frozenset({"CON", "PRN", "AUX", "NUL"}@@ -1014,7 +1020,40 @@ def create_import_case(name: str) -> Case:while Case.name_taken(candidate):candidate = f"{base} {index}"index += 1- return Case.create(candidate)+ case = Case.create(candidate)+ # An empty shell until the import lands: out of the switcher meanwhile, and+ # removed at the next start if the process dies before it does.+ layout.mark_import_scaffold(case.path)+ return case+++#: How the folders an import works in are named beside the case it builds.+_SCAFFOLD_SUFFIX = re.compile(r"\.(?:incoming|import-shell-[0-9a-f]{32})$")+++def sweep_scaffolds() -> int:+ """Remove what imports left behind when the process stopped under them: a+ staging folder holding a half-extracted bundle, a shell set aside, an empty case+ that never received its data. Each carries the import mark, and none holds work+ of the analyst's: the bundle they came from is still wherever it was. An import+ this process is running is left alone. Returns how many folders went."""+ parent = config.cases_dir()+ if not parent.is_dir():+ return 0+ with _secret_lock:+ building = set(_building)+ removed = 0+ for path in list(parent.iterdir()):+ if not path.is_dir() or not layout.is_import_scaffold(path):+ continue+ if _SCAFFOLD_SUFFIX.sub("", path.name) in building:+ continue+ try:+ shutil.rmtree(path)+ removed += 1+ except OSError as exc: # a file still open on Windows: the next start+ logger.warning("could not remove an interrupted import: %s", exc)+ return removeddef _install_running_job(db_path: Path, job: dict[str, Any]) -> None:@@ -1055,6 +1094,10 @@ def import_into(if staging.exists():raise BundleError(f"import staging path '{staging.name}' already exists")staging.mkdir()+ layout.mark_import_scaffold(staging)+ # A destination the caller made itself is marked only for the swap, then given+ # back unmarked if the import fails.+ shell_marked = layout.is_import_scaffold(case.path)# A format-1 bundle names its members relative to the tool root, so the# directory they extract into has to exist first. A format-2 bundle carries# `azimut/` itself and this is a no-op it does not mind.@@ -1090,7 +1133,11 @@ def import_into()if job is not None:_install_running_job(staged_db, job)+ layout.mark_import_scaffold(case.path)case.path.rename(old)+ # Unmarked before it takes the case's place, never after: a crash between the+ # two must leave a staging folder to sweep, not a finished case marked.+ layout.unmark_import_scaffold(staging)staging.rename(case.path)imported = Case.open(case.id)# After the open, because opening is what migrates a case from an older@@ -1122,6 +1169,8 @@ def import_into(shutil.rmtree(staging, ignore_errors=True)if old.exists() and not case.path.exists():old.rename(case.path)+ if not shell_marked:+ layout.unmark_import_scaffold(case.path)raise@@ -1162,6 +1211,8 @@ def queue_import(header = inspect_bundle(source, password=password)_require_import_space(Path(source), header)case = create_import_case(header["case_name"])+ with _secret_lock:+ _building.add(case.id)job = case.enqueue_job(IMPORT_JOB,payload={@@ -1193,8 +1244,13 @@ def _handle_export(case: Case, job: dict[str, Any]) -> None:sealed = bool(job["payload"].get("sealed"))password = _take_secret(job["id"])if sealed and not password:- raise workqueue.JobFailed("Password expired; restart the export")- export_case(case, password=password, output=Path(job["payload"]["output"]))+ raise workqueue.JobRefused("the password is no longer held, so start the export again")+ try:+ export_case(case, password=password, output=Path(job["payload"]["output"]))+ except BundleError as exc:+ # A refusal of the export itself (no room left on the disk, an output outside+ # the bundles folder) is the same on every attempt.+ raise workqueue.JobRefused(str(exc)) from excdef _handle_import(case: Case, job: dict[str, Any]) -> None:@@ -1203,7 +1259,7 @@ def _handle_import(case: Case, job: dict[str, Any]) -> None:password = _take_secret(job["id"])try:if sealed and not password:- error = "Password expired; restart the import"+ error = "the password is no longer held, so start the import again"else:import_into(case,@@ -1213,10 +1269,12 @@ def _handle_import(case: Case, job: dict[str, Any]) -> None:)returnexcept Exception as exc:- error = str(exc)+ error = errors.explain(exc)finally:if job["payload"].get("cleanup_source"):source.unlink(missing_ok=True)+ with _secret_lock:+ _building.discard(case.id)with _secret_lock:_removed_jobs[job["id"]] = {**job,diff --git a/src/azimut/engine/diagnostics.py b/src/azimut/engine/diagnostics.pyindex 1962a7c..1ac72f5 100644--- a/src/azimut/engine/diagnostics.py+++ b/src/azimut/engine/diagnostics.py@@ -341,6 +341,42 @@ def install_kind() -> str:_environment: dict[str, str] | None = None+def bundled_parts() -> dict[str, bool]:+ """Whether the parts a frozen build drops without a word when its spec forgets+ them are here: the zone database (Windows has none of its own, and local times+ would quietly read as UTC), the PDF faces and the font subsetter, the capture+ extension that Settings installs, and the scrapers' metadata, without which a+ stale copy updated into the workspace shadows the newer one the build ships. The+ release smoke test asks for all of them."""+ import importlib.metadata+ from datetime import datetime, timedelta+ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError++ from . import extinstall, pdffonts, scrapers++ try:+ zones = ZoneInfo("Asia/Tokyo").utcoffset(datetime(2026, 1, 1)) == timedelta(hours=9)+ except (ZoneInfoNotFoundError, ValueError):+ zones = False+ try:+ import fontTools.subset # noqa: F401 (fpdf2 subsets every face it embeds)++ subsetter = True+ except ImportError:+ subsetter = False+ faces = all((pdffonts.FONT_DIR / name).is_file() for name in pdffonts.CORE_FACES.values())+ try:+ versions = all(importlib.metadata.version(dist) for dist in scrapers.SCRAPERS)+ except importlib.metadata.PackageNotFoundError:+ versions = False+ return {+ "zones": zones,+ "pdf_fonts": faces and subsetter,+ "extension": bool(extinstall.bundled_version()) and bool(extinstall.payload_digest()),+ "scrapers": versions,+ }++def environment() -> dict[str, str]:"""The build and machine facts a maintainer needs to reproduce a bug.@@ -367,6 +403,9 @@ def environment() -> dict[str, str]:"Python": platform.python_version(),"ffmpeg": ffmpeg_line,}+ missing = [name for name, present in bundled_parts().items() if not present]+ if missing:+ _environment["Missing"] = ", ".join(missing)return dict(_environment)diff --git a/src/azimut/engine/exportdir.py b/src/azimut/engine/exportdir.pyindex 8ad1cbd..655e484 100644--- a/src/azimut/engine/exportdir.py+++ b/src/azimut/engine/exportdir.py@@ -109,7 +109,7 @@ def resolve(raw: str) -> Path:if not target.is_dir():raise ExportDirError("that is a file, not a folder")if _is_machinery(target):- raise ExportDirError("that folder belongs to Azimut — pick another one")+ raise ExportDirError("that folder belongs to Azimut, pick another one")if not _writable(target):raise ExportDirError("that folder is not writable")return targetdiff --git a/src/azimut/engine/ffmpeg.py b/src/azimut/engine/ffmpeg.pyindex 755e89a..fbadb5c 100644--- a/src/azimut/engine/ffmpeg.py+++ b/src/azimut/engine/ffmpeg.py@@ -94,15 +94,27 @@ def info() -> dict[str, str | bool | None]:"""path = ffmpeg_path()if path is None:- return {"available": False, "path": None, "source": None, "version": None}+ return {"available": False, "path": None, "source": None, "version": None, "notice": False}return {"available": True,"path": path,"source": "bundled" if path == _bundled("ffmpeg") else "path","version": _version(path),+ "notice": notice_path() is not None,}+def notice_path() -> Path | None:+ """The notice a binary carries for its bundled ffmpeg: which build, where its+ source is, and its licence (scripts/vendor_ffmpeg.py writes it). None outside a+ frozen build, where ffmpeg is the system's own."""+ base = getattr(sys, "_MEIPASS", None)+ if base is None:+ return None+ candidate = Path(base) / "ffmpeg-licenses" / "NOTICE.txt"+ return candidate if candidate.is_file() else None++def location_for_ytdlp() -> str | None:"""Directory to hand yt-dlp as ``ffmpeg_location``, or None to let it searchPATH itself.diff --git a/src/azimut/engine/geoconfirmed.py b/src/azimut/engine/geoconfirmed.pyindex fc6adcc..06e70f0 100644--- a/src/azimut/engine/geoconfirmed.py+++ b/src/azimut/engine/geoconfirmed.py@@ -253,7 +253,7 @@ def area(box: list[float] | tuple[float, ...] | None) -> list[float] | None:west, south, east, north = (float(v) for v in box)if not (-180 <= west < east <= 180 and -90 <= south < north <= 90):raise maplayers.LayerError(- "that area is not a box on the map — it may cross the antimeridian"+ "that area is not a box on the map, and may cross the antimeridian")return [round(west, 6), round(south, 6), round(east, 6), round(north, 6)]diff --git a/src/azimut/engine/inspect.py b/src/azimut/engine/inspect.pyindex 1d64fb4..5a38017 100644--- a/src/azimut/engine/inspect.py+++ b/src/azimut/engine/inspect.py@@ -21,6 +21,7 @@ from __future__ import annotationsimport base64import ioimport json+import loggingimport reimport subprocessimport tempfile@@ -38,6 +39,8 @@ from . import ffmpeg as ffmpeg_enginefrom . import media as media_enginefrom . import stitch+logger = logging.getLogger(__name__)+SUGGEST_CAP = 60 # hard cap on how many "sharpest frame" suggestions we return# The sharpest-frame scan reads *every* frame in one ffmpeg pass, decoded to@@ -47,6 +50,21 @@ SUGGEST_CAP = 60 # hard cap on how many "sharpest frame" suggestions we returnSCAN_DIM = 480++def ffmpeg_failed(what: str, stderr: bytes | None) -> RuntimeError:+ """ffmpeg's last word, without the path it names, as the reason a step failed.++ Its stderr runs to a screen of build flags and stream maps; the log keeps all of+ it and the page gets one line: "ffmpeg could not scan this video (Invalid data+ found when processing input)".+ """+ text = (stderr or b"").decode("utf-8", "replace").strip()+ if text:+ logger.warning("ffmpeg failed to %s a video:\n%s", what, text[-4000:])+ last = text.splitlines()[-1].rsplit(": ", 1)[-1].strip() if text else ""+ reason = f" ({last[:120]})" if last else ""+ return RuntimeError(f"ffmpeg could not {what} this video{reason}")+def _scan_timeout(duration: float) -> float:"""Allow slow software decoding without letting a broken scan run forever."""return max(30.0, min(1800.0, duration * 4 + 15))@@ -393,7 +411,7 @@ def extract_frame(video_path: Path, time_s: float) -> Image.Image:capture_output=True, timeout=60,)if proc.returncode != 0 or not proc.stdout:- raise RuntimeError((proc.stderr or b"").decode("utf-8", "replace").strip() or "frame decode failed")+ raise ffmpeg_failed("read a frame of", proc.stderr)return Image.open(io.BytesIO(proc.stdout)).convert("RGB")@@ -571,13 +589,9 @@ def scan_focus(if timed_out.is_set():raise RuntimeError("frame scan timed out")if proc.returncode not in (0, None):- raise RuntimeError(- (err or b"").decode("utf-8", "replace").strip() or "frame scan failed"- )+ raise ffmpeg_failed("scan", err)if not out:- raise RuntimeError(- (err or b"").decode("utf-8", "replace").strip() or "frame scan decoded nothing"- )+ raise ffmpeg_failed("decode any frame of", err)if set_progress:set_progress({"percent": 100.0})return out@@ -919,9 +933,7 @@ def enhance_video(capture_output=True, timeout=600,)if proc.returncode != 0 or not tmp.exists():- raise RuntimeError(- (proc.stderr or b"").decode("utf-8", "replace").strip() or "video enhance failed"- )+ raise ffmpeg_failed("enhance", proc.stderr)name = f"{stem}{'' if label else '_enhanced'}.mp4"source = _derivation(video_rel, _source_sha(case, video_rel), op="enhance-video",diff --git a/src/azimut/engine/maplayers.py b/src/azimut/engine/maplayers.pyindex 21bd7c2..504b73d 100644--- a/src/azimut/engine/maplayers.py+++ b/src/azimut/engine/maplayers.py@@ -252,7 +252,7 @@ def parse(raise LayerError("the file is empty")if len(data) > MAX_SOURCE_BYTES:raise LayerError(- f"the file is {_megabytes(len(data))} — the limit is "+ f"the file is {_megabytes(len(data))}, and the limit is "f"{_megabytes(MAX_SOURCE_BYTES)}")fmt = sniff(data, filename)@@ -675,7 +675,7 @@ def _geometry(geometry: Any) -> dict[str, Any] | None:points = sum(1 for _ in _coordinates(geometry))if points > MAX_GEOMETRY_POINTS:raise LayerError(- f"one shape in this file has {points:,} points — the limit is "+ f"one shape in this file has {points:,} points, and the limit is "f"{MAX_GEOMETRY_POINTS:,}")return {"type": type_, "coordinates": coordinates}@@ -684,8 +684,8 @@ def _geometry(geometry: Any) -> dict[str, Any] | None:def _bound(features: list[dict[str, Any]]) -> None:if len(features) >= MAX_FEATURES:raise LayerError(- f"this file holds more than {MAX_FEATURES:,} features — past that it "- "is a dataset, not a layer"+ f"this file holds more than {MAX_FEATURES:,} features, which is a dataset "+ "rather than a layer")@@ -2265,7 +2265,7 @@ def download(declared = response.headers.get("content-length")if declared and declared.isdigit() and int(declared) > limit:raise LayerFetchError(- f"that source is {_megabytes(int(declared))} — the limit is "+ f"that source is {_megabytes(int(declared))}, and the limit is "f"{_megabytes(limit)}")chunks: list[bytes] = []@@ -2293,7 +2293,7 @@ def _status_reason(exc: "httpx.HTTPStatusError", address: str) -> str:code = exc.response.status_codeif MY_MAPS_FEED.split("?", 1)[0] in address and code in (401, 403, 404):return (- "Google would not serve that map. It has to be shared publicly — "+ "Google would not serve that map. It has to be shared publicly: ""open it in My Maps, then Share, then anyone with the link.")return f"that source answered {code}"diff --git a/src/azimut/engine/proofimport.py b/src/azimut/engine/proofimport.pyindex 6b5ab93..3561aa4 100644--- a/src/azimut/engine/proofimport.py+++ b/src/azimut/engine/proofimport.py@@ -252,15 +252,6 @@ def staged_pairs(case: Case, token: str, slot: str) -> list[tuple[Path, dict[strreturn [(path, staged) for path, staged in found if path is not None]-def fill_slot(case: Case, token: str, slot: str, staged: dict[str, Any]) -> dict[str, Any]:- """Record what a download or a hand-attached file put in a slot, alone.-- Filling replaces: retrying a failed source download does not leave the abandoned- attempt on disk, and re-picking a picture drops the one that was there.- """- return fill_files(case, token, slot, [staged])--def fill_files(case: Case, token: str, slot: str, staged: list[dict[str, Any]], *, for_url: str = "") -> dict[str, Any]:@@ -602,9 +593,9 @@ def preview(case: Case, token: str, form: dict[str, Any]) -> dict[str, Any]:{"code": "gps-conflict","text": (- f"The file states {own['lat']:.6f}, {own['lon']:.6f} — "- f"{round(away):,} m from the coordinates entered."- ).replace(",", " "),+ f"The file states {own['lat']:.6f}, {own['lon']:.6f}, "+ f"{f'{round(away):,}'.replace(',', ' ')} m from the coordinates entered."+ ),})diff --git a/src/azimut/engine/proposals.py b/src/azimut/engine/proposals.pyindex 46701b6..7f7aadf 100644--- a/src/azimut/engine/proposals.py+++ b/src/azimut/engine/proposals.py@@ -176,9 +176,15 @@ class _Mark:self.at: str | None = stored.get("at") or Noneself.read: set[str] = set(stored.get("read") or [])self.newest, self.newest_ids = self.at, set(self.read)+ # Filed before the mark, then edited into something worth reading.+ self.again: set[str] = set(stored.get("again") or [])+ self.revisited: set[str] = set()def fresh(self, entity: dict[str, Any]) -> bool:at, entity_id = _filed_at(entity), str(entity["id"])+ if entity_id in self.again:+ self.revisited.add(entity_id)+ return Trueif self.at is not None and (at < self.at or (at == self.at and entity_id in self.read)):return Falseif at and (self.newest is None or at > self.newest):@@ -202,7 +208,13 @@ def _propose_accounts(case: "Case", mark: _Mark, counts: dict[str, int]) -> Noneheld: dict[str, str] = {}for account_id, label in case.labels_of_type("account"):held.setdefault(entity_engine.identity_key("account", label), account_id)- for entity in _page_all(case, list(URL_ATTRS), mark.at):+ filed = _page_all(case, list(URL_ATTRS), mark.at)+ seen = {entity["id"] for entity in filed}+ for entity_id in sorted(mark.again - seen):+ edited = case.get_entity(entity_id)+ if edited is not None and edited.get("type") in URL_ATTRS:+ filed.append(edited)+ for entity in filed:if not mark.fresh(entity):continueaccount = account_from_url(_address(entity))@@ -337,7 +349,13 @@ def propose(case: "Case") -> dict[str, int]:_propose_sites(case, mark, counts)stored = mark.stored()if stored is not None:- case.set_link_pass(stored)+ with case._lock:+ # An edit made while the pass ran names its entity for the next one.+ current = case.link_pass() or {}+ left = [i for i in current.get("again") or [] if i not in mark.revisited]+ if left:+ stored["again"] = left+ case.set_link_pass(stored)return counts@@ -351,6 +369,38 @@ def on_filed(case: "Case", entity_type: str) -> None:workqueue.enqueue(case, KIND, key="case")+#: The attributes a pass reads, so an edit that names none of them costs no lookup.+_READ_ATTRS = frozenset({"lat", "lon", *URL_ATTRS.values()})+++def may_change_reading(patch: dict[str, Any]) -> bool:+ """Whether an edit names anything a pass reads."""+ return not _READ_ATTRS.isdisjoint(patch.get("attrs") or {})+++def _reading(entity: dict[str, Any]) -> Any:+ """What a pass reads off an entity: a place's point, a file's or a bookmark's address."""+ if str(entity.get("type") or "") in SITE_TYPES:+ return point_of(entity)+ return str(_address(entity) or "").strip() or None+++def on_changed(case: "Case", before: dict[str, Any], after: dict[str, Any]) -> None:+ """Queue a pass when an edit gives a filed entity something new to read: a place a+ point or a new one, a file or a bookmark an address or a new one.++ Passes read past a mark set by filing time, which an edit does not move, so a+ place geolocated after it was filed would otherwise never be read again. The same+ value sent back is not new: a Save in Details or a second Promote resends it, and+ reading the entity again would bring back every proposal the analyst dropped.+ """+ reading = _reading(after)+ if reading is None or reading == _reading(before):+ return+ if case.revisit_links(str(after["id"])):+ workqueue.enqueue(case, KIND, key="case")++def _handle(case: "Case", job: dict[str, Any]) -> None:propose(case)@@ -369,23 +419,14 @@ def unreviewed(link: dict[str, Any]) -> bool:return provenance.get("by") == BY and provenance.get("status") == "suggested"-def pending(case: "Case") -> dict[str, int]:+def counted(suggestions: dict[str, Any]) -> dict[str, int]:"""How many proposals still wait for the analyst, by what they say."""- waiting = {"accounts": 0, "posted": 0, "sites": 0}- for link in case.list_links():- if not unreviewed(link):- continue- if link["type"] == link_engine.POSTED:- waiting["posted"] += 1- elif link["type"] == link_engine.SAME_SITE_AS:- waiting["sites"] += 1- waiting["accounts"] = sum(- 1- for entity in _page_all(case, ["account"])- if (entity.get("provenance") or {}).get("by") == BY- and (entity.get("provenance") or {}).get("status") == "suggested"- )- return waiting+ links, entities = suggestions["links"], suggestions["entities"]+ return {+ "accounts": entities.get("account", 0),+ "posted": links.get(link_engine.POSTED, 0),+ "sites": links.get(link_engine.SAME_SITE_AS, 0),+ }# -- what a proof shares with the rest of the case -----------------------------diff --git a/src/azimut/engine/scrapers.py b/src/azimut/engine/scrapers.pyindex e6f35d4..f1244e0 100644--- a/src/azimut/engine/scrapers.py+++ b/src/azimut/engine/scrapers.py@@ -32,6 +32,7 @@ from __future__ import annotationsimport hashlibimport importlib.metadata+import reimport shutilimport sysimport tempfile@@ -45,7 +46,7 @@ from typing import Anyimport httpx-from .. import config+from .. import config, errorsfrom . import dirswap# distribution name on PyPI -> module name it imports as@@ -101,9 +102,35 @@ def bundled_version(dist: str) -> str | None:return str(version) if version else None+def _version_key(version: str) -> tuple[int, ...]:+ return tuple(int(part) for part in re.findall(r"\d+", version))+++def live_runtime_version(dist: str) -> str | None:+ """The workspace copy's version when it is the one to import, else None.++ The workspace outlives the program: an update pressed under one build is+ still there after the next build ships a newer scraper, and a stale copy+ would shadow it until someone found Reset. So the copy wins only when it is+ newer than the build's own. The build's version is read from its metadata,+ never by importing, because importing the bundled module here would pin it in+ sys.modules ahead of a copy that is newer. The binaries carry that metadata+ (`copy_metadata` in packaging/azimut.spec, checked by the release smoke test);+ a build without it cannot compare, and keeps the copy the analyst asked for.+ """+ runtime = runtime_version(dist)+ if runtime is None:+ return None+ try:+ bundled = importlib.metadata.version(dist)+ except importlib.metadata.PackageNotFoundError:+ return runtime+ return runtime if _version_key(runtime) > _version_key(bundled) else None++def active_version(dist: str) -> tuple[str | None, str]:"""The version that import would actually get, and where it comes from."""- runtime = runtime_version(dist)+ runtime = live_runtime_version(dist)if runtime is not None:return runtime, "runtime"return bundled_version(dist), "bundled"@@ -155,7 +182,7 @@ def activate() -> dict[str, str]:roots: dict[str, Path] = {}shadowed: dict[str, str] = {}for dist, module in SCRAPERS.items():- version = runtime_version(dist)+ version = live_runtime_version(dist)if version is None:continueroots[module] = dist_dir(dist)@@ -243,7 +270,7 @@ def update(dist: str) -> dict[str, Any]:version, url, sha256 = _pypi_wheel(dist)with _lock:- if version == runtime_version(dist):+ if version in (before, runtime_version(dist)):return {"dist": dist,"updated": False,@@ -327,6 +354,6 @@ def status(check_pypi: bool = False) -> list[dict[str, Any]]:except Exception as exc:# Offline is the normal case for this app, not an error state.entry["latest"] = None- entry["check_error"] = str(exc)+ entry["check_error"] = errors.explain(exc)out.append(entry)return outdiff --git a/src/azimut/engine/sentinel.py b/src/azimut/engine/sentinel.pyindex b877f9a..c1811c0 100644--- a/src/azimut/engine/sentinel.py+++ b/src/azimut/engine/sentinel.py@@ -554,21 +554,6 @@ RADAR_ID = "sentinel1"_PASS_TIME_RE = re.compile(r"^([01]\d|2[0-3])([0-5]\d)([0-5]\d)$")-def radar_variant_id(day: str | None = None, time: str = "") -> str:- """The radar basemap's id for one pass: ``sentinel1~2026-05-14~054210``.-- A day alone mosaics every pass of that day, and no day at all is the most- recent pass, which is the layer's own default. The time rides without its- colons, because the id is also a folder name in the tile cache.- """- if not day:- return RADAR_ID- parts = [RADAR_ID, day]- if time:- parts.append(time.replace(":", ""))- return VARIANT_SEP.join(parts)--def parse_radar_variant(spec: str) -> tuple[str, str]:"""``"2026-05-14~054210"`` → ``("2026-05-14", "05:42:10")``; the time may be absent."""parts = spec.split(VARIANT_SEP)diff --git a/src/azimut/engine/sheetfromcase.py b/src/azimut/engine/sheetfromcase.pyindex 7bad737..103c72e 100644--- a/src/azimut/engine/sheetfromcase.py+++ b/src/azimut/engine/sheetfromcase.py@@ -820,6 +820,18 @@ def refresh_files()+def _all_of_type(case: "Case", entity_type: str) -> list[dict[str, Any]]:+ """Every entity of one type, paged, so the read never walks the rest of the case."""+ out: list[dict[str, Any]] = []+ cursor: str | None = None+ while True:+ page = case.page_entities(limit=500, cursor=cursor, types=[entity_type])+ out.extend(page.get("items", []))+ cursor = page.get("next_cursor")+ if not cursor:+ return out++def files_preview(case: "Case") -> dict[str, Any]:"""What a files worklist would hold, and the one the case already has.@@ -830,7 +842,7 @@ def files_preview(case: "Case") -> dict[str, Any]:files = imported_files(case)answered, _, _ = _file_graph(case) if files else ({}, {}, {})sheets = sorted(- (entity for entity in case.list_entities() if entity.get("type") == "sheet"),+ _all_of_type(case, "sheet"),key=lambda entity: str((entity.get("provenance") or {}).get("at") or ""),reverse=True,)diff --git a/src/azimut/engine/workqueue.py b/src/azimut/engine/workqueue.pyindex f716653..7f2b557 100644--- a/src/azimut/engine/workqueue.py+++ b/src/azimut/engine/workqueue.py@@ -16,6 +16,11 @@ Settlement is central, so a handler only decides *what happened*:succeed- raises `JobFailed`, or anything unexpected -> the job is recorded failed andretried until its attempt budget is spent+- raises `JobRefused` -> the job is recorded failed at once: what stopped it (no+ room on the disk for an export) would stop every retry the same way++What a failure records is what the analyst reads, so anything unexpected is put in+a sentence (`errors.explain`) and its raw text goes to the log.Work only ever starts from a user action (an import, a regenerate, a backfill)or from crash recovery — never from merely opening a case or a tab.@@ -23,13 +28,18 @@ or from crash recovery — never from merely opening a case or a tab.from __future__ import annotations+import loggingimport threadingimport timefrom typing import TYPE_CHECKING, Any, Callable+from .. import errors+if TYPE_CHECKING:from ..workspace import Case as CaseType+logger = logging.getLogger(__name__)+Handler = Callable[["CaseType", dict[str, Any]], None]#: kind -> handler. Producers register at import time (see engine/thumbnails.py@@ -46,6 +56,10 @@ class JobFailed(Exception):"""The job failed this time and deserves another attempt."""+class JobRefused(Exception):+ """The job cannot succeed as asked, and another attempt would fail the same way."""++class JobRemoved(Exception):"""The handler removed its owning case, so no row remains to settle."""@@ -88,8 +102,11 @@ def _settle(case: "CaseType", job: dict[str, Any]) -> bool:case.cancel_job(job["id"])except JobFailed as exc:case.fail_job(job["id"], str(exc))+ except JobRefused as exc:+ case.fail_job(job["id"], str(exc), final=True)except Exception as exc: # a handler bug must not stall the queue- case.fail_job(job["id"], f"{type(exc).__name__}: {exc}")+ logger.warning("job %s (%s) failed", job["id"], job["kind"], exc_info=True)+ case.fail_job(job["id"], errors.explain(exc))else:case.complete_job(job["id"])return Falsediff --git a/src/azimut/engine/workspacemove.py b/src/azimut/engine/workspacemove.pyindex 674301f..41bbcd3 100644--- a/src/azimut/engine/workspacemove.py+++ b/src/azimut/engine/workspacemove.py@@ -33,7 +33,7 @@ from datetime import datetimefrom pathlib import Pathfrom typing import Any, Callable-from .. import config, layout+from .. import config, errors, layoutfrom ..workspace import ensure_dirfrom . import workspacelockfrom .bundles import disk_reserve@@ -559,7 +559,7 @@ def _run(move: Move) -> None:move.done = Trueexcept Exception as exc: # one failure surface: the analyst reads `error`logger.warning("workspace move failed at %s: %s", move.step, exc)- move.error = str(exc) or exc.__class__.__name__+ move.error = errors.explain(exc)move.done = Trueshutil.rmtree(staging, ignore_errors=True)finally:diff --git a/src/azimut/errors.py b/src/azimut/errors.pynew file mode 100644index 0000000..622b3df--- /dev/null+++ b/src/azimut/errors.py@@ -0,0 +1,111 @@+"""What a failure says to the analyst, as one clause they can act on.++An OSError's text carries an errno and a path, Pillow's names the buffer it was handed,+httpx's holds the URL and its key, and a KeyError is a bare quoted word. That text stays+in the log. The page gets a clause from here, written to follow "could not save the+image: " or to stand alone.++The app's own exceptions (CaseError, SheetError and the rest) already speak in+sentences, so they pass through unchanged.+"""++from __future__ import annotations++import errno+import logging+import subprocess+import zipfile+from typing import Any++import httpx+from PIL import UnidentifiedImageError++logger = logging.getLogger("azimut")++UNEXPECTED = "an unexpected error stopped it. Settings → System → Report an issue has its log"++# Python's own mistakes: their text is for whoever reads the code, never for the page.+_INTERNAL = (KeyError, IndexError, TypeError, AttributeError, AssertionError, NameError)+++def explain(exc: BaseException) -> str:+ """One clause for a failure, lowercase, with no closing full stop."""+ if isinstance(exc, UnidentifiedImageError):+ return "this file is not a picture Azimut can read"+ if isinstance(exc, zipfile.BadZipFile):+ return "this file is not a readable archive"+ if isinstance(exc, subprocess.TimeoutExpired):+ return "it took too long and was stopped"+ if isinstance(exc, httpx.TimeoutException):+ return "the service did not answer in time"+ if isinstance(exc, httpx.HTTPStatusError):+ return f"the service answered {exc.response.status_code}"+ if isinstance(exc, httpx.HTTPError):+ return "the service could not be reached"+ if isinstance(exc, OSError):+ return _disk(exc)+ if isinstance(exc, _INTERNAL):+ logger.warning("unexpected %s: %s", type(exc).__name__, exc)+ return UNEXPECTED+ text = str(exc).strip()+ return text.rstrip(".") if text else UNEXPECTED+++def _disk(exc: OSError) -> str:+ if isinstance(exc, PermissionError) or exc.errno in (errno.EACCES, errno.EPERM):+ return "the system refused access to that file or folder"+ if isinstance(exc, FileNotFoundError):+ return "a file it needed is no longer there"+ if exc.errno == errno.ENOSPC:+ return "the disk is full"+ if exc.errno == errno.EROFS:+ return "that folder is read-only"+ if exc.errno == errno.ENAMETOOLONG:+ return "a file name or path is too long for this system"+ return "the file system refused it"+++def validation_sentence(errors: list[dict[str, Any]]) -> str:+ """A request the schema refused, said the way a form says it: "Name is too long+ (80 characters at most)". The first three problems, joined."""+ parts = [_one(error) for error in errors[:3]]+ sentence = "; ".join(part for part in parts if part)+ return sentence or "The request did not hold what this action needs"+++def _one(error: dict[str, Any]) -> str:+ loc = [part for part in error.get("loc", ()) if part not in ("body", "query", "path")]+ names = [str(part) for part in loc if isinstance(part, str)]+ field = names[-1].replace("_", " ").capitalize() if names else ""+ ctx = error.get("ctx") or {}+ kind = str(error.get("type", ""))+ if kind == "missing":+ reason = "is required"+ elif kind == "string_too_long":+ reason = f"is too long ({ctx.get('max_length')} characters at most)"+ elif kind == "string_too_short":+ reason = "cannot be empty" if ctx.get("min_length") == 1 else f"needs at least {ctx.get('min_length')} characters"+ elif kind == "too_long":+ reason = f"holds too many items ({ctx.get('max_length')} at most)"+ elif kind == "too_short":+ reason = f"needs at least {ctx.get('min_length')} items"+ elif kind in ("greater_than_equal", "greater_than"):+ reason = f"must be at least {ctx.get('ge', ctx.get('gt'))}"+ elif kind in ("less_than_equal", "less_than"):+ reason = f"must be at most {ctx.get('le', ctx.get('lt'))}"+ elif kind == "string_pattern_mismatch":+ reason = "holds characters it cannot take"+ elif kind == "literal_error":+ reason = f"must be one of {ctx.get('expected')}"+ elif kind in ("int_parsing", "float_parsing", "int_type", "float_type", "int_from_float"):+ reason = "must be a number"+ elif kind == "bool_parsing":+ reason = "must be yes or no"+ elif kind == "json_invalid":+ return "The request was not valid JSON"+ elif kind == "extra_forbidden":+ reason = "is not a field this action takes"+ else:+ reason = str(error.get("msg", "")).removeprefix("Value error, ")+ return f"{field}: {reason}" if field else reason+ return f"{field} {reason}" if field else reason[0].upper() + reason[1:]diff --git a/src/azimut/jobs.py b/src/azimut/jobs.pyindex 0a83cbd..422a9fc 100644--- a/src/azimut/jobs.py+++ b/src/azimut/jobs.py@@ -6,10 +6,15 @@ GET /api/jobs/{id}. Local single-user app — no persistence needed.from __future__ import annotations+import loggingimport threadingimport uuidfrom typing import Any, Callable+from . import errors++logger = logging.getLogger(__name__)+_jobs: dict[str, dict[str, Any]] = {}_lock = threading.Lock()@@ -53,8 +58,9 @@ def start(kind: str, work: Callable[..., Any], *, stoppable: bool = False) -> stwith _lock:_jobs[job_id].update(status="done", result=result)except Exception as exc: # surfaced to the UI, not swallowed+ logger.warning("job %s (%s) failed: %r", job_id, kind, exc)with _lock:- _jobs[job_id].update(status="error", error=str(exc))+ _jobs[job_id].update(status="error", error=errors.explain(exc))threading.Thread(target=runner, daemon=True).start()return job_iddiff --git a/src/azimut/launcher.py b/src/azimut/launcher.pyindex 4d761ed..25bd63a 100644--- a/src/azimut/launcher.py+++ b/src/azimut/launcher.py@@ -15,12 +15,19 @@ the browser anyway.from __future__ import annotationsimport atexit+import json+import os+import socketimport threadingimport time+import urllib.requestimport webbrowserimport uvicorn+#: How many ports past the asked one are tried when another program holds it.+PORT_TRIES = 20+def _build_server(port: int) -> uvicorn.Server:config = uvicorn.Config(@@ -51,6 +58,74 @@ def _open_when_ready(server: uvicorn.Server, url: str) -> None:threading.Thread(target=wait_and_open, daemon=True).start()+def _port_is_free(port: int) -> bool:+ """Whether the server could bind this port. On POSIX the probe sets SO_REUSEADDR+ as uvicorn does, or a connection left in TIME-WAIT would read as a live holder;+ on Windows the same option would let the probe steal a port that is in use."""+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:+ if os.name != "nt":+ probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ try:+ probe.bind(("127.0.0.1", port))+ except OSError:+ return False+ return True+++def _azimut_answers(port: int) -> bool:+ """Whether what listens on this port is Azimut, asked the way its tab would ask.+ No proxy: a system proxy must not be handed a question about this machine."""+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))+ try:+ with opener.open(f"http://127.0.0.1:{port}/api/health", timeout=2) as answer:+ body = json.loads(answer.read(4096))+ except (OSError, ValueError):+ return False+ return isinstance(body, dict) and body.get("status") == "ok" and "version" in body+++def _holder_port() -> int | None:+ """The port of an Azimut on this machine that already holds the workspace.++ Two starts need not ask for the same port to meet: the first may have moved to a+ free one while another program held its own, and that program may have let go+ since. Asking the port alone would miss the first and start a second server,+ which would find the workspace taken and offer to take it anyway.+ """+ try:+ from .engine import workspacelock++ payload = workspacelock.holder()+ except Exception: # an unreadable lock is the server's to explain, not ours+ return None+ port = (payload or {}).get("port")+ if not isinstance(port, int) or (payload or {}).get("host") != socket.gethostname():+ return None+ return port if _azimut_answers(port) else None+++def choose_port(port: int) -> tuple[int, bool]:+ """The port to serve on, and whether Azimut already runs there.++ Started twice, Azimut should send the second start to the first one's tab, not+ die on a bind error in a console that closes before anyone reads it. A port held+ by some other program gives way to the next free one.+ """+ held = _holder_port()+ if held is not None:+ return held, True+ if _port_is_free(port):+ return port, False+ if _azimut_answers(port):+ return port, True+ for candidate in range(port + 1, port + 1 + PORT_TRIES):+ if _port_is_free(candidate):+ return candidate, False+ raise SystemExit(+ f"Ports {port} to {port + PORT_TRIES} are all in use. Start Azimut with --port and a free number."+ )++def serve(port: int, *, open_browser: bool = True) -> None:"""Run the server (blocking) and, unless told not to, open the browser tab."""from . import server as server_modulediff --git a/src/azimut/layout.py b/src/azimut/layout.pyindex 7172e67..fdcce8e 100644--- a/src/azimut/layout.py+++ b/src/azimut/layout.py@@ -651,6 +651,25 @@ def is_case(root: Path) -> bool:return manifest(root).is_file() or unwrapped_manifest(root).is_file()+#: Left at the root of a folder a bundle import is building: the new case's shell, its+#: staging folder, and the shell set aside at the swap. Such a folder is not a case+#: yet, so the switcher and the folders to adopt leave it out, and a start that finds+#: one left behind by a crash removes it (`engine/bundles.sweep_scaffolds`).+IMPORT_SCAFFOLD = ".azimut-importing"+++def is_import_scaffold(root: Path) -> bool:+ return (root / IMPORT_SCAFFOLD).is_file()+++def mark_import_scaffold(root: Path) -> None:+ (root / IMPORT_SCAFFOLD).write_bytes(b"")+++def unmark_import_scaffold(root: Path) -> None:+ (root / IMPORT_SCAFFOLD).unlink(missing_ok=True)++def extracted_database(root: Path) -> Path:"""The case database in a freshly extracted bundle, whatever its vintage.diff --git a/src/azimut/repository.py b/src/azimut/repository.pyindex b4aad4c..0c1087b 100644--- a/src/azimut/repository.py+++ b/src/azimut/repository.py@@ -134,6 +134,13 @@ class CaseRepository(Protocol):def list_links(self) -> list[dict[str, Any]]:...+ def suggestions(self, by: str, *, limit: int) -> dict[str, Any]:+ """What one filer proposed and nobody has reviewed yet, counted in SQL:+ ``{"links": {type: n}, "entities": {type: n}, "items": [first `limit` edges]}``.+ The proposals panel reads it on every case revision, so it never walks the+ whole graph."""+ ...+def get_link(self, link_id: str) -> dict[str, Any] | None:"""One edge by id, or None. The single-row read behind editing a relation,so correcting one never walks the graph."""@@ -698,7 +705,7 @@ class CaseRepository(Protocol):def complete_job(self, job_id: str) -> None:...- def fail_job(self, job_id: str, error: str) -> dict[str, Any]:+ def fail_job(self, job_id: str, error: str, *, final: bool = False) -> dict[str, Any]:...def cancel_job(self, job_id: str) -> None:diff --git a/src/azimut/server.py b/src/azimut/server.pyindex 6b51f1e..946746d 100644--- a/src/azimut/server.py+++ b/src/azimut/server.py@@ -9,11 +9,12 @@ from pathlib import Pathfrom typing import Any, AsyncIteratorfrom fastapi import FastAPI, Request+from fastapi.exceptions import RequestValidationErrorfrom fastapi.responses import FileResponse, JSONResponse, PlainTextResponsefrom fastapi.staticfiles import StaticFilesfrom starlette.types import ASGIApp, Message, Receive, Scope, Send-from . import __version__, config+from . import __version__, config, errorsfrom .engine import workspacelock, workspacemovelogger = logging.getLogger(__name__)@@ -302,8 +303,11 @@ def create_app() -> FastAPI:# handle, which is what lets Windows delete the folder afterwards.workspacelock.release()+ # No /docs, /redoc or /openapi.json: the docs page pulls Swagger UI from a CDN,+ # and that script would run on this origin with the whole API in reach.app = FastAPI(- title="Azimut", version=__version__, docs_url="/api/docs", lifespan=lifespan+ title="Azimut", version=__version__, lifespan=lifespan,+ docs_url=None, redoc_url=None, openapi_url=None,)from .api import (@@ -347,6 +351,14 @@ def create_app() -> FastAPI:async def _sheet_unwritable(_: Request, exc: sheet_engine.SheetUnwritable) -> JSONResponse:return JSONResponse(status_code=409, content={"detail": str(exc)})+ # A body the schema refused, said as a form would say it ("Name is too long (80+ # characters at most)") rather than as pydantic's list of locations and types.+ @app.exception_handler(RequestValidationError)+ async def _refused(_: Request, exc: RequestValidationError) -> JSONResponse:+ return JSONResponse(+ status_code=422, content={"detail": errors.validation_sentence(list(exc.errors()))}+ )+# extension-origin CORS, /api/ingest/* only (see ingest.install_cors)ingest.install_cors(app)# Inside the local guard: a request that isn't allowed to reach the app at@@ -361,6 +373,17 @@ def create_app() -> FastAPI:def health() -> dict[str, str]:return {"status": "ok", "version": __version__}+ # Registered after every router, so it only catches an /api path nothing serves.+ # Without it the SPA fallback below answers 200 with index.html, and a tab left+ # open across an update that retired a route reads "Unexpected token '<'".+ @app.api_route(+ "/api/{rest:path}",+ methods=["GET", "POST", "PUT", "PATCH", "DELETE"],+ include_in_schema=False,+ )+ def unknown_api(rest: str) -> JSONResponse:+ return JSONResponse(status_code=404, content={"detail": "Not Found"})+# Built frontend (frontend/ builds into src/azimut/static/).if (STATIC_DIR / "index.html").exists():app.mount("/assets", StaticFiles(directory=STATIC_DIR / "assets"), name="assets")diff --git a/src/azimut/sqlite_backend.py b/src/azimut/sqlite_backend.pyindex 1361599..26e5c30 100644--- a/src/azimut/sqlite_backend.py+++ b/src/azimut/sqlite_backend.py@@ -349,6 +349,8 @@ CREATE INDEX idx_temporal_kind ON temporal_items(kind);# cancel makes it `cancelled`. An interrupted `running` job (a crash mid-work) is# recovered on open back to `queued` or `failed` per its retry count._JOB_TERMINAL = frozenset({"ready", "failed", "cancelled"})+# Set in a running keyed job's payload by a second enqueue: run once more at the end.+_RERUN = "_rerun"T = TypeVar("T")@@ -786,6 +788,31 @@ class SqliteCase:with self._connect() as conn:return [self._link(r) for r in conn.execute("SELECT * FROM links ORDER BY rowid")]+ def suggestions(self, by: str, *, limit: int) -> dict[str, Any]:+ with self._connect() as conn:+ links = {+ r["type"]: r["n"]+ for r in conn.execute(+ "SELECT type, COUNT(*) AS n FROM links"+ " WHERE prov_by = ? AND prov_status = 'suggested' GROUP BY type",+ (by,),+ )+ }+ entities = {+ r["type"]: r["n"]+ for r in conn.execute(+ "SELECT type, COUNT(*) AS n FROM entities"+ " WHERE prov_by = ? AND prov_status = 'suggested' GROUP BY type",+ (by,),+ )+ }+ rows = conn.execute(+ "SELECT * FROM links WHERE prov_by = ? AND prov_status = 'suggested'"+ " ORDER BY rowid LIMIT ?",+ (by, limit),+ ).fetchall()+ return {"links": links, "entities": entities, "items": [self._link(r) for r in rows]}+def get_link(self, link_id: str) -> dict[str, Any] | None:with self._connect() as conn:row = conn.execute("SELECT * FROM links WHERE id = ?", (link_id,)).fetchone()@@ -3508,8 +3535,14 @@ class SqliteCase:self._write(op)def pending_merge_work(self) -> list[dict[str, Any]]:+ # Every case open asks this, and merge records are kept for Undo, so their+ # payloads only grow. SQLite skips the ones that never named the key; only the+ # few that did are parsed here.with self._connect() as conn:- rows = conn.execute("SELECT * FROM entity_merges ORDER BY rowid").fetchall()+ rows = conn.execute(+ "SELECT * FROM entity_merges WHERE instr(payload_json, '\"pending_sheets\"') > 0"+ " ORDER BY rowid"+ ).fetchall()return [self._merge(row, payload=True) for row in rows if json.loads(row["payload_json"]).get("pending_sheets")]def finish_merge_work(self, merge_id: str) -> None:@@ -3706,9 +3739,10 @@ class SqliteCase:Keyed jobs are idempotent: a second enqueue for the same ``(kind, key)``never stacks a duplicate. A job already ``running`` is left running (the- worker owns it); any other prior state — including a finished ``ready``- one, so a re-enqueue is how a thumbnail is regenerated — is reset to a- fresh ``queued`` attempt. The keyless form is a plain append.+ worker owns it) and marked to run once more when it ends, since what it+ read may predate this enqueue; any other prior state — including a+ finished ``ready`` one, so a re-enqueue is how a thumbnail is regenerated+ — is reset to a fresh ``queued`` attempt. The keyless form is a plain append."""now = _now()@@ -3719,6 +3753,11 @@ class SqliteCase:).fetchone()if row is not None:if row["state"] == "running":+ again = {**(payload or {}), _RERUN: True}+ conn.execute(+ "UPDATE jobs SET payload_json = ?, updated_at = ? WHERE id = ?",+ (json.dumps(again, ensure_ascii=False), now, row["id"]),+ )return self._job(row)conn.execute("UPDATE jobs SET state = 'queued', attempts = 0, error = NULL,"@@ -3771,18 +3810,38 @@ class SqliteCase:return self._write(op)def complete_job(self, job_id: str) -> None:- """Mark a finished job ``ready``."""- self._set_job_state(job_id, "ready", error=None)+ """Mark a finished job ``ready``, or queue it again when it was enqueued+ while it ran: the run that just ended may have missed what came in."""+ def op(conn: sqlite3.Connection) -> None:+ row = conn.execute("SELECT payload_json FROM jobs WHERE id = ?", (job_id,)).fetchone()+ if row is None:+ raise CaseError(f"job '{job_id}' not found")+ payload = json.loads(row["payload_json"] or "{}")+ if payload.pop(_RERUN, False):+ conn.execute(+ "UPDATE jobs SET state = 'queued', attempts = 0, error = NULL,"+ " payload_json = ?, updated_at = ? WHERE id = ?",+ (json.dumps(payload, ensure_ascii=False), _now(), job_id),+ )+ else:+ conn.execute(+ "UPDATE jobs SET state = 'ready', error = NULL, updated_at = ? WHERE id = ?",+ (_now(), job_id),+ )++ self._write(op)- def fail_job(self, job_id: str, error: str) -> dict[str, Any]:+ def fail_job(self, job_id: str, error: str, *, final: bool = False) -> dict[str, Any]:"""Record a failure: back to ``queued`` while attempts remain, else- ``failed``. Returns the resulting job row so the worker can see whether a- retry is pending."""+ ``failed``; straight to ``failed`` when ``final``, for a failure another+ attempt would only repeat. Returns the resulting job row so the worker can+ see whether a retry is pending."""def op(conn: sqlite3.Connection) -> dict[str, Any]:row = conn.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()if row is None:raise CaseError(f"job '{job_id}' not found")- state = "queued" if row["attempts"] < row["max_attempts"] else "failed"+ retry = not final and row["attempts"] < row["max_attempts"]+ state = "queued" if retry else "failed"conn.execute("UPDATE jobs SET state = ?, error = ?, updated_at = ? WHERE id = ?",(state, error[:2000], _now(), job_id),diff --git a/src/azimut/store/merges.py b/src/azimut/store/merges.pyindex b677b6f..6b26884 100644--- a/src/azimut/store/merges.py+++ b/src/azimut/store/merges.py@@ -311,7 +311,6 @@ def merge_rows("links_dropped": [*({"reason": "loop", "link": link} for link in loops),*({"reason": "twin", "link": link} for link in twins),- *({"reason": "cycle", "link": link} for link in refused),],"images_moved": images_moved,"images_dropped": images_dropped,diff --git a/src/azimut/workspace.py b/src/azimut/workspace.pyindex 8341839..925899e 100644--- a/src/azimut/workspace.py+++ b/src/azimut/workspace.py@@ -545,7 +545,7 @@ class Case(CaseStore):if not parent.is_dir():continuefor path in sorted(parent.iterdir(), key=lambda candidate: candidate.name):- if not layout.is_case(path):+ if not layout.is_case(path) or layout.is_import_scaffold(path):continuecase = cls(path)try:@@ -613,7 +613,9 @@ class Case(CaseStore):and two spellings of "already taken" would drift."""wanted = name.strip().casefold()- for case in cls.list_all():+ # An import under way holds its name too, or a second import of the same+ # bundle would take it while the first is still unpacking.+ for case in cls.list_all(scaffolds=True):if case.get("scratch") or case["id"] == exclude_id:continueif str(case.get("name", "")).strip().casefold() == wanted:@@ -621,7 +623,9 @@ class Case(CaseStore):return False@classmethod- def list_all(cls, *, q: str | None = None, limit: int | None = None) -> list[dict[str, Any]]:+ def list_all(+ cls, *, q: str | None = None, limit: int | None = None, scaffolds: bool = False+ ) -> list[dict[str, Any]]:out: list[dict[str, Any]] = []for parent, scratch in ((config.cases_dir(), False), (config.scratch_dir(), True)):if not parent.is_dir():@@ -629,6 +633,9 @@ class Case(CaseStore):for path in sorted(parent.iterdir()):if not layout.is_case(path):continue+ # What a bundle import is building is not a case until it lands.+ if not scaffolds and layout.is_import_scaffold(path):+ continuecase = cls(path)health = "ok"try:@@ -972,10 +979,16 @@ class Case(CaseStore):return entitydef update_entity(self, entity_id: str, patch: dict[str, Any]) -> dict[str, Any]:+ from .engine import proposals+with self._lock:self._follow_note_rename(entity_id, patch)self._follow_named_artifact_rename(entity_id, patch)- return self._graph().update_entity(entity_id, patch)+ before = self.get_entity(entity_id) if proposals.may_change_reading(patch) else None+ entity = self._graph().update_entity(entity_id, patch)+ if before is not None:+ proposals.on_changed(self, before, entity)+ return entitydef _follow_named_artifact_rename(self, entity_id: str, patch: dict[str, Any]) -> None:@@ -1131,11 +1144,16 @@ class Case(CaseStore):# ancestor of every leaf, so the tree is well-formed on its own.@staticmethod- def _normalize_folder(name: str) -> str:+ def _normalize_folder(name: str, *, existing: bool = False) -> str:parts = [p.strip() for p in str(name).split("/")]parts = [p for p in parts if p]if not parts:raise CaseError("folder name is required")+ # "." and ".." mirror onto a slug that is not their label, and both land on+ # the same directory as their parent. A folder made before this rule can+ # still be renamed away, so only a new name is held to it.+ if not existing and any(not p.strip(".") for p in parts):+ raise CaseError("a folder name needs a letter or a digit")# Folders nest, so without a bound the deepest path in a case is# unbounded too — and note files will mirror this tree on disk.if len(parts) > layout.MAX_FOLDER_DEPTH:@@ -1154,7 +1172,7 @@ class Case(CaseStore):"""from .store import folders as folder_store- source = self._normalize_folder(old)+ source = self._normalize_folder(old, existing=True)target = self._normalize_folder(new)with self._lock:existing = self.list_folders()@@ -1169,7 +1187,7 @@ class Case(CaseStore):raise CaseError("another folder already has that name")for path in existing:if folder_store.in_subtree(path, source):- self._normalize_folder(folder_store.moved(path, source, target))+ self._normalize_folder(folder_store.moved(path, source, target), existing=True)inside = self._graph().entities_in_folder(source)folders = self._graph().rename_folder(source, target)self._follow_refiled(inside)@@ -1258,7 +1276,8 @@ class Case(CaseStore):# -- proposed links ------------------------------------------------------## How far `engine/proposals` has read the case, kept in the manifest so it travels- # with a bundle: `{"at": <newest filing moment read>, "read": [ids filed then]}`.+ # with a bundle: `{"at": <newest filing moment read>, "read": [ids filed then],+ # "again": [ids an edit asked to be read again]}`.# A pass reads only past it, which is what keeps a dropped proposal from coming back.def link_pass(self) -> dict[str, Any] | None:@@ -1271,6 +1290,21 @@ class Case(CaseStore):data["link_pass"] = markself._write_json(data)+ def revisit_links(self, entity_id: str) -> bool:+ """Name an entity the next pass reads again although it was filed before the+ mark, because an edit gave it something to read. False when no pass has run+ yet: the first one reads everything anyway."""+ with self._lock:+ data = self.read()+ mark = data.get("link_pass")+ if not isinstance(mark, dict) or not isinstance(mark.get("at"), str):+ return False+ again = list(mark.get("again") or [])+ if entity_id not in again:+ data["link_pass"] = {**mark, "again": [*again, entity_id]}+ self._write_json(data)+ return True+@property@@ -1401,7 +1435,10 @@ def list_workspace_folders() -> list[dict[str, Any]]:return [{"name": path.name, "state": folder_state(path)}for path in sorted(parent.iterdir(), key=lambda item: item.name.casefold())- if path.is_dir() and not path.name.startswith(".") and not layout.is_case(path)+ if path.is_dir()+ and not path.name.startswith(".")+ and not layout.is_case(path)+ and not layout.is_import_scaffold(path)]@@ -1441,6 +1478,18 @@ def restore_manifest(name: str) -> "Case":})write_readme(path)+ # The link pass keeps its mark in the manifest that was lost, and its proposals in+ # the database that was not. A case showing a pass ran gets a mark dated now, or+ # the next pass would read it all again and bring back every proposal dropped.+ from .engine import proposals++ ran = bool(case.list_jobs(kind=proposals.KIND, state="ready")) or any(+ (link.get("provenance") or {}).get("by") == proposals.BY for link in case.list_links()+ )+ if ran:+ at = _now()+ same_second = [e["id"] for e in case.list_entities() if (e.get("provenance") or {}).get("at") == at]+ case.set_link_pass({"at": at, "read": sorted(same_second)})return case@@ -1462,7 +1511,9 @@ def open_workspace() -> None:config.ensure_workspace()scrapers.activate()Case.migrate_all()- for housekeeping in (Case.cleanup_scratch, bundles.cleanup_uploads, workqueue.recover_all):+ for housekeeping in (+ bundles.sweep_scaffolds, Case.cleanup_scratch, bundles.cleanup_uploads, workqueue.recover_all+ ):try:housekeeping()except Exception: # noqa: BLE001 - see the docstringdiff --git a/tests/test_analyzers.py b/tests/test_analyzers.pyindex 7548f0f..dae535e 100644--- a/tests/test_analyzers.py+++ b/tests/test_analyzers.py@@ -1407,3 +1407,24 @@ def test_band_products_are_padded_and_keyed_apart_from_older_layouts():assert analyzers.product_cache_id(body.b, "surface").endswith(f"~surface~v{analyzers.PRODUCT_VERSION}")assert EDGE == 512 + 2 * analyzers.PADassert WATER == analyzers.SCL_WATER+++def test_a_deleted_area_leaves_its_groups_and_comes_back_with_a_restore(client, scenario):+ """Groups are not guarded like routines: deleting an area they hold is allowed,+ and the group stops counting it rather than listing a dead id."""+ case, body = scenario+ ring = Zone.model_validate(body["zones"][0]).ring()+ shared = client.post(f"/api/cases/{case.id}/analysis/areas", json={+ "name": "Port", "geometry": {"type": "Polygon", "coordinates": [ring + [ring[0]]]},+ }).json()+ client.post(f"/api/cases/{case.id}/analysis/zones", json={"title": "Coast", "area_ids": [shared["id"]]})++ assert client.delete(f"/api/cases/{case.id}/analysis/areas/{shared['id']}").status_code == 200+ [group] = client.get(f"/api/cases/{case.id}/analysis/zones").json()+ assert (group["area_ids"], group["areas"]) == ([], 0)++ trash = client.get(f"/api/cases/{case.id}/trash").json()+ [entry] = trash["groups"]+ assert client.post(f"/api/cases/{case.id}/trash/{entry['id']}/restore").status_code == 200+ [group] = client.get(f"/api/cases/{case.id}/analysis/zones").json()+ assert group["area_ids"] == [shared["id"]]diff --git a/tests/test_binary_smoke.py b/tests/test_binary_smoke.pyindex 531fcc6..05bc321 100644--- a/tests/test_binary_smoke.py+++ b/tests/test_binary_smoke.py@@ -25,6 +25,12 @@ def test_check_application_exercises_health_frontend_and_bundled_ffmpeg(monkeypa"application/json",json.dumps({"available": True, "source": "bundled"}),),+ "/api/settings/ffmpeg/notice": (200, "text/plain", "SHA-256: abc\nGNU GENERAL PUBLIC LICENSE"),+ "/api/settings/bundled": (+ 200,+ "application/json",+ json.dumps({"zones": True, "pdf_fonts": True, "extension": True}),+ ),}seen = []@@ -36,7 +42,37 @@ def test_check_application_exercises_health_frontend_and_bundled_ffmpeg(monkeypamonkeypatch.setattr(smoke_binary, "_request", request)smoke_binary.check_application("http://127.0.0.1:8477")- assert seen == ["/api/health", "/", "/api/settings/ffmpeg"]+ assert seen == [+ "/api/health", "/", "/api/settings/ffmpeg", "/api/settings/ffmpeg/notice", "/api/settings/bundled",+ ]+++ ("path", "answer", "says"),+ [+ ("/api/settings/ffmpeg/notice", (404, "application/json", "{}"), "licence notice"),+ (+ "/api/settings/bundled",+ (200, "application/json", json.dumps({"zones": False, "pdf_fonts": True, "extension": True})),+ "zones",+ ),+ ],+)+def test_check_application_rejects_a_binary_missing_a_silent_part(monkeypatch, path, answer, says):+ """A spec that forgets tzdata, the fonts, the extension or ffmpeg's notice still+ builds a binary that starts. Only asking for them catches it."""+ responses = {+ "/api/health": (200, "application/json", json.dumps({"status": "ok"})),+ "/": (200, "text/html", '<div id="app"></div>'),+ "/api/settings/ffmpeg": (200, "application/json", json.dumps({"available": True, "source": "bundled"})),+ "/api/settings/ffmpeg/notice": (200, "text/plain", "SHA-256: abc GNU"),+ "/api/settings/bundled": (200, "application/json", json.dumps({"zones": True, "pdf_fonts": True, "extension": True})),+ }+ responses[path] = answer+ monkeypatch.setattr(smoke_binary, "_request", lambda url: responses[url.removeprefix("http://127.0.0.1:8477")])++ with pytest.raises(RuntimeError, match=says):+ smoke_binary.check_application("http://127.0.0.1:8477")def test_check_application_rejects_path_ffmpeg(monkeypatch):diff --git a/tests/test_bundles.py b/tests/test_bundles.pyindex 4e18f16..643aaa3 100644--- a/tests/test_bundles.py+++ b/tests/test_bundles.py@@ -234,6 +234,97 @@ def test_sealed_chunks_detect_truncation_before_any_case_swap(bundle_case):assert destination.list_entities() == []+def test_an_export_with_no_room_fails_once_and_says_why(bundle_case, monkeypatch):+ """It read "BundleError: not enough free space…" after three identical attempts."""+ tries = []++ def full(target, total):+ tries.append(target)+ raise bundles.BundleError("not enough free space to export this case while keeping a disk safety reserve")++ monkeypatch.setattr(bundles, "_require_export_space", full)+ job = bundles.queue_export(bundle_case)+ workqueue.drain(bundle_case)++ settled = bundle_case.get_job(job["id"])+ assert settled["state"] == "failed"+ assert settled["error"] == "not enough free space to export this case while keeping a disk safety reserve"+ assert len(tries) == 1+++def _names():+ return sorted(row["name"] for row in Case.list_all())+++def test_an_import_is_out_of_the_switcher_until_it_lands(bundle_case, monkeypatch):+ """The shell and the staging folder both carry a manifest. Listed, they were two+ cases named "Source case (imported)" for as long as the bundle took to unpack."""+ exported = bundles.export_case(bundle_case)+ seen = {}+ real = bundles._prepare_import_database++ def midway(*args, **kwargs):+ seen["names"] = _names()+ seen["scaffolds"] = sorted(+ path.name for path in config.cases_dir().iterdir() if layout.is_import_scaffold(path)+ )+ return real(*args, **kwargs)++ monkeypatch.setattr(bundles, "_prepare_import_database", midway)+ imported, _ = bundles.queue_import(exported)+ workqueue.drain(imported)++ assert seen["names"] == ["Source case"]+ assert seen["scaffolds"] == [imported.id, f"{imported.id}.incoming"]+ assert _names() == ["Source case", "Source case (imported)"]+ assert not layout.is_import_scaffold(imported.path)+ assert [path.name for path in config.cases_dir().iterdir() if layout.is_import_scaffold(path)] == []+++def test_a_start_removes_what_an_interrupted_import_left(bundle_case):+ """Killed mid-import (the console closed on a big bundle), the empty shell and+ the half-extracted staging folder stayed, and the switcher listed both."""+ shell = bundles.create_import_case("Kyiv strike")+ staging = shell.path.with_name(f"{shell.id}.incoming")+ shutil.copytree(bundle_case.path, staging)+ layout.mark_import_scaffold(staging)+ set_aside = shell.path.with_name(f"{shell.id}.import-shell-{'0' * 32}")+ shutil.copytree(shell.path, set_aside)+ assert _names() == ["Source case"]++ assert bundles.sweep_scaffolds() == 3+ assert sorted(path.name for path in config.cases_dir().iterdir() if path.is_dir()) == [+ bundle_case.path.name+ ]+ assert Case.open(bundle_case.id).list_entities()+++def test_the_sweep_leaves_an_import_under_way_alone(bundle_case):+ exported = bundles.export_case(bundle_case)+ imported, _ = bundles.queue_import(exported)++ assert bundles.sweep_scaffolds() == 0+ assert imported.path.is_dir()++ workqueue.drain(imported)+ assert Case.open(imported.id).list_entities()+++def test_a_failed_import_gives_back_the_destination_its_caller_made(bundle_case, monkeypatch):+ exported = bundles.export_case(bundle_case)+ destination = Case.create("Received")++ def broken(*args, **kwargs):+ raise bundles.BundleError("the bundle does not contain a complete case")++ monkeypatch.setattr(bundles, "_prepare_import_database", broken)+ with pytest.raises(bundles.BundleError):+ bundles.import_into(destination, exported)++ assert not layout.is_import_scaffold(destination.path)+ assert "Received" in _names()++def test_importing_the_same_bundle_twice_names_the_second_destination_apart(bundle_case):"""`Case.create` numbers a taken folder by itself now, so the distinct namethe switcher shows has to be asked for on the name, not fallen into."""diff --git a/tests/test_detect_rules.py b/tests/test_detect_rules.pyindex 82ee2db..49a7435 100644--- a/tests/test_detect_rules.py+++ b/tests/test_detect_rules.py@@ -27,7 +27,6 @@ from azimut.engine.analysis_models import (Recipe,Rule,RunInput,- frames_for,is_radar,is_single,recipe_products,@@ -206,12 +205,10 @@ def test_what_a_recipe_reads_follows_from_its_rules():change = recipe(LOSS, GREEN_BEFORE)assert not is_single(change) and not is_radar(change)assert recipe_products(change) == ["bands-B04-B08"]- assert frames_for(change) == 4 # picture and one product, on each datepresent = recipe({"measure": "band", "band": "B12", "on": "b", "op": "ge", "value": 0.3},{"measure": "index", "index": "bsi", "on": "b", "op": "ge", "value": 0})assert is_single(present)assert recipe_products(present) == ["bands-B02-B04-B08", "bands-B11-B12"]- assert frames_for(present) == 3 # one date: its picture and two productsclasses = recipe({"measure": "class", "classes": ["water"], "on": "b", "op": "is"})assert recipe_products(classes) == ["bands-B08"]radar = recipe({"measure": "radar", "polarisation": "ratio", "on": "change", "op": "moved", "value": 3})diff --git a/tests/test_errors.py b/tests/test_errors.pynew file mode 100644index 0000000..ccfdd26--- /dev/null+++ b/tests/test_errors.py@@ -0,0 +1,85 @@+"""What a failure says on the page: one clause, never the exception's own text."""++from __future__ import annotations++import errno+import subprocess+import time+import zipfile++import httpx+import pytest+from PIL import UnidentifiedImageError++from azimut import errors, jobs+from azimut.engine import inspect as inspect_engine+from azimut.workspace import CaseError+++ ("exc", "said"),+ [+ (PermissionError(errno.EACCES, "Permission denied", "/home/someone/case"), "the system refused access to that file or folder"),+ (FileNotFoundError(errno.ENOENT, "No such file", "/tmp/x"), "a file it needed is no longer there"),+ (OSError(errno.ENOSPC, "No space left on device"), "the disk is full"),+ (UnidentifiedImageError("cannot identify image file <_io.BytesIO object at 0x7f>"), "this file is not a picture Azimut can read"),+ (zipfile.BadZipFile("File is not a zip file"), "this file is not a readable archive"),+ (subprocess.TimeoutExpired(["ffmpeg"], 60), "it took too long and was stopped"),+ (httpx.ConnectError("[Errno -2] Name or service not known"), "the service could not be reached"),+ ],+)+def test_system_failures_become_a_clause_without_their_text(exc, said):+ assert errors.explain(exc) == said+++def test_the_apps_own_sentences_pass_through():+ assert errors.explain(CaseError("a folder name needs a letter or a digit.")) == "a folder name needs a letter or a digit"++[email protected]("exc", [KeyError("survivor"), TypeError("'NoneType' object is not subscriptable")])+def test_pythons_own_mistakes_never_reach_the_page(exc):+ said = errors.explain(exc)+ assert said == errors.UNEXPECTED+ assert "NoneType" not in said and "survivor" not in said+++def test_a_refused_body_reads_like_a_form(client):+ case_id = client.post("/api/cases", json={"name": "Errors"}).json()["id"]+ r = client.post(f"/api/cases/{case_id}/analysis-views", json={"name": "x" * 500})+ assert r.status_code == 422+ detail = r.json()["detail"]+ assert isinstance(detail, str)+ assert "String should" not in detail and "loc" not in detail+++def test_the_validation_sentence_names_the_field_and_the_bound():+ said = errors.validation_sentence([+ {"type": "string_too_long", "loc": ("body", "name"), "msg": "String should have at most 80 characters", "ctx": {"max_length": 80}},+ {"type": "less_than_equal", "loc": ("body", "lat"), "msg": "Input should be less than or equal to 90", "ctx": {"le": 90}},+ {"type": "missing", "loc": ("body", "case_id"), "msg": "Field required"},+ ])+ assert said == "Name is too long (80 characters at most); Lat must be at most 90; Case id is required"+++def test_a_background_job_reports_a_clause(monkeypatch):+ def work(progress):+ raise PermissionError(errno.EACCES, "Permission denied", "/home/someone/secret")++ job_id = jobs.start("test", work)+ for _ in range(200):+ state = jobs.get(job_id)+ if state and state["status"] != "running":+ break+ time.sleep(0.01)+ assert state["status"] == "error"+ assert state["error"] == "the system refused access to that file or folder"+++def test_ffmpeg_says_its_last_word_without_the_path():+ stderr = (+ b"ffmpeg version N-1 Copyright (c) 2000-2026\n configuration: --enable-gpl\n"+ b"/home/someone/case/media/clip.mp4: Invalid data found when processing input\n"+ )+ exc = inspect_engine.ffmpeg_failed("scan", stderr)+ assert str(exc) == "ffmpeg could not scan this video (Invalid data found when processing input)"+ assert inspect_engine.ffmpeg_failed("enhance", b"").args[0] == "ffmpeg could not enhance this video"diff --git a/tests/test_folder_adoption.py b/tests/test_folder_adoption.pyindex dd4ed18..154a8e6 100644--- a/tests/test_folder_adoption.py+++ b/tests/test_folder_adoption.py@@ -166,3 +166,34 @@ def test_a_folder_is_not_adopted_without_being_asked(client):assert client.get("/api/cases").json() == []assert not layout.tool_root(config.cases_dir() / "Parked here").exists()+++def test_a_recovered_case_that_had_link_passes_does_not_propose_its_dropped_links_again(client, monkeypatch):+ """The pass's mark lived in the lost manifest. Without one, the next pass would+ read the whole case and bring back every proposal the analyst dropped."""+ from azimut.engine import proposals, workqueue++ monkeypatch.setattr(workqueue, "start_workers", False)+ case_id = client.post("/api/cases", json={"name": "Lost mark"}).json()["id"]+ for label, lat in (("A", 45.0300), ("B", 45.0310)):+ client.post(f"/api/cases/{case_id}/entities", json={"type": "place", "label": label, "attrs": {"lat": lat, "lon": 15.74}})+ case = Case.open(case_id)+ workqueue.drain(case)+ [dropped] = [link for link in case.list_links() if proposals.unreviewed(link)]+ case.remove_link(dropped["id"])+ layout.manifest(config.cases_dir() / case_id).unlink()++ assert client.post("/api/workspace/folders/recover", json={"name": case_id}).status_code == 200++ assert Case.open(case_id).link_pass() is not None+ assert proposals.propose(Case.open(case_id))["sites"] == 0+++def test_a_recovered_case_that_never_had_a_pass_keeps_no_mark(client):+ case_id = client.post("/api/cases", json={"name": "No pass"}).json()["id"]+ client.post(f"/api/cases/{case_id}/notes", json={"title": "Lead", "content": "Body"})+ layout.manifest(config.cases_dir() / case_id).unlink()++ client.post("/api/workspace/folders/recover", json={"name": case_id})++ assert Case.open(case_id).link_pass() is Nonediff --git a/tests/test_folders.py b/tests/test_folders.pyindex 695dafe..885c5ed 100644--- a/tests/test_folders.py+++ b/tests/test_folders.py@@ -7,6 +7,7 @@ import sqlite3from contextlib import closingimport graph_read+import pytestfrom PIL import Imagefrom azimut.engine import bundles@@ -272,3 +273,20 @@ def test_a_bundle_carries_the_work_folder(client):destination = Case.create(bundles.imported_name("Travels"))result = bundles.import_into(destination, bundles.export_case(source))assert Case.open(result["case_id"]).work_folder() == "Airbase"++[email protected]("name", ["..", ".", "Airbase/..", "./North", "..."])+def test_a_folder_name_made_only_of_dots_is_refused(client, name):+ """`..` would mirror onto its parent's directory under a label that is not its+ own, so it is refused wherever a new folder name comes in."""+ cid = _case(client)+ client.post(f"/api/cases/{cid}/folders", json={"name": "Airbase"})+ assert client.post(f"/api/cases/{cid}/folders", json={"name": name}).status_code in (400, 409, 422)+ res = client.post(f"/api/cases/{cid}/folders/rename", json={"source": "Airbase", "target": name})+ assert res.status_code in (400, 409, 422)+ assert client.get(f"/api/cases/{cid}/folders").json() == ["Airbase"]+++def test_a_folder_named_with_dots_and_letters_is_kept(client):+ cid = _case(client)+ assert client.post(f"/api/cases/{cid}/folders", json={"name": "v1.2"}).status_code == 200diff --git a/tests/test_launcher.py b/tests/test_launcher.pyindex db5197d..1813ded 100644--- a/tests/test_launcher.py+++ b/tests/test_launcher.py@@ -55,9 +55,87 @@ def test_serve_opens_the_browser_tab_when_ready(monkeypatch):def test_cli_forwards_arguments_to_serve(monkeypatch):captured = {}+ monkeypatch.setattr(cli, "choose_port", lambda port: (port, False))monkeypatch.setattr(cli, "serve", lambda port, open_browser: captured.update(port=port, open_browser=open_browser))monkeypatch.setattr(sys, "argv", ["azimut", "--port", "9999", "--no-browser"])cli.main()assert captured == {"port": 9999, "open_browser": False}+++def test_cli_sends_a_second_start_to_the_running_tab(monkeypatch, capsys):+ """Started twice, Azimut opens the first one's tab instead of dying on a bind+ error in a console that closes before anyone reads it."""+ opened = []+ monkeypatch.setattr(cli, "choose_port", lambda port: (port, True))+ monkeypatch.setattr(cli, "serve", lambda *a, **k: (_ for _ in ()).throw(AssertionError("served twice")))+ monkeypatch.setattr(cli.webbrowser, "open", opened.append)+ monkeypatch.setattr(sys, "argv", ["azimut", "--port", "9999"])+ cli.main()+ assert opened == ["http://127.0.0.1:9999"]+ assert "already running" in capsys.readouterr().out+++def test_cli_moves_to_the_next_port_when_another_program_holds_it(monkeypatch, capsys):+ captured = {}+ monkeypatch.setattr(cli, "choose_port", lambda port: (port + 1, False))+ monkeypatch.setattr(cli, "serve", lambda port, open_browser: captured.update(port=port))+ monkeypatch.setattr(sys, "argv", ["azimut", "--port", "9999", "--no-browser"])+ cli.main()+ assert captured == {"port": 10000}+ assert "in use by another program" in capsys.readouterr().out+++def test_choose_port_tells_azimut_from_another_program():+ import socket+ import threading+ from http.server import BaseHTTPRequestHandler, HTTPServer++ class Health(BaseHTTPRequestHandler):+ body = b'{"status": "ok", "version": "0.0.0"}'++ def do_GET(self):+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.end_headers()+ self.wfile.write(self.body)++ def log_message(self, *args):+ pass++ azimut = HTTPServer(("127.0.0.1", 0), Health)+ threading.Thread(target=azimut.serve_forever, daemon=True).start()+ try:+ assert launcher.choose_port(azimut.server_port) == (azimut.server_port, True)+ finally:+ azimut.shutdown()+ azimut.server_close()++ other = socket.socket()+ other.bind(("127.0.0.1", 0))+ other.listen(1)+ try:+ port = other.getsockname()[1]+ chosen, running = launcher.choose_port(port)+ assert running is False and chosen != port+ finally:+ other.close()+++def test_a_second_start_finds_the_azimut_holding_the_workspace_on_another_port(monkeypatch):+ """The first start moved to a free port while another program held 8477, which+ has let go since. Asking 8477 alone would start a second server, and that one+ would find the workspace taken."""+ import socket++ from azimut.engine import workspacelock++ monkeypatch.setattr(workspacelock, "holder", lambda root=None: {"host": socket.gethostname(), "port": 8478})+ monkeypatch.setattr(launcher, "_azimut_answers", lambda port: port == 8478)+ assert launcher.choose_port(8477) == (8478, True)++ # Another machine holding a shared folder is the server's to explain, not ours.+ monkeypatch.setattr(workspacelock, "holder", lambda root=None: {"host": "elsewhere", "port": 8478})+ monkeypatch.setattr(launcher, "_port_is_free", lambda port: True)+ assert launcher.choose_port(8477) == (8477, False)diff --git a/tests/test_merges.py b/tests/test_merges.pyindex bd6b2c1..50bed69 100644--- a/tests/test_merges.py+++ b/tests/test_merges.py@@ -313,3 +313,21 @@ def test_interrupted_undo_replays_once_on_reopen_and_blocks_bundle(client, case,assert case.get_merge(result['merge']) is NoneCase.open(case.id)assert json.loads(path.read_text()) == before+++def test_opening_a_case_parses_only_merges_with_work_left(client, case, monkeypatch):+ """Merge records stay for Undo and every request opens the case, so finished+ merges must cost the open nothing, however many there are."""+ keep = subject(case, 'Keep')+ for n in range(4):+ post(client, case, keep, subject(case, f'Twin {n}'))+ parsed = []+ real = json.loads++ def counting(text, *args, **kwargs):+ parsed.append(text)+ return real(text, *args, **kwargs)++ monkeypatch.setattr(json, 'loads', counting)+ assert case.pending_merge_work() == []+ assert parsed == []diff --git a/tests/test_proof_import.py b/tests/test_proof_import.pyindex 3a46493..54cba3e 100644--- a/tests/test_proof_import.py+++ b/tests/test_proof_import.py@@ -546,7 +546,7 @@ def test_a_video_cannot_be_the_proof_s_picture(client):staged = media_engine.stage_descriptor(_write(case_of(case_id), token, "clip.mp4", b"video-bytes"), {"type": "manual"})- import_engine.fill_slot(case_of(case_id), token, "panel", staged)+ import_engine.fill_files(case_of(case_id), token, "panel", [staged])report = preview(client, case_id, token)assert report["ready"] is Falseassert any("pictures" in line for line in report["blocking"])diff --git a/tests/test_proposals.py b/tests/test_proposals.pyindex fc03d2c..f9b4e7e 100644--- a/tests/test_proposals.py+++ b/tests/test_proposals.py@@ -515,3 +515,127 @@ def test_the_graph_names_a_coordinate_point_and_leaves_a_named_one(client):assert nodes[coords]["caption"] == "Caracas"assert nodes[coords]["label"] == "10.490000, -66.880000"assert "caption" not in nodes[named]+++# -- edited after filing -----------------------------------------------------------------+++def test_a_place_geolocated_after_filing_is_read_again(client):+ """Filed first, located later: the usual order. The pass reads past a mark set by+ filing time, so the edit itself has to name the place for the next pass."""+ case_id = make_case(client)+ add(client, case_id, "place", "A", lat=NEAR[0][0], lon=NEAR[0][1])+ unplaced = add(client, case_id, "place", "Hangar")["id"]+ case = case_of(case_id)+ assert proposals.propose(case)["sites"] == 0++ response = client.patch(+ f"/api/cases/{case_id}/entities/{unplaced}", json={"attrs": {"lat": NEAR[1][0], "lon": NEAR[1][1]}}+ )+ assert response.status_code == 200, response.text+ assert case.list_jobs(kind=proposals.KIND, state="queued")++ assert proposals.propose(case)["sites"] == 1+ assert "again" not in case.link_pass()+ # Read once more, then never again for that edit.+ assert proposals.propose(case)["sites"] == 0+++def test_an_edit_that_gives_nothing_to_read_queues_no_pass(client):+ case_id = make_case(client)+ place = add(client, case_id, "place", "A", lat=NEAR[0][0], lon=NEAR[0][1])["id"]+ case = case_of(case_id)+ proposals.propose(case)+ for job in case.list_jobs():+ case.complete_job(job["id"])++ client.patch(f"/api/cases/{case_id}/entities/{place}", json={"label": "Renamed"})++ assert not case.list_jobs(kind=proposals.KIND, state="queued")+ assert "again" not in case.link_pass()+++def test_a_bookmark_given_its_address_later_is_read_for_its_account(client):+ case_id = make_case(client)+ bookmark = add(client, case_id, "bookmark", "Post")["id"]+ case = case_of(case_id)+ proposals.propose(case)++ client.patch(f"/api/cases/{case_id}/entities/{bookmark}", json={"attrs": {"url": "https://t.me/rybar/61234"}})+ proposals.propose(case)++ [link] = links_of_type(case, "posted")+ assert link["to"] == bookmark+++def _settled(case):+ for job in case.list_jobs(kind=proposals.KIND, state="queued"):+ case.complete_job(job["id"])+++def test_a_point_sent_back_unchanged_does_not_bring_back_a_dropped_proposal(client):+ """A second Promote of a places sheet resends every point it holds. Reading those+ places again would propose once more what the analyst dropped; a real move is new."""+ case_id = make_case(client)+ add(client, case_id, "place", "A", lat=NEAR[0][0], lon=NEAR[0][1])+ second = add(client, case_id, "place", "B", lat=NEAR[1][0], lon=NEAR[1][1])["id"]+ case = case_of(case_id)+ assert proposals.propose(case)["sites"] == 1+ [link] = links_of_type(case, "same-site-as")+ assert client.delete(f"/api/cases/{case_id}/proposals/{link['id']}").status_code == 200+ _settled(case)++ resent = {"attrs": {"lat": NEAR[1][0], "lon": NEAR[1][1], "notes": "checked"}}+ assert client.patch(f"/api/cases/{case_id}/entities/{second}", json=resent).status_code == 200+ assert not case.list_jobs(kind=proposals.KIND, state="queued")+ assert "again" not in case.link_pass()+ assert proposals.propose(case)["sites"] == 0++ moved = {"attrs": {"lat": NEAR[2][0], "lon": NEAR[2][1]}}+ assert client.patch(f"/api/cases/{case_id}/entities/{second}", json=moved).status_code == 200+ assert case.list_jobs(kind=proposals.KIND, state="queued")+ assert proposals.propose(case)["sites"] == 1+++def test_a_file_renamed_with_its_source_unchanged_keeps_a_dropped_proposal_dropped(client):+ """Details saves a file's stated source with its title, changed or not."""+ url = "https://x.com/BashaReport/status/1"+ case_id = make_case(client)+ item = client.post(+ f"/api/cases/{case_id}/media/upload",+ files={"file": ("shot.png", io.BytesIO(png(3)), "image/png")},+ data={"source_url": url},+ ).json()["item"]+ case = case_of(case_id)+ assert proposals.propose(case)["posted"] == 1+ [posted] = links_of_type(case, "posted")+ assert client.delete(f"/api/cases/{case_id}/proposals/{posted['id']}").status_code == 200+ _settled(case)++ saved = {"path": item["path"], "title": "Renamed", "notes": "", "source_url": url}+ assert client.patch(f"/api/cases/{case_id}/media", json=saved).status_code == 200++ assert not case.list_jobs(kind=proposals.KIND, state="queued")+ assert proposals.propose(case) == {"accounts": 0, "posted": 0, "sites": 0}+ assert not links_of_type(case, "posted")+++def test_the_waiting_proposals_are_read_without_walking_the_graph(client, monkeypatch):+ """The panel reads this on every case revision while Graph is mounted, so it is+ counted and listed in SQL, never by materialising every link."""+ from azimut.sqlite_backend import SqliteCase++ case_id = make_case(client)+ for n, (lat, lon) in enumerate(NEAR):+ add(client, case_id, "place", f"P{n}", lat=lat, lon=lon)+ case = case_of(case_id)+ download(case, "https://x.com/BashaReport/status/1", 1)+ proposals.propose(case)++ def whole_graph(*args, **kwargs):+ raise AssertionError("the proposals read walked every link")++ monkeypatch.setattr(SqliteCase, "list_links", whole_graph)+ body = client.get(f"/api/cases/{case_id}/proposals").json()+ assert body["pending"] == {"accounts": 1, "posted": 1, "sites": 2}+ assert body["listed"] == 3diff --git a/tests/test_radar_detect.py b/tests/test_radar_detect.pyindex 64e103c..80e17f4 100644--- a/tests/test_radar_detect.py+++ b/tests/test_radar_detect.py@@ -562,8 +562,6 @@ def test_a_radar_variant_draws_one_pass_and_names_it(monkeypatch, tmp_path):"sentinel1~../etc"):with pytest.raises(KeyError):tiles.get_provider(bad)- assert sentinel.radar_variant_id("2026-05-14", "05:42:10") == "sentinel1~2026-05-14~054210"- assert sentinel.radar_variant_id() == "sentinel1"def test_radar_difference_needs_two_passes_of_one_track(client):diff --git a/tests/test_release_gate.py b/tests/test_release_gate.pyindex 8afca90..a41dcf9 100644--- a/tests/test_release_gate.py+++ b/tests/test_release_gate.py@@ -200,6 +200,17 @@ def test_pdf_font_licenses_are_complete_and_packaged():assert 'collect_data_files("azimut")' in spec+def test_the_binary_carries_the_scrapers_metadata():+ """`engine/scrapers.py` reads the version a build ships from its metadata, never by+ importing it, to decide whether a copy updated into the workspace is newer.+ collect_submodules ships the modules without it, so the spec copies it by name."""+ from azimut.engine import scrapers++ spec = (Path(__file__).resolve().parent.parent / "packaging" / "azimut.spec").read_text()+ for dist in scrapers.SCRAPERS:+ assert f'copy_metadata("{dist}")' in spec++def test_storage_and_jobs_add_no_new_runtime_dependency():"""The store, the durable queue and the thumbnail worker stay on the standardlibrary plus deps already declared — nothing that would need a new wheel ondiff --git a/tests/test_scrapers.py b/tests/test_scrapers.pyindex 647c0f9..f4cea93 100644--- a/tests/test_scrapers.py+++ b/tests/test_scrapers.py@@ -344,3 +344,31 @@ def test_activate_is_idempotent(monkeypatch, fake_dist):scrapers.activate()finders = [f for f in sys.meta_path if isinstance(f, scrapers._RuntimeFinder)]assert len(finders) == 1+++def _runtime_copy(version: str) -> None:+ root = scrapers.dist_dir(DIST)+ (root / MODULE).mkdir(parents=True)+ (root / MODULE / "__init__.py").write_text(f'__version__ = "{version}"\n', encoding="utf-8")+ (root / f"{MODULE}-{version}.dist-info").mkdir()+++ ("bundled", "source", "shadowed"),+ [("2026.9.9", "bundled", {}), ("2025.12.31", "runtime", {MODULE: "2026.1.1"})],+)+def test_a_runtime_copy_wins_only_when_newer_than_the_build(monkeypatch, fake_dist, bundled, source, shadowed):+ """An update pressed under an older build must not shadow the newer scraper the+ next build ships: the workspace outlives the program."""+ _runtime_copy("2026.1.1")+ real = importlib.metadata.version+ monkeypatch.setattr(+ scrapers.importlib.metadata, "version", lambda dist: bundled if dist == DIST else real(dist)+ )+ assert scrapers.active_version(DIST) == ("2026.1.1" if source == "runtime" else bundled, source)+ assert scrapers.activate() == shadowed+++def test_a_frozen_build_without_metadata_keeps_the_runtime_copy(fake_dist):+ _runtime_copy("2026.1.1")+ assert scrapers.active_version(DIST) == ("2026.1.1", "runtime")diff --git a/tests/test_server_guard.py b/tests/test_server_guard.pyindex 1e9197c..4554fb6 100644--- a/tests/test_server_guard.py+++ b/tests/test_server_guard.py@@ -110,3 +110,21 @@ def test_a_foreign_tile_request_spends_nothing_and_reaches_no_provider(client, massert r.status_code == 403assert reached == []assert config.load_settings().get("usage") == before++[email protected]("path", ["/api/docs", "/api/redoc", "/openapi.json", "/api/openapi.json"])+def test_the_api_docs_are_not_served(client, path):+ """The docs page loads Swagger UI from a CDN onto this origin, where it could+ read every route, keys included. Nothing in the app links to it."""+ r = client.get(path)+ assert r.status_code in (404, 200)+ assert "swagger" not in r.text.lower()+ assert "openapi" not in r.headers.get("content-type", "")++[email protected]("method", ["get", "post", "delete"])+def test_an_unknown_api_path_is_a_json_404_not_the_page(client, method):+ r = getattr(client, method)("/api/no-such-route/here")+ assert r.status_code == 404+ assert r.headers["content-type"].startswith("application/json")+ assert r.json() == {"detail": "Not Found"}diff --git a/tests/test_settings_api.py b/tests/test_settings_api.pyindex 18b77f4..7dce754 100644--- a/tests/test_settings_api.py+++ b/tests/test_settings_api.py@@ -1,5 +1,7 @@"""Settings API: API keys management, key tests, usage counters (all offline)."""+import json+import httpximport pytest@@ -27,6 +29,7 @@ def test_ffmpeg_info_reports_bundled_copy(client, monkeypatch):"path": "/opt/azimut/ffmpeg","source": "bundled","version": "n7.1",+ "notice": False,}@@ -35,7 +38,7 @@ def test_ffmpeg_info_reports_missing(client, monkeypatch):monkeypatch.setattr(ffmpeg, "ffmpeg_path", lambda: None)body = client.get("/api/settings/ffmpeg").json()- assert body == {"available": False, "path": None, "source": None, "version": None}+ assert body == {"available": False, "path": None, "source": None, "version": None, "notice": False}def test_put_keys_lights_up_keyed_providers(client):@@ -390,7 +393,10 @@ def test_test_key_mapbox_ok_and_failure(client, monkeypatch):monkeypatch.setattr(httpx, "get", unauthorized)result = client.post("/api/settings/keys/mapbox/test").json()assert result["ok"] is False- assert result["detail"]+ assert result["detail"] == "the provider answered 401"+ # httpx puts the URL, token included, in its message: none of it may reach+ # the page, settings.json or the backup that carries provider_status.+ assert "pk.abc" not in json.dumps(client.get("/api/settings").json()["provider_status"])def test_test_key_google_mints_a_session(client, monkeypatch):@@ -433,7 +439,14 @@ def test_test_key_sentinelhub_reports_the_services_own_words(client, monkeypatchmonkeypatch.setattr(httpx, "get", bad)result = client.post("/api/settings/keys/sentinelhub/test").json()assert result["ok"] is False- assert result["detail"] == "Invalid instance id: inst-uuid"+ assert result["detail"] == "Invalid instance id: <key>"++ def forbidden(url, **kwargs):+ return httpx.Response(403, request=httpx.Request("GET", url))++ monkeypatch.setattr(httpx, "get", forbidden)+ result = client.post("/api/settings/keys/sentinelhub/test").json()+ assert result == {"ok": False, "detail": "the provider answered 403"}def test_sentinel2_tile_proxy_offsets_the_matrix_and_counts_tiles(client, monkeypatch):@@ -1151,3 +1164,49 @@ def test_detect_prefs_keep_the_place_names(client):saved = client.put("/api/settings/prefs", json={"detect_view": {"overlays": everything}})assert saved.status_code == 200, saved.textassert saved.json()["detect_view"]["overlays"] == everything+++def test_a_source_run_has_every_part_a_binary_can_lose(client):+ """What the release smoke test asks a binary: zones, PDF faces, the extension,+ the scrapers' metadata."""+ assert client.get("/api/settings/bundled").json() == {+ "zones": True, "pdf_fonts": True, "extension": True, "scrapers": True,+ }+++def test_a_build_without_the_scrapers_metadata_is_reported(monkeypatch):+ """PyInstaller collects the scraper modules but not their .dist-info. Without it+ a stale workspace copy shadows the scraper the build ships, so the smoke test fails."""+ import importlib.metadata++ from azimut.engine import diagnostics++ def missing(dist):+ raise importlib.metadata.PackageNotFoundError(dist)++ monkeypatch.setattr(importlib.metadata, "version", missing)+ assert diagnostics.bundled_parts()["scrapers"] is False+++def test_the_ffmpeg_notice_is_served_only_for_a_bundled_build(client, monkeypatch, tmp_path):+ import sys++ assert client.get("/api/settings/ffmpeg/notice").status_code == 404+ licenses = tmp_path / "ffmpeg-licenses"+ licenses.mkdir()+ (licenses / "NOTICE.txt").write_text("Build: N-1\nSHA-256: abc\n", encoding="utf-8")+ (licenses / "GPL-3.0.txt").write_text("GNU GENERAL PUBLIC LICENSE\n", encoding="utf-8")+ monkeypatch.setattr(sys, "_MEIPASS", str(tmp_path), raising=False)++ r = client.get("/api/settings/ffmpeg/notice")+ assert r.status_code == 200+ assert r.text.startswith("Build: N-1") and "===== GPL-3.0.txt =====" in r.text+++def test_a_bug_report_names_a_missing_bundled_part(monkeypatch):+ from azimut.engine import diagnostics++ monkeypatch.setattr(diagnostics, "_environment", None)+ monkeypatch.setattr(diagnostics, "bundled_parts", lambda: {"zones": False, "pdf_fonts": True, "extension": True})+ assert diagnostics.environment()["Missing"] == "zones"+ monkeypatch.setattr(diagnostics, "_environment", None)diff --git a/tests/test_settings_backup.py b/tests/test_settings_backup.pyindex 1daa5d9..020af52 100644--- a/tests/test_settings_backup.py+++ b/tests/test_settings_backup.py@@ -400,3 +400,19 @@ def test_a_backup_naming_the_retired_labels_layer_still_imports(client):)assert res.status_code == 200, res.textassert client.get("/api/settings").json()["detect_view"]["overlays"] == ["roads"]+++def test_a_backup_from_an_unpaired_machine_keeps_this_ones_pairing(client):+ """The machine the backup came from never revealed its token. Restoring it on a+ paired machine must leave that pairing alone, or the extension silently stops."""+ token = client.post("/api/settings/ingest-token").json()["ingest_token"]+ r = client.post("/api/settings/import", json={"settings": {"ingest_token": "", "units": "imperial"}})+ assert r.status_code == 200, r.text+ assert "ingest_token" not in r.json()["imported"]+ assert client.get("/api/settings").json()["ingest_token"] == token+++def test_an_unpaired_machine_exports_no_empty_token(client):+ assert "ingest_token" not in client.get("/api/settings/export").json()["settings"]+ token = client.post("/api/settings/ingest-token").json()["ingest_token"]+ assert client.get("/api/settings/export").json()["settings"]["ingest_token"] == tokendiff --git a/tests/test_sheet_files_worklist.py b/tests/test_sheet_files_worklist.pyindex abbeaf9..e9a7b52 100644--- a/tests/test_sheet_files_worklist.py+++ b/tests/test_sheet_files_worklist.py@@ -226,6 +226,20 @@ def test_the_preview_counts_and_finds_the_worklist_already_built(client):assert after["sheet"] == made["id"]+def test_the_preview_finds_its_sheet_without_reading_the_whole_case(client, monkeypatch):+ """The Sheet home asks for this on every visit, so it pages sheets by type."""+ from azimut.sqlite_backend import SqliteCase++ case_id, *_ = a_scene(client)+ made = build(client, case_id)++ def whole_case(*args, **kwargs):+ raise AssertionError("files_preview read every entity")++ monkeypatch.setattr(SqliteCase, "list_entities", whole_case)+ assert client.get(f"/api/cases/{case_id}/sheets/from-case/files").json()["sheet"] == made["id"]++def test_the_list_says_what_each_sheet_is_and_how_far_along(client):case_id, *_ = a_scene(client)built = build(client, case_id)diff --git a/tests/test_updates.py b/tests/test_updates.pyindex e8970e2..8da4175 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.1"-EXTENSION_PAYLOAD = "b3bcdad2bbc30c451e7ab9388dbfa26b5f7151f5b95fc89e868223a7893dd4f2"+EXTENSION_PAYLOAD = "39ae74f8fbe3eee32a95f5c73816bb6c6a4dd424a26004a48e527261325227c6"# The digest itself lives in engine/extinstall.py, because the update button# compares the same number: what the app ships against what the installed folderdiff --git a/tests/test_vendor_ffmpeg.py b/tests/test_vendor_ffmpeg.pyindex 30e97fe..fe68b26 100644--- a/tests/test_vendor_ffmpeg.py+++ b/tests/test_vendor_ffmpeg.py@@ -74,6 +74,21 @@ def test_vendor_verifies_and_extracts_exact_members(tmp_path, monkeypatch):assert provenance["target"] == "test"assert json.loads((output / "ffmpeg-provenance.json").read_text()) == provenance+ # A GPL build travels with its licence and a way to its source, inside the binary.+ licenses = output / "ffmpeg-licenses"+ notice = (licenses / "NOTICE.txt").read_text(encoding="utf-8")+ assert ffmpeg_archive.as_uri() in notice and ffmpeg_hash in notice+ assert "https://ffmpeg.org/download.html#get-sources" in notice+ assert "ffmpeg -L" in notice # the fixture cannot run, so the notice says how to ask+ assert {p.name for p in licenses.glob("*.txt")} >= {"GPL-2.0.txt", "GPL-3.0.txt", "LGPL-2.1.txt"}+ assert "GNU GENERAL PUBLIC LICENSE" in (licenses / "GPL-3.0.txt").read_text(encoding="utf-8")+++def test_every_pinned_builder_names_where_its_build_scripts_live():+ for archives in vendor_ffmpeg.ARTIFACTS.values():+ for archive in archives:+ assert vendor_ffmpeg.BUILD_SOURCES[archive.source].startswith("https://")+def test_vendor_rejects_a_bad_digest_without_installing_tools(tmp_path, monkeypatch):archive_path = tmp_path / "ffmpeg.zip"diff --git a/tests/test_workqueue.py b/tests/test_workqueue.pyindex eae7d20..d1c6970 100644--- a/tests/test_workqueue.py+++ b/tests/test_workqueue.py@@ -66,6 +66,39 @@ def test_a_failing_handler_retries_until_the_attempt_budget_is_spent(case):assert len(attempts) == job["max_attempts"]+def test_a_refused_job_fails_at_once(case):+ """No room for an export is no room on the next two attempts either."""+ attempts = []++ def handler(c, job):+ attempts.append(job["id"])+ raise workqueue.JobRefused("not enough free space to export this case")++ workqueue.register("alpha", handler)+ workqueue.enqueue(case, "alpha", payload={})++ workqueue.drain(case)+ job = case.list_jobs(kind="alpha")[0]+ assert (job["state"], job["error"], len(attempts)) == (+ "failed", "not enough free space to export this case", 1,+ )+++def test_an_unexpected_failure_is_recorded_as_a_sentence(case, tmp_path):+ """The job's error is what the analyst reads: no class name, no errno, no path."""+ target = tmp_path / "Operation Heron" / "bundle.zip"++ def handler(c, job):+ raise OSError(28, "No space left on device", str(target))++ workqueue.register("alpha", handler)+ workqueue.enqueue(case, "alpha", payload={})++ workqueue.drain(case)+ job = case.list_jobs(kind="alpha")[0]+ assert job["error"] == "the disk is full"++def test_a_job_of_an_unknown_kind_is_cancelled_not_left_running(case):workqueue.enqueue(case, "gamma", payload={})@@ -200,3 +233,24 @@ def test_letting_others_through_with_nothing_else_registered_claims_nothing(case# would run inside the firstassert workqueue.drain(case) == 2assert nested == [False, False]+++def test_a_keyed_job_enqueued_while_it_runs_runs_once_more(case):+ """A pass that started before a filing may have missed it, so the second+ enqueue is kept: one more run at the end, with the newer payload, never two."""+ seen: list[str] = []++ def handler(c, job):+ seen.append(job["payload"]["n"])+ if len(seen) == 1:+ workqueue.enqueue(c, "pass", key="case", payload={"n": "2"})+ workqueue.enqueue(c, "pass", key="case", payload={"n": "3"})++ workqueue.register("pass", handler)+ workqueue.enqueue(case, "pass", key="case", payload={"n": "1"})++ assert workqueue.drain(case) == 2+ assert seen == ["1", "3"]+ [job] = case.list_jobs()+ assert job["state"] == "ready"+ assert job["payload"] == {"n": "3"}