The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.
JavaScript
Audit 0.3.1: keep case files and bundles safe, fix case-only renames, and hold the Linux glibc floor (#87)
OsintMeThat1a5f9f6db70b
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 5ebcf0c..4b42c23 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -94,7 +94,9 @@ jobs:fail-fast: falsematrix:include:- - os: ubuntu-latest+ # Pinned, not -latest: the binary carries this image's libstdc++, so+ # the image sets the oldest glibc it starts on (README: 2.38+).+ - os: ubuntu-24.04asset: azimut-linux-x86_64ffmpeg_target: linux-x86_64- os: windows-latest@@ -137,6 +139,9 @@ jobs:BIN=dist-bin/azimut[ "${{ runner.os }}" = "Windows" ] && BIN=dist-bin/azimut.exeuv run --no-sync python scripts/smoke_binary.py "$BIN"+ - name: Hold the glibc floor the README states+ if: runner.os == 'Linux'+ run: uv run --no-sync python scripts/check_glibc_floor.py dist-bin/azimut- name: Name the asset per-OSshell: bashrun: |diff --git a/README.md b/README.mdindex 94636f5..fda0623 100644--- a/README.md+++ b/README.md@@ -33,8 +33,8 @@ azimut # starts on http://127.0.0.1:8477 and opens a browser tabNo 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, run,-and it opens in your browser.+[Releases page](https://github.com/OsintMeThat/azimut/releases). Download it, run+it, and it opens in your browser.Your cases and settings live under `~/Azimut`, outside the app: upgrading orremoving Azimut leaves them alone. [Install in detail](#install-in-detail) covers@@ -140,20 +140,30 @@ opens Azimut in your browser.| Windows | `azimut-windows-x86_64.exe` || macOS (Apple Silicon) | `azimut-macos-arm64` || macOS (Intel, 14+) | No standalone binary; install with `pipx` or `pip` |-| Linux | `azimut-linux-x86_64` |+| Linux (glibc 2.38+) | `azimut-linux-x86_64` |++The Linux binary needs glibc 2.38 or newer: Ubuntu 24.04, Debian 13, Fedora 39+or later. On an older distribution (Ubuntu 22.04, Debian 12, RHEL 9), install+with `pipx` instead.First run, the binaries are **unsigned**, so the OS warns before letting themopen:-- **macOS**: right-click the file → **Open** → **Open** (Gatekeeper only- offers "Open" from the context menu for unidentified developers), or run- `xattr -d com.apple.quarantine ./azimut-macos-*` once.+- **macOS**: a browser download is neither executable nor trusted yet. In+ Terminal, from the folder it landed in:+ ```bash+ chmod +x azimut-macos-arm64+ xattr -d com.apple.quarantine azimut-macos-arm64+ ./azimut-macos-arm64+ ```+ Instead of `xattr`, you can open it once and allow it in **System Settings →+ Privacy & Security → Open Anyway**.- **Windows**: SmartScreen shows "Windows protected your PC"; click **Moreinfo** → **Run anyway**.- **Linux**: mark it executable with `chmod +x azimut-linux-x86_64`.-Azimut checks for a newer release on startup by default and links the download.-Settings can disable that check, and **Settings → System → Check for updates**-runs it manually. Replace the old binary with the new one. To uninstall, delete+On startup, Azimut asks GitHub for a newer release and PyPI for newer+downloaders by default, and links the download. Settings can disable that check,+and **Settings → System → Check for updates** runs it manually. Replace the old binary with the new one. To uninstall, deletethe binary. Either way `~/Azimut` stays put, so cases open unchanged.The downloadable binaries bundle a static **ffmpeg** (and ffprobe), so video@@ -165,7 +175,7 @@ The bundled ffmpeg is redistributed under its own license; see### From source-Requires Python 3.11+ and Node.js 20+ for the frontend build.+Requires Python 3.11+ and Node.js 20.19+ or 22.12+ for the frontend build.macOS and Linux:@@ -245,12 +255,12 @@ On a 2D map it can draw Azimut's own tools over the site: measure, the case'ssaved points, sun and moon, a search grid that opens in the app afterwards, andreference windows holding the case's own images and videos beside the imagery.The scale is measured off the map rather than assumed, so the tools switch-themselves off — with the reason shown — on a view they cannot compute on.+themselves off on a view they cannot compute on, and say why.On Chrome, Edge and Brave, install it from **Settings → Capture extension**: theapp writes the extension into a folder it owns, you load that folder unpackedonce and paste the pairing token. Because the app owns the folder, later updates-are one button — it rewrites the files and the extension restarts itself.+are one button: it rewrites the files and the extension restarts itself.Firefox refuses an unsigned extension and forgets an unpacked one on exit, so itinstalls the signed `azimut-capture-<version>.xpi` instead. **Settings → Capture@@ -281,16 +291,19 @@ it back, and the release tag must match it.The capture extension keeps **its own** version: the app release that lastchanged a shipped file, so it lags whenever the extension is left alone.-`tests/test_updates.py` digests what the extension ships and fails either way —+`tests/test_updates.py` digests what the extension ships and fails either way:a change without a bump, or a bump without a change. When you do change theextension, set `extension/manifest.json` to the current app version and recordthe digest the failing test prints.Within a development cycle that version cannot move: it is already the app's own.So the update button compares the **digest** instead, which the installed folder-records in its `install.json` — meaning any edit under `extension/` shows up as+records in its `install.json`, so any edit under `extension/` shows up asan available update immediately, with no bump and no restart. That is also the-loop for testing the updater (`docs/superpowers/specs/2026-09-10-extension-self-update-design.md`).+loop for testing the updater: Settings → Capture extension → **Install**, load+the extension from the folder it shows, edit a file under `extension/`, then+reopen Settings. **Update** lights up, and pressing it+rewrites the folder and reloads the extension.### Signing the extension for Firefox@@ -300,17 +313,19 @@ from publishing: `--channel unlisted` runs automated validation, puts no listingon addons.mozilla.org, and hands the file back.Run it **after** the release carrying that version exists, from a checkout of the-tag, with credentials from the AMO developer hub:+tag, with credentials from the AMO developer hub kept in a file outside the repo.+Never type the secret at a prompt or pass it as an argument, where the shell+history keeps it.```bash-export AMO_JWT_ISSUER=... AMO_JWT_SECRET=...+source ~/.config/azimut/amo.env # AMO_JWT_ISSUER + AMO_JWT_SECRET, 0600 file outside the repopython3 scripts/sign_extension.py # signs, writes packaging/updates.jsongh release upload v0.3.1 dist-xpi/azimut-capture-0.3.1.xpi```Then commit `packaging/updates.json`. That file is what`browser_specific_settings.gecko.update_url` points at, served raw from `main`,-and Firefox re-reads it about once a day — so a release that changed the+and Firefox re-reads it about once a day, so a release that changed theextension is not delivered to Firefox users until it lands on the branch.After that manifest PR is merged, verify the public manifest, asset URL andsigned bytes together:@@ -321,8 +336,8 @@ python3 scripts/sign_extension.py --verify-releaseTwo rules the script enforces rather than trusts:-- **It signs what the extension ships**, not the `extension/` directory —- `extinstall.shipped_files()`, so the XPI, the .zip and the folder the app owns+- **It signs what the extension ships**, not the `extension/` directory+ (`extinstall.shipped_files()`), so the XPI, the .zip and the folder the app ownsare the same bytes.- **A version is signed once.** AMO refuses a second copy of one it already has,and the extension's version deliberately stays put across releases that leavediff --git a/docs/ONTOLOGY.md b/docs/ONTOLOGY.mdindex ed93ed6..d7761fa 100644--- a/docs/ONTOLOGY.md+++ b/docs/ONTOLOGY.md@@ -5,14 +5,16 @@> new vocabulary. Tool proposals enter as `suggested` and remain distinct from> analyst-confirmed findings.-**Storage schema: `9`.** The manifest carries `{"azimut": {"schema": 9,+**Storage schema: `11`.** The manifest carries `{"azimut": {"schema": 11,"storage": "sqlite"}}`. Schema 3 moved the graph from `case.json` to per-case`case.db`; schema 9 gives that case its final folder layout and aligns eachfile-backed visible name with its filename stem in one idempotent migration.Schemas 4–8 were unreleased development checkpoints and normalize through the-same jump. The entity/link shape is unchanged since v1. Breaking changes require+same jump. Schema 11 gives each file one Inspect work, dates every kept Detect pin+and stands every saved comparison on the map; 10 was a development checkpoint.+The entity/link shape is unchanged since v1. Breaking changes requirea manifest schema bump and migration. The internal SQLite schema is at version-17: 8 adds `links.confidence`, 9 rebuilds the entity search index so a case+18: 8 adds `links.confidence`, 9 rebuilds the entity search index so a casesearch reaches the declared fields (§2) rather than stopping at the label and thenotes, 11 adds `links.nature` — what kind of tie an edge states, in the analyst'sown words, and only where the verb declares a qualifier (§3) — and 10 adds@@ -132,7 +134,7 @@ to one clause — no full stop, no em-dash, under a hundred characters.| `class` | a model the case counts with, never one particular object | `equipment-type` || `identifier` | a handle on a system | `account`, `email`, `phone`, `domain`, `ip`, `network` || `collected` | bytes gathered into the case rather than written, so one may depict a place | `media`, `capture` |-| `document` | it is read rather than gathered: made or consulted | `proof`, `post`, `note`, `sheet`, `inspect-session`, `collage`, `compare-session`, `bookmark` |+| `document` | it is read rather than gathered: made or consulted | `proof`, `post`, `note`, `sheet`, `inspect-session`, `collage`, `compare-session`, `map-layer`, `analysis-zones`, `analysis-area`, `analysis-follow-up`, `analysis-run`, `bookmark` || `place` | a point, never a thing | `place` || `claim` | a statement about the graph, carrying its own reasoning | `claim` |@@ -161,7 +163,7 @@ picture of the case is about it. The line that matters is between the first two|---|---|---|---|| `subject` | the case is about it | `person`, `organization`, `vehicle`, `vessel`, `aircraft`, `structure`, `equipment-type`, `account`, `email`, `phone`, `domain`, `ip`, `network`, `media`, `place`, `claim` | a node || `attestation` | a wrapper around something the case already holds | `bookmark`, `proof`, `capture` | folded into the edge that carries its provenance, drawn or not (below) |-| `annex` | consulted rather than seen, hanging off one node | `note`, `sheet`, `inspect-session`, `collage`, `compare-session` | out of the case readings, drawn by **My work** |+| `annex` | consulted rather than seen, hanging off one node | `note`, `sheet`, `inspect-session`, `collage`, `compare-session`, `map-layer`, `analysis-zones`, `analysis-area`, `analysis-follow-up`, `analysis-run` | out of the case readings, drawn by **My work** || `deliverable` | what the case produced | `post` | out of the case readings, drawn by **My work** |A bookmark stays drawn because it is not a leaf: *this account posted it, this@@ -183,9 +185,13 @@ answer by omission (`tests/test_entities.py`).| `proof` | document | attestation | ✅ | proof-composer | `spec` (json), `path` (png) | yes || `post` | document | deliverable | ✅ | post-composer | `draft` (json) | yes || `inspect-session` | document | annex | ✅ | inspect | `spec` (json), one per file | yes |-| `collage` | document | annex | ✅ | inspect | `spec` (json) | yes |+| `collage` | document | annex | ✅ | collage | `spec` (json) | yes || `compare-session` | document | annex | ✅ | compare | `spec` (json), `preview?`, `lat`, `lon`, `zoom`, `bearing`, `footprint?`, `geo?` | yes || `map-layer` | document | annex | ✅ | map layers | `spec` (json), `format`, `source_url?` | yes (spec + snapshot + icons) |+| `analysis-area` | document | annex | ✅ | detect | `spec` (json): a named, coloured area routines share | yes (`.analysis/areas-<id>.json`) |+| `analysis-zones` | document | annex | ✅ | detect | `spec` (json): a saved set of areas | yes (`.analysis/zones-<id>.json`) |+| `analysis-follow-up` | document | annex | ✅ | detect | `spec` (json): an analyzer, its areas and a date rule | yes (`.analysis/followups-<id>.json`) |+| `analysis-run` | document | annex | ✅ | detect | `spec` (json): candidates, frozen inputs and review decisions | yes (`.analysis/runs-<id>.json` + `.assets/` previews) || `note` | document | annex | ✅ | notebook | `path`, `folder?` | yes (Markdown) || `sheet` | document | annex | ✅ | sheet | `path` (csv) | yes (CSV + sidecar) || `bookmark` | document | attestation | ✅ | capture extension | `url`, `fetched_at?`, `archive_url?`, `reliability?` | no (a URL) |diff --git a/docs/RELEASE_NOTES.md b/docs/RELEASE_NOTES.mdindex d8c6cfe..0030588 100644--- a/docs/RELEASE_NOTES.md+++ b/docs/RELEASE_NOTES.md@@ -16,8 +16,8 @@ maps made elsewhere on yours.change, damaged or razed buildings, new structures and vehicles, and floods.They use a Sentinel-1 layer you add to your Copernicus configuration, andSettings → Imagery walks you through it.-- **Build your own analyzer** from up to six rules on a band, an index, a ground- class or radar, and watch what each rule keeps on the map as you change it.+- **New analyzer** builds your own from up to six rules on a band, an index, a+ ground class or radar, and shows on the map what each rule keeps as you change it.Checks are places you trust, pinned as "should be found" or "should stayempty", and they turn red when a rule stops holding. Five examples ship withtheir checks: Lahaina, Grünheide, Kakhovka, Dubai and Fujairah.@@ -27,11 +27,11 @@ maps made elsewhere on yours.each pass covered and how cloudy it was. A finished run says how much it read,so "nothing found" and "never looked" stay apart.- Candidates come strongest first, one at a time, sized along their footprint.- **Keep as a pin** files one with its own evidence crop and a claim dated by the- passes that found it; nothing else reaches the case.+ **Pin** files one with its own evidence crop and a claim dated by the passes+ that found it; **Keep** leaves it in the run. Nothing else reaches the case.- A candidate opens in Compare on the passes that found it.-- Areas can be saved with the case. A watch keeps an analyzer, its areas and a- date rule together, and **Run again** repeats the sweep.+- Areas can be saved with the case. A routine keeps an analyzer, its areas and a+ date rule together, and **Run routine** repeats the sweep.- Detect needs Copernicus credentials in Settings.## Compare@@ -132,8 +132,47 @@ maps made elsewhere on yours.- Over another map site, the extension's points tool draws one position at atime, like the app. Its media windows take files up to 512 MB.+## Security and privacy++- A case file opened in a tab, such as an SVG or a web page from a received+ bundle, is shown without running its script.+- A web page open in your browser can no longer make Azimut fetch tiles or run+ lookups on your keys: a request from another site is refused.+- A bundle no longer carries folder paths of the machine that exported it, nor+ the database journal of a save in progress.+- Over another map site, the extension's panel is out of that site's reach: it+ can neither read the panel nor press its buttons.+- A key a provider refuses no longer appears in the error message.+- A followed map layer received in a bundle reads its source only when you press+ Refresh, and a refresh never asks an icon host again. Stored icons are checked+ before they are shown.+- Home and the Guide say what the startup check asks: GitHub for a new release,+ PyPI for the downloaders.+## Fixes+- Changing only the case of a collage, comparison, draft or proof name renames it+ on Windows and macOS, where it used to delete the collage or be refused.+- Two names that differ only by case can no longer sit side by side on Linux and+ block a bundle export. When an export does refuse, it names both files.+- A layer, proof, draft or grid with "#" in its name opens and deletes itself, not+ the one whose name stops before it.+- A proof date or description cleared in Details stays cleared.+- A layer refresh keeps a legend or title change made while it was reading, and a+ layer deleted meanwhile stays deleted.+- Undoing a Detect pin takes its evidence picture to the Trash with it.+- A routine whose area is in the Trash asks for the area back first. One whose+ area is gone for good still opens and says so.+- A new comparison no longer picks up the kept images of a deleted one with the+ same name.+- A damaged KMZ or a deeply nested GeoJSON is refused with a reason instead of a+ server error.+- Notes, proofs, drafts and layer settings are written whole, so a save cut+ short keeps the previous version.+- The tile cache clears tiles older than 30 days at startup, including those+ Detect read.+- Copies of 0.3.0 Inspect sessions stay out of bundles and go with their file+ once it leaves the Trash.- Geo Report's map links read as site names, in the app and in the savedMarkdown note, instead of internal ids.- A tab left open across an update no longer asks for interface files that are@@ -151,13 +190,16 @@ maps made elsewhere on yours.Download the ready-to-run file for Windows x86_64, Linux x86_64 or AppleSilicon macOS and run it. Each one includes the interface, `ffmpeg` and the-fonts used for PDF export.+fonts used for PDF export. The Linux file needs glibc 2.38 or newer (Ubuntu+24.04, Debian 13, Fedora 39 or later); on an older distribution, install with+`pipx install azimut`.On Intel Macs (macOS 14 or newer), install the Python package instead:`pipx install azimut` or `pip install azimut`.-The downloads are unsigned, so your system will warn you the first time. The-README explains the prompt for each platform.+The downloads are unsigned, so your system will warn you the first time. On+macOS, make the file executable with `chmod +x` before opening it. The README+gives the steps for each platform.The capture extension changed in this release. Chrome, Edge and Brave usersupdate it from Settings → Capture extension. Firefox updates the signed add-on bydiff --git a/docs/SPEC.md b/docs/SPEC.mdindex a791e00..943272b 100644--- a/docs/SPEC.md+++ b/docs/SPEC.md@@ -16,7 +16,8 @@ proofs, notes and exports in one portable case folder.## 2. Principles1. **Local-first.** No account, telemetry or upload. Network access follows a- network-dependent action, except for the optional startup release check.+ network-dependent action, except for the optional startup version check+ (GitHub releases, PyPI for the downloaders).2. **Portable cases.** Files hold media, notes and proofs; per-case SQLite holdsthe graph. A closed case folder is complete and can be copied as-is.3. **Focused tools.** One tab performs one task and also works in a promotable@@ -88,7 +89,7 @@ The entity/link schema has existed since v1. Full vocabulary lives in| class | equipment-type || identifier | account, email, phone, domain, ip, network || collected | media, capture |- | document | proof, post, note, inspect-session, collage, bookmark |+ | document | proof, post, note, sheet, inspect-session, collage, compare-session, map-layer, analysis-* (Detect), bookmark || place | place || claim | claim |@@ -277,8 +278,7 @@ supplies, since a ridge ends the day well before the flat horizon does.Toward v4: archive-on-download and a Wayback CDX snapshot timeline with diff; web-page saveextension; provenance stamp on exports (short hash, optionally visible) that-re-identifies a shared PNG in its case;-Sentinel-2 change detection with an NDVI difference over a date range; source+re-identifies a shared PNG in its case; sourcelocation pattern-of-life map and timeline; cross-case handle/coordinate/facesearch; optional quota-aware X publishing.@@ -373,9 +373,13 @@ stops making sense.recoverable per-case job queue drained by one worker. Details in[STORAGE_AND_PERFORMANCE.md](STORAGE_AND_PERFORMANCE.md).- **Security posture** (single-user localhost): `127.0.0.1` bind + Host/Origin- guard (DNS rebinding), 0600/0700 perms, hard 100 MP Pillow limit, content-hashed+ guard (DNS rebinding), which also refuses a foreign page's `Sec-Fetch-Site` on+ the API and the case files, since an image or a link sends no Origin on a GET;+ 0600/0700 perms, hard 100 MP Pillow limit, content-hashednames for images pasted into a proof (no client-chosen path), token-gated- ingest island for the extension. The one route that reads a case file back out+ ingest island for the extension. A case file is served `nosniff`, and under a+ `sandbox` policy unless its type only displays, so an SVG or a page that arrived+ in a bundle never runs script in the app's origin. The one route that reads a case file back outof that island — the attachments a composer hand-off carries — fences on the**resolved** path, so `media/../case.json` is refused where a prefix read offthe request would have served it. Filling a composer and handing a picture to a@@ -404,7 +408,9 @@ stops making sense.thumbnails or link tallies, a sweep's own spec, a case's images and videos byname — and the panelitself reaches them only through the worker's own allowlist, since a content- script's fetch would carry the map site's origin and be refused. Keeping those+ script's fetch would carry the map site's origin and be refused. It is drawn+ in a closed shadow root and acts only on events the browser dispatched, so the+ map site can neither read the panel nor press it. Keeping thosepanels in step adds one more, and it is the narrowest of them: a read-onlystream of what changed, never of what it says, so an event names a case and afile and the panel re-reads it through the routes it already had. The worker@@ -456,7 +462,9 @@ stops making sense.the distinction drawn is that this is the sharing mechanism the map's owncreator switched on, not a way around a quota. It is fetched only when theanalyst subscribes, presses Refresh, or switches the layer on for the first- time in a session, when it asked to be re-read then. Every added layer starts+ time in a session, when it asked to be re-read then. A layer received in a+ bundle is not re-read on switch-on, since its sender set that and chose the+ address; it waits for a Refresh pressed here. Every added layer startsoff when the app or the page opens again, so a layer heavy enough to take thetab down does not take it down again on reload; a shape it stops answering infails with a sentencediff --git a/docs/STORAGE_AND_PERFORMANCE.md b/docs/STORAGE_AND_PERFORMANCE.mdindex dfb0b00..9d02237 100644--- a/docs/STORAGE_AND_PERFORMANCE.md+++ b/docs/STORAGE_AND_PERFORMANCE.md@@ -93,13 +93,15 @@ for a case to fit under it on Windows, and names it as a warning elsewhere.<case>/ # the analyst's: Azimut writes nothing here but azimut/README.txt # which half of the folder is whoseazimut/- case.json # small manifest: name, dates, storage format and schema+ case.json # small manifest: name, dates, storage format, schema and to-do listsnotes.md # case-wide Markdown notenotes/ # note bodies, named after their title, filed as in the notebookmedia/ # imported, downloaded and derived media.meta/ # one sidecar per media.dl/ # in-progress downloads (transient).thumbs/ # disposable thumbnail cache+ sheets/ # CSV tables, one file per sheet+ .meta/ # what the grid remembers: widths, sort, colours, cell linksproofs/ # rendered PNGs.meta/ # editable specs and pasted assetsexports/ # finished exports and the analyst's own files@@ -107,10 +109,13 @@ for a case to fit under it on Windows, and names it as a warning elsewhere.case.db # entities, links, folders, catalog and jobs (SQLite)entity-images/ # private, bounded entity photos and their thumbnails.drafts/ # post drafts- .inspect/ # saved Inspect session specs+ .inspect/ # one Inspect work per file (.v1/ keeps 0.3.0 sessions)+ .collages/ # collage layouts; the picture is media.compare/ # saved Compare session specs.analysis/ # saved areas, saved detections, runs and the frames behind their results.search/ # saved Grid Search state+ .layers/ # added map layers: spec, snapshot, icons+ .cache/ # parsed GeoJSON, rebuilt from the snapshot.trash/ # deleted artifacts grouped by delete action, in numbered slots```@@ -136,8 +141,8 @@ new directory level or a raised cap breaks it.schema fields. It no longer holds the graph, so the case switcher can identify acase without opening its database. `case.db` is the source of truth for mutablestructured state (entities, links, folders, jobs). The files under `media/`,-`proofs/`, `.drafts/`, `.inspect/`, `.compare/` and `notes/` are the source of truth for their-own content.+`proofs/`, `sheets/`, `.drafts/`, `.inspect/`, `.collages/`, `.compare/`, `.analysis/`,+`.layers/` and `notes/` are the source of truth for their own content.App-wide preferences stay outside cases under `<workspace>/.azimut/settings/`:`settings.json`, `templates.json`, `signature.png` and the optional@@ -146,8 +151,8 @@ there with independent atomic renames, so a partial move resumes. If bothlocations differ, the current hidden file wins and the legacy copy is retainedbeside it under a `.legacy` name.-For media, proof PNGs, notes, drafts, Inspect sessions and Compare sessions, the human-readable-filename stem is the name Azimut shows. Spaces, case and Unicode survive;+For media, proof PNGs, notes, drafts, Inspect works, collages and Compare sessions, the+human-readable filename stem is the name Azimut shows. Spaces, case and Unicode survive;characters forbidden by Windows are replaced and the returned canonical stemis written back to the UI. Renaming moves the file and its companions, rewritesexact stored paths in the graph, jobs, sidecars and tool specs, and rebinds the@@ -459,8 +464,10 @@ Exports run as `bundle-export` jobs and write atomically to`<workspace>/.azimut/bundles/`, then stream to the browser as an attachment. The firstZIP member is `bundle-header.json`; the last is `bundle.json`, which lists everyother member with its size and SHA-256. The database is copied consistently,-its trash and unfinished jobs are removed, and it is vacuumed before packaging.-`.trash/`, `media/.thumbs/` and `media/.dl/` never travel.+its trash and every job are removed (a finished export or import still names+folders of this machine), and it is vacuumed before packaging. `.trash/`,+`media/.thumbs/`, `media/.dl/` and SQLite's journal beside `case.db` never travel;+a journal an older export packed is verified and then dropped on import.Export also reserves filesystem headroom before writing its temporary output.Bundle format 2 carries the complete case under a `case/` member prefix:@@ -633,8 +640,9 @@ Work starts only from a user action (an import, a regenerate) or crash recovery,never from merely opening a case or tab. A job lifecycle is `queued → running →ready`, or `failed` once its retry budget is spent, or `cancelled` (its media isgone). A job left `running` by an interrupted process is reclaimed to `queued` (or-`failed`) on case open and on server startup (`Case.recover_jobs`,-`server._recover_jobs`), so work resumes instead of stalling.+`failed`) on server startup and whenever the workspace root changes+(`workqueue.recover_all`, which runs `Case.recover_jobs` on every case), so work+resumes instead of stalling.### Budget, repair, retry statesdiff --git a/docs/UI.md b/docs/UI.mdindex f00c415..5f1f66c 100644--- a/docs/UI.md+++ b/docs/UI.md@@ -23,7 +23,7 @@ in `frontend/src/lib/workspaces.js` and appear as tabs, never as new rail entrie| **Case** (topbar) | Board, Graph, Timeline, Sheet | v5: Orchestrator || **Sources** | Media Library, Files, Reverse Search | Channel Monitor, Evidence Locker || **Examine** | Inspect, Collage | Edit Provenance, Shot contact sheet, OCR, Image Compare, Hints, Sky Clock, audio |-| **Map** | Satellite, Compare, Detect, Coords & Sky | Imagery Wayback, Event layers, Ground Imagery, Measures, Viewshed, OSM Query, Map Board |+| **Map** | Satellite, Compare, Detect, Coords & Sky | Event layers, Ground Imagery, Measures, Viewshed, OSM Query, Map Board || **Compose** | Geo Proof, Geo Report, Notebook | Report Builder, GIF maker |**Case is not on the rail.** The rail reads as a sequence of stages, and the case is@@ -1270,7 +1270,9 @@ transparent PNG of the pieces trimmed to their bounds.frames are joined, the latest session carries on, typed names and notes are kept inits notes, relations move to it, and each collage becomes a collage document namedafter the session that built it. The sessions are copied as they were to-`.inspect/.v1/` first. A session brought back from the Trash merges the same way.+`.inspect/.v1/` first. The copies stay on this machine, never in a bundle, and go+once their file has left the Trash for good. A session brought back from the Trash+merges the same way.## Map@@ -1372,7 +1374,9 @@ metres, which grows the mask past the soft edge the classification leaves.Detection, Display and Filters tabs separate the rest of the settings, with hover descriptions.The settings panel offers automatic/manual thresholds, tone matching, alignment,smoothing, cleanup, minimum area, class filters, palettes and heat/class/outline-displays. A spectral index skips the automatic threshold: it is highlighted past+displays. Smoothing and cleanup can take small real changes with the noise, and+the Thermal palette is only colours, not a heat reading. A spectral index skips+the automatic threshold: it is highlighted pasta stated index change, the line Detect draws, so panning cannot move it. Tonematching defaults to automatic, which means none on Sentinel-2 — two passesalready corrected to surface reflectance have no exposure left to match, anddiff --git a/extension/README.md b/extension/README.mdindex 6f44176..d50ec83 100644--- a/extension/README.md+++ b/extension/README.md@@ -37,7 +37,7 @@ Two roads, because the browsers disagree about what a permanent extension is.### Chrome, Edge, Brave (Windows, macOS, Linux)In Azimut → **Settings → Capture extension**, press **Install**. The app writes-the extension into a folder it owns and shows you the path. Copy that path —+the extension into a folder it owns and shows you the path. Copy that path:pasting it into the browser's picker works everywhere, and the folder is hiddenunder `.azimut/`, so navigating to it is the harder road.@@ -67,7 +67,7 @@ addons.mozilla.org.**Chrome, Edge, Brave**: Settings → **Capture extension** → **Update**, once thebutton lights up. Azimut rewrites the folder and the extension restarts and-re-attaches itself, so nothing needs reloading — not the extension, not the page.+re-attaches itself, so neither the extension nor the page needs reloading.Your pairing survives. Even without pressing anything it lands eventually, sinceChrome re-reads unpacked extensions when it starts.@@ -78,7 +78,7 @@ Two things worth knowing there:- Chrome derives an extension's identity from its folder, so if you already hadthe extension loaded from a folder of your own, that copy and this one are twoextensions. Settings names the one to remove. Removing it loses its stored- pairing, so paste the token again afterwards — once.+ pairing, so paste the token again afterwards, once.**Firefox**: nothing to press. A signed package is sealed, so Azimut cannotrewrite it and the Update button does not apply. Firefox reads Azimut's update@@ -94,7 +94,7 @@ than hidden:to check earlier: it does not implement the API that would.- Firefox updates the add-on without knowing which Azimut sits beside it, so anapp left un-updated can end up paired with a newer add-on. Settings and the- extension's own options page both say so, and the answer is to update the app —+ extension's own options page both say so, and the answer is to update the app:its newer flows report that they could not run rather than misbehave.## Map tools@@ -105,14 +105,14 @@ on. Press it again to close it. Six tools share it:| Tool | What it does ||---|---|| Measure | Distance along a clicked path, or the area it encloses. Same formulas and same wording as the app. |-| Points | Draws one of the case's three positions — its located media, its places, its captures — on the map, and files a new point. |+| Points | Draws one of the case's three positions (its located media, its places, its captures) on the map, and files a new point. || Sun & moon | Plants a point and draws the day's sun and moon arcs around it, with a date and an hour slider. || Grid | Drags a box or clicks out a shape, cuts it into metric cells, and marks each cleared or flagged. The grid is saved into the case and opens in the app's own Grid Search. || Refs | Floats an image or a video from the case over the map, to compare against the imagery while you pan. |-| Fires | Lays NASA FIRMS thermal detections over the site: the last 24 h to 7 days, or any past day or range up to 31 days picked from a calendar drawn inside the panel. Needs a FIRMS key in Azimut's own Settings — without one the seat is greyed and says so — and stops at z14 where one mark stops meaning one detection. |+| Fires | Lays NASA FIRMS thermal detections over the site: the last 24 h to 7 days, or any past day or range up to 31 days picked from a calendar drawn inside the panel. Needs a FIRMS key in Azimut's own Settings (without one the seat is greyed and says so), and stops at z14 where one mark stops meaning one detection. |Only the open tool draws, and pressing it again puts it down: the map goes back to-being a map. What you told a tool stays in it — a measured path, a planted point,+being a map. What you told a tool stays in it: a measured path, a planted point,an open sweep all come back when you pick it up again. Reference windows and thefire layer are the exceptions: the windows are not on the map, and the fires areground rather than drawing, so both stay while you measure over them.@@ -150,7 +150,7 @@ say so, and pressing the toolbar button on that tab puts it back.**A reference window is scratch.** Drag it by its header, resize it from thecorner, wheel to zoom into the image, double-click the title bar to fold it away.Nothing about it is filed, nothing comes back next visit, and the panel and its-windows step out of the frame before a capture is taken — a reference floating+windows step out of the frame before a capture is taken, because a reference floatingover a map must never end up inside the evidence.**Add reference** lists the case's images and videos, searched, filtered by kind@@ -158,15 +158,15 @@ and ordered by the app rather than by this tab: what crosses is one page of a canever the case. A video plays in the window, with its own controls.Two limits worth knowing. A reference has to be **under 512 MB**, and it crosses in-pieces, so a long clip opens the way it does in the app's own Satellite tab — the+pieces, so a long clip opens the way it does in the app's own Satellite tab: thewindow counts up while it arrives. A published thread's attachments answer to alower ceiling, **48 MB**, since those are pushed into the composer's page whole.And a video is the one thing here a site can refuse: an image is decoded andpainted on a canvas, which asks the page's content policy nothing, while a videoneeds a URL and some sites will not load one. When that happens the window says so.-Reference windows work where the geometric tools do not — Street View, a pitched-camera, a globe — since nothing about holding a reference up needs the ground to+Reference windows work where the geometric tools do not (Street View, a pitched+camera, a globe), since nothing about holding a reference up needs the ground tobe measurable, and they stay on screen while you use another tool.**It works from what the site writes about itself.** Every one of these maps states@@ -183,8 +183,8 @@ bar is not under the middle of the window on most of these sites: Yandex draws i210 px to the right of it, behind its results panel, Bing 40 px down under itsheader. The app ships what its own calibration run measured, so a fresh installdraws from the right pixel on the sites whose chrome does not move-(`docs/MAP_SITES.md`). Apple's sidebar does move — it folds away in a narrow-window — so Apple starts at the middle and is measured instead.+(`docs/MAP_SITES.md`). Apple's sidebar does move (it folds away in a narrow+window), so Apple starts at the middle and is measured instead.Measuring it takes a zoom. A pan can never see the offset, because it slides alongwith the map; a zoom can, since every one of these maps zooms about a point it@@ -192,7 +192,7 @@ holds still while the centre moves underneath. So the first zoom you make measurit, the panel remembers it for that site and that window shape, and every zoomafter checks it again. Until then the status line says "zoom once to place it",and the tooltip on that line carries the offset being drawn from and where it came-from — which is what to read when something lands somewhere the ground is not.+from, which is what to read when something lands somewhere the ground is not.**Google Earth is read like the others.** Its 2D map is Web Mercator, drawn aboutthe middle of the window, and `d` and `y` in its address bar give the scale. A link@@ -201,8 +201,8 @@ it, and Earth draws it nearer than it says. So until you move the map once, whicis when Earth writes the ground in, the panel shows "Move the map once so itsaddress bar gives the scale" and draws nothing.-Apple states a live span but a stale `z` — it carries whatever the opening-link had and never rewrites it — so the span is read and the `z` ignored. Bing+Apple states a live span but a stale `z` (it carries whatever the opening+link had and never rewrites it), so the span is read and the `z` ignored. Bingrounds: its wheel moves a third of a level and it writes one decimal, so thefraction is worked out from the same held pixel rather than read. Whole levels areexact everywhere, which is what a double-click lands on.@@ -227,7 +227,7 @@ app's own Saved layer merges them.**One position is drawn at a time**, the same three the app's Saved panel offersand in the same order: the located media the case collected, the places droppedby hand, the captures taken of them. The panel opens on the media, and switching-position reads that position — a file carries no coordinates of its own and is+position reads that position, because a file carries no coordinates of its own and isnot in the index the other two come from. Filing a point goes to Places, so thepoint just filed is drawn rather than swallowed.@@ -237,7 +237,7 @@ in any other map you have the panel open on. Nothing needs reloading and nothingneeds pressing: the app says what changed and each side re-reads that much.A grid swept from two places at once both lands, because what travels is the-cells you marked and never a copy of the grid — so two sweeps of different cells+cells you marked and never a copy of the grid, so two sweeps of different cellskeep each other's work, and the same cell twice is simply the last mark. A griddiscarded elsewhere closes here and says so.@@ -247,13 +247,13 @@ map rather than Street View, 2D rather than 3D. A degree or two is not pitched:these viewers never come back to a clean zero, and a view that looks level istreated as level. Placing a pointstill works wherever geometry is off, anchored on the point the address bar-names — where the camera stands — and the panel says so.+names (where the camera stands), and the panel says so.**Turning the map is fine.** Drag Google Earth's compass and the drawing turnswith it. Only tilting the camera switches the geometric tools off.Zoomed far out there are two cases and they get different answers. On a **flat-map drawn small** — Google and Bing below level 8 — the tools stay on: the middle+map drawn small** (Google and Bing below level 8), the tools stay on: the middleof the screen is still right, the edges drift, and the drawing is dimmed and saysso rather than disappearing. It is a look at a region's work, not a measurement;zoom in and it is exact again. Sun & moon is the exception and is never dimmed:@@ -282,8 +282,8 @@ measured places the drawing again without asking.token → **Save & test**.The token allows this extension to file captures through the local Azimut-server, to read back the media and proofs a thread attaches, and — for the map-tools — the points, search grids, images and videos of the case you pick. Rotate it in+server, to read back the media and proofs a thread attaches, and, for the map+tools, the points, search grids, images and videos of the case you pick. Rotate it inSettings to revoke existing pairings.## Fill the composer@@ -292,7 +292,7 @@ Geo Report's **Publish** opens the site's full composer, types each post of thethread and attaches its pictures. Nothing is posted: the composer is left filledand the button is yours.-There is one switch and it is in the app — **Settings → Publishing → Let the+There is one switch and it is in the app: **Settings → Publishing → Let theextension fill the composer**, on by default. Nothing to set here.The filling runs in the page's own world, which is the only place a composer@@ -316,9 +316,9 @@ without you pasting or dragging anything.This is the one flow where the page acts on what it is given: an engine searchesthe moment it holds a picture. That is what the button was pressed for, and it-still takes that press — nothing is sent to an engine you did not open.+still takes that press: nothing is sent to an engine you did not open.-The switch is in the app — **Settings → General → Let the extension open the+The switch is in the app: **Settings → General → Let the extension open theengine with the image**, on by default. Nothing to set here.If the engine has changed its markup, or the image is too large to carry, thediff --git a/extension/mapoverlay.js b/extension/mapoverlay.jsindex 83a4643..c18b12e 100644--- a/extension/mapoverlay.js+++ b/extension/mapoverlay.js@@ -271,8 +271,15 @@zIndex: "2147483000",pointerEvents: "none",});- const root = host.attachShadow({ mode: "open" });+ // Closed, and created from this script's own world: the map site's scripts share+ // the DOM, and an open root would hand them every case name, point and picture+ // the panel shows. `host.shadowRoot` reads null to them.+ const root = host.attachShadow({ mode: "closed" });document.documentElement.appendChild(host);+ // The site can also dispatch events as well as the analyst can click, so only+ // the browser's own are acted on. `=== false` because a test DOM leaves the+ // flag unset; a browser always sets it.+ const trusted = (fn) => (event) => (event.isTrusted === false ? undefined : fn(event));// Ground first, so it is under the drawing: FIRMS is a picture of what was// burning, and a measured path over it has to stay legible.const ground = document.createElement("div");@@ -2261,7 +2268,7 @@// --- what the panel's controls do ------------------------------------------- panel.addEventListener("click", async (event) => {+ panel.addEventListener("click", trusted(async (event) => {const target = event.target.closest("[data-act]");if (!target) return;const act = target.dataset.act;@@ -2435,9 +2442,9 @@syncArmed();return render();}- });+ }));- panel.addEventListener("change", async (event) => {+ panel.addEventListener("change", trusted(async (event) => {const act = event.target.dataset.act;if (act === "case") {state.caseId = event.target.value;@@ -2465,9 +2472,9 @@const metres = Number(event.target.value);if (metres >= 10) tools.grid.cellM = metres;}- });+ }));- panel.addEventListener("input", (event) => {+ panel.addEventListener("input", trusted((event) => {const act = event.target.dataset.act;if (act === "pin-title") state.pinTitle = event.target.value;if (act === "grid-title") state.gridTitle = event.target.value;@@ -2481,11 +2488,11 @@if (readout) readout.textContent = tools.sky.readout() ?? "";redraw();}- });+ }));// Dragging the panel by its header. Remembered per site, because a panel that// covers the sidebar on one map covers the map itself on another.- panel.addEventListener("pointerdown", (event) => {+ panel.addEventListener("pointerdown", trusted((event) => {if (!event.target.closest("header") || event.target.closest("[data-act]")) return;const start = { x: event.clientX, y: event.clientY };const rect = panel.getBoundingClientRect();@@ -2501,7 +2508,7 @@};window.addEventListener("pointermove", move, true);window.addEventListener("pointerup", up, true);- });+ }));// --- what is remembered, per site ------------------------------------------@@ -2629,17 +2636,17 @@// --- lifecycle -------------------------------------------------------------const listeners = [- [window, "pointerdown", onPointerDown, true],- [window, "pointermove", onPointerMove, true],- [window, "pointerup", onPointerUp, true],- [window, "click", onClick, true],- [window, "dblclick", onDoubleClick, true],- [window, "wheel", onWheel, { capture: true, passive: true }],+ [window, "pointerdown", trusted(onPointerDown), true],+ [window, "pointermove", trusted(onPointerMove), true],+ [window, "pointerup", trusted(onPointerUp), true],+ [window, "click", trusted(onClick), true],+ [window, "dblclick", trusted(onDoubleClick), true],+ [window, "wheel", trusted(onWheel), { capture: true, passive: true }],[window, "resize", onResize, false],[document, "visibilitychange", onShown, false],- [layer.canvas, "pointerdown", canvasDown, false],- [layer.canvas, "pointermove", canvasMove, false],- [layer.canvas, "pointerup", canvasUp, false],+ [layer.canvas, "pointerdown", trusted(canvasDown), false],+ [layer.canvas, "pointermove", trusted(canvasMove), false],+ [layer.canvas, "pointerup", trusted(canvasUp), false],];for (const [node, type, fn, opts] of listeners) node.addEventListener(type, fn, opts);const poll = setInterval(() => readUrl(), URL_POLL_MS);@@ -2682,7 +2689,8 @@delete window.__AZIMUT_MAP_TOOLS__;}- window.__AZIMUT_MAP_TOOLS__ = { close, state, tools };+ // This world's window, which the site cannot see: the root rides here for tests.+ window.__AZIMUT_MAP_TOOLS__ = { close, state, tools, root };(async () => {await restore();diff --git a/frontend/package.json b/frontend/package.jsonindex 684036f..d2edc74 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -3,6 +3,9 @@"private": true,"version": "0.1.2","type": "module",+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ },"scripts": {"dev": "vite","build": "vite build",diff --git a/frontend/src/components/ConfirmDialog.render.test.js b/frontend/src/components/ConfirmDialog.render.test.jsindex 45987bc..7aeace2 100644--- a/frontend/src/components/ConfirmDialog.render.test.js+++ b/frontend/src/components/ConfirmDialog.render.test.js@@ -84,6 +84,60 @@ describe('focus', () => {});});+describe('tone', () => {+ const confirmButton = (label) =>+ [...document.querySelectorAll('[role="alertdialog"] button')].find(+ (b) => b.textContent.trim() === label+ );++ it('marks an action nothing comes back from as danger', () => {+ open(ConfirmDialog, {+ title: 'Empty the trash', message: 'x', tone: 'danger', confirmLabel: 'Empty', oncancel: () => {},+ });+ const dialog = document.querySelector('[role="alertdialog"]');++ expect(dialog.classList.contains('danger')).toBe(true);+ expect(dialog.querySelector('.badge').classList.contains('danger')).toBe(true);+ expect(confirmButton('Empty').classList.contains('btn-danger')).toBe(true);+ });++ it('keeps the plain accent for a delete the trash can undo', () => {+ open(ConfirmDialog, { title: 'Delete', message: 'x', confirmLabel: 'Delete', oncancel: () => {} });+ const dialog = document.querySelector('[role="alertdialog"]');++ expect(dialog.classList.contains('danger')).toBe(false);+ expect(dialog.querySelector('.badge').classList.contains('danger')).toBe(false);+ expect(confirmButton('Delete').classList.contains('btn-primary')).toBe(true);+ expect(confirmButton('Delete').classList.contains('btn-danger')).toBe(false);+ });+});++describe('consequences', () => {+ it('shows what can come back apart from what goes with it and what is scarred', () => {+ open(ConfirmDialog, {+ title: 'Delete',+ message: 'x',+ consequences: { cascade: [{ label: 'Clip work' }], tombstone: [{ label: 'Harbour proof' }] },+ restorable: 'Restore it from the trash',+ oncancel: () => {},+ });+ const blocks = [...document.querySelectorAll('.conseq')];++ expect(blocks).toHaveLength(3);+ expect(blocks[0].classList.contains('danger')).toBe(true);+ expect(blocks[0].textContent).toContain('Clip work');+ expect(blocks[1].textContent).toContain('Harbour proof');+ const restorable = document.querySelector('.conseq.restorable');+ expect(restorable.textContent.trim()).toBe('Restore it from the trash');+ expect(restorable.classList.contains('danger')).toBe(false);+ });++ it('draws no consequence block when there is none to state', () => {+ open(ConfirmDialog, { title: 'Delete', message: 'x', oncancel: () => {} });+ expect(document.querySelector('.conseq')).toBeNull();+ });+});+describe('enter', () => {it('is not answered by the window, so a stray press cannot confirm', () => {const onconfirm = vi.fn();diff --git a/frontend/src/components/ConfirmDialog.test.js b/frontend/src/components/ConfirmDialog.test.jsdeleted file mode 100644index 6e50c55..0000000--- a/frontend/src/components/ConfirmDialog.test.js+++ /dev/null@@ -1,18 +0,0 @@-import { describe, expect, it } from 'vitest';-import { readFileSync } from 'node:fs';--const source = readFileSync(new URL('./ConfirmDialog.svelte', import.meta.url), 'utf8');--describe('confirmation register', () => {- it('shows the recoverable consequence separately from losses and scars', () => {- expect(source).toContain("restorable = ''");- expect(source).toContain('{#if restorable}');- expect(source).toContain('class="conseq restorable"');- expect(source).toContain('<Icon name="undo"');- });-- it('reserves danger for actions that cannot be restored', () => {- expect(source).toContain("tone: 'danger' → nothing comes back");- expect(source).toContain("tone: 'default' → reversible");- });-});diff --git a/frontend/src/components/EntityDetails.test.js b/frontend/src/components/EntityDetails.test.jsindex b6dd1cb..c235cd2 100644--- a/frontend/src/components/EntityDetails.test.js+++ b/frontend/src/components/EntityDetails.test.js@@ -179,7 +179,6 @@ describe('the three tabs', () => {it('does not collapse hand-made entities into a different one-scroll layout', () => {expect(source).not.toContain('unifiedDetails');- expect(source).not.toContain('isManualEntityType');expect(source).toContain("{#if tab === 'info'}");expect(source).toContain("{#if tab === 'connections'}");expect(source).toContain("{#if tab === 'time'}");diff --git a/frontend/src/components/FolderBrowser.svelte b/frontend/src/components/FolderBrowser.svelteindex d896504..b6e21b5 100644--- a/frontend/src/components/FolderBrowser.svelte+++ b/frontend/src/components/FolderBrowser.svelte@@ -7,9 +7,7 @@//// `entries` are the picker's items already narrowed by its own chips/filters,// each carrying `id` and `attrs.folder`; `matches` then hides the ones the- // search box excludes without collapsing the folders around them. A picker- // with a richer flat row (Satellite's saved work) passes it as the `row`- // snippet instead of settling for icon + label.+ // search box excludes without collapsing the folders around them.import Icon from './Icon.svelte';import { buildTree } from '../lib/folderTree.js';import { browseCrumbs, browserView } from '../lib/folderBrowse.js';@@ -25,9 +23,6 @@emptyText = 'Nothing here.',icon = () => 'file',label = (entry) => entry.label ?? '',- // A picker whose flat list has its own row (thumbnail, actions) passes it- // here rather than dropping to icon+label the moment you open a folder.- row = null,onnavigate,onselect,onconfirm,@@ -53,21 +48,17 @@</button>{/each}{#each files as entry (entry.id)}- {#if row}- {@render row(entry)}- {:else}- <button- type="button"- class="browser-row"- class:selected={isSelected(entry)}- aria-pressed={mark ? isSelected(entry) : undefined}- onclick={() => onselect?.(entry)}- ondblclick={() => onconfirm?.(entry)}- >- <Icon name={icon(entry)} size={18} /><span>{label(entry)}</span>- {#if mark && isSelected(entry)}<Icon name="check" size={14} />{/if}- </button>- {/if}+ <button+ type="button"+ class="browser-row"+ class:selected={isSelected(entry)}+ aria-pressed={mark ? isSelected(entry) : undefined}+ onclick={() => onselect?.(entry)}+ ondblclick={() => onconfirm?.(entry)}+ >+ <Icon name={icon(entry)} size={18} /><span>{label(entry)}</span>+ {#if mark && isSelected(entry)}<Icon name="check" size={14} />{/if}+ </button>{/each}{#if view.children.length === 0 && files.length === 0}<p class="browser-empty">{emptyText}</p>diff --git a/frontend/src/components/FolderBrowser.test.js b/frontend/src/components/FolderBrowser.test.jsindex 181300a..2be838e 100644--- a/frontend/src/components/FolderBrowser.test.js+++ b/frontend/src/components/FolderBrowser.test.js@@ -1,5 +1,4 @@import { describe, expect, it } from 'vitest';-import { createRawSnippet } from 'svelte';import { render } from 'svelte/server';import FolderBrowser from './FolderBrowser.svelte';import { UNFILED } from '../lib/folderBrowse.js';@@ -56,24 +55,4 @@ describe('FolderBrowser', () => {expect(body).toContain('Bridge!');});-- it('hands the entries to the caller’s row snippet when it passes one', () => {- const row = createRawSnippet((entry) => ({- render: () => `<div class="rich-row">${entry().label} with a thumbnail</div>`,- }));-- const body = at('field', { row });-- expect(body).toContain('Bridge with a thumbnail');- expect(body).not.toContain('browser-row"'); // the default entry button stays out- });-- it('keeps its own folders and crumbs around a caller’s rows', () => {- const row = createRawSnippet((entry) => ({ render: () => `<div>${entry().label}</div>` }));-- const body = at('field', { row });-- expect(body).toContain('folder-row'); // field/day-1- expect(body).toContain('Case media');- });});diff --git a/frontend/src/components/SheetToCase.svelte b/frontend/src/components/SheetToCase.svelteindex 8df657e..986e9d7 100644--- a/frontend/src/components/SheetToCase.svelte+++ b/frontend/src/components/SheetToCase.svelte@@ -444,7 +444,7 @@{#if statementColumn}<p class="label">What <em>{statementColumn}</em> states</p><div class="nested">- <SheetDate {table} {meta} {count} subject={subjectColumn} {onanchors}+ <SheetDate {table} {meta} subject={subjectColumn} {onanchors}onchoices={(answer) => (statement = answer)} /></div>{/if}diff --git a/frontend/src/components/TemporalInput.svelte b/frontend/src/components/TemporalInput.svelteindex 70407b1..f8d94af 100644--- a/frontend/src/components/TemporalInput.svelte+++ b/frontend/src/components/TemporalInput.svelte@@ -8,12 +8,7 @@} from '../lib/temporalInput.js';import { formatTemporalValue } from '../lib/timeline.js';- // `compact` is for a narrow column — the proof composer's 300px side panel —- // where the three-part date row does not fit and overflows its own container.- // It stacks the parts instead, which is what the editor already does on a- // narrow window; the difference is that a media query reads the viewport and- // cannot see that a wide window holds a narrow column.- let { id, value = '', compact = false, onchange, onvaliditychange } = $props();+ let { id, value = '', onchange, onvaliditychange } = $props();let state = $state(readTemporalInput(''));let sent = $state('');const rawValue = $derived(writeTemporalInput(state));@@ -50,7 +45,7 @@}</script>-<div class="temporal-editor" class:compact>+<div class="temporal-editor"><label class="field format-field"><span>Format</span><select@@ -330,43 +325,6 @@.temporal-preview small { color: var(--text-3); }.temporal-preview code { margin-left: auto; color: var(--text-3); overflow-wrap: anywhere; }.temporal-preview.error { border-left-color: var(--danger); color: var(--danger); }- /* Compact: the parts pair up instead of stacking, and the controls carry their- own names. Four labelled rows made this one field taller than the coordinates- and the sources above it put together, for a value most proofs answer with a- single day. The selects say what they hold — Date, Day, Exact as stated — so- the label above each becomes a caption of the word underneath it; it stays- for a screen reader, which cannot see the option. */- .compact { gap: 5px; }- .compact .field > span {- position: absolute;- width: 1px;- height: 1px;- margin: -1px;- padding: 0;- border: 0;- overflow: hidden;- clip-path: inset(50%);- white-space: nowrap;- }- /* Precision sits beside the value it qualifies — "Day" is three characters and- had a row of its own. Reading order is left to right then down, and it is- also the order the controls are reached in: nothing here is moved out of the- sequence it is written in. */- .compact .date-parts { grid-template-columns: auto minmax(0, 1fr); }- .compact .timestamp-parts { grid-template-columns: repeat(2, minmax(0, 1fr)); }- /* Certainty is a sentence, not a word, and a timestamp needs its own width. */- .compact .certainty-field,- .compact .datetime-field { grid-column: 1 / -1; }- .compact .range-parts,- .compact .time-range-parts { grid-template-columns: 1fr; }- .compact .format-field { justify-self: stretch; }- .compact .format,- .compact .precision,- .compact .zone,- .compact .offset { width: 100%; }- /* The guide is a wide table, and the column it opens in clips what overflows- it. Held to the column, it scrolls inside itself instead of being cut off. */- .compact .advanced-guide { width: 100%; }@media (max-width: 620px) {.date-parts, .timestamp-parts, .range-parts, .time-range-parts { grid-template-columns: 1fr; }.format-field { justify-self: stretch; }diff --git a/frontend/src/components/TemporalInput.test.js b/frontend/src/components/TemporalInput.test.jsindex 87e9d6a..9f1e48c 100644--- a/frontend/src/components/TemporalInput.test.js+++ b/frontend/src/components/TemporalInput.test.js@@ -25,25 +25,8 @@ describe('temporal input', () => {});});-describe('temporal input in a narrow column', () => {+describe('temporal input controls', () => {it('sizes its own controls, since a caller cannot style into a component', () => {expect(source).toContain('.input-sm { padding: 4px 7px; font-size: var(--fs-xs); }');});-- it('pairs the parts and hides the captions rather than stacking four rows', () => {- expect(source).toContain('class:compact');- expect(source).toContain('.compact .date-parts { grid-template-columns: auto minmax(0, 1fr); }');- expect(source).toContain('clip-path: inset(50%)');- });-- it('keeps the labels in the markup, where a screen reader still reads them', () => {- // The compact rule hides them visually. Removing them would take the- // accessible name of every wrapping label with it.- expect(source).toContain('<span>Precision</span>');- expect(source).toContain('<span>Certainty</span>');- });-- it('holds the syntax guide to the column it opens in', () => {- expect(source).toContain('.compact .advanced-guide { width: 100%; }');- });});diff --git a/frontend/src/lib/autosave.svelte.js b/frontend/src/lib/autosave.svelte.jsindex 4508c8c..570bba6 100644--- a/frontend/src/lib/autosave.svelte.js+++ b/frontend/src/lib/autosave.svelte.js@@ -16,36 +16,37 @@export function createAutosave({ write, delay = 800 }) {const state = $state({ status: 'idle', error: '' });let timer = null;+ // The writes in flight, as one promise: it settles only once no rewrite is owed,+ // so a change made during a write is waited for along with it.let running = null;let again = false;- async function run() {+ function run() {clearTimeout(timer);timer = null;if (running) {again = true;return running;}- running = (async () => {- state.status = 'saving';- try {- await write();- state.status = 'saved';- state.error = '';- } catch (e) {- state.status = 'error';- state.error = e?.message || 'save failed';- }+ const chain = (async () => {+ do {+ again = false;+ state.status = 'saving';+ try {+ await write();+ state.status = 'saved';+ state.error = '';+ } catch (e) {+ state.status = 'error';+ state.error = e?.message || 'save failed';+ }+ } while (again);})();- try {- await running;- } finally {- running = null;- }- if (again) {- again = false;- await run();- }+ running = chain;+ chain.then(() => {+ if (running === chain) running = null;+ });+ return chain;}return {@@ -56,8 +57,8 @@ export function createAutosave({ write, delay = 800 }) {timer = setTimeout(run, delay);},async flush() {- if (timer || again) return run();- if (running) await running;+ if (timer) await run();+ else if (running) await running;},/** Forget a pending write, for a document that is being thrown away. */cancel() {diff --git a/frontend/src/lib/autosave.svelte.test.js b/frontend/src/lib/autosave.svelte.test.jsindex b47a39c..5f5f4e5 100644--- a/frontend/src/lib/autosave.svelte.test.js+++ b/frontend/src/lib/autosave.svelte.test.js@@ -78,6 +78,87 @@ describe('createAutosave', () => {expect(write).toHaveBeenCalledTimes(1);});+ describe('a change made while a write is in flight', () => {+ /** Two writes the test ends by hand, logging when each starts and ends. */+ function twoWrites() {+ const log = [];+ const writes = [deferred(), deferred()];+ let n = 0;+ const write = vi.fn(() => {+ const i = n++;+ log.push(`start ${i + 1}`);+ return writes[i].promise.then(() => log.push(`end ${i + 1}`));+ });+ return { log, writes, write };+ }++ async function flushAfterBothWrites(saver, { log, writes }) {+ saver.flush().then(() => log.push('flushed'));+ writes[0].resolve();+ await vi.advanceTimersByTimeAsync(0);+ expect(log).toEqual(['start 1', 'end 1', 'start 2']);+ writes[1].resolve();+ await vi.advanceTimersByTimeAsync(0);+ expect(log).toEqual(['start 1', 'end 1', 'start 2', 'end 2', 'flushed']);+ expect(saver.pending).toBe(false);+ }++ it('is waited for by flush while its timer is still counting', async () => {+ const writes = twoWrites();+ const saver = createAutosave({ write: writes.write, delay: 100 });+ saver.schedule();+ await vi.advanceTimersByTimeAsync(100);+ saver.schedule(); // the timer is pending, the first write still running++ await flushAfterBothWrites(saver, writes);+ });++ it('is waited for by flush once it is queued behind the write', async () => {+ const writes = twoWrites();+ const saver = createAutosave({ write: writes.write, delay: 100 });+ saver.schedule();+ await vi.advanceTimersByTimeAsync(100);+ saver.schedule();+ await vi.advanceTimersByTimeAsync(100); // the timer fired into the running write++ await flushAfterBothWrites(saver, writes);+ });++ it('leaves the status of that second write when flush returns', async () => {+ const first = deferred();+ const second = deferred();+ const write = vi.fn().mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);+ const saver = createAutosave({ write, delay: 100 });+ saver.schedule();+ await vi.advanceTimersByTimeAsync(100);+ saver.schedule();++ let seen = null;+ saver.flush().then(() => (seen = { ...saver.state }));+ first.resolve();+ setTimeout(() => second.reject(new Error('gone')), 50);+ await vi.advanceTimersByTimeAsync(50);+ expect(write).toHaveBeenCalledTimes(2);+ expect(seen).toEqual({ status: 'error', error: 'gone' });+ });+ });++ it('keeps saving after a write that throws before it returns a promise', async () => {+ const write = vi.fn(() => {+ throw new Error('bad state');+ });+ const saver = createAutosave({ write, delay: 10 });+ saver.schedule();+ await saver.flush();+ expect(saver.state.status).toBe('error');+ expect(saver.pending).toBe(false);++ write.mockResolvedValue();+ saver.schedule();+ await saver.flush();+ expect(saver.state.status).toBe('saved');+ });+it('says a failed write failed, and tries again when asked', async () => {const write = vi.fn().mockRejectedValueOnce(new Error('disk full')).mockResolvedValue();const saver = createAutosave({ write, delay: 10 });diff --git a/frontend/src/lib/calendar.js b/frontend/src/lib/calendar.jsindex 9cef8d2..20f0976 100644--- a/frontend/src/lib/calendar.js+++ b/frontend/src/lib/calendar.js@@ -26,16 +26,7 @@ const MONTH = /^\d{4}-\d{2}$/;const pad = (value) => String(value).padStart(2, '0');-/** A `YYYY-MM-DD` as a UTC date, or null — the same strictness as the service- * routes, so a half-typed field never becomes a request. */-export function parseDay(iso) {- if (!DAY.test(String(iso ?? ''))) return null;- const at = new Date(`${iso}T00:00:00Z`);- // '2026-02-31' parses to March 3rd, which is not the day that was typed- return Number.isNaN(at.getTime()) || dayOf(at) !== iso ? null : at;-}--/** …and back. */+/** A UTC date as `YYYY-MM-DD`. */export function dayOf(at) {return at.toISOString().slice(0, 10);}diff --git a/frontend/src/lib/calendar.test.js b/frontend/src/lib/calendar.test.jsindex 388611a..75fa842 100644--- a/frontend/src/lib/calendar.test.js+++ b/frontend/src/lib/calendar.test.js@@ -6,7 +6,6 @@ import {monthOf,monthOutOfRange,outOfRange,- parseDay,shiftMonth,today,yearMonths,@@ -14,19 +13,6 @@ import {} from './calendar.js';describe('reading a day', () => {- it('takes the one form the services and the fields agree on', () => {- expect(parseDay('2026-09-12')?.toISOString()).toBe('2026-09-12T00:00:00.000Z');- for (const bad of ['', null, '12/09/2026', '2026-9-1', '2026-09-12T10:00']) {- expect(parseDay(bad), String(bad)).toBe(null);- }- });-- it('refuses a day that does not exist, rather than sliding into the next month', () => {- // `new Date('2026-02-31')` is March 3rd, which is not the day that was typed- expect(parseDay('2026-02-31')).toBe(null);- expect(parseDay('2024-02-29')).not.toBe(null); // …and a leap day does exist- });-it('reads today in UTC, the clock the fire layer keeps', () => {expect(today(new Date('2026-09-12T23:30:00Z'))).toBe('2026-09-12');});diff --git a/frontend/src/lib/composer.js b/frontend/src/lib/composer.jsindex be3f22d..93f9290 100644--- a/frontend/src/lib/composer.js+++ b/frontend/src/lib/composer.js@@ -194,11 +194,6 @@ export function footerBand(footerSize = FOOTER_SIZE, lines = 1) {return Math.round(footerSize + 13) * Math.max(1, lines);}-// Default band heights, derived from the size defaults so they can't drift out-// of sync when those change (they mirror legendLineHeight()/footerBand()).-export const LEGEND_LINE_H = legendLineHeight();-export const FOOTER_H = footerBand();-/** Distinct row indices in ascending order (default row 0). */function rowOrder(panels) {return [...new Set(panels.map((p) => p.row ?? 0))].sort((a, b) => a - b);diff --git a/frontend/src/lib/composer.test.js b/frontend/src/lib/composer.test.jsindex 9fe6a05..80f722e 100644--- a/frontend/src/lib/composer.test.js+++ b/frontend/src/lib/composer.test.js@@ -1,6 +1,6 @@import { describe, it, expect } from 'vitest';import {- PAD, PANEL_H, GAP, ROW_GAP, FOOTER_H, LEGEND_LINE_H,+ PAD, PANEL_H, GAP, ROW_GAP,layoutPanels, layoutPanelsFree, freeNormalizeDelta, panelsBottom,panelsBlockHeight, panelHeight, panelScale, captionBand, legendLineHeight, footerBand,docSize, legendColumns, legendRowCount, toSpec, offsetShape, copyShapeSpec, autoLayoutRows, TWEET_GUIDES,@@ -210,7 +210,7 @@ describe('docSize — free layout', () => {];const { width, height } = docSize(panels, [], {}, {}, [], 'free');expect(width).toBe(2720 + PAD);- expect(height).toBe(1020 + FOOTER_H + PAD);+ expect(height).toBe(1020 + footerBand() + PAD);});});@@ -276,7 +276,7 @@ describe('docSize', () => {it('sizes a single panel with no legend', () => {const { width, height } = docSize([landscape(1000, 500, { caption: 'c' })], [], {});expect(width).toBe(PAD + 1440 + PAD);- expect(height).toBe(PAD + (PANEL_H + captionBand()) + FOOTER_H + PAD);+ expect(height).toBe(PAD + (PANEL_H + captionBand()) + footerBand() + PAD);});it('accounts for custom caption / legend / footer sizes', () => {@@ -295,8 +295,8 @@ describe('docSize', () => {const shapes = [{ kind: 'rect', color: '#ff5252', panel: 'p1' }];const notes = { '#ff5252': 'road junction' };const { height } = docSize(panels, shapes, notes);- const legendH = 10 + 1 * LEGEND_LINE_H;- expect(height).toBe(PAD + panelsBlockHeight(panels) + legendH + FOOTER_H + PAD);+ const legendH = 10 + 1 * legendLineHeight();+ expect(height).toBe(PAD + panelsBlockHeight(panels) + legendH + footerBand() + PAD);});});@@ -1640,7 +1640,7 @@ describe('docSize — footer can be switched off', () => {const panels = [landscape(1000, 500)];const on = docSize(panels, [], {}, { footerEnabled: true });const off = docSize(panels, [], {}, { footerEnabled: false });- expect(on.height - off.height).toBe(FOOTER_H);+ expect(on.height - off.height).toBe(footerBand());});it('footer off + no captions + no margins reduces to just the panels', () => {diff --git a/frontend/src/lib/entityIcon.js b/frontend/src/lib/entityIcon.jsindex e2aac3d..4c64b08 100644--- a/frontend/src/lib/entityIcon.js+++ b/frontend/src/lib/entityIcon.js@@ -45,13 +45,6 @@ export function mediaKindOf(e) {return 'file';}-/** Media entities normally carry the same `kind` the Media Library uses to tell- * video from image; fall back to the file extension for entities filed before- * that attr existed. */-export function isVideoEntity(e) {- return mediaKindOf(e) === 'video';-}-/** The icon a media kind is drawn with. The registry cannot make this call: a* `media` is one type, and what the bytes are is a property of the file. */const MEDIA_ICONS = { image: 'image', video: 'video', audio: 'audio', file: 'file' };diff --git a/frontend/src/lib/entityIcon.test.js b/frontend/src/lib/entityIcon.test.jsindex 46c3b64..8188f2b 100644--- a/frontend/src/lib/entityIcon.test.js+++ b/frontend/src/lib/entityIcon.test.js@@ -64,18 +64,6 @@ describe('entityIcon', () => {});});-describe('isVideoEntity', () => {- it('falls back to the extension for media filed before `kind` existed', () => {- expect(mod.isVideoEntity({ attrs: { path: 'raw/clip_04.MP4' } })).toBe(true);- expect(mod.isVideoEntity({ attrs: { path: 'raw/frame.png' } })).toBe(false);- expect(mod.isVideoEntity({ attrs: {} })).toBe(false);- });-- it('trusts `kind` over the extension', () => {- expect(mod.isVideoEntity({ attrs: { kind: 'image', path: 'weird.mp4' } })).toBe(false);- });-});-describe('madeHereLabel / madeHereBy', () => {it('names the act for material the case made out of what it holds', () => {expect(mod.madeHereLabel({ origin: 'inspect', op: 'frame' })).toBe('Frame');diff --git a/frontend/src/lib/entityTypes.svelte.js b/frontend/src/lib/entityTypes.svelte.jsindex 170b46c..ea87397 100644--- a/frontend/src/lib/entityTypes.svelte.js+++ b/frontend/src/lib/entityTypes.svelte.js@@ -124,12 +124,6 @@ export function entityTypes() {return registry.types;}-/** The families, in the order the registry lists their types. What the board- * filters by first: a handful of readings is a menu, every type is a list. */-export function entityFamilies() {- return [...new Set(registry.types.map((entry) => entry.family))];-}-/** The types an analyst creates by hand, for a create menu. A `media` is born* from an import, so it is not one of them. */export function creatableTypes() {@@ -147,11 +141,6 @@ export function promotableTypes() {return registry.types.filter((entry) => entry.promotable);}-/** Whether this type is entered as a graph record rather than born from a tool. */-export function isManualEntityType(type) {- return Boolean(entryFor(type)?.manual);-}-/** Whether Details may attach presentation photos to this type. */export function hasImageGallery(type) {return Boolean(entryFor(type)?.image_gallery);diff --git a/frontend/src/lib/entityTypes.test.js b/frontend/src/lib/entityTypes.test.jsindex e93d89f..5418861 100644--- a/frontend/src/lib/entityTypes.test.js+++ b/frontend/src/lib/entityTypes.test.js@@ -127,10 +127,9 @@ describe('the entity vocabulary', () => {expect(marked.map((f) => f.heads)).toEqual(['', '']);});- it('names the families in registry order, which is what the board filters by', async () => {+ it('lists the types in registry order', async () => {await mod.loadEntityTypes();- expect(mod.entityFamilies()).toEqual(['actor', 'place', 'collected', 'document']);expect(mod.entityTypes().map((e) => e.type)).toEqual(['person', 'place', 'media', 'bookmark']);});@@ -157,8 +156,6 @@ describe('the entity vocabulary', () => {// a media is born from an import and a place from a save, so neither belongs// in a create menuexpect(mod.creatableTypes().map((e) => e.type)).toEqual(['person']);- expect(mod.isManualEntityType('person')).toBe(true);- expect(mod.isManualEntityType('media')).toBe(false);});it('says which types have presentation photos', async () => {diff --git a/frontend/src/lib/extensionMapEngine.test.js b/frontend/src/lib/extensionMapEngine.test.jsindex 62cab04..957f3ba 100644--- a/frontend/src/lib/extensionMapEngine.test.js+++ b/frontend/src/lib/extensionMapEngine.test.js@@ -158,23 +158,15 @@ function open({ recording, size, ratio = 1, parse, storage = {}, firefox = falsestatus: () =>panel.state.collapsed? ''- : document- .getElementById('azimut-map-tools')- .shadowRoot.querySelector('.status span').textContent,- canvas: () => document.getElementById('azimut-map-tools').shadowRoot.querySelector('canvas'),+ : window.__AZIMUT_MAP_TOOLS__.root.querySelector('.status span').textContent,+ canvas: () => window.__AZIMUT_MAP_TOOLS__.root.querySelector('canvas'),/** The offset the panel settled on, where the analyst can read it. */statusTitle: () =>- document- .getElementById('azimut-map-tools')- .shadowRoot.querySelector('.status span')- .getAttribute('title') ?? '',+ window.__AZIMUT_MAP_TOOLS__.root.querySelector('.status span').getAttribute('title') ?? '',/** Pick a tool up, the way the analyst does — nothing is drawn until one* is open, so nothing about the drawing can be asserted until one is. */pick: (id) =>- document- .getElementById('azimut-map-tools')- .shadowRoot.querySelector(`[data-tab="${id}"]`)- .click(),+ window.__AZIMUT_MAP_TOOLS__.root.querySelector(`[data-tab="${id}"]`).click(),};}@@ -880,7 +872,7 @@ describe('zoomed out', () => {* them — so out there the panel refuses and says what to do instead.*/describe('a globe camera, which is not a map', () => {- const root = () => document.getElementById('azimut-map-tools').shadowRoot;+ const root = () => window.__AZIMUT_MAP_TOOLS__.root;const google = () => fixture.recordings.find((r) => r.site === 'google-maps');const keyed = {'/api/ingest/firms/sensors': { keyed: true, sensors: [{ id: 'viirs', label: 'VIIRS' }] },@@ -1094,7 +1086,7 @@ describe('Google Earth', () => {*/describe('a reference whose name does not fit', () => {const LONG = 'Long clip - 10. Mykhailivka railway bridge battles, 05 September, drone footage';- const root = () => document.getElementById('azimut-map-tools').shadowRoot;+ const root = () => window.__AZIMUT_MAP_TOOLS__.root;it('keeps the name reachable, and lets every box round it shrink', async () => {const recording = fixture.recordings.find((r) => r.site === 'google-maps');@@ -1126,7 +1118,7 @@ describe('a reference whose name does not fit', () => {* labelled, like everything else drawn out there, but never switched off.*/describe('the sky tool, zoomed out', () => {- const root = () => document.getElementById('azimut-map-tools').shadowRoot;+ const root = () => window.__AZIMUT_MAP_TOOLS__.root;it('stays available on a globe, where only the distances are doubtful', async () => {const recording = fixture.recordings.find((r) => r.site === 'google-maps');@@ -1162,7 +1154,7 @@ describe('the sky tool, zoomed out', () => {* click.*/describe('the fire layer in the panel', () => {- const root = () => document.getElementById('azimut-map-tools').shadowRoot;+ const root = () => window.__AZIMUT_MAP_TOOLS__.root;const seat = () => root().querySelector('[data-tab="fires"]');const google = () => fixture.recordings.find((r) => r.site === 'google-maps');@@ -1226,7 +1218,7 @@ describe('the fire layer in the panel', () => {const nw = M.toScreen({ lat: asked.north, lon: asked.west }, view, area);const se = M.toScreen({ lat: asked.south, lon: asked.east }, view, area);- const img = document.getElementById('azimut-map-tools').shadowRoot.querySelector('img');+ const img = window.__AZIMUT_MAP_TOOLS__.root.querySelector('img');const px = (name) => Number.parseFloat(img.style[name]);// the box is centred and pulled back by half itself, so its north edge is// the top of the ground it was drawn for@@ -1304,3 +1296,53 @@ describe('the fire layer in the panel', () => {expect(live.state.tool).toBe('fires');});});++// --- the page the panel is drawn over ----------------------------------------++/**+ * The panel lives in someone else's page, and that page's scripts share the DOM.+ * Neither what it shows (case names, points, pictures) nor its buttons may be+ * reachable from them.+ */+describe('the site under the panel', () => {+ const untrusted = (type) => {+ const event = new window.MouseEvent(type, { bubbles: true, composed: true });+ Object.defineProperty(event, 'isTrusted', { value: false });+ return event;+ };++ it('reads no shadow root off the panel', async () => {+ panel = open({ parse: () => null });+ await tick();++ expect(document.getElementById('azimut-map-tools').shadowRoot).toBeNull();+ expect(window.__AZIMUT_MAP_TOOLS__.root.querySelector('[data-tab="measure"]')).not.toBeNull();+ });++ it('cannot press a button for the analyst', async () => {+ panel = open({ parse: () => null });+ await tick();+ const tab = window.__AZIMUT_MAP_TOOLS__.root.querySelector('[data-tab="pins"]');++ tab.dispatchEvent(untrusted('click'));+ await tick();+ expect(panel.state.tool).not.toBe('pins');++ tab.click();+ await tick();+ expect(panel.state.tool).toBe('pins');+ });++ it('cannot click the map through the panel either', async () => {+ panel = open({ parse: () => null });+ await tick();+ const asked = panel.api.runtime.sendMessage.mock.calls.length;++ for (const type of ['pointerdown', 'pointerup', 'click', 'dblclick']) {+ window.dispatchEvent(untrusted(type));+ }+ await tick();++ expect(panel.api.runtime.sendMessage.mock.calls.length).toBe(asked);+ });+});diff --git a/frontend/src/lib/extensionMapFiles.test.js b/frontend/src/lib/extensionMapFiles.test.jsindex 949778b..c7f4e81 100644--- a/frontend/src/lib/extensionMapFiles.test.js+++ b/frontend/src/lib/extensionMapFiles.test.js@@ -131,7 +131,7 @@ function open({ bytes, chunk }) {undefined);const panel = window.__AZIMUT_MAP_TOOLS__;- const root = () => document.getElementById('azimut-map-tools').shadowRoot;+ const root = () => window.__AZIMUT_MAP_TOOLS__.root;return {...panel,root,diff --git a/frontend/src/lib/extensionMapLink.test.js b/frontend/src/lib/extensionMapLink.test.jsindex 5da9d7b..6a92f0f 100644--- a/frontend/src/lib/extensionMapLink.test.js+++ b/frontend/src/lib/extensionMapLink.test.js@@ -271,7 +271,7 @@ function open({ extra = {}, href = 'https://www.openstreetmap.org/#map=17/50.45/undefined);const panel = window.__AZIMUT_MAP_TOOLS__;- const root = () => document.getElementById('azimut-map-tools').shadowRoot;+ const root = () => window.__AZIMUT_MAP_TOOLS__.root;const link = () => links.at(-1);return {...panel,diff --git a/frontend/src/lib/extensionMapSync.test.js b/frontend/src/lib/extensionMapSync.test.jsindex a34441b..39e49ba 100644--- a/frontend/src/lib/extensionMapSync.test.js+++ b/frontend/src/lib/extensionMapSync.test.js@@ -137,7 +137,7 @@ function open({ answers } = {}) {undefined);const panel = window.__AZIMUT_MAP_TOOLS__;- const root = () => document.getElementById('azimut-map-tools').shadowRoot;+ const root = () => window.__AZIMUT_MAP_TOOLS__.root;return {...panel,app,@@ -359,7 +359,7 @@ describe('an open sweep', () => {describe('the beta badge', () => {const badge = () =>- document.getElementById('azimut-map-tools').shadowRoot.querySelector('header .beta');+ window.__AZIMUT_MAP_TOOLS__.root.querySelector('header .beta');it('marks every tool that draws on the ground, on whichever map', async () => {// It used to name Google Earth. The caveat was never about the site: thesediff --git a/frontend/src/lib/guide.js b/frontend/src/lib/guide.jsindex d454054..e4754e0 100644--- a/frontend/src/lib/guide.js+++ b/frontend/src/lib/guide.js@@ -55,8 +55,8 @@ export const GUIDE = [text: 'Azimut owns the azimut/ directory inside a case and leaves the rest of the folder alone. A closed case can be copied as it is.',},{- label: 'Nothing leaves this machine',- text: 'Network access follows an action that needs it, such as a map tile or a download. The one call made on its own is an optional check for a new release, and Settings turns it off.',+ 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.',},{label: 'The rail is a sequence',@@ -212,7 +212,7 @@ export const GUIDE = [},{label: 'Somebody else’s map over yours',- text: 'Add a layer opens a KML, KMZ, GeoJSON or GPX file, follows a public My Maps, or brings in a GeoConfirmed conflict by dates and area. Its legend and its time strip filter it, and nothing in it joins the case.',+ text: 'Add a layer opens a KML, KMZ, GeoJSON or GPX file, follows a public My Maps, or brings in a GeoConfirmed conflict by dates and area. Its legend and its time strip filter it. It is saved with the case, and its features never become entities.',},{label: 'The search bar answers before it asks',@@ -228,7 +228,7 @@ export const GUIDE = [},{label: 'Compare keeps the ground fixed',- text: 'Read two locked views side by side, by swipe, opacity or blink. On a matched pair, Difference highlights what changed over any of them; notes, shapes and stamped markers stay editable in the saved comparison and appear in its outputs.',+ text: 'Read two locked views side by side, by swipe, fade or blink. On a matched pair, Difference highlights what changed over any of them; notes, shapes and stamped markers stay editable in the saved comparison and appear in its outputs.',},{label: 'All dates, and when it appeared',diff --git a/frontend/src/lib/inspect.js b/frontend/src/lib/inspect.jsindex 9ac110d..dccbf11 100644--- a/frontend/src/lib/inspect.js+++ b/frontend/src/lib/inspect.js@@ -388,33 +388,6 @@ export function quadEdgeMidpoints(quad) {}));}-/**- * Move one edge of `quad` by the drag (dx, dy) *projected onto that edge's- * outward normal* — a resize that keeps the edge parallel and the opposite edge- * fixed. Works on a warped quad (both endpoints shift together) and composes- * with the per-corner warp, since it only moves two of the four points.- */-export function moveQuadEdge(quad, side, dx, dy) {- const [a, b] = QUAD_SIDES[side];- const ex = quad[b][0] - quad[a][0];- const ey = quad[b][1] - quad[a][1];- const len = Math.hypot(ex, ey) || 1;- let nx = -ey / len;- let ny = ex / len;- const [cx, cy] = quadCentroid(quad);- const mx = (quad[a][0] + quad[b][0]) / 2;- const my = (quad[a][1] + quad[b][1]) / 2;- if ((mx - cx) * nx + (my - cy) * ny < 0) {- nx = -nx;- ny = -ny;- }- const t = dx * nx + dy * ny; // drag projected onto the outward normal- const out = quad.map(([x, y]) => [x, y]);- out[a] = [quad[a][0] + nx * t, quad[a][1] + ny * t];- out[b] = [quad[b][0] + nx * t, quad[b][1] + ny * t];- return out;-}-/** Centroid (mean of the 4 corners) of a quad. */export function quadCentroid(quad) {const cx = (quad[0][0] + quad[1][0] + quad[2][0] + quad[3][0]) / 4;@@ -451,13 +424,6 @@ export function collageBounds(nodes, pad = 0) {};}-/** Mean distance from the centroid to the corners — the quad's "radius". */-export function quadRadius(quad) {- const [cx, cy] = quadCentroid(quad);- const d = quad.reduce((s, [x, y]) => s + Math.hypot(x - cx, y - cy), 0);- return d / quad.length || 1;-}-/** Rotate a quad by `rad` radians around a fixed point (its centroid by default). */export function rotateQuad(quad, rad, center = null) {const [cx, cy] = center ?? quadCentroid(quad);diff --git a/frontend/src/lib/inspect.test.js b/frontend/src/lib/inspect.test.jsindex 9aec35c..68a0c43 100644--- a/frontend/src/lib/inspect.test.js+++ b/frontend/src/lib/inspect.test.js@@ -1,7 +1,7 @@import { describe, it, expect } from 'vitest';import {clampCrop, moveCrop, resizeCropByHandle,- QUAD_SIDES, quadEdgeMidpoints, moveQuadEdge, quadCentroid,+ QUAD_SIDES, quadEdgeMidpoints, quadCentroid,quadsBounds, translateQuad, moveQuads, rotateQuads, scaleQuads, pinholeOps,buildFrameOps, hasVideoEdits, normalizeRightAngleRotation, rotationOps,sourceStem, timecode, frameSaveName, frameSaveNames, saveNameOf,@@ -136,7 +136,7 @@ describe('resizeCropByHandle', () => {});});-describe('quad side resize', () => {+describe('quad side handles', () => {const rect = [[0, 0], [100, 0], [100, 80], [0, 80]]; // TL,TR,BR,BLit('exposes an edge midpoint per side', () => {@@ -145,38 +145,6 @@ describe('quad side resize', () => {expect(mids[0]).toMatchObject({ side: 0, x: 50, y: 0 }); // topexpect(mids[2]).toMatchObject({ side: 2, x: 50, y: 80 }); // bottom});-- it('grows the rect by dragging the right edge outward', () => {- const out = moveQuadEdge(rect, 1, 40, 0); // right edge, drag +x- expect(out[1][0]).toBe(140); // TR moved out- expect(out[2][0]).toBe(140); // BR moved out- expect(out[0]).toEqual([0, 0]); // left edge fixed- expect(out[3]).toEqual([0, 80]);- });-- it('ignores drag parallel to the edge (projects onto the normal)', () => {- const out = moveQuadEdge(rect, 1, 0, 30); // right edge, drag along the edge- expect(out[1][0]).toBe(100);- expect(out[2][0]).toBe(100);- });-- it('keeps the opposite edge fixed on a warped quad', () => {- const warped = [[10, 5], [110, 0], [120, 90], [0, 85]];- const out = moveQuadEdge(warped, 0, 0, -20); // top edge outward (up)- // bottom corners unchanged- expect(out[2]).toEqual(warped[2]);- expect(out[3]).toEqual(warped[3]);- // top corners moved- expect(out[0]).not.toEqual(warped[0]);- expect(out[1]).not.toEqual(warped[1]);- });-- it('moving an edge out then back returns near the start', () => {- const c0 = quadCentroid(rect);- const out = moveQuadEdge(moveQuadEdge(rect, 1, 40, 0), 1, -40, 0);- const c1 = quadCentroid(out);- expect(near(c0[0], c1[0], 1e-9)).toBe(true);- });});// ---------------------------------------------------------------------------diff --git a/frontend/src/lib/map/addedLayers.js b/frontend/src/lib/map/addedLayers.jsindex 09fe07f..f2d41c5 100644--- a/frontend/src/lib/map/addedLayers.js+++ b/frontend/src/lib/map/addedLayers.js@@ -37,9 +37,6 @@ export const PALETTE = ['#9aa7ff',];-/** Past this a snapshot is old enough that the row says so before it redraws. */-export const FRESH_FOR_HOURS = 24;-/*** Whether a layer follows its source rather than holding a file: a pasted* address, or a GeoConfirmed conflict. Those are re-read on Refresh and on casediff --git a/frontend/src/lib/map/analyzers.js b/frontend/src/lib/map/analyzers.jsindex 9433857..7b678a9 100644--- a/frontend/src/lib/map/analyzers.js+++ b/frontend/src/lib/map/analyzers.js@@ -15,13 +15,6 @@ export function marksToZones(marks, previous = []) {}));}-/** Detect reads Sentinel-2 bands, so a map showing anything else has nothing to give it. */-export function mapSource(side) {- if (side?.provider !== 'sentinel2') return null;- return { provider: 'sentinel2', date: side.sentinel?.date || '',- layer: side.sentinel?.layer || 'TRUE_COLOR', maxcc: side.sentinel?.maxcc ?? 30 };-}-/** Display clustering changes only marker layout; persisted candidates stay intact. */export function displayGroups(rows, project, radius = 24) {const groups = [];diff --git a/frontend/src/lib/map/analyzers.test.js b/frontend/src/lib/map/analyzers.test.jsindex 39f9493..7f7ee5f 100644--- a/frontend/src/lib/map/analyzers.test.js+++ b/frontend/src/lib/map/analyzers.test.js@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest';-import { analyzerGroups, analyzerLock, coverage, describeMeasure, displayGroups, framesPerTile, mapSource, marksToZones, readableDuration, sizeBand, sizeOf, sourceLabel, viewZone, zoneMarks, zoneRing } from './analyzers.js';+import { analyzerGroups, analyzerLock, coverage, describeMeasure, displayGroups, framesPerTile, marksToZones, readableDuration, sizeBand, sizeOf, sourceLabel, viewZone, zoneMarks, zoneRing } from './analyzers.js';describe('saved analysis geometry', () => {it('keeps geographic points and names when drawings are edited', () => {@@ -8,11 +8,7 @@ describe('saved analysis geometry', () => {expect(marksToZones(marks, zones)).toEqual(zones);expect(marksToZones([{ ...marks[0], points: [[2, 2], [3, 2], [3, 3]] }], zones)[0].name).toBe('Port');});- it('takes only Sentinel-2 from the maps, because Detect reads its bands', () => {- expect(mapSource({ provider: 'google' })).toBeNull();- expect(mapSource({ provider: 'esri-wayback', wayback_release: 123 })).toBeNull();- expect(mapSource({ provider: 'sentinel2', sentinel: { date: '2026-05-11', layer: 'SWIR', maxcc: 20 } }))- .toEqual({ provider: 'sentinel2', date: '2026-05-11', layer: 'SWIR', maxcc: 20 });+ it('names a run by the date it read, or the release an older run read', () => {expect(sourceLabel({ provider: 'sentinel2', date: '2026-05-11' })).toBe('2026-05-11');// runs saved before still say what they readexpect(sourceLabel({ provider: 'esri-wayback', release: 7 })).toBe('Wayback release 7');diff --git a/frontend/src/lib/map/changeCapture.js b/frontend/src/lib/map/changeCapture.jsindex f1a83b3..80eac4e 100644--- a/frontend/src/lib/map/changeCapture.js+++ b/frontend/src/lib/map/changeCapture.js@@ -33,7 +33,7 @@ const grow = (box, share) => {const covers = (outer, inner) => outer.west <= inner.west && outer.east >= inner.east&& outer.south <= inner.south && outer.north >= inner.north;-/** Only for tests and for a case being closed: the held frames are per session. */+/** For tests only: the held frames otherwise last as long as the page. */export function forgetBandFrames() {held.clear();}diff --git a/frontend/src/lib/map/compare.js b/frontend/src/lib/map/compare.jsindex d7601c4..b31df51 100644--- a/frontend/src/lib/map/compare.js+++ b/frontend/src/lib/map/compare.js@@ -41,12 +41,6 @@ export const COMPARE_LAYERS = Object.freeze([{ id: 'saved', label: 'Saved work', hint: 'Places and captures in this case', group: 'case' },]);-export const LAYER_GROUPS = Object.freeze([- { id: 'reference', label: 'Reference' },- { id: 'events', label: 'Dated observations' },- { id: 'case', label: 'This case' },-]);-const LAYER_IDS = new Set(COMPARE_LAYERS.map((layer) => layer.id));/** Keep a session's layer list ordered, unique and supported. */diff --git a/frontend/src/lib/map/facade.js b/frontend/src/lib/map/facade.jsindex ee46caf..0c8ce26 100644--- a/frontend/src/lib/map/facade.js+++ b/frontend/src/lib/map/facade.js@@ -46,9 +46,6 @@ const EVENTS = {contextmenu: ['contextmenu'],};-/** The vocabulary `on()` accepts. */-export const MAP_EVENTS = Object.keys(EVENTS);-/*** How much deeper the app's zoom counts than the engine's.*diff --git a/frontend/src/lib/map/facade.test.js b/frontend/src/lib/map/facade.test.jsindex ab322e4..03d915f 100644--- a/frontend/src/lib/map/facade.test.js+++ b/frontend/src/lib/map/facade.test.js@@ -1,6 +1,5 @@import { describe, expect, it, vi } from 'vitest';import {- MAP_EVENTS,engineEvents,engineZoom,exactViewZoom,@@ -277,8 +276,9 @@ describe('framing a set of points', () => {describe('the event vocabulary', () => {it('names what happened to the view, not what the engine calls it', () => {- expect(MAP_EVENTS).toEqual(['view-settled', 'view-move', 'rotate', 'click', 'contextmenu']);expect(engineEvents('view-settled')).toEqual(['moveend']);+ expect(engineEvents('view-move')).toEqual(['move']);+ for (const name of ['rotate', 'click', 'contextmenu']) expect(engineEvents(name)).toEqual([name]);});it('refuses a name it does not know', () => {diff --git a/frontend/src/lib/map/groundFrame.js b/frontend/src/lib/map/groundFrame.jsindex 1d1228e..e98e78a 100644--- a/frontend/src/lib/map/groundFrame.js+++ b/frontend/src/lib/map/groundFrame.js@@ -174,15 +174,4 @@ export function compassAngle(value) {return folded >= 360 - 1e-9 ? 0 : folded;}-/**- * The ground corners of a view, as `[lon, lat]`, clockwise from top-left.- * What a computed overlay remembers about where it lies.- */-export function frameCorners(frame) {- const toGround = screenToMercator(frame);- return [[0, 0], [frame.width, 0], [frame.width, frame.height], [0, frame.height]].map(- ([x, y]) => fromMercator(...apply(toGround, x, y))- );-}-export const cssMatrix = (m) => `matrix(${m.a}, ${m.b}, ${m.c}, ${m.d}, ${m.e}, ${m.f})`;diff --git a/frontend/src/lib/map/passStrip.js b/frontend/src/lib/map/passStrip.jsindex c8d0126..6c44f14 100644--- a/frontend/src/lib/map/passStrip.js+++ b/frontend/src/lib/map/passStrip.js@@ -130,13 +130,6 @@ export function entryOf(entries, archive, side) {return day ? entries.find((entry) => entry.key === day) ?? null : null;}-/** What a side becomes when the strip shows a row on it. */-export function sidePatch(archive, entry) {- if (archive === WAYBACK_ID) return { wayback_release: entry.release };- if (archive === RADAR_ID) return { radar: { date: entry.date, time: entry.time } };- return { sentinel: { date: entry.date } };-}-// -- the bracket ------------------------------------------------------------------/**diff --git a/frontend/src/lib/map/passStrip.test.js b/frontend/src/lib/map/passStrip.test.jsindex 612abd2..0e3dafe 100644--- a/frontend/src/lib/map/passStrip.test.js+++ b/frontend/src/lib/map/passStrip.test.js@@ -7,7 +7,6 @@ import {lookupPath,lookupWindow,nextProbe,- sidePatch,startBracket,stripArchive,stripEntries,@@ -57,8 +56,6 @@ describe('the strip', () => {{ release: 55, acquired: '2025-02-20' }, { release: 41, acquired: '2023-06-11' }] });expect(wayback.map((row) => row.release)).toEqual([41, 55]);expect(entryOf(wayback, 'esri-wayback', { wayback_release: null })).toBe(wayback[1]);- expect(sidePatch('esri-wayback', wayback[0])).toEqual({ wayback_release: 41 });- expect(sidePatch('sentinel1', radar[0])).toEqual({ radar: { date: '2026-05-02', time: '05:42:40' } });});});diff --git a/frontend/src/lib/map/tools.js b/frontend/src/lib/map/tools.jsindex 49c03d7..3cdfbba 100644--- a/frontend/src/lib/map/tools.js+++ b/frontend/src/lib/map/tools.js@@ -102,33 +102,6 @@ export const MAP_ACTIONS = [},];-/**- * What can be drawn over the imagery.- *- * These never take a rail seat. That distinction is the point of the rework:- * the old cluster mixed "what I am doing" with "what is shown", and put OSM- * labels and saved pins in a toolbox.- *- * `handoff: true` marks a layer that only exists because another tool sent- * something here — a sheet's coordinate column, a Timeline window. It appears- * in the list when it arrives and leaves when it is closed, so it is never an- * empty switch.- */-export const MAP_LAYERS = [- { id: 'labels', label: 'OSM labels', icon: 'text' },- { id: 'boundaries', label: 'Borders', icon: 'polygon' },- { id: 'roads', label: 'Roads', icon: 'line' },- { id: 'railway', label: 'OSM railways', icon: 'line' },- { id: 'power', label: 'Power lines', icon: 'network' },- { id: 'seamarks', label: 'Sea marks', icon: 'ship' },- { id: 'gpstraces', label: 'GPS traces', icon: 'freehand' },- { id: 'firms', label: 'Active fires', icon: 'flame' },- { id: 'nightlights', label: 'Night lights', icon: 'moon' },- { id: 'saved', label: 'Saved work', icon: 'pin' },- { id: 'sheet', label: 'Sheet points', icon: 'table', handoff: true },- { id: 'timeline', label: 'Timeline points', icon: 'clock', handoff: true },-];-/** The rail's entries, in order, with the one-shot actions filed in their group. */export function railEntries(modes = MAP_MODES, actions = MAP_ACTIONS) {return [diff --git a/frontend/src/lib/map/tools.test.js b/frontend/src/lib/map/tools.test.jsindex 16c5bc4..bfcb858 100644--- a/frontend/src/lib/map/tools.test.js+++ b/frontend/src/lib/map/tools.test.js@@ -1,7 +1,6 @@import { describe, expect, it } from 'vitest';import {MAP_ACTIONS,- MAP_LAYERS,MAP_MODES,arm,armedId,@@ -132,13 +131,8 @@ describe('the declarations themselves', () => {}});- it('keeps every id unique across modes, actions and layers', () => {- const ids = [...MAP_MODES, ...MAP_ACTIONS, ...MAP_LAYERS].map((entry) => entry.id);+ it('keeps every id unique across modes and actions', () => {+ const ids = [...MAP_MODES, ...MAP_ACTIONS].map((entry) => entry.id);expect(new Set(ids).size).toBe(ids.length);});-- it('gives no layer a rail seat', () => {- const rail = new Set(railEntries().map((entry) => entry.id));- for (const layer of MAP_LAYERS) expect(rail.has(layer.id)).toBe(false);- });});diff --git a/frontend/src/lib/naming.js b/frontend/src/lib/naming.jsindex 020946b..f7e1dd5 100644--- a/frontend/src/lib/naming.js+++ b/frontend/src/lib/naming.js@@ -36,18 +36,6 @@ export function slugify(text, fallback) {return name;}-/**- * A name that doesn't collide with `taken`: `base` when free, else `base 2`,- * `base 3`, … `taken` is a Set or array of names already in the case.- */-export function uniqueName(base, taken) {- const set = taken instanceof Set ? taken : new Set(taken);- if (!set.has(base)) return base;- let n = 2;- while (set.has(`${base} ${n}`)) n += 1;- return `${base} ${n}`;-}-/*** Name for a fresh item of `kind`: "Collage 1", "Proof 1", … taking the lowest* free number so the case doesn't count past the gaps deletions leave behind.@@ -106,16 +94,6 @@ export function savedEntities(entities, kind) {});}-/** The name one filed entity is saved under, or '' if it carries no spec.- * This is the name the tools reopen by, so it has to follow the spec's folder- * wherever the case layout moves it. */-export function specStem(entity, kind) {- const { dir, attr } = SPEC_ATTR[kind];- const spec = entity?.attrs?.[attr];- if (typeof spec !== 'string' || !spec.startsWith(dir) || !spec.endsWith('.json')) return '';- return spec.slice(dir.length, -5);-}-/** Slugs of everything of `kind` already saved — the collision set. */export function savedSlugs(entities, kind) {const { dir, attr } = SPEC_ATTR[kind];diff --git a/frontend/src/lib/naming.test.js b/frontend/src/lib/naming.test.jsindex 925b695..2925373 100644--- a/frontend/src/lib/naming.test.js+++ b/frontend/src/lib/naming.test.js@@ -1,6 +1,6 @@import { describe, it, expect } from 'vitest';import {- MAX_SLUG, NAME_PREFIX, slugify, uniqueName, nextName, isDefaultName,+ MAX_SLUG, NAME_PREFIX, slugify, nextName, isDefaultName,savedEntities, savedSlugs, savedTitles, savedTitle, specAttr, specPath,} from './naming.js';@@ -40,18 +40,6 @@ describe('nextName — the default name of a fresh item', () => {});});-describe('uniqueName — a typed name that has to read apart', () => {- it('returns the base when it is free', () => {- expect(uniqueName('Rooftop', new Set())).toBe('Rooftop');- expect(uniqueName('Rooftop', ['Bridge'])).toBe('Rooftop');- });-- it('numbers past the base and any run already taken', () => {- expect(uniqueName('Rooftop', new Set(['Rooftop']))).toBe('Rooftop 2');- expect(uniqueName('Rooftop', ['Rooftop', 'Rooftop 2', 'Rooftop 3'])).toBe('Rooftop 4');- });-});-describe('isDefaultName — an assigned name is not a description', () => {it('recognizes the names this app assigns', () => {expect(isDefaultName('Proof 1', 'proof')).toBe(true);diff --git a/frontend/src/lib/proofIcons.js b/frontend/src/lib/proofIcons.jsindex a742f88..2c669b7 100644--- a/frontend/src/lib/proofIcons.js+++ b/frontend/src/lib/proofIcons.js@@ -133,13 +133,6 @@ export function iconOrigin(name, size) {return { x: -ax * size, y: -ay * size };}-/** Box a placed symbol covers, in the surface's natural pixels. */-export function iconBox(shape) {- const size = shape.size ?? ICON_SIZE_DEFAULT;- const origin = iconOrigin(shape.name, size);- return { x: (shape.x ?? 0) + origin.x, y: (shape.y ?? 0) + origin.y, w: size, h: size };-}-/*** Placed side in natural pixels, so a symbol reads the same on a 4000px frame* and an 800px one. Mirrors how stroke width is normalised by `baseScale`.diff --git a/frontend/src/lib/proofIcons.test.js b/frontend/src/lib/proofIcons.test.jsindex 4244771..2a8d277 100644--- a/frontend/src/lib/proofIcons.test.js+++ b/frontend/src/lib/proofIcons.test.js@@ -5,7 +5,6 @@ import {PROOF_ICONS,glyphInk,iconAnchor,- iconBox,iconByName,iconOrigin,iconSizeFor,@@ -60,9 +59,13 @@ describe('where a symbol sits', () => {});it('keeps the pin’s tip still while it is resized', () => {- const pin = { name: 'point', x: 300, y: 200 };- const small = iconBox({ ...pin, size: 40 });- const large = iconBox({ ...pin, size: 120 });+ // the box a pin stored at (300, 200) covers, drawn at `size`+ const boxAt = (size) => {+ const origin = iconOrigin('point', size);+ return { x: 300 + origin.x, y: 200 + origin.y, w: size, h: size };+ };+ const small = boxAt(40);+ const large = boxAt(120);// the tip is the anchor, so it reads the same out of both boxesconst tipOf = (box) => ({ x: box.x + box.w / 2, y: box.y + box.h * (22.4 / ICON_BOX) });expect(tipOf(small).x).toBeCloseTo(tipOf(large).x);diff --git a/frontend/src/lib/radar.js b/frontend/src/lib/radar.jsindex ef1218e..45f76ac 100644--- a/frontend/src/lib/radar.js+++ b/frontend/src/lib/radar.js@@ -32,14 +32,6 @@ export function radarId(baseId, pass) {return [baseId, pass.date, pass.time.replace(/:/g, '')].join(SEP);}-/** …and back: the pass an id names, or null for the plain basemap. */-export function passOf(providerId) {- const [base, day, time] = String(providerId ?? '').split(SEP);- if (base !== RADAR_ID || !DAY.test(day ?? '') || !/^\d{6}$/.test(time ?? '')) return null;- const pass = { date: day, time: `${time.slice(0, 2)}:${time.slice(2, 4)}:${time.slice(4)}` };- return validPass(pass) ? pass : null;-}-function minutes(time) {const [, hours, mins, secs] = TIME.exec(time);return Number(hours) * 60 + Number(mins) + (Number(secs) >= 30 ? 1 : 0);diff --git a/frontend/src/lib/radar.test.js b/frontend/src/lib/radar.test.jsindex c8e87c6..8f0df75 100644--- a/frontend/src/lib/radar.test.js+++ b/frontend/src/lib/radar.test.js@@ -1,19 +1,16 @@import { describe, expect, it } from 'vitest';-import { RADAR_ID, onTrack, orbitMark, passLabel, passOf, radarId, sameTrack, validPass } from './radar.js';+import { RADAR_ID, onTrack, orbitMark, passLabel, radarId, sameTrack, validPass } from './radar.js';describe('a Sentinel-1 pass on the provider id', () => {- it('rides as a day and a time without colons, and comes back', () => {+ it('rides as a day and a time without colons', () => {const pass = { date: '2026-05-14', time: '05:42:10' };expect(radarId(RADAR_ID, pass)).toBe('sentinel1~2026-05-14~054210');- expect(passOf('sentinel1~2026-05-14~054210')).toEqual(pass);});it('stays the plain id for the most recent pass, and on any other basemap', () => {expect(radarId(RADAR_ID, null)).toBe(RADAR_ID);expect(radarId(RADAR_ID, { date: '2026-05-14', time: '5:42' })).toBe(RADAR_ID);expect(radarId('sentinel2', { date: '2026-05-14', time: '05:42:10' })).toBe('sentinel2');- expect(passOf('sentinel1')).toBe(null);- expect(passOf('sentinel1~2026-05-14~99')).toBe(null);expect(validPass({ date: '2026-05-14', time: '24:00:00' })).toBe(false);});diff --git a/frontend/src/lib/reveal.js b/frontend/src/lib/reveal.jsindex 3490923..d3bd356 100644--- a/frontend/src/lib/reveal.js+++ b/frontend/src/lib/reveal.js@@ -1,9 +1,9 @@/*** Open a folder in the system's own file manager.*- * The browser can't do this, so the backend does it (`engine/reveal.py`). Neither- * call sends a path: the case id, or nothing at all for the workspace, is the- * whole input, so the button can only ever open the folder it names.+ * The browser can't do this, so the backend does it (`engine/reveal.py`). The+ * case folder is asked for by id alone, so the button can only ever open the+ * folder it names.*/import { api } from './api.js';@@ -12,10 +12,6 @@ export function revealCaseFolder(caseId) {return api.post(`/api/cases/${encodeURIComponent(caseId)}/reveal`);}-export function revealWorkspaceFolder() {- return api.post('/api/settings/reveal-workspace');-}-/*** Show the folder holding one of a case's files.*diff --git a/frontend/src/lib/reveal.test.js b/frontend/src/lib/reveal.test.jsindex 442d67b..1a0c20c 100644--- a/frontend/src/lib/reveal.test.js+++ b/frontend/src/lib/reveal.test.js@@ -1,6 +1,6 @@import { beforeEach, expect, it, vi } from 'vitest';import { api } from './api.js';-import { revealCaseFolder, revealMediaFolder, revealWorkspaceFolder } from './reveal.js';+import { revealCaseFolder, revealMediaFolder } from './reveal.js';vi.mock('./api.js', () => ({ api: { post: vi.fn() } }));@@ -18,11 +18,6 @@ it('escapes the id, so it cannot carry a path into the URL', async () => {expect(api.post).toHaveBeenCalledWith('/api/cases/..%2Fetc/reveal');});-it('opens the workspace with no argument at all', async () => {- await revealWorkspaceFolder();- expect(api.post).toHaveBeenCalledWith('/api/settings/reveal-workspace');-});-it('sends the file path so the folder it sits in can be shown', async () => {await revealMediaFolder('case-1', 'media/site plan.pdf');expect(api.post).toHaveBeenCalledWith('/api/cases/case-1/media/reveal', {diff --git a/frontend/src/lib/sentinel.js b/frontend/src/lib/sentinel.jsindex 91febe7..811888c 100644--- a/frontend/src/lib/sentinel.js+++ b/frontend/src/lib/sentinel.js@@ -107,12 +107,6 @@ export function validDay(day) {return validWindow(day, day);}-/** How a window reads in the UI: a day, a range, or the layer's own default. */-export function windowLabel(from, to) {- if (!validWindow(from, to)) return 'most recent';- return from === to ? from : `${from} → ${to}`;-}-/*** The calendar month a day belongs to, and month arithmetic on 'YYYY-MM'.* Day 1 of the target month, so a 31st can never spill into the next one.@@ -200,12 +194,3 @@ export function coverageRequestPath({ lat, lon, layer, date, maxcc = DEFAULT_MAXexport function dateAfterCoverage(current, candidate, available) {return available ? candidate : current;}--/**- * The date range a date search should default to: the last `days` days, ending- * today. Sentinel-2 revisits every ~5 days, so a month is several passes —- * enough that the list is never empty, short enough to stay readable.- */-export function defaultSearchWindow(days = 30, now = new Date()) {- return { from: daysBefore(days, now), to: isoDay(now) };-}diff --git a/frontend/src/lib/sentinel.test.js b/frontend/src/lib/sentinel.test.jsindex e4f247d..d56e93c 100644--- a/frontend/src/lib/sentinel.test.js+++ b/frontend/src/lib/sentinel.test.js@@ -10,7 +10,6 @@ import {daysBefore,validWindow,validDay,- windowLabel,cloudLabel,cloudClass,monthOf,@@ -18,7 +17,6 @@ import {monthLabel,monthBounds,monthGrid,- defaultSearchWindow,sentinelPlaceKey,coverageRequestPath,dateAfterCoverage,@@ -128,15 +126,6 @@ describe('validWindow', () => {});});-describe('windowLabel', () => {- it('reads as a day, a range, or the layer default', () => {- expect(windowLabel('2026-05-01', '2026-05-01')).toBe('2026-05-01');- expect(windowLabel('2026-05-01', '2026-05-31')).toBe('2026-05-01 → 2026-05-31');- expect(windowLabel('', '')).toBe('most recent');- expect(windowLabel('2026-05-31', '2026-05-01')).toBe('most recent');- });-});-describe('cloudLabel', () => {it('is the reason to skip a date without paying to find out', () => {expect(cloudLabel(3.4)).toBe('3% cloud');@@ -216,13 +205,6 @@ describe('monthGrid', () => {});});-describe('defaultSearchWindow', () => {- it('covers several revisits (Sentinel-2 passes every ~5 days)', () => {- const now = new Date(Date.UTC(2026, 6, 14));- expect(defaultSearchWindow(30, now)).toEqual({ from: '2026-06-14', to: '2026-07-14' });- });-});-describe('coverage checks', () => {it('buckets nearby map centres together', () => {expect(sentinelPlaceKey(48.85837, 2.29448)).toBe('48.858,2.294');diff --git a/frontend/src/lib/state.test.js b/frontend/src/lib/state.test.jsindex 9dfafe8..86eae3a 100644--- a/frontend/src/lib/state.test.js+++ b/frontend/src/lib/state.test.js@@ -15,6 +15,16 @@ vi.mock('./api.js', () => ({api: { get: vi.fn(), post: vi.fn(), put: vi.fn(), patch: vi.fn(), del: vi.fn() },}));+// The two bridge probes wait 700 ms of real time for an answer, and the startup+// check does not await them. Left real, their timers outlive the test that+// started them and can fire after happy-dom is torn down. Here nothing answers,+// at once; extBridge.test.js covers the probes themselves.+vi.mock('./extBridge.js', async (importOriginal) => ({+ ...(await importOriginal()),+ pingExtensions: vi.fn(async () => []),+ extensionState: vi.fn(async () => []),+}));+async function freshState() {vi.resetModules();return import('./state.svelte.js');@@ -258,6 +268,22 @@ describe('startup update check', () => {expect(updatesState.extension).toBe(null);});+ it('leaves no bridge timer running once a test is over', async () => {+ const { api } = await import('./api.js');+ api.get.mockReset().mockRejectedValue(new Error('offline'));+ const { checkForUpdatesOnStart } = await freshState();+ const { pingExtensions, extensionState } = await import('./extBridge.js');+ vi.useFakeTimers();+ try {+ await checkForUpdatesOnStart();+ expect(pingExtensions).toHaveBeenCalled();+ expect(extensionState).toHaveBeenCalled();+ expect(vi.getTimerCount()).toBe(0);+ } finally {+ vi.useRealTimers();+ }+ });+it('does not surface an offline failure', async () => {const { api } = await import('./api.js');api.get.mockReset().mockRejectedValue(new Error('offline'));diff --git a/frontend/src/lib/trash.test.js b/frontend/src/lib/trash.test.jsindex 8f1097e..00b065d 100644--- a/frontend/src/lib/trash.test.js+++ b/frontend/src/lib/trash.test.js@@ -123,7 +123,7 @@ describe('deleting a selection', () => {});it('names the row when there is one, and previews what goes with it', async () => {- const get = vi.fn(async () => ({ cascade: [{ label: 'Inspect session' }], tombstone: [] }));+ const get = vi.fn(async () => ({ cascade: [{ label: 'Inspect work' }], tombstone: [] }));const prompt = await entityDeletePrompt('case-1', [rows[1]], { get });expect(get).toHaveBeenCalledWith('/api/cases/case-1/entities/e2/dependents');diff --git a/frontend/src/lib/wayback.js b/frontend/src/lib/wayback.jsindex 0c32c94..3a43826 100644--- a/frontend/src/lib/wayback.js+++ b/frontend/src/lib/wayback.js@@ -26,13 +26,6 @@ export function waybackId(baseId, release) {return `${baseId}${SEP}${release}`;}-/** …and back: the release an id names, or null for the plain basemap. */-export function releaseOf(providerId) {- const [base, spec] = String(providerId ?? '').split(SEP);- if (base !== WAYBACK_ID || !/^\d{1,9}$/.test(spec ?? '')) return null;- return Number(spec);-}-/*** The releases the picker walks through, newest first.*diff --git a/frontend/src/lib/wayback.test.js b/frontend/src/lib/wayback.test.jsindex 993cd29..0fbf446 100644--- a/frontend/src/lib/wayback.test.js+++ b/frontend/src/lib/wayback.test.js@@ -4,7 +4,6 @@ import {changesKey,positionOf,releaseDate,- releaseOf,releaseYearBefore,stepRelease,validRelease,@@ -36,13 +35,6 @@ describe('the id a release rides on', () => {expect(waybackId(WAYBACK_ID, bad)).toBe(WAYBACK_ID);}});-- it('reads the release back out of an id', () => {- expect(releaseOf('esri-wayback~64776')).toBe(64776);- expect(releaseOf('esri-wayback')).toBeNull();- expect(releaseOf('sentinel2~SWIR')).toBeNull();- expect(releaseOf('esri-wayback~../x')).toBeNull();- });});describe('what the picker offers', () => {diff --git a/frontend/src/tools/Overview.render.test.js b/frontend/src/tools/Overview.render.test.jsindex 98afeaf..3a2e688 100644--- a/frontend/src/tools/Overview.render.test.js+++ b/frontend/src/tools/Overview.render.test.js@@ -386,7 +386,8 @@ describe('with no case open', () => {await open();expect(target.querySelector('.door')).toBeTruthy();expect(target.querySelectorAll('.stage')).toHaveLength(4); // the rail, as a sequence- expect(target.textContent).toContain('Nothing leaves this machine.');+ // it opened having asked GitHub and PyPI for versions, so it promises no silence+ expect(target.textContent).not.toContain('Nothing leaves this machine');});it('names the first case from the door itself', async () => {diff --git a/frontend/src/tools/Overview.svelte b/frontend/src/tools/Overview.svelteindex 2a19a31..82c3ef1 100644--- a/frontend/src/tools/Overview.svelte+++ b/frontend/src/tools/Overview.svelte@@ -417,7 +417,6 @@Read the guide<Icon name="arrowRight" size={13} /></button>- <span class="door-note">Nothing leaves this machine.</span></div></div>{/if}@@ -1015,8 +1014,4 @@gap: 12px;margin-top: 40px;}- .door-note {- font-size: var(--fs-xs);- color: var(--text-3);- }</style>diff --git a/frontend/src/tools/PostComposer.svelte b/frontend/src/tools/PostComposer.svelteindex c168b79..d36c162 100644--- a/frontend/src/tools/PostComposer.svelte+++ b/frontend/src/tools/PostComposer.svelte@@ -610,7 +610,7 @@}// Pull the proof's coordinates + source into the post so the fields fill in.try {- const spec = await api.get(`/api/cases/${caseState.current.id}/proofs/${item.name}`);+ const spec = await api.get(`/api/cases/${caseState.current.id}/proofs/${encodeURIComponent(item.name)}`);// Its sentence, once the spec is here. The picker row carries a filename// and a thumbnail, so the title above was only ever a stand-in for this.if (blank && spec.description?.trim()) description = spec.description.trim();@@ -792,7 +792,7 @@deleteEntry = null;try {const caseId = caseState.current.id;- const result = await api.del(`/api/cases/${caseId}/drafts/${entry.name}`);+ const result = await api.del(`/api/cases/${caseId}/drafts/${encodeURIComponent(entry.name)}`);await Promise.all([openDraftList(), reloadCase()]);deletedToast(caseId, result, entry.title);} catch (e) {@@ -803,7 +803,7 @@async function loadDraft(name) {if (!caseState.current) return;try {- const doc = await api.get(`/api/cases/${caseState.current.id}/drafts/${name}`);+ const doc = await api.get(`/api/cases/${caseState.current.id}/drafts/${encodeURIComponent(name)}`);const s = doc.state ?? {};description = s.description ?? '';coordsText = s.coordsText ?? '';diff --git a/frontend/src/tools/ProofComposer.svelte b/frontend/src/tools/ProofComposer.svelteindex 36b341a..700b17a 100644--- a/frontend/src/tools/ProofComposer.svelte+++ b/frontend/src/tools/ProofComposer.svelte@@ -3580,7 +3580,7 @@// confirmed PNG to copy yet.if (dirty || !savedName) return;const cid = caseState.current.id;- const result = await api.post(`/api/cases/${cid}/proofs/${savedName}/export`);+ const result = await api.post(`/api/cases/${cid}/proofs/${encodeURIComponent(savedName)}/export`);exportDir = result.folder;toast(`${result.file} written to ${destinationLabel(result.folder)}`, 'ok', 5200, {label: 'Show',@@ -3868,7 +3868,7 @@deleteEntry = null;try {const caseId = caseState.current.id;- const result = await api.del(`/api/cases/${caseId}/proofs/${entry.name}`);+ const result = await api.del(`/api/cases/${caseId}/proofs/${encodeURIComponent(entry.name)}`);await Promise.all([openProofList(), reloadCase()]);deletedToast(caseId, result, entry.title);} catch (e) {@@ -3884,7 +3884,7 @@async function openProof(entry) {const run = ++openRun;- const spec = await api.get(`/api/cases/${caseState.current.id}/proofs/${entry.name}`);+ const spec = await api.get(`/api/cases/${caseState.current.id}/proofs/${encodeURIComponent(entry.name)}`);if (run !== openRun) return;const style = normalizeProofStyle(spec);resetDoc();diff --git a/frontend/src/tools/ProofComposer.test.js b/frontend/src/tools/ProofComposer.test.jsindex 4588126..5a512f4 100644--- a/frontend/src/tools/ProofComposer.test.js+++ b/frontend/src/tools/ProofComposer.test.js@@ -61,7 +61,7 @@ describe('Proof Composer header', () => {expect(source).toContain('kind="proofs"');expect(source).toContain('confirmLabel="Export here"');expect(source).toContain('onchosen={useExportFolder}');- expect(source).toContain('api.post(`/api/cases/${cid}/proofs/${savedName}/export`)');+ expect(source).toContain('api.post(`/api/cases/${cid}/proofs/${encodeURIComponent(savedName)}/export`)');expect(source).toContain('/proofs/export/reveal`');expect(source).toContain('if (dirty || !savedName) await save();');expect(source).toContain('if (dirty || !savedName) return;');diff --git a/frontend/src/tools/compare/DifferenceBar.svelte b/frontend/src/tools/compare/DifferenceBar.svelteindex b1524c6..c0a402e 100644--- a/frontend/src/tools/compare/DifferenceBar.svelte+++ b/frontend/src/tools/compare/DifferenceBar.svelte@@ -148,17 +148,17 @@</div>{#if tab === 'detection'}- <label title="Colour compares appearance; structure compares edges; index compares Sentinel-2 spectral bands.">Method+ <label title="What to compare: colour, edges or a spectral index.">Method<select aria-label="Method" bind:value={settings.method}>{#each CHANGE_METHODS as method}<option value={method.id} disabled={!status.methods.includes(method.id)}>{method.label}</option>{/each}</select></label>{#if settings.method === 'index'}- <label title="Select the spectral quantity to compare between the two passes.">Index+ <label title="The spectral index compared between the two passes.">Index<select bind:value={settings.index}>{#each CHANGE_INDICES as entry}<option value={entry.id}>{entry.label} · {entry.hint}</option>{/each}</select></label>{:else}- <label title="Automatic adapts to this view; manual keeps a sensitivity-based threshold.">Threshold+ <label title="Adapt the threshold to this view, or follow the sensitivity.">Threshold<select bind:value={settings.threshold}><option value="auto">Automatic</option><option value="manual">Manual</option></select></label>{/if}@@ -176,10 +176,10 @@{/if}{#if tab === 'display'}- <label title="Show the detected pixels as classes, a signal heatmap or outlines.">Display+ <label title="Draw the change as classes, a signal heatmap or outlines.">Display<select bind:value={settings.display}>{#each CHANGE_DISPLAYS as display}<option value={display.id}>{display.label}</option>{/each}</select></label>- <label title="Change only the overlay colours; Thermal is a palette, not a thermal sensor.">Palette+ <label title="Overlay colours only, none of them a sensor reading.">Palette<select bind:value={settings.palette}><option value="directional">Directional</option><option value="colourblind">Colour-blind</option><option value="thermal">Thermal</option></select></label><div class="classes">{#each CHANGE_CLASSES as entry}<label class="check"><input type="checkbox" bind:group={settings.classes} value={entry} /> {entry}</label>{/each}</div>@@ -189,7 +189,7 @@{/if}{#if tab === 'filters'}- <label title="Reduce exposure differences; this may suppress broad real changes.">Tone matching+ <label title="Even out exposure, at the risk of hiding a broad change.">Tone matching<select bind:value={settings.normalize}><option value="auto">Automatic</option><option value="none">None</option><option value="mean">Mean brightness</option><option value="histogram">Histogram</option>@@ -205,13 +205,13 @@</p>{/if}<label title="Search for a small image offset before comparing pixels.">Alignment · ±{settings.alignment}px<input type="range" min="0" max="8" bind:value={settings.alignment} /></label>- <label title="Reduce pixel noise before thresholding; zero preserves small details.">Smoothing · {settings.smoothing}px<input type="range" min="0" max="4" bind:value={settings.smoothing} /></label>- <label title="Remove isolated speckles; larger settings can also remove small real changes.">Cleanup · {settings.cleanup}<input type="range" min="0" max="3" bind:value={settings.cleanup} /></label>+ <label title="Reduce pixel noise before thresholding.">Smoothing · {settings.smoothing}px<input type="range" min="0" max="4" bind:value={settings.smoothing} /></label>+ <label title="Remove isolated speckles.">Cleanup · {settings.cleanup}<input type="range" min="0" max="3" bind:value={settings.cleanup} /></label><label title="Discard connected regions below this ground area.">Minimum area (m²)<input type="number" min="0" max="1000000" bind:value={settings.min_area} /></label>{#if status.clouds}<label class="check" title="Exclude cloud, read from Sentinel-2's scene classification."><input type="checkbox" bind:checked={settings.ignore_clouds} /> Mask clouds</label><label class="check" title="Exclude the shadow cloud casts, which moves with the sun."><input type="checkbox" bind:checked={settings.ignore_shadows} /> Mask shadows</label>- <label title="Grow the cloud and shadow mask, to take the soft edge a mask leaves behind.">Mask margin · {settings.cloud_margin} m<input aria-label="Cloud mask margin" type="range" min="0" max="200" step="10" bind:value={settings.cloud_margin} /></label>+ <label title="Grow the mask over the soft edge a cloud leaves.">Mask margin · {settings.cloud_margin} m<input aria-label="Cloud mask margin" type="range" min="0" max="200" step="10" bind:value={settings.cloud_margin} /></label>{/if}<label class="check"><input type="checkbox" bind:checked={settings.zones} /> List change zones</label><button class="link" onclick={() => (settings = changeSettings())}>Reset settings</button>diff --git a/frontend/src/tools/compare/DifferenceBar.test.js b/frontend/src/tools/compare/DifferenceBar.test.jsindex 37c380e..c7ab257 100644--- a/frontend/src/tools/compare/DifferenceBar.test.js+++ b/frontend/src/tools/compare/DifferenceBar.test.js@@ -1,6 +1,9 @@// @vitest-environment happy-domimport { describe, expect, it, vi } from 'vitest';import { flushSync, mount, unmount } from 'svelte';+import { readFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';import DifferenceBar from './DifferenceBar.svelte';import { changeSettings } from '../../lib/map/changeAssist.js';@@ -31,6 +34,21 @@ const base = (target, label) =>.find((entry) => entry.textContent.trim() === label);describe('Difference strip', () => {+ it('keeps every tooltip to one short clause', () => {+ // The settings sit on three tabs, so the written titles are read off the+ // component rather than opened one tab at a time.+ const here = dirname(fileURLToPath(import.meta.url));+ const source = readFileSync(join(here, 'DifferenceBar.svelte'), 'utf8');+ const tips = [...source.matchAll(/title=(?:"([^"]*)"|\{([^}]*)\})/g)].flatMap(([, text, code]) =>+ text !== undefined ? [text] : [...code.matchAll(/'([^']+)'|`([^`]+)`/g)].map((m) => m[1] ?? m[2]));++ expect(tips.length).toBeGreaterThan(15);+ for (const tip of tips) {+ expect(tip.length, tip).toBeLessThanOrEqual(60);+ expect(tip, tip).not.toContain(';');+ }+ });+it('keeps an index reading as a Detect analyzer, and offers nothing for the picture methods', () => {const onanalyzer = vi.fn();const index = render({ settings: changeSettings({ method: 'index', index: 'nbr' }),diff --git a/frontend/src/tools/detect/AnalyzerBuilder.svelte b/frontend/src/tools/detect/AnalyzerBuilder.svelteindex 6680596..7e82877 100644--- a/frontend/src/tools/detect/AnalyzerBuilder.svelte+++ b/frontend/src/tools/detect/AnalyzerBuilder.svelte@@ -550,10 +550,10 @@<button class="btn btn-primary btn-sm read" disabled={reading} onclick={readFrames}>{reading ? 'Reading from Copernicus…' : preview ? 'Read the rest of the view' : 'Show the detections here'}</button>- <p class="hint">{missing} frame{missing === 1 ? '' : 's'} from Copernicus, one request each. Frames already read stay live as you move.</p>+ <p class="hint">{missing} frame{missing === 1 ? '' : 's'} from Copernicus, one request each, and the frames already read stay live as you move.</p>{/if}{#if preview}- {#if preview.clipped}<p class="hint">The preview covers the middle of the view, {limits.preview_span ?? 3} tiles a side. Zoom in to see all of it.</p>{/if}+ {#if preview.clipped}<p class="hint">The preview covers only the middle {limits.preview_span ?? 3} tiles a side of this view.</p>{/if}<p class="hint">Click the map to read every rule at a point and mark it in a check.</p>{/if}{/if}@@ -604,7 +604,7 @@<AnalyzerSettings bind:recipe {capability} expanded /></section><section aria-label="Description">- <label title="What this analyzer looks for, and what it cannot tell you. Left empty, it takes the sentence at the top.">Description+ <label title="What this analyzer looks for and cannot tell you.">Description<textarea bind:value={recipe.description} maxlength="500" placeholder={phrase}></textarea></label></section>diff --git a/frontend/src/tools/detect/AnalyzerChecks.svelte b/frontend/src/tools/detect/AnalyzerChecks.svelteindex 00c00ff..03c6509 100644--- a/frontend/src/tools/detect/AnalyzerChecks.svelte+++ b/frontend/src/tools/detect/AnalyzerChecks.svelte@@ -68,8 +68,8 @@{/if}</div>{#if !checks.length}- <p class="hint">A check is a place you trust, two passes, and pins where a candidate should come out or none- should. Rerun it after each change and it says which rule broke what. Checks are optional.</p>+ <p class="hint">Checks are optional places you trust, pinned on two passes where a candidate should come out or+ none should, and rerun to show which rule broke what.</p>{/if}{#each checks as check (check.id)}diff --git a/frontend/src/tools/detect/AnalyzerLabel.svelte b/frontend/src/tools/detect/AnalyzerLabel.svelteindex 0e3ff0e..d1d45b0 100644--- a/frontend/src/tools/detect/AnalyzerLabel.svelte+++ b/frontend/src/tools/detect/AnalyzerLabel.svelte@@ -6,7 +6,7 @@<details class="look"><summary>Label and colour</summary><fieldset class="fields" disabled={readonly}>- <label title="The label each candidate carries. It does not change what is detected.">Candidate label+ <label title="The label each candidate carries.">Candidate label<input bind:value={recipe.phenomenon} maxlength="120" /></label><div class="row">diff --git a/frontend/src/tools/detect/AnalyzerLibrary.svelte b/frontend/src/tools/detect/AnalyzerLibrary.svelteindex ff4e337..2d02a23 100644--- a/frontend/src/tools/detect/AnalyzerLibrary.svelte+++ b/frontend/src/tools/detect/AnalyzerLibrary.svelte@@ -139,7 +139,7 @@{#if mode === 'list'}<div class="cmp-dock-body">{#if error}<p class="warn" role="alert">{error}</p>{/if}- <p class="hint">An analyzer is what a detection looks for. Start from an example, build your own from rules you try on the map, or copy a calibrated built-in to tune it.</p>+ <p class="hint">Start from an example, build your own from rules you try on the map, or copy a calibrated built-in to tune it.</p><button class="btn btn-primary" onclick={() => (mode = 'base')}><Icon name="plus" size={14} /> New analyzer</button><section aria-label="My analyzers">@@ -185,7 +185,7 @@{#if error}<p class="warn" role="alert">{error}</p>{/if}{#if examples.length}<h3>Start from an example</h3>- <p class="hint">A ready analyzer with its checks. Run them, change a rule and see which check turns red.</p>+ <p class="hint">A ready analyzer whose checks turn red when a rule you change breaks one.</p><div class="examples">{#each examples as example (example.id)}<button class="pick base grow" style={`--tint: ${example.recipe.colour}`} disabled={busy}@@ -201,7 +201,7 @@<span class="name">Build your own rules<small>Say what a pixel has to show, on A, on B or between them, and watch each rule on the map as you set it.</small></span></button><h3>Or start from a built-in</h3>- <p class="hint">Its calibrated method comes with it; you tune how picky it is. The ones marked rules open as the rules they apply.</p>+ <p class="hint">A built-in brings its calibrated method for you to tune, and one marked rules opens as the rules it applies.</p><div class="bases">{#each [...builtins, ...custom] as entry (entry.id)}{@const rules = catalogue?.as_rules?.[entry.id]}@@ -227,7 +227,7 @@{#if error}<p class="warn" role="alert">{error}</p>{/if}<h3>{isNew ? 'New analyzer' : readonly ? recipe.name : `Edit ${recipe.name}`}</h3><p class="measures"><span>Measures</span> {capability.label ?? recipe.method}</p>- {#if readonly}<p class="hint">A built-in can't be changed. Copy it to tune your own.</p>{/if}+ {#if readonly}<p class="hint">A built-in can't be changed, so copy it to tune your own.</p>{/if}<fieldset class="fields" disabled={readonly}><label title="The name shown in the analyzer library across all cases.">Name<input aria-label="Analyzer name" bind:value={recipe.name} maxlength="120" />diff --git a/frontend/src/tools/detect/AnalyzerSettings.render.test.js b/frontend/src/tools/detect/AnalyzerSettings.render.test.jsindex 3695874..dd6c74f 100644--- a/frontend/src/tools/detect/AnalyzerSettings.render.test.js+++ b/frontend/src/tools/detect/AnalyzerSettings.render.test.js@@ -1,6 +1,9 @@// @vitest-environment happy-domimport { afterEach, expect, it } from 'vitest';import { flushSync, mount, unmount } from 'svelte';+import { readdirSync, readFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';import AnalyzerSettings from './AnalyzerSettings.svelte';/** A threshold is shown only where the method reads it, in the unit it reads it in. */@@ -35,3 +38,22 @@ it('offers no cleanup or smoothing to a method that reads one image', () => {expect(text).not.toContain('Smoothing');expect(text).toContain('Group within');});++it('keeps the builder notes to one sentence and its tooltips to one clause', () => {+ // Read off the components themselves: most of these sit behind a mode, a tab+ // or a readonly state that no single mount reaches.+ const here = dirname(fileURLToPath(import.meta.url));+ const files = readdirSync(here).filter((name) => /^Analyzer\w*\.svelte$/.test(name));+ expect(files.length).toBeGreaterThan(4);+ for (const name of files) {+ const source = readFileSync(join(here, name), 'utf8');+ for (const [, body] of source.matchAll(/<p class="(?:hint|note)[^"]*"[^>]*>([\s\S]*?)<\/p>/g)) {+ const note = body.replace(/\{[^}]*\}/g, 'x').replace(/\s+/g, ' ').trim();+ expect(note.replace(/[.?!]$/, ''), `${name}: ${note}`).not.toMatch(/[.?!] |;/);+ }+ for (const [, tip] of source.matchAll(/title="([^"]*)"/g)) {+ expect(tip.length, `${name}: ${tip}`).toBeLessThanOrEqual(60);+ expect(tip.replace(/[.?!]$/, ''), `${name}: ${tip}`).not.toMatch(/[.?!] |;/);+ }+ }+});diff --git a/frontend/src/tools/detect/AnalyzerSettings.svelte b/frontend/src/tools/detect/AnalyzerSettings.svelteindex 381fea0..372261d 100644--- a/frontend/src/tools/detect/AnalyzerSettings.svelte+++ b/frontend/src/tools/detect/AnalyzerSettings.svelte@@ -74,7 +74,7 @@<label class="grow" title="Drop candidates smaller than this.">Min area (m²)<input aria-label="Minimum area" type="number" min="0" max="100000000" bind:value={recipe.parameters.min_area} /></label>- <label class="grow" title="Drop candidates larger than this; 0 keeps them all.">Max area (m²)+ <label class="grow" title="Drop candidates larger than this, or none at 0.">Max area (m²)<input aria-label="Maximum area" type="number" min="0" max="100000000" bind:value={recipe.parameters.max_area} /></label></div>@@ -85,7 +85,7 @@</select></label>{/if}- <label title="Keep only candidates of this shape, measured along their own length.">Shape+ <label title="Keep only candidates of this shape.">Shape<select aria-label="Candidate shape" value={recipe.parameters.shape ?? 'any'}onchange={(event) => (recipe.parameters = { ...recipe.parameters, shape: event.currentTarget.value })}>{#each SHAPES as [id, label] (id)}<option value={id}>{label}</option>{/each}@@ -109,14 +109,14 @@<details><summary>{single && !rules ? 'Grouping' : 'Noise and grouping'}</summary>{#if !single || rules}- <label title="Remove specks narrower than this; it also removes small real objects.">Noise cleanup · {recipe.parameters.cleanup}px<input type="range" min="0" max="3" bind:value={recipe.parameters.cleanup} /></label>+ <label title="Remove specks narrower than this, real ones included.">Noise cleanup · {recipe.parameters.cleanup}px<input type="range" min="0" max="3" bind:value={recipe.parameters.cleanup} /></label>{#if capability.smoothing_m}- <label title="Average the radar over this much ground first; wider is quieter and coarser.">Averaging · {capability.smoothing_m * Math.max(1, recipe.parameters.smoothing)} m<input aria-label="Radar averaging" type="range" min="1" max="3" bind:value={recipe.parameters.smoothing} /></label>+ <label title="Average the radar over this ground to quiet its speckle.">Averaging · {capability.smoothing_m * Math.max(1, recipe.parameters.smoothing)} m<input aria-label="Radar averaging" type="range" min="1" max="3" bind:value={recipe.parameters.smoothing} /></label>{:else}- <label title="Blur the reading first; zero keeps the finest detail.">Smoothing · {recipe.parameters.smoothing}px<input type="range" min="0" max="3" bind:value={recipe.parameters.smoothing} /></label>+ <label title="Blur the reading first, or not at all at zero.">Smoothing · {recipe.parameters.smoothing}px<input type="range" min="0" max="3" bind:value={recipe.parameters.smoothing} /></label>{/if}{/if}- <label title="Join candidates this close; zero joins only touching ones.">Group within (m)<input type="number" min="0" max="500" bind:value={recipe.parameters.merge_metres} /></label>+ <label title="Join candidates this close, only touching ones at zero.">Group within (m)<input type="number" min="0" max="500" bind:value={recipe.parameters.merge_metres} /></label></details>{/if}</fieldset>diff --git a/frontend/src/tools/detect/DetectDetection.render.test.js b/frontend/src/tools/detect/DetectDetection.render.test.jsnew file mode 100644index 0000000..efaf231--- /dev/null+++ b/frontend/src/tools/detect/DetectDetection.render.test.js@@ -0,0 +1,26 @@+// @vitest-environment happy-dom+import { afterEach, expect, it } from 'vitest';+import { flushSync, mount, unmount } from 'svelte';+import DetectDetection from './DetectDetection.svelte';++const detection = { id: 'f1', title: 'Harbour watch', history: [], areas: 0, method: 'change' };++let live, target;+afterEach(() => { if (live) unmount(live); target?.remove(); });++function open(detail) {+ target = document.createElement('div');+ document.body.append(target);+ live = mount(DetectDetection, { target, props: { detection, detail } });+ flushSync();+}++it('says so when an area the routine drew on was deleted for good', () => {+ open({ zones: [], missing_areas: ['a1b2c3d4e5f6'] });+ expect(target.textContent).toContain('An area it drew on was deleted. Edit the routine to add one.');+});++it('says nothing of the kind while every area is there', () => {+ open({ zones: [{ id: 'z1' }] });+ expect(target.textContent).not.toContain('deleted');+});diff --git a/frontend/src/tools/detect/DetectDetection.svelte b/frontend/src/tools/detect/DetectDetection.svelteindex c58a430..cca9522 100644--- a/frontend/src/tools/detect/DetectDetection.svelte+++ b/frontend/src/tools/detect/DetectDetection.svelte@@ -48,6 +48,11 @@<p class="meta">{[detection.analyzer, plural(detection.areas ?? 0, 'area'),ruleLabel(detection.date_rule, single)].filter(Boolean).join(' · ')}</p><p class={`state ${state.tone}`}>{state.text}</p>+ {#if detail?.missing_areas?.length}+ <p class="state warn">+ {detail.missing_areas.length === 1 ? 'An area it drew on was' : 'Areas it drew on were'} deleted. Edit the routine to add one.+ </p>+ {/if}{#if detection.active?.status === 'running'}<progress max={detection.active.total || 1} value={detection.active.progress ?? 0}></progress>{/if}diff --git a/frontend/src/tools/detect/DetectPanel.test.js b/frontend/src/tools/detect/DetectPanel.test.jsindex 45b108c..cfdb583 100644--- a/frontend/src/tools/detect/DetectPanel.test.js+++ b/frontend/src/tools/detect/DetectPanel.test.js@@ -646,7 +646,7 @@ it('builds an analyzer from rules, tries it on the view, reads a point and keepsexpect(asked).toHaveLength(1);expect(asked[0][1]).toMatchObject({ read: false, a: { date: '2026-05-04' }, b: { date: '2026-05-11' }, bounds: VIEW,recipe: { method: 'rules', match: 'all' } });- expect(target.textContent).toContain('2 frames from Copernicus, one request each.');+ expect(target.textContent).toContain('2 frames from Copernicus, one request each,');button('Show the detections here').click(); await settle();expect(post).toHaveBeenLastCalledWith('/api/compare/analyzers/preview', expect.objectContaining({ read: true }));diff --git a/frontend/src/tools/mapdock.css b/frontend/src/tools/mapdock.cssindex cb777d7..ce3d4fb 100644--- a/frontend/src/tools/mapdock.css+++ b/frontend/src/tools/mapdock.css@@ -130,38 +130,6 @@}.cmp-range:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 4px; }-.cmp-switch {- position: relative;- flex: 0 0 auto;- width: 30px;- height: 17px;- border-radius: 99px;- background: rgba(255, 255, 255, 0.18);- transition: background 0.15s var(--ease);-}-.cmp-switch::after {- content: '';- position: absolute;- top: 2px;- left: 2px;- width: 13px;- height: 13px;- border-radius: 50%;- background: #f5f6f7;- box-shadow: 0 1px 2px rgba(0, 0, 0, 0.4);- transition: transform 0.15s var(--ease);-}-.cmp-switch.on { background: var(--accent); }-.cmp-switch.on::after { transform: translateX(13px); }--.cmp-kicker {- color: var(--glass-dim);- font-size: 10px;- font-weight: 700;- letter-spacing: 0.08em;- text-transform: uppercase;-}-.cmp-mono {font-family: var(--font-mono);font-variant-numeric: tabular-nums;@@ -169,8 +137,8 @@/* The column beside the stage. Both computing modes use it, so setting up adifference and setting up a detection have the same shape: a header that- names the mode and says in one line what it reads, a scrolling body, and- one action pinned at the foot that never scrolls out of reach. It takes+ names the mode, a scrolling body, and one action pinned at the foot that+ never scrolls out of reach. It takeswidth from the maps rather than covering them — the map stays the thingyou are working on. */.cmp-dock {@@ -189,13 +157,6 @@border-bottom: 1px solid var(--border);}.cmp-dock > header strong { flex: 1; font-size: var(--fs-sm); }-.cmp-dock-lead {- padding: 9px 12px;- border-bottom: 1px solid var(--border);- color: var(--text-2);- font-size: var(--fs-xs);- line-height: 1.45;-}.cmp-dock-body {display: grid;flex: 1;@@ -219,34 +180,8 @@}.cmp-dock-foot .reason.warn { color: var(--warn); }-/* One numbered step. The number is the whole instruction about order. */-.cmp-step { display: grid; gap: 8px; }-.cmp-step > header {- display: flex;- align-items: center;- gap: 8px;- min-height: 24px;-}-.cmp-step > header > strong {- flex: 1;- font-size: var(--fs-xs);- font-weight: 700;- letter-spacing: 0.06em;- text-transform: uppercase;-}-.cmp-step-n {- display: grid;- place-items: center;- width: 19px;- height: 19px;- border-radius: 50%;- color: var(--text-3);- background: var(--bg-3);- font: 700 10px/1 var(--font-sans);-}-.cmp-step.done .cmp-step-n { color: var(--bg-0); background: var(--accent); }-/* Notes are small wherever they sit in a dock, not only inside a step: a- paragraph that escapes this rule renders at body size and shouts. */+/* Notes are small wherever they sit in a dock: a paragraph that escapes this+ rule renders at body size and shouts. */.cmp-dock .hint { color: var(--text-3); font-size: var(--fs-xs); line-height: 1.45; margin: 0; }.cmp-dock .warn { color: var(--warn); font-size: var(--fs-xs); line-height: 1.45; margin: 0; }diff --git a/frontend/src/tools/satellite/AddLayerDialog.render.test.js b/frontend/src/tools/satellite/AddLayerDialog.render.test.jsindex 253b997..19f5dd6 100644--- a/frontend/src/tools/satellite/AddLayerDialog.render.test.js+++ b/frontend/src/tools/satellite/AddLayerDialog.render.test.js@@ -62,6 +62,26 @@ describe('the add-a-layer dialog', () => {expect(document.body.textContent).toContain('fetched once, now');});+ it('keeps every note to one sentence, and never says the layer stays out of the case', () => {+ show();+ const notes = () =>+ [...document.body.querySelectorAll('.lead, .note')].map((node) => node.textContent.trim());+ const [file] = ticks();+ const read = [...notes()];+ file.checked = true;+ file.dispatchEvent(new Event('change', { bubbles: true }));+ flushSync();+ read.push(...notes());++ expect(read.length).toBeGreaterThan(3);+ for (const note of read) {+ expect(note.replace(/\s+/g, ' ').replace(/[.?!]$/, ''), note).not.toMatch(/[.?!] /);+ expect(note).not.toContain('—');+ // a layer is saved with the case and travels in its bundles+ expect(note).not.toMatch(/joins the case/);+ }+ });+it('hands the answer to the caller with the address', () => {const onurl = vi.fn();show({ onurl });diff --git a/frontend/src/tools/satellite/AddLayerDialog.svelte b/frontend/src/tools/satellite/AddLayerDialog.svelteindex aefce21..5bb9e0e 100644--- a/frontend/src/tools/satellite/AddLayerDialog.svelte+++ b/frontend/src/tools/satellite/AddLayerDialog.svelte@@ -45,8 +45,8 @@<Modal title="Add a layer" {onclose} width="460px"><p class="lead">- A KML, KMZ, GeoJSON or GPX file, or a public map to follow. Its features are- drawn and filtered here; nothing in it joins the case.+ A KML, KMZ, GeoJSON or GPX file, or a public map to follow, drawn over the+ imagery with its features kept out of the case graph.</p><section>@@ -67,7 +67,7 @@</label><p class="note">{fileIcons- ? "Icons inside a KMZ are read from the file. Icons at web addresses are fetched once, now."+ ? 'Icons inside a KMZ are read from it, and icons at web addresses are fetched once, now.': 'Nothing leaves this machine.'}</p></section>@@ -90,11 +90,10 @@{busy ? 'Reading…' : 'Subscribe'}</button><!-- The one sentence this feature owes before it fetches: what it will ask- for, when, and what it will not do on its own. -->+ for, and every moment it asks. --><p class="note">- A My Maps share link, or any KML or GeoJSON address. It is read now, when- you press Refresh, and the first time you switch it on after opening- Azimut — never on a timer, and never while the layer is off.+ A My Maps link or any KML or GeoJSON address, read now, on Refresh, and when+ first switched on after opening Azimut.</p></section>diff --git a/frontend/src/tools/satellite/AddedLayersOverlay.svelte b/frontend/src/tools/satellite/AddedLayersOverlay.svelteindex 04afc70..aac93a1 100644--- a/frontend/src/tools/satellite/AddedLayersOverlay.svelte+++ b/frontend/src/tools/satellite/AddedLayersOverlay.svelte@@ -38,7 +38,7 @@*/function iconUrlFor(row) {if (!row.icons) return null;- const base = `/api/cases/${caseId}/map-layers/${row.name}/icons`;+ const base = `/api/cases/${caseId}/map-layers/${encodeURIComponent(row.name)}/icons`;return (key) => `${base}/${key}`;}diff --git a/frontend/src/tools/satellite/GeoConfirmedDialog.svelte b/frontend/src/tools/satellite/GeoConfirmedDialog.svelteindex c874f19..b46bf00 100644--- a/frontend/src/tools/satellite/GeoConfirmedDialog.svelte+++ b/frontend/src/tools/satellite/GeoConfirmedDialog.svelte@@ -84,8 +84,8 @@<Modal title="GeoConfirmed" {onclose} width="460px"><p class="lead">- Events GeoConfirmed's volunteers geolocated, each with its sources. They are- drawn and filtered here; nothing joins the case.+ Events GeoConfirmed's volunteers geolocated, each with its sources, drawn here+ and kept out of the case graph.</p>{#if reading}diff --git a/frontend/src/tools/satellite/PlaceSearch.render.test.js b/frontend/src/tools/satellite/PlaceSearch.render.test.jsnew file mode 100644index 0000000..66c82ad--- /dev/null+++ b/frontend/src/tools/satellite/PlaceSearch.render.test.js@@ -0,0 +1,96 @@+// @vitest-environment happy-dom+/**+ * The search bar, mounted: what it does when its suggestions fail, and what+ * Enter does with nothing highlighted.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { flushSync, mount, unmount } from 'svelte';++const get = vi.fn();+vi.mock('../../lib/api.js', () => ({ api: { get } }));+const { default: PlaceSearch } = await import('./PlaceSearch.svelte');++let live;+let target;++function open(props = {}) {+ const onsubmit = vi.fn();+ const onpick = vi.fn();+ live = mount(PlaceSearch, {+ target,+ props: { value: '', savedRows: [], centre: { lat: 50, lon: 30 }, onpick, onsubmit, ...props },+ });+ flushSync();+ return { onsubmit, onpick, input: target.querySelector('input[role="combobox"]') };+}++function type(input, text) {+ input.value = text;+ input.dispatchEvent(new Event('input', { bubbles: true }));+ flushSync();+}++function press(input, key) {+ const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true });+ input.dispatchEvent(event);+ flushSync();+ return event;+}++const goButton = () =>+ [...target.querySelectorAll('button')].find((node) => node.textContent.trim() === 'Go');++beforeEach(() => {+ vi.useFakeTimers();+ get.mockReset();+ localStorage.clear();+ target = document.createElement('div');+ document.body.append(target);+});++afterEach(() => {+ if (live) unmount(live);+ live = null;+ target.remove();+ vi.useRealTimers();+});++describe('a failed suggestion', () => {+ it('leaves the bar working: Go and Enter still hand the text over', async () => {+ get.mockRejectedValue(new Error('offline'));+ const { input, onsubmit } = open();++ type(input, 'Kyiv');+ await vi.advanceTimersByTimeAsync(1000);+ flushSync();++ // both lookups were tried and both failed, quietly+ expect(get.mock.calls.map(([path]) => path.split('?')[0])).toEqual([+ '/api/geo/suggest',+ '/api/geo/places',+ ]);+ expect(target.querySelector('[role="listbox"]')).toBeNull();+ expect(goButton().disabled).toBe(false);++ press(input, 'Enter');+ expect(onsubmit).toHaveBeenCalledWith('Kyiv');+ });+});++describe('Enter with nothing highlighted', () => {+ it('hands the text to the bar and stops the lookups still on the clock', async () => {+ get.mockResolvedValue({ coords: null, cities: [], places: [] });+ const { input, onsubmit, onpick } = open();++ type(input, 'Kyiv centre');+ const event = press(input, 'Enter');+ await vi.advanceTimersByTimeAsync(2000);++ expect(event.defaultPrevented).toBe(true);+ expect(onsubmit).toHaveBeenCalledTimes(1);+ expect(onsubmit).toHaveBeenCalledWith('Kyiv centre');+ expect(onpick).not.toHaveBeenCalled();+ // the bar's own search asks for itself, so this one never reaches the geocoder+ expect(get).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/tools/satellite/PlaceSearch.test.js b/frontend/src/tools/satellite/PlaceSearch.test.jsindex 3e51bdb..2ef5162 100644--- a/frontend/src/tools/satellite/PlaceSearch.test.js+++ b/frontend/src/tools/satellite/PlaceSearch.test.js@@ -52,10 +52,6 @@ describe('what typing costs', () => {it('leaves the list alone when the geocoder request was dropped rather than answered', () => {expect(source).toContain('if (!body.busy) places = body.places ?? []');});-- it('survives a failed suggestion without breaking the bar', () => {- expect(source).toContain('/* the bar still works without suggestions */');- });});describe('choosing', () => {@@ -77,8 +73,8 @@ describe('choosing', () => {expect(source).toContain('function settle() {');expect(source).toContain('clearTimeout(localTimer);\n clearTimeout(remoteTimer);');expect(source).toContain('function choose(item) {\n settle();');- // …and the same when Enter hands the text to the bar's own search- expect(source).toContain("// the bar's own search takes it from here, and asks for itself");+ // Enter handing the text to the bar's own search settles too, and a failed+ // suggestion leaves the bar working: PlaceSearch.render.test.js mounts both.});it('remembers what was picked', () => {diff --git a/frontend/src/tools/satellite/SavedRow.svelte b/frontend/src/tools/satellite/SavedRow.svelteindex cd81413..48240b7 100644--- a/frontend/src/tools/satellite/SavedRow.svelte+++ b/frontend/src/tools/satellite/SavedRow.svelte@@ -18,7 +18,6 @@coords,fullscreen = false,dense = false,- active = false,hovered = false,// set only by the folder view of the tree, where there is somewhere to dropdraggable = false,@@ -67,7 +66,6 @@<divclass="row"class:dense- class:activeclass:hoveredclass:draggabledata-saved-id={row.key ?? row.id}@@ -173,10 +171,6 @@.row.hovered {background: var(--bg-2);}- .row.active {- background: var(--accent-soft);- box-shadow: inset 2px 0 0 var(--accent);- }.row.draggable {cursor: grab;}@@ -316,9 +310,6 @@opacity: 1;pointer-events: auto;}- .row.active .actions {- background: linear-gradient(to right, transparent, var(--bg-2) 16px);- }.act {display: grid;place-items: center;diff --git a/frontend/src/tools/satellite/state/addedLayers.svelte.js b/frontend/src/tools/satellite/state/addedLayers.svelte.jsindex 8729b07..e7e3c8d 100644--- a/frontend/src/tools/satellite/state/addedLayers.svelte.js+++ b/frontend/src/tools/satellite/state/addedLayers.svelte.js@@ -159,7 +159,7 @@ export function createAddedLayersState({ api, notify, ensureCase, reloadCase })renewed.add(layer.name);return act(layer.name, async () => {try {- const row = await api.post(`/api/cases/${caseId}/map-layers/${layer.name}/refresh`);+ const row = await api.post(`/api/cases/${caseId}/map-layers/${encodeURIComponent(layer.name)}/refresh`);if (loadedFor !== caseId) return;if (row.sha256 !== layer.sha256) forget(row.name);replace(row);@@ -178,7 +178,7 @@ export function createAddedLayersState({ api, notify, ensureCase, reloadCase })*/async function drawing(caseId, name) {if (drawings.has(name)) return drawings.get(name);- const data = await api.get(`/api/cases/${caseId}/map-layers/${name}/data`, {+ const data = await api.get(`/api/cases/${caseId}/map-layers/${encodeURIComponent(name)}/data`, {cache: 'no-cache',});drawings.set(name, data);@@ -262,7 +262,7 @@ export function createAddedLayersState({ api, notify, ensureCase, reloadCase })}async function patch(caseId, name, body) {- const row = await api.patch(`/api/cases/${caseId}/map-layers/${name}`, body);+ const row = await api.patch(`/api/cases/${caseId}/map-layers/${encodeURIComponent(name)}`, body);replace(row);return row;}@@ -402,7 +402,7 @@ export function createAddedLayersState({ api, notify, ensureCase, reloadCase })refresh(caseId, layer) {return act(layer.name, async () => {try {- const row = await api.post(`/api/cases/${caseId}/map-layers/${layer.name}/refresh`);+ const row = await api.post(`/api/cases/${caseId}/map-layers/${encodeURIComponent(layer.name)}/refresh`);if (row.sha256 !== layer.sha256) forget(row.name);replace(row);notify(@@ -418,7 +418,7 @@ export function createAddedLayersState({ api, notify, ensureCase, reloadCase })async remove(caseId, layer) {return act(layer.name, async () => {try {- await api.del(`/api/cases/${caseId}/map-layers/${layer.name}`);+ await api.del(`/api/cases/${caseId}/map-layers/${encodeURIComponent(layer.name)}`);forget(layer.name);show(layer.name, false);renewed.delete(layer.name);diff --git a/frontend/src/tools/satellite/state/addedLayers.svelte.test.js b/frontend/src/tools/satellite/state/addedLayers.svelte.test.jsindex 81420b2..e41787d 100644--- a/frontend/src/tools/satellite/state/addedLayers.svelte.test.js+++ b/frontend/src/tools/satellite/state/addedLayers.svelte.test.js@@ -285,6 +285,34 @@ describe('the acts on a row', () => {});});+describe('a name the URL would cut', () => {+ it('encodes every name it puts in a path, so "Ops #2" never reaches "Ops"', async () => {+ const ops = followed({ name: 'Ops #2', title: 'Ops #2', refresh: { on_open: false } });+ rows = [ops];+ api.post = vi.fn(async (path) => {+ calls.push(['POST', path]);+ return ops;+ });+ const layers = store();+ layers.load('c1');+ await settle();+ calls.length = 0;++ await layers.drawing('c1', 'Ops #2');+ await layers.refresh('c1', layers.rows[0]);+ await layers.toggleCategory('c1', layers.rows[0], 'Checkpoints');+ await layers.remove('c1', layers.rows[0]);++ const paths = calls.map(([, path]) => path);+ expect(paths).toEqual([+ '/api/cases/c1/map-layers/Ops%20%232/data',+ '/api/cases/c1/map-layers/Ops%20%232/refresh',+ '/api/cases/c1/map-layers/Ops%20%232',+ '/api/cases/c1/map-layers/Ops%20%232',+ ]);+ });+});+describe('adding', () => {it('posts a file as multipart and closes the dialog on success', async () => {const layers = store();diff --git a/frontend/src/tools/satellite/state/grid.svelte.js b/frontend/src/tools/satellite/state/grid.svelte.jsindex 3f0b176..711be83 100644--- a/frontend/src/tools/satellite/state/grid.svelte.js+++ b/frontend/src/tools/satellite/state/grid.svelte.js@@ -472,7 +472,7 @@ export function createGridState({const marks = unsent;unsent = {};try {- const answer = await api.post(`/api/cases/${id}/search-grids/${slug}/marks`, { marks });+ const answer = await api.post(`/api/cases/${id}/search-grids/${encodeURIComponent(slug)}/marks`, { marks });if (name === slug) baseRevision = answer?.revision ?? baseRevision;} catch (e) {// Put them back, without stepping on any made since: a mark that has been@@ -492,7 +492,7 @@ export function createGridState({unsent = {};try {const spec = JSON.parse(JSON.stringify(grid)); // strip the $state proxy- const saved = await api.put(`/api/cases/${id}/search-grids/${slug}`, {+ const saved = await api.put(`/api/cases/${id}/search-grids/${encodeURIComponent(slug)}`, {spec,title: grid.title,base_revision: baseRevision,@@ -514,7 +514,7 @@ export function createGridState({async function saveOverTheirMarks(slug) {const id = caseId();try {- const fresh = await api.get(`/api/cases/${id}/search-grids/${slug}`);+ const fresh = await api.get(`/api/cases/${id}/search-grids/${encodeURIComponent(slug)}`);if (name !== slug) return; // moved on alreadygrid.statuses = mergedStatuses(fresh);baseRevision = fresh.revision ?? 0;@@ -549,7 +549,7 @@ export function createGridState({const id = caseId();if (!id || specDirty) return;try {- const fresh = await api.get(`/api/cases/${id}/search-grids/${slug}`);+ const fresh = await api.get(`/api/cases/${id}/search-grids/${encodeURIComponent(slug)}`);if (name !== slug) return;const statuses = mergedStatuses(fresh);grid = { ...fresh, statuses };@@ -829,7 +829,7 @@ export function createGridState({hidden = false;await flushSave(); // persist the grid we're leavingtry {- grid = await api.get(`/api/cases/${id}/search-grids/${slug}`);+ grid = await api.get(`/api/cases/${id}/search-grids/${encodeURIComponent(slug)}`);name = slug;unsent = {}; // whatever is left belonged to the grid we just leftspecDirty = false;@@ -855,7 +855,7 @@ export function createGridState({const id = caseId();if (id) {try {- await api.del(`/api/cases/${id}/search-grids/${slug}`);+ await api.del(`/api/cases/${id}/search-grids/${encodeURIComponent(slug)}`);} catch {/* the file may already be gone — nothing left to do */}diff --git a/frontend/vite.config.js b/frontend/vite.config.jsindex 786057a..4936bf7 100644--- a/frontend/vite.config.js+++ b/frontend/vite.config.js@@ -29,12 +29,14 @@ export default defineConfig({build: {outDir: '../src/azimut/static',emptyOutDir: true,- // Mermaid's Langium parser lands in one ~660 kB chunk, read off local disk- // and only when a note holds a diagram whose grammar needs it. The default- // 500 kB limit flags it on every build, which trains us to ignore the- // warning. Our own chunks top out under 200 kB, so anything reaching this- // ceiling is still a regression worth reading.- chunkSizeWarningLimit: 700,+ // Two third-party chunks are large on purpose, and each loads only when it is+ // needed: MapLibre GL (the `basemap-*` chunk, about 1,030 kB, for the tools+ // that draw a map) and Mermaid's Langium parser (about 660 kB, when a note+ // holds a diagram whose grammar needs it). A limit below MapLibre warns on every+ // build, which trains us to ignore the warning, so the ceiling sits just+ // above it. Our own chunks top out near 310 kB (the entry), so anything+ // reaching this ceiling is still a regression worth reading.+ chunkSizeWarningLimit: 1100,},server: {proxy: {diff --git a/scripts/check_glibc_floor.py b/scripts/check_glibc_floor.pynew file mode 100644index 0000000..3aef2ad--- /dev/null+++ b/scripts/check_glibc_floor.py@@ -0,0 +1,83 @@+"""Refuse a Linux release binary that needs a newer glibc than the README promises.++PyInstaller copies the build machine's own `libstdc++.so.6`, `libgcc_s.so.1` and+`libz.so.1` into the single-file binary, which loads them before the system's. The+glibc those were linked against is therefore the oldest one the binary starts on,+and it is set by the runner image, not by anything in this repository. The release+workflow pins that image; this reads every ELF the binary carries and fails the+build when one of them asks for more than `FLOOR`, so the README can never promise+less than the binary needs.+"""++from __future__ import annotations++import argparse+import re+import sys+from collections.abc import Iterator+from pathlib import Path++#: What README.md states for the Linux binary ("glibc 2.38 or newer").+FLOOR = (2, 38)++_VERSION = re.compile(rb"GLIBC_(\d+)\.(\d+)(?:\.(\d+))?(?![\d.])")+++def glibc_versions(data: bytes) -> set[tuple[int, ...]]:+ """Every `GLIBC_x.y[.z]` version an ELF image names."""+ return {+ tuple(int(part) for part in match.groups() if part is not None)+ for match in _VERSION.finditer(data)+ }+++def embedded_elves(binary: Path) -> Iterator[tuple[str, bytes]]:+ """The bootloader, then every shared object packed into the binary."""+ from PyInstaller.archive.readers import CArchiveReader++ archive = CArchiveReader(str(binary))+ # Only the bootloader's own bytes: what follows it is compressed and could+ # spell anything.+ start = getattr(archive, "_start_offset", 0) or len(binary.read_bytes())+ yield binary.name, binary.read_bytes()[:start]+ for name, entry in archive.toc.items():+ if entry[-1] != "b":+ continue+ data = archive.extract(name)+ if data.startswith(b"\x7fELF"):+ yield name, data+++def over_floor(+ members: Iterator[tuple[str, bytes]], floor: tuple[int, ...] = FLOOR+) -> list[tuple[str, tuple[int, ...]]]:+ """(member, highest version) for each member asking for more than `floor`."""+ out = []+ for name, data in members:+ versions = glibc_versions(data)+ if versions and max(versions) > floor:+ out.append((name, max(versions)))+ return out+++def _dotted(version: tuple[int, ...]) -> str:+ return ".".join(str(part) for part in version)+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument("binary", type=Path)+ args = parser.parse_args(argv)+ members = list(embedded_elves(args.binary))+ highest = max(+ (max(v) for _name, data in members if (v := glibc_versions(data))), default=None+ )+ print(f"{len(members)} ELF images; highest glibc asked for: {_dotted(highest or (0,))}")+ failures = over_floor(iter(members))+ for name, version in failures:+ print(f"{name} needs GLIBC_{_dotted(version)}, above the {_dotted(FLOOR)} floor")+ return 1 if failures else 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/sign_extension.py b/scripts/sign_extension.pyindex 5e993b0..7345b5b 100644--- a/scripts/sign_extension.py+++ b/scripts/sign_extension.py@@ -16,10 +16,12 @@ a release is what moves it (see the release checklist).Usage, from the repo root, after the release carrying this version exists::- export AMO_JWT_ISSUER=user:12345:67- export AMO_JWT_SECRET=<secret from the AMO developer hub>+ source ~/.config/azimut/amo.env # AMO_JWT_ISSUER + AMO_JWT_SECRET, 0600 file outside the repopython3 scripts/sign_extension.py+Never type the secret at a prompt or pass it as an argument, where the shell+history keeps it.+The tag defaults to ``v{extension version}``, because the extension carries theversion of the release that last changed it — the same number the update buttonand the version gate already answer to. ``--from-xpi`` rebuilds the updatediff --git a/src/azimut/api/analyzers.py b/src/azimut/api/analyzers.pyindex 51eebfe..88028d6 100644--- a/src/azimut/api/analyzers.py+++ b/src/azimut/api/analyzers.py@@ -25,6 +25,7 @@ from ..engine.analysis_models import (AreaGeometry, Bounds, Check, Latitude, Longitude, Model, Recipe, RunInput, SceneClass, ShortId, Source, Zone,ZoneSet, is_single,)+from ..workspace import Casefrom .cases import delete_by_path, delete_entities_deep, get_caserouter = APIRouter(prefix="/api", tags=["analyzers"])@@ -635,6 +636,25 @@ def promote(case_id: str, ident: str, result_id: str, body: Promotion) -> dict[sreturn {"entity": entity, "image": filed["item"]["path"], "claim": claim, "result": result}+def _own_evidence(case: Case, place: dict[str, Any] | None, claim: str | None) -> str | None:+ """The picture Keep filed for this pin, while nothing else has come to use it.++ It was imported for the pin alone, so undoing the pin takes it along. Anything+ tied to it since (a proof composed from it, a statement kept because the+ analyst wrote to it) keeps it in the case.+ """+ path = ((place or {}).get("attrs") or {}).get("evidence")+ media_entity = case.find_entity(attr="path", value=path) if path else None+ if media_entity is None or place is None:+ return None+ ours = {place["id"], claim}+ for link in case.links_of(media_entity["id"]):+ other = link["to"] if link["from"] == media_entity["id"] else link["from"]+ if other not in ours:+ return None+ return str(media_entity["id"])++@router.delete("/cases/{case_id}/analysis/runs/{ident}/results/{result_id}/promote")def unpromote(case_id: str, ident: str, result_id: str) -> dict[str, Any]:"""Undo keeping: the pin and its evidence go to Trash, the candidate returns.@@ -648,7 +668,8 @@ def unpromote(case_id: str, ident: str, result_id: str) -> dict[str, Any]:result = result_of(saved, result_id)entity = kept_entity(case, result)claim = analysis_dating.withdrawable(case, ident, result_id)- going = [each for each in (entity["id"] if entity else None, claim) if each]+ evidence = _own_evidence(case, entity, claim)+ going = [each for each in (entity["id"] if entity else None, claim, evidence) if each]removed = delete_entities_deep(case, going) if going else Noneresult.update(entity_id=None, review="new", reviewed_at=engine.now())engine.persist_run(case, saved)diff --git a/src/azimut/api/compare.py b/src/azimut/api/compare.pyindex 0e49426..444ff55 100644--- a/src/azimut/api/compare.py+++ b/src/azimut/api/compare.py@@ -33,6 +33,7 @@ import ioimport jsonimport warningsfrom datetime import datetime, timezone+from pathlib import PurePosixPathfrom typing import Any, Literalfrom fastapi import APIRouter, File, Form, HTTPException, UploadFile@@ -47,7 +48,7 @@ from ..engine import links as link_enginefrom ..engine import media as media_enginefrom ..workspace import Case, CaseErrorfrom .cases import delete_by_path, get_case-from .naming import read_created_at, slugify+from .naming import case_only, holders, read_created_at, slugifyfrom .satellite import locate_on_save, saved_changedrouter = APIRouter(prefix="/api", tags=["compare"])@@ -464,18 +465,56 @@ def load_session(case_id: str, name: str) -> dict[str, Any]:@router.post("/cases/{case_id}/compare/sessions")def save_session(case_id: str, body: SessionIn) -> dict[str, Any]:case = get_case(case_id)- case.subdir(layout.COMPARE_DIR).mkdir(parents=True, exist_ok=True)+ with case.lock:+ saved, located = _save_session(case, body)+ # Outside the lock: locating the point may ask a geocoder for its country.+ if located:+ locate_on_save(case, *located)+ saved_changed(case)+ return saved+++def _save_session(+ case: Case, body: SessionIn+) -> tuple[dict[str, Any], tuple[str, float, float] | None]:+ """Names answer to Windows and macOS, and to the Trash.++ A name is taken by another comparison whatever its case, since two that differ+ only by case are one file on two of the three systems. A name in the Trash is+ not free either: the kept images of the deleted comparison still point at it,+ and would attach themselves to a new one standing somewhere else.+ """+ folder = case.subdir(layout.COMPARE_DIR)name = slugify(body.title, "Comparison")- rel = layout.compare_session_rel(name)- path = case.resolve_inside(rel)old = slugify(body.rename_from, "Comparison") if body.rename_from else Noneold_rel = layout.compare_session_rel(old) if old and old != name else None- if old_rel and path.exists():- raise HTTPException(status_code=409, detail="another comparison already uses that name")- if body.rename_from is None and path.exists() and not body.overwrite:- raise HTTPException(status_code=409, detail="a comparison already uses that name")-- previous = case.resolve_inside(layout.compare_session_rel(old or name))+ trashed = case.trashed_stems(layout.COMPARE_DIR)+ if old_rel:+ if holders(folder, name, source=old):+ raise HTTPException(status_code=409, detail="another comparison already uses that name")+ if name.casefold() in trashed and not case_only(old, name):+ raise HTTPException(+ status_code=409, detail="a comparison in the Trash uses that name"+ )+ elif body.rename_from is None:+ if holders(folder, name, source=name if body.overwrite else None):+ raise HTTPException(status_code=409, detail="a comparison already uses that name")+ if name.casefold() in trashed:+ taken = {p.stem.casefold() for p in folder.glob("*.json")} | trashed+ name = layout.free_stem(taken, name, "Comparison")+ rel = layout.compare_session_rel(name)+ path = case.resolve_inside(rel)+ if old_rel and case_only(old, name):+ source = case.resolve_inside(old_rel)+ # The name asked for, not `path`'s: Windows resolves a path to the case+ # already on disk.+ if source.is_file():+ path = source.with_name(PurePosixPath(rel).name)+ media_engine.rename_path(source, path)++ previous = path if old_rel and case_only(old, name) else case.resolve_inside(+ layout.compare_session_rel(old or name)+ )reading = _validated_spec(body.spec)saved = {"azimut_compare": 1,@@ -499,11 +538,10 @@ def save_session(case_id: str, body: SessionIn) -> dict[str, Any]:by="compare")["id"]if old_rel:comparisons.follow_rename(case, old_rel, rel)- case.resolve_inside(old_rel).unlink(missing_ok=True)- if stale:- locate_on_save(case, entity_id, placed["lat"], placed["lon"])- saved_changed(case)- return {"name": name, "title": name, "spec_path": rel}+ if not case_only(old, name):+ case.resolve_inside(old_rel).unlink(missing_ok=True)+ located = (entity_id, placed["lat"], placed["lon"]) if stale else None+ return {"name": name, "title": name, "spec_path": rel}, locateddef _gif_bytes(a: Image.Image, b: Image.Image, animation: str, interval: int = 700) -> bytes:@@ -836,6 +874,6 @@ def sentinel_frame(body: BandFrameIn) -> Response:raise HTTPException(status_code=422, detail=str(exc)) from excexcept Exception as exc:config.record_usage("sentinelhub", 1)- raise HTTPException(status_code=502, detail=f"band request failed: {exc}") from exc+ raise HTTPException(status_code=502, detail=f"band request failed: {tiles.upstream_failure(exc)}") from excconfig.record_usage("sentinelhub", 1)return Response(content=data, media_type="image/png", headers={"Cache-Control": "no-store"})diff --git a/src/azimut/api/drafts.py b/src/azimut/api/drafts.pyindex a483844..cb51b24 100644--- a/src/azimut/api/drafts.py+++ b/src/azimut/api/drafts.py@@ -19,9 +19,10 @@ from pydantic import BaseModel, Fieldfrom ..engine import artifacts as artifact_enginefrom ..engine import links as link_engine+from ..engine import media as media_enginefrom ..workspace import CaseErrorfrom .cases import delete_by_path, get_case-from .naming import read_created_at, slugify+from .naming import case_only, holders, read_created_at, slugifyfrom .. import layoutrouter = APIRouter(prefix="/api", tags=["drafts"])@@ -167,21 +168,32 @@ def save_draft(case_id: str, body: DraftIn) -> dict[str, Any]:# holds would leave two entities pointing at one file, and there is no sane# merge of the two. The first save of an unbound composer still writes over# a same-named draft — there the analyst is updating that one.+ # Taken is judged without case, the draft being saved excepted: two names that+ # differ only by case are one file on Windows and macOS.old = slugify(body.rename_from, "draft") if body.rename_from else Noneold_rel = layout.draft_rel(old) if old and old != name else None- if old_rel and path.exists():+ if holders(path.parent, name, source=old if old_rel else name):raise HTTPException(status_code=409, detail="another draft already uses that name")+ recased = case_only(old, name)+ if recased and old:+ # One file under both names there: renamed in place, never deleted as "the old one".+ source = case.resolve_inside(layout.draft_rel(old))+ # The name asked for, not `path`'s: Windows resolves a path to the case+ # already on disk.+ if source.is_file():+ path = source.with_name(PurePosixPath(rel).name)+ media_engine.rename_path(source, path)data = {"azimut_draft": DRAFT_MARKER,"title": name,- "created_at": read_created_at(case.resolve_inside(layout.draft_rel(old or name))) or _now(),+ "created_at": read_created_at(+ path if recased else case.resolve_inside(layout.draft_rel(old or name))+ ) or _now(),"updated_at": _now(),"state": body.state,}- path.write_text(- json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"- )+ media_engine.write_json_atomic(path, data)# upsert the post entity (analyst action → confirmed). A rename rebinds the# entity the old name held rather than filing a second one, so the draft@@ -200,7 +212,7 @@ def save_draft(case_id: str, body: DraftIn) -> dict[str, Any]:attrs={"draft": rel},by="post-composer",)["id"]- if old_rel:+ if old_rel and not recased:case.resolve_inside(layout.draft_rel(str(old))).unlink(missing_ok=True)# A post is derived from the proof it announces and the media it attaches —diff --git a/src/azimut/api/files.py b/src/azimut/api/files.pyindex fc24dae..31650b4 100644--- a/src/azimut/api/files.py+++ b/src/azimut/api/files.py@@ -3,6 +3,10 @@Only paths inside a case directory are reachable (Case.resolve_inside refusestraversal), and the server itself binds to localhost only.+A case file comes from anywhere: a bundle someone sent, a page a download pulled.+Opened in a tab it would be a page of this origin, with every power the app has, so+anything a browser could run script in is served sandboxed: shown, never run.+Every response carries an ETag and revalidates, so reopening a picker costs oneconditional request per image instead of a full redownload. Thumbnail URLsembed the content hash and a generation counter, so they are handed out as@@ -23,6 +27,29 @@ router = APIRouter(prefix="/files", tags=["files"])IMMUTABLE = "public, max-age=31536000, immutable"REVALIDATE = "no-cache"+#: Types that only ever display. Everything else (SVG, HTML, XML and whatever the+#: extension does not name) can carry script, and gets `SANDBOX`. PDF stays out+#: because a sandboxed page cannot load the browser's viewer, and a PDF's own+#: script already runs in that viewer's sandbox, not in this origin.+PASSIVE_PREFIXES = ("video/", "audio/")+PASSIVE_TYPES = frozenset({+ "image/png", "image/jpeg", "image/gif", "image/webp", "image/avif", "image/bmp",+ "image/tiff", "image/x-icon", "image/vnd.microsoft.icon", "image/heic", "image/heif",+ "application/pdf", "text/plain", "text/csv", "application/json",+})+SANDBOX = (+ "sandbox; default-src 'none'; img-src 'self' data:; media-src 'self'; "+ "style-src 'unsafe-inline'"+)+++def _security_headers(media_type: str) -> dict[str, str]:+ headers = {"x-content-type-options": "nosniff"}+ kind = media_type.split(";")[0].strip().lower()+ if kind not in PASSIVE_TYPES and not kind.startswith(PASSIVE_PREFIXES):+ headers["content-security-policy"] = SANDBOX+ return headers+@router.get("/{case_id}/{rel_path:path}")def case_file(case_id: str, rel_path: str, request: Request) -> Response:@@ -39,7 +66,9 @@ def case_file(case_id: str, rel_path: str, request: Request) -> Response:# edited in place (Inspect writes back) invalidates its own cache entry.response = FileResponse(path, stat_result=path.stat())response.headers["cache-control"] = cache+ guard = _security_headers(response.media_type or "")+ response.headers.update(guard)etag = response.headers.get("etag", "")if etag and request.headers.get("if-none-match") == etag:- return Response(status_code=304, headers={"etag": etag, "cache-control": cache})+ return Response(status_code=304, headers={"etag": etag, "cache-control": cache, **guard})return responsediff --git a/src/azimut/api/media.py b/src/azimut/api/media.pyindex c753e08..f7941fe 100644--- a/src/azimut/api/media.py+++ b/src/azimut/api/media.py@@ -33,10 +33,6 @@ class DownloadIn(BaseModel):use_cookies: bool = False-class DeleteIn(BaseModel):- path: str--class ExportIn(BaseModel):"""One media file to copy out. Where it goes is the folder saved for media(engine/exportdir.py), never something the request names."""diff --git a/src/azimut/api/naming.py b/src/azimut/api/naming.pyindex 6501904..eac1748 100644--- a/src/azimut/api/naming.py+++ b/src/azimut/api/naming.py@@ -18,7 +18,30 @@ from typing import Anyfrom ..layout import MAX_SLUG, slugify-__all__ = ["MAX_SLUG", "slugify", "read_created_at"]+__all__ = ["MAX_SLUG", "slugify", "read_created_at", "holders", "case_only"]+++def holders(folder: Path, name: str, *, source: str | None = None) -> list[str]:+ """The stems in `folder` that Windows and macOS would take for `name`.++ Compared without case: Linux keeps `Harbour` beside `harbour`, the other two+ systems see one file, and a bundle refuses the pair, so the stricter rule is+ the one a name answers to. `source` is the stem the save starts from, which+ never collides with itself, a change of case included.+ """+ if not folder.is_dir():+ return []+ folded = name.casefold()+ return [+ path.stem+ for path in folder.glob("*.json")+ if path.stem.casefold() == folded and path.stem != source+ ]+++def case_only(old: str | None, new: str) -> bool:+ """Whether a rename changes only the case, which is one file on Windows and macOS."""+ return old is not None and old != new and old.casefold() == new.casefold()def read_created_at(path: Path) -> str | None:diff --git a/src/azimut/api/proofs.py b/src/azimut/api/proofs.pyindex 46f7399..f85d12d 100644--- a/src/azimut/api/proofs.py+++ b/src/azimut/api/proofs.py@@ -37,14 +37,13 @@ from ..engine import thumbnails as thumbnail_enginefrom ..workspace import Case, CaseError, ensure_dirfrom .cases import delete_by_path, get_casefrom .cases.common import delete_entity_deep-from .naming import read_created_at, slugify+from .naming import case_only, holders, read_created_at, slugifyfrom .satellite import locate_on_savefrom .. import layoutrouter = APIRouter(prefix="/api", tags=["proofs"])-ASSETS_SUFFIX = ".assets"ASSET_NAME = re.compile(r"^[0-9a-f]{16}\.(?:png|jpe?g|webp)$")MAX_ASSET_BYTES = 20 * 1024 * 1024MAX_ASSETS = 12@@ -103,8 +102,7 @@ def _now() -> str:def _write_spec(path: Path, spec: dict[str, Any]) -> None:- ensure_dir(path.parent)- path.write_text(json.dumps(spec, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")+ media_engine.write_json_atomic(path, spec)#: What a proof says about itself in words and in time, beside the composition.@@ -307,10 +305,12 @@ def load_proof(case_id: str, name: str) -> dict[str, Any]:if isinstance(spec, dict) and proof is not None:opened = satellite_engine.open_spec(case, proof["id"], spec)attrs = proof.get("attrs") or {}+ # Present at all, it wins, blank included: clearing a date in Details is+ # the analyst taking it back, and the spec still holding it is stale.for key, attr in (("when", "when"), ("description", "notes")):- stated = attrs.get(attr)- if isinstance(stated, str) and stated.strip():- opened[key] = stated.strip()+ if attr in attrs:+ stated = attrs[attr]+ opened[key] = (stated.strip() or None) if isinstance(stated, str) else Nonereturn openedreturn spec@@ -361,10 +361,13 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:# holds would leave two entities pointing at one spec, and there is no sane# merge of the two. The first save of an unbound composer still writes over# a same-named proof — there the analyst is updating that one.+ # Taken is judged without case, the proof being saved excepted: two names that+ # differ only by case are one file on Windows and macOS.old = slugify(body.rename_from, "proof") if body.rename_from else Noneold_rel = layout.proof_spec_rel(old) if old and old != name else None- if old_rel and spec_path.exists():+ if holders(spec_path.parent, name, source=old if old_rel else name):raise HTTPException(status_code=409, detail="another proof already uses that name")+ recased = case_only(old, name)# Decoded up front: a bad batch must be refused before anything is written.incoming = _decode_assets(body.assets)@@ -387,9 +390,17 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:detail=f"the export must be under {MAX_EXPORT_BYTES // 1024 // 1024} MB",)+ if recased and old:+ # One file under both names on Windows and macOS: each is renamed in place,+ # and nothing is deleted as "the old one", which there is the same file.+ for rel_of in (layout.proof_spec_rel, layout.proof_export_rel, layout.proof_assets_rel):+ source = case.resolve_inside(rel_of(old))+ if source.exists():+ media_engine.rename_path(source, source.with_name(Path(rel_of(name)).name))+ spec_path = case.resolve_inside(rel)# The export moves with the spec, so a rename saved without fresh pixels# keeps the PNG the proof already had rather than dropping it.- if old_rel and old:+ elif old_rel and old:old_png = case.resolve_inside(layout.proof_export_rel(old))if old_png.exists():if png_bytes is not None:@@ -417,7 +428,7 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:spec["title"] = namespec["when"] = when or Nonespec["description"] = description or None- previous = case.resolve_inside(layout.proof_spec_rel(old or name))+ previous = case.resolve_inside(layout.proof_spec_rel(name if recased else old or name))spec.setdefault("created_at", read_created_at(previous) or _now())spec["updated_at"] = _now()if png_rel:@@ -474,7 +485,7 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:},by="proof-composer",)["id"]- if old_rel:+ if old_rel and not recased:case.resolve_inside(layout.proof_spec_rel(str(old))).unlink(missing_ok=True)# A proof is derived from what it composes *and* from what it rests on: the samediff --git a/src/azimut/api/satellite.py b/src/azimut/api/satellite.pyindex 59b6970..206e44f 100644--- a/src/azimut/api/satellite.py+++ b/src/azimut/api/satellite.py@@ -250,7 +250,7 @@ def sentinel_layers(check: bool = False) -> dict[str, Any]:return {"layers": [{"id": e.id, "label": e.label, "hint": e.hint} for e in sentinel.LAYERS],"source": "catalogue",- "detail": f"could not read the instance's layers: {exc}",+ "detail": f"could not read the instance's layers: {tiles.upstream_failure(exc)}",}if not found:return {@@ -286,7 +286,7 @@ def sentinel_dates(config.record_usage("sentinelhub", 1)raise HTTPException(status_code=422, detail=str(exc)) from excexcept Exception as exc:- raise HTTPException(status_code=502, detail=f"date lookup failed: {exc}") from exc+ raise HTTPException(status_code=502, detail=f"date lookup failed: {tiles.upstream_failure(exc)}") from excconfig.record_usage("sentinelhub", 1)return {"dates": found, "start": start, "end": end}@@ -328,7 +328,7 @@ def sentinel_acquisitions(body: AcquisitionQuery) -> dict[str, Any]:except ValueError as exc:raise HTTPException(status_code=422, detail=str(exc)) from excexcept Exception as exc:- raise HTTPException(status_code=502, detail=f"pass lookup failed: {exc}") from exc+ raise HTTPException(status_code=502, detail=f"pass lookup failed: {tiles.upstream_failure(exc)}") from excconfig.record_usage("sentinelhub", 1)return {**found, "start": body.start, "end": body.end}@@ -378,7 +378,7 @@ def sentinel1_layer(body: RadarLayerQuery) -> dict[str, Any]:except HTTPException:raiseexcept Exception as exc:- raise HTTPException(status_code=502, detail=f"layer check failed: {exc}") from exc+ raise HTTPException(status_code=502, detail=f"layer check failed: {tiles.upstream_failure(exc)}") from excdetail = (tried[-1]["detail"] if body.layer and tried else"no layer of this instance reads Sentinel-1 VV and VH")return {"ok": False, "layer": body.layer, "serves": None if body.layer else True,@@ -407,7 +407,7 @@ def sentinel_coverage(except ValueError as exc:raise HTTPException(status_code=422, detail=str(exc)) from excexcept Exception as exc:- raise HTTPException(status_code=502, detail=f"coverage check failed: {exc}") from exc+ raise HTTPException(status_code=502, detail=f"coverage check failed: {tiles.upstream_failure(exc)}") from excconfig.record_usage("sentinelhub", 1)return result@@ -422,7 +422,7 @@ def wayback_releases() -> dict[str, Any]:try:listed = wayback.releases()except Exception as exc:- raise HTTPException(status_code=502, detail=f"could not read the release list: {exc}") from exc+ raise HTTPException(status_code=502, detail=f"could not read the release list: {tiles.upstream_failure(exc)}") from excreturn {"releases": [{"release": r.number, "date": r.date} for r in listed]}@@ -442,7 +442,7 @@ def wayback_changes(try:found = wayback.local_changes(lat, lon, zoom)except Exception as exc:- raise HTTPException(status_code=502, detail=f"could not read this point's history: {exc}") from exc+ raise HTTPException(status_code=502, detail=f"could not read this point's history: {tiles.upstream_failure(exc)}") from excreturn {"changes": [{"release": c.release, "acquired": c.acquired, "source": c.source} for c in found@@ -496,7 +496,7 @@ def _serve_tile(try:upstream = _client().get(url)except httpx.HTTPError as exc:- raise HTTPException(status_code=502, detail=f"tile fetch failed: {exc}") from exc+ raise HTTPException(status_code=502, detail=f"tile fetch failed: {tiles.upstream_failure(exc)}") from exc# a stale Google session token answers 401/403 — re-mint once, transparentlyif attempt == 1 and provider.session and upstream.status_code in (401, 403):google_tiles.invalidate(google_tiles.key_from_url(provider.url))@@ -714,7 +714,7 @@ def firms_answer(url: str) -> Response:try:response = httpx.get(url, headers={"User-Agent": tiles.USER_AGENT}, timeout=20)except Exception as exc:- raise HTTPException(status_code=502, detail=f"FIRMS unreachable: {exc}") from exc+ raise HTTPException(status_code=502, detail=f"FIRMS unreachable: {tiles.upstream_failure(exc)}") from excif response.status_code >= 400 or "xml" in response.headers.get("content-type", ""):raise HTTPException(status_code=502, detail=firms.service_error(response.text) or "FIRMS refused the request"@@ -1065,7 +1065,7 @@ def capture(case_id: str, body: CaptureIn) -> dict[str, Any]:except tiles.TileFetchError as exc:raise HTTPException(status_code=422, detail=str(exc)) from excexcept Exception as exc: # network / provider failure- raise HTTPException(status_code=502, detail=f"tile fetch failed: {exc}") from exc+ raise HTTPException(status_code=502, detail=f"tile fetch failed: {tiles.upstream_failure(exc)}") from exc# the recorded point is the marker (== center unless it was moved off-center)marker_lat, marker_lon = provenance["lat"], provenance["lon"]diff --git a/src/azimut/api/settings.py b/src/azimut/api/settings.pyindex 460b71a..fbbf062 100644--- a/src/azimut/api/settings.py+++ b/src/azimut/api/settings.py@@ -346,21 +346,6 @@ class StatusIn(BaseModel):detail: str = ""[email protected]("/settings/reveal-workspace")-def reveal_workspace() -> dict[str, str]:- """Open the workspace folder in the system file manager.-- About already prints the path; this saves copying it into a file manager by- hand, which is what the first analyst to ask ended up doing with a shortcut.- """- root = config.workspace_root()- try:- reveal.reveal(root)- except reveal.RevealError as exc:- raise HTTPException(status_code=409, detail=str(exc)) from exc- return {"path": str(root)}--# ---- the capture extension's own folder --------------------------------------## Deliberately here and not under /api/ingest/: that prefix is the token-gateddiff --git a/src/azimut/config.py b/src/azimut/config.pyindex fcd8ee6..aa8b14e 100644--- a/src/azimut/config.py+++ b/src/azimut/config.py@@ -147,10 +147,11 @@ DEFAULT_SETTINGS: dict[str, Any] = {# Empty means "not minted yet" — never a valid credential."ingest_token": "",# App self-update pop-up (frontend App.svelte + engine/updates.py):- # - update_check_on_start: ask GitHub for the latest release when the page- # loads, and pop a notice if one is newer. On by default so a binary user- # (no package manager behind them) hears about releases; the one network- # call Azimut makes on mount, and the toggle in Settings turns it off.+ # - update_check_on_start: ask GitHub for the latest release, and PyPI for+ # the two downloaders, when the page loads, and pop a notice if one is+ # newer. On by default so a binary user (no package manager behind them)+ # hears about releases; the one check Azimut makes on mount, and the toggle+ # in Settings turns both halves off.# - update_dismissed_version: the release the user chose "don't show again"# for. The pop-up stays quiet for that exact tag; a newer one shows again."update_check_on_start": True,diff --git a/src/azimut/engine/analyzers.py b/src/azimut/engine/analyzers.pyindex f4cb74b..27033db 100644--- a/src/azimut/engine/analyzers.py+++ b/src/azimut/engine/analyzers.py@@ -244,7 +244,7 @@ def relpath(kind: str, ident: str) -> str:raise ValueError("unknown analysis item")if len(ident) != 12:raise ValueError("unknown analysis item")- return f"{layout.ANALYSIS_DIR}/{kind}-{ident}.json"+ return layout.analysis_rel(kind, ident)def read(case: Case, kind: str, ident: str) -> dict[str, Any]:@@ -257,8 +257,18 @@ def read(case: Case, kind: str, ident: str) -> dict[str, Any]:if not saved.get("area_dates"):saved = share_areas(case, saved, ident)media.write_json_atomic(path, saved)- saved["zones"] = [area_zone(read(case, "areas", pair["area_id"])).model_dump()- for pair in saved["area_dates"]]+ # An area deleted for good leaves the routine openable, without it and+ # saying so, rather than a file every listing silently skips.+ zones, kept, missing = [], [], []+ for pair in saved["area_dates"]:+ try:+ zones.append(area_zone(read(case, "areas", pair["area_id"])).model_dump())+ kept.append(pair)+ except FileNotFoundError:+ missing.append(pair["area_id"])+ saved["zones"], saved["area_dates"] = zones, kept+ if missing:+ saved["missing_areas"] = missingreturn saved@@ -567,9 +577,9 @@ def frame(case: Case, run: dict[str, Any], source: Source, x: int, y: int,z, size = GRIDedge = size + 2 * PAD if product else sizekey = _key(source, z, x, y, product)- name = f"{key}.png"- assets_rel = layout.analysis_assets_rel(f"runs-{run['id']}")- destination = case.resolve_inside(f"{assets_rel}/{name}")+ frame_rel = layout.analysis_asset_rel(run["id"], key)+ name = frame_rel.rsplit("/", 1)[-1]+ destination = case.resolve_inside(frame_rel)raw = None# Reuse permanent evidence from this case, including after a bundle import.for folder in case.subdir(layout.ANALYSIS_DIR).glob("runs-*.assets"):@@ -630,7 +640,7 @@ def frame(case: Case, run: dict[str, Any], source: Source, x: int, y: int,destination.write_bytes(raw)else:Image.fromarray(pixels).save(destination, "PNG")- run["frames"][key] = {"path": f"{assets_rel}/{name}", "source": source.model_dump(),+ run["frames"][key] = {"path": frame_rel, "source": source.model_dump(),"tile": [z, x, y], "index": product,"sha256": hashlib.sha256(destination.read_bytes()).hexdigest()}return pixels@@ -676,11 +686,13 @@ def ring_statistics(values: Any, water: Any, outer: int, guard: int) -> tuple[Anreturn mean, deviation, count / float(outer * outer - guard * guard)-def local_contrast(values: Any, water: Any, outer: int, guard: int) -> tuple[Any, Any]:+def local_contrast(values: Any, water: Any, outer: int, guard: int) -> tuple[Any, Any, Any]:"""How far each pixel stands above the water around it, in deviations.A vessel is not bright, it is brighter than its own patch of sea — which iswhat lets one threshold work over a calm lagoon and a sunlit swell alike.+ Returns the contrast, the share of water in each ring and the ring's mean,+ which the vessel detector also reads the excess over."""import numpy as np@@ -689,7 +701,7 @@ def local_contrast(values: Any, water: Any, outer: int, guard: int) -> tuple[Any# step would then read as a hundred-sigma detection. One digital number is# the floor because one digital number is the smallest difference there is.contrast = (values - mean) / np.maximum(deviation, 1.0)- return np.where(share > 0, contrast, 0.0), share+ return np.where(share > 0, contrast, 0.0), share, meandef sun_position(day: str, lat: float) -> tuple[float, float]:@@ -884,10 +896,8 @@ def _vessels(product: Any, inside: Any, blocked: Any, metres: float,# Land is non-water in bulk. A hull is non-water too, but a small one.land = components_over(data & ~wet, metres * metres, LAND_M2)land = cv2.dilate(land.astype(np.uint8), np.ones((5, 5), np.uint8)).astype(bool)- mean8, deviation8, share = ring_statistics(nir, water, VESSEL_RING, VESSEL_GUARD)- mean11, deviation11, _ = ring_statistics(swir, water, VESSEL_RING, VESSEL_GUARD)- near = np.where(share > 0, (nir - mean8) / np.maximum(deviation8, 1.0), 0.0)- short = np.where(share > 0, (swir - mean11) / np.maximum(deviation11, 1.0), 0.0)+ near, share, mean8 = local_contrast(nir, water, VESSEL_RING, VESSEL_GUARD)+ short, _, mean11 = local_contrast(swir, water, VESSEL_RING, VESSEL_GUARD)unit = 255 * sentinel.BAND_GAINok = inside & data & ~blocked & ~land & (share > VESSEL_WATER_SHARE)# Calibrated between 3 deviations, where small boats start to show amongdiff --git a/src/azimut/engine/bundles.py b/src/azimut/engine/bundles.pyindex c106c34..ae331ba 100644--- a/src/azimut/engine/bundles.py+++ b/src/azimut/engine/bundles.py@@ -80,6 +80,11 @@ BUNDLED_ROOTS = frozenset(#: first open — refusing the member outright would strand every bundle already#: exported. Format 2 never uses these, so this set dies with format 1.IMPORTABLE_ROOTS = BUNDLED_ROOTS | {"case.db", "exports", "inspect", "search"}++#: SQLite's own files beside the database. A journal exists while any connection is+#: writing, holds pages of the database from before the export cleaned it, and+#: opened beside an imported database it would be rolled back into it.+DB_COMPANIONS = ("-journal", "-wal", "-shm")NOT_BUNDLED = {layout.TRASH_DIR: "deleted artifacts do not travel","media/.thumbs": "content-addressed thumbnails are rebuilt",@@ -89,6 +94,15 @@ NOT_BUNDLED = {f"{layout.LAYERS_DIR}/{layout.LAYER_CACHE_DIR}": ("a map layer's parsed copy is rebuilt from its snapshot"),+ # A 0.3.0 session kept as it was, for the machine that merged it to undo by+ # hand; the work it became is what travels.+ f"{layout.INSPECT_DIR}/.v1": "a pre-0.3.1 session copy stays on the machine that merged it",+ **{+ f"{layout.DATA_DIR}/{layout.PRE_HIDDEN_DB}{suffix}": (+ "SQLite's transaction state belongs to this machine"+ )+ for suffix in DB_COMPANIONS+ },}#: Extensions whose bytes are already compressed. Deflating them burns CPU on@@ -242,9 +256,16 @@ def _validate_member_names(names: list[str]) -> None:)if any(not _safe_member(name) for name in names):raise BundleError("the bundle contains a path that is not portable")- portable = [_portable_member_key(name) for name in names]- if len(portable) != len(set(portable)):- raise BundleError("the bundle contains paths that collide on another operating system")+ seen: dict[str, str] = {}+ for name in names:+ key = _portable_member_key(name)+ if key in seen:+ # Named, since the analyst has to rename one of the two to export.+ raise BundleError(+ f"'{seen[key]}' and '{name}' are one file on Windows and macOS; "+ "rename one of them"+ )+ seen[key] = namedef disk_reserve(total: int) -> int:@@ -311,8 +332,35 @@ def _included(rel: str) -> bool:return PurePosixPath(rel).parts[0] in BUNDLED_ROOTS+def _tool_member(name: str, version: int) -> str | None:+ """A member's path under the tool root, or None when it is the analyst's own."""+ if version < WRAPPED_MEMBERS:+ return name+ parts = PurePosixPath(name).parts+ if len(parts) >= 3 and parts[0] == BUNDLE_ROOT and parts[1] == layout.TOOL_DIR:+ return "/".join(parts[2:])+ return None+++def _db_companion(name: str, version: int) -> bool:+ """Whether a member is a journal an Azimut before 0.3.1 could export.++ It is accepted, so those bundles still import, and dropped after its digest is+ checked, so it never lands beside the database it would roll back into.+ """+ inside = _tool_member(name, version)+ if inside is None:+ return False+ member = PurePosixPath(inside)+ return member.parent.as_posix() in (layout.DATA_DIR, ".") and any(+ member.name == f"{layout.PRE_HIDDEN_DB}{suffix}" for suffix in DB_COMPANIONS+ )++def _importable(rel: str, version: int) -> bool:"""Whether a bundle member may land, at the naming its format declares."""+ if _db_companion(rel, version):+ return Trueif version < WRAPPED_MEMBERS:return PurePosixPath(rel).parts[0] in IMPORTABLE_ROOTSparts = PurePosixPath(rel).parts@@ -411,7 +459,11 @@ def _clean_database(source: Path, target: Path) -> None:try:conn.execute("PRAGMA foreign_keys = ON")conn.execute("DELETE FROM trash")- conn.execute("DELETE FROM jobs WHERE state IN ('queued', 'running')")+ # Every job, finished ones too: the queue is this machine's work, and an+ # export's or an import's payload names folders on it (the workspace, the+ # Downloads folder a bundle came from), which is the account's own name.+ # An import rebuilds what it needs, thumbnails first.+ conn.execute("DELETE FROM jobs")conn.commit()conn.execute("VACUUM")finally:@@ -901,6 +953,8 @@ def _verify_and_extract(sink.write(chunk)if size != expected_size or digest.hexdigest() != record["sha256"]:raise BundleError(f"bundle member '{info.filename}' failed verification")+ if _db_companion(info.filename, declared):+ destination.unlink()return header@@ -1039,7 +1093,10 @@ def import_into(ensure_dir(layout.data_dir(imported.path))for directory in layout.content_dirs(imported.path):ensure_dir(directory)- from . import thumbnails+ from . import maplayers, thumbnails++ # A followed layer re-read on first switch-on would call the sender's server.+ maplayers.receive(imported)for item in imported.list_media_items():if item.get("kind") in thumbnails.THUMBNAILED_KINDS:diff --git a/src/azimut/engine/entities.py b/src/azimut/engine/entities.pyindex e0cfe28..6e4d14e 100644--- a/src/azimut/engine/entities.py+++ b/src/azimut/engine/entities.py@@ -555,7 +555,7 @@ ENTITY_TYPES: tuple[EntityType, ...] = (hint="a CSV table in the case, edited as a grid"),# One per file: the frames cut from it and the edits over them, saved as they# are made. Nothing in it outlives the file, so it depends on it.- EntityType("inspect-session", "Inspect session", DOCUMENT, "inspect", ANNEX,+ EntityType("inspect-session", "Inspect work", DOCUMENT, "inspect", ANNEX,hint="the frames and edits made over one file, which die with it"),# A layout of pieces from any number of files. Its pieces are recipes rather# than pixels, so a lost source leaves a gap rather than voiding the layout,@@ -565,12 +565,12 @@ ENTITY_TYPES: tuple[EntityType, ...] = (EntityType("compare-session", "Compare session", DOCUMENT, "compare", ANNEX,hint="two map sources, their layers and the shared camera"),EntityType("analysis-zones", "Analysis areas", DOCUMENT, "polygon", ANNEX,- hint="saved geographic areas reusable by any Compare analyzer"),+ hint="saved geographic areas reusable by any Detect analyzer"),EntityType("analysis-area", "Area", DOCUMENT, "mapArea", ANNEX,hint="a named area shared by detections in this case"),- # Named "watch" everywhere a user reads it: the type id is storage, and+ # Named "routine" everywhere a user reads it: the type id is storage, and# renaming that would migrate files for a word nobody sees.- EntityType("analysis-follow-up", "Analysis watch", DOCUMENT, "clock", ANNEX,+ EntityType("analysis-follow-up", "Detect routine", DOCUMENT, "clock", ANNEX,hint="an analyzer, its areas and a date rule, rerun on demand"),EntityType("analysis-run", "Analysis run", DOCUMENT, "changes", ANNEX,hint="candidate detections with frozen inputs and review decisions"),diff --git a/src/azimut/engine/inspectwork.py b/src/azimut/engine/inspectwork.pyindex 4253530..be0a086 100644--- a/src/azimut/engine/inspectwork.py+++ b/src/azimut/engine/inspectwork.py@@ -97,24 +97,6 @@ def _check_size(spec: dict[str, Any]) -> None:raise CaseError("that is too large to save")-def _free_title(taken: set[str], title: str, fallback: str) -> str:- """`title` as a filename stem, numbered past whatever `taken` already holds.-- `taken` is casefolded: two stems differing only by case are one file on Windows- and macOS.- """- base = layout.slugify(title, fallback)- if base.casefold() not in taken:- return base- n = 2- while True:- suffix = f" {n}"- candidate = layout.slugify(f"{base[: layout.MAX_SLUG - len(suffix)]}{suffix}", fallback)- if candidate.casefold() not in taken:- return candidate- n += 1--def _stems(case: "Case", directory: str) -> set[str]:folder = case.tool_root / directoryif not folder.is_dir():@@ -122,26 +104,8 @@ def _stems(case: "Case", directory: str) -> set[str]:return {path.stem.casefold() for path in folder.glob("*.json")}-def _trashed_stems(case: "Case", directory: str) -> set[str]:- """Names in `directory` that a delete moved into the Trash.-- A new artifact must not take one: the restore would find its path occupied and- refuse, and clearing a file's work then starting over is exactly when someone- wants the old frames back.- """- prefix = f"{directory}/"- out = set()- for head in case.list_trash():- group = case.get_trash_group(head["id"]) or {}- for rel in (group.get("payload") or {}).get("files") or []:- rel = str(rel)- if rel.startswith(prefix) and rel.endswith(".json") and "/" not in rel[len(prefix):]:- out.add(Path(rel).stem.casefold())- return out--def _taken(case: "Case", directory: str) -> set[str]:- return _stems(case, directory) | _trashed_stems(case, directory)+ return _stems(case, directory) | case.trashed_stems(directory)def _describes_nothing(name: str, file_label: str) -> bool:@@ -149,7 +113,7 @@ def _describes_nothing(name: str, file_label: str) -> bool:"Inspect 3" was the old default; a work is born under its file's name, numberedwhen that name was taken. Neither tells anyone anything the file does not. The- name is the file's label as `_free_title` wrote it: a long label is cut to fit+ name is the file's label as `layout.free_stem` wrote it: a long label is cut to fita filename and a character Windows forbids is replaced."""if _DEFAULT_SESSION.match(name):@@ -312,7 +276,7 @@ def save_work(case: "Case", subject: str, spec: dict[str, Any]) -> dict[str, Anycreated = previous.get("created_at") or _now()else:label = str(entity.get("label") or Path(subject).stem)- title = _free_title(_taken(case, layout.INSPECT_DIR), label, "Inspect")+ title = layout.free_stem(_taken(case, layout.INSPECT_DIR), label, "Inspect")rel = layout.session_rel(title)created = _now()active = spec.get("activeFrameId")@@ -357,7 +321,7 @@ def follow_file_rename(case: "Case", subject: str, old_labels: list[str], label:if not any(_describes_nothing(current, old) for old in old_labels if old):returnstem = Path(rel).stem.casefold()- wanted = _free_title(_taken(case, layout.INSPECT_DIR) - {stem}, label, "Inspect")+ wanted = layout.free_stem(_taken(case, layout.INSPECT_DIR) - {stem}, label, "Inspect")if wanted != current:case.update_entity(entity["id"], {"label": wanted})@@ -448,7 +412,7 @@ def save_collage(with case.lock:case.subdir(layout.COLLAGE_DIR)if name is None:- final = _free_title(_taken(case, layout.COLLAGE_DIR), title, "Collage")+ final = layout.free_stem(_taken(case, layout.COLLAGE_DIR), title, "Collage")old_rel = Noneelse:current = layout.slugify(name, "Collage")@@ -468,7 +432,17 @@ def save_collage(}if previous.get("migrated_from"):written["migrated_from"] = previous["migrated_from"]- if old_rel:+ if old_rel and final.casefold() == current.casefold():+ # A change of case only. Windows and macOS see one file under both+ # names, so deleting "the old one" would delete the collage: rename it.+ source = case.resolve_inside(old_rel)+ if source.is_file():+ media_engine.rename_path(source, source.with_name(Path(rel).name))+ _write(case.resolve_inside(rel), written)+ existing = case.find_entity(attr="spec", value=old_rel)+ if existing:+ case.update_entity(existing["id"], {"label": final, "attrs": {"spec": rel}})+ elif old_rel:# Written under the new name before the old file goes, so a crash in# between leaves the collage twice rather than not at all._write(case.resolve_inside(rel), written)@@ -533,6 +507,37 @@ def _keep_legacy(case: "Case", rel: str) -> None:shutil.copy2(source, target)+def forget_legacy(case: "Case") -> int:+ """Drop the 0.3.0 copies of sessions on a file that is gone for good.++ `_keep_legacy` keeps a session as it was, in case the merge ever needs undoing+ by hand. That need ends with the file: once it is neither in the case nor in the+ Trash, its work is gone, and a copy nothing shows would keep the notes and names+ the analyst deleted. Returns how many copies went.+ """+ folder = case.tool_root / layout.INSPECT_DIR / ".v1"+ if not folder.is_dir():+ return 0+ with case.lock:+ waiting: set[str] = set()+ for head in case.list_trash():+ group = case.get_trash_group(head["id"]) or {}+ waiting.update(str(rel) for rel in (group.get("payload") or {}).get("files") or [])+ dropped = 0+ for path in sorted(folder.glob("*.json")):+ subject = _subject(_read(path) or {})+ if not subject or subject in waiting:+ continue+ try:+ present = case.resolve_inside(subject).exists()+ except CaseError:+ present = False+ if not present:+ path.unlink(missing_ok=True)+ dropped += 1+ return dropped++def _extract_collages(case: "Case",rel: str,@@ -553,7 +558,7 @@ def _extract_collages(while f"collage {n}" in taken:n += 1wanted = f"Collage {n}"- title = _free_title(taken, wanted, "Collage")+ title = layout.free_stem(taken, wanted, "Collage")body = {"width": collage.get("width"),"height": collage.get("height"),@@ -736,7 +741,7 @@ def _merge_subject()wanted = typed or file_labeltaken = _taken(case, layout.INSPECT_DIR) - {Path(rel).stem.casefold()}- title = _free_title(taken, wanted, "Inspect")+ title = layout.free_stem(taken, wanted, "Inspect")if title != Path(rel).stem:entity = case.update_entity(entity["id"], {"label": title})rel = str((entity.get("attrs") or {}).get("spec") or rel)diff --git a/src/azimut/engine/maplayers.py b/src/azimut/engine/maplayers.pyindex dafc101..b2e4f9c 100644--- a/src/azimut/engine/maplayers.py+++ b/src/azimut/engine/maplayers.py@@ -50,6 +50,7 @@ import hashlibimport jsonimport reimport zipfile+import zlibfrom collections import Counterfrom datetime import date, datetime, timedelta, timezonefrom io import BytesIO@@ -66,6 +67,7 @@ from defusedxml.ElementTree import ParseError, fromstring as parse_xmlfrom xml.etree.ElementTree import Elementfrom .. import layout+from ..workspace import write_text_atomicfrom .tiles import USER_AGENTif TYPE_CHECKING: # pragma: no cover - typing only@@ -267,12 +269,16 @@ def parse(source_format = fmticons: dict[str, dict[str, Any]] = {}- if fmt == "geojson":- features, name = _from_geojson(data, filename)- elif fmt == "kml":- features, name, icons = _from_kml(data)- else:- features, name = _from_gpx(data)+ try:+ if fmt == "geojson":+ features, name = _from_geojson(data, filename)+ elif fmt == "kml":+ features, name, icons = _from_kml(data)+ else:+ features, name = _from_gpx(data)+ except RecursionError as exc:+ # JSON a few thousand arrays deep, before any bound on depth could be read+ raise LayerError("this file nests deeper than any map layer does") from excif not features:raise LayerError("the file holds no points, lines or areas")@@ -720,8 +726,14 @@ def _kml_out_of_kmz(data: bytes) -> tuple[bytes, str]:member = _main_kml(entries)if member is None:raise LayerError("this KMZ holds no KML file")- with archive.open(member) as handle:- return handle.read(MAX_SOURCE_BYTES + 1), member.filename+ # The member is only inflated here, so this is where a damaged archive+ # shows: a bad checksum, a broken deflate stream, a method or an+ # encryption the zip module does not read.+ try:+ with archive.open(member) as handle:+ return handle.read(MAX_SOURCE_BYTES + 1), member.filename+ except (zipfile.BadZipFile, zlib.error, NotImplementedError, RuntimeError, EOFError) as exc:+ raise LayerError("this KMZ could not be read: it is damaged or packed in a way Azimut does not read") from excdef _escapes(name: str) -> bool:@@ -1238,12 +1250,13 @@ def _gpx_point(element: Element) -> list[float] | None:def icon_images(- descriptors: dict[str, dict[str, Any]], *, source: bytes = b""+ descriptors: dict[str, dict[str, Any]], *, source: bytes = b"", web: bool = True) -> dict[str, bytes]:"""key → the PNG to store for it, skipping every one that could not be made.`source` is the original bytes, which is how a KMZ's own icons are found: its- hrefs name members of the archive the layer was read from.+ hrefs name members of the archive the layer was read from. `web` false reads+ only those, and asks no other host for anything."""if not descriptors:return {}@@ -1255,7 +1268,7 @@ def icon_images(for key in list(descriptors)[:MAX_ICONS]:descriptor = descriptors[key]if _on_the_web(descriptor):- if fetched >= MAX_FETCHED_ICONS:+ if not web or fetched >= MAX_FETCHED_ICONS:continuefetched += 1raw = _icon_bytes(descriptor, archive)@@ -1314,8 +1327,11 @@ def _zipped_icon(archive: zipfile.ZipFile, href: str) -> bytes:continueif entry.file_size > MAX_ICON_BYTES:return b""- with archive.open(entry) as handle:- return handle.read(MAX_ICON_BYTES + 1)+ try:+ with archive.open(entry) as handle:+ return handle.read(MAX_ICON_BYTES + 1)+ except (zipfile.BadZipFile, zlib.error, NotImplementedError, RuntimeError, EOFError):+ return b""return b""@@ -1641,29 +1657,91 @@ def _read_spec(case: "Case", name: str) -> dict[str, Any]:def _write_spec(case: "Case", name: str, spec: dict[str, Any]) -> None:case.subdir(layout.LAYERS_DIR)path = case.resolve_inside(layout.layer_spec_rel(name))- path.write_text(json.dumps(spec, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")+ write_text_atomic(path, json.dumps(spec, indent=2, ensure_ascii=False) + "\n")def _free_name(case: "Case", title: str) -> str:- """A stem no other layer holds. Two files called `Roads` are two layers."""- case.subdir(layout.LAYERS_DIR)+ """A stem no other layer holds. Two files called `Roads` are two layers.++ Held means whatever the case, since `Roads` and `roads` are one file on Windows+ and macOS, and held by a layer in the Trash too, which would not come back.+ """+ folder = case.subdir(layout.LAYERS_DIR)+ taken = {path.stem.casefold() for path in folder.glob("*.json")}+ taken |= case.trashed_stems(layout.LAYERS_DIR)base = layout.slugify(title, "Layer")name, counter = base, 1- while case.resolve_inside(layout.layer_spec_rel(name)).exists():+ while name.casefold() in taken:suffix = f"-{counter}"name = f"{base[: layout.MAX_SLUG - len(suffix)]}{suffix}"counter += 1return name+def _pictograms(+ parsed: dict[str, Any], data: bytes, *, icons: bool, web: bool = True+) -> dict[str, bytes]:+ """The source's own pictograms, composed: the one place `icons` decides anything.++ False and no href is read, off the web or out of the archive, and the map draws+ the app's own shapes. This is the half that may reach the network, so it runs+ before the case is locked rather than while it is.+ """+ return icon_images(parsed["icons"] if icons else {}, source=data, web=web)+++def _kept_web_icons(case: "Case", name: str, parsed: dict[str, Any]) -> dict[str, bytes]:+ """The web pictograms already stored for a layer, for the keys its source still names.++ A layer's icons leave for a third-party host on the tick at import and never+ afterwards (SPEC §9), so a refresh keeps the ones it has rather than asking+ again, and a pictogram new to the source is drawn as the app's own shape.+ """+ out = {}+ for key, descriptor in (parsed.get("icons") or {}).items():+ if not _on_the_web(descriptor):+ continue+ try:+ out[key] = icon(case, name, key)+ except LayerError:+ continue+ return out+++def receive(case: "Case") -> int:+ """Hand a received case's followed layers to the analyst who opened it.++ `refresh.on_open` re-reads a layer the first time it is switched on. In a+ bundle it was set by whoever sent it, for an address they chose, so switching+ the layer on would tell their server who opened it, and when. Turned off here,+ a received layer reads its source only on a Refresh pressed on this machine.+ Returns how many were turned off.+ """+ folder = case.tool_root / layout.LAYERS_DIR+ turned = 0+ if not folder.is_dir():+ return 0+ with case.lock:+ for path in sorted(folder.glob("*.json")):+ try:+ spec = _read_spec(case, path.stem)+ except LayerError:+ continue+ if (spec.get("source") or {}).get("kind") not in FOLLOWED:+ continue+ if (spec.get("refresh") or {}).get("on_open"):+ spec["refresh"] = {**spec["refresh"], "on_open": False}+ _write_spec(case, path.stem, spec)+ turned += 1+ return turned++def _store(- case: "Case", name: str, data: bytes, parsed: dict[str, Any], *, icons: bool+ case: "Case", name: str, data: bytes, parsed: dict[str, Any], images: dict[str, bytes]) -> dict[str, Any]:"""Write the snapshot, its pictograms and its derived cache.- The one place `icons` decides anything: false and no href is read, off the- web or out of the archive, and the map draws the app's own shapes. The spec- is the caller's to write.+ The spec is the caller's to write."""case.subdir(layout.LAYERS_DIR)case.resolve_inside(layout.layer_snapshot_rel(name)).write_bytes(data)@@ -1672,14 +1750,12 @@ def _store("sha256": digest(data),"bytes": len(data),"at": _now(),- "icons": _write_icons(case, name, parsed["icons"] if icons else {}, source=data),+ "icons": _write_icons(case, name, images),}-def _write_icons(- case: "Case", name: str, descriptors: dict[str, dict[str, Any]], *, source: bytes-) -> int:- """Compose what a source asked for into one zip, and say how many landed.+def _write_icons(case: "Case", name: str, images: dict[str, bytes]) -> int:+ """Put the composed pictograms into one zip, and say how many landed.Built whole in memory before anything is written, so a fetch that dieshalfway leaves the layer with the icons it had rather than half a set. Stored@@ -1687,7 +1763,6 @@ def _write_icons(directory that happens to be one file."""path = case.resolve_inside(layout.layer_icons_rel(name))- images = icon_images(descriptors, source=source)if not images:path.unlink(missing_ok=True)return 0@@ -1703,15 +1778,41 @@ _ICON_KEY = re.compile(r"[0-9a-f]{1,32}")def icon(case: "Case", name: str, key: str) -> bytes:- """One stored pictogram, by the key the features that draw it name it with."""+ """One stored pictogram, by the key the features that draw it name it with.++ The icons file travels in bundles, so the one read here may have been made by+ somebody else. It is bounded before a byte is inflated, and decoded and+ re-encoded before it is served, so the browser still only loads PNGs this+ process produced.+ """if not _ICON_KEY.fullmatch(str(key or "")):raise LayerError("that is not an icon of this layer")path = case.resolve_inside(layout.layer_icons_rel(name))+ missing = LayerError("this layer has no such icon")try:with zipfile.ZipFile(path) as archive:- return archive.read(f"{key}.png")- except (OSError, KeyError, zipfile.BadZipFile) as exc:- raise LayerError("this layer has no such icon") from exc+ entry = archive.getinfo(f"{key}.png")+ if entry.file_size > MAX_ICON_BYTES or (+ entry.compress_size and entry.file_size / entry.compress_size > MAX_COMPRESSION_RATIO+ ):+ raise missing+ with archive.open(entry) as handle:+ data = handle.read(MAX_ICON_BYTES + 1)+ except (OSError, KeyError, EOFError, RuntimeError, NotImplementedError,+ zipfile.BadZipFile, zlib.error) as exc:+ raise missing from exc+ if len(data) > MAX_ICON_BYTES:+ raise missing+ try:+ with Image.open(BytesIO(data)) as opened:+ if opened.format != "PNG" or max(opened.size) > MAX_ICON_CANVAS:+ raise missing+ opened.load()+ buffer = BytesIO()+ opened.save(buffer, format="PNG")+ except (OSError, ValueError, Image.DecompressionBombError) as exc:+ raise missing from exc+ return buffer.getvalue()def _write_cache(case: "Case", name: str, geojson: dict[str, Any]) -> Path:@@ -1799,13 +1900,14 @@ def save_detection_snapshot(case: "Case", key: str, title: str,return add_source(case, data, parsed, title=title, icons=False,source={"kind": "file", "name": "detect.geojson", "format": "geojson", "detection_key": key})name = existing["name"]- spec = _read_spec(case, name)- spec["snapshot"] = _store(case, name, data, parsed, icons=False)- spec["summary"] = parsed["summary"]- spec["updated_at"] = _now()- live = {row["name"] for row in parsed["summary"]["categories"]}- spec["hidden"] = [entry for entry in spec.get("hidden", []) if entry in live]- _write_spec(case, name, spec)+ with case.lock:+ spec = _read_spec(case, name)+ spec["snapshot"] = _store(case, name, data, parsed, {})+ spec["summary"] = parsed["summary"]+ spec["updated_at"] = _now()+ live = {row["name"] for row in parsed["summary"]["categories"]}+ spec["hidden"] = [entry for entry in spec.get("hidden", []) if entry in live]+ _write_spec(case, name, spec)return row(name, spec)@@ -1853,28 +1955,30 @@ def add_source(start switched off — only those the source actually holds."""summary = parsed["summary"]- name = _free_name(case, title or summary["title"])live = {entry["name"] for entry in summary["categories"]}- spec: dict[str, Any] = {- "azimut_layer": SPEC_VERSION,- "title": summary["title"],- "source": source,- "hidden": sorted(set(hidden) & live),- # What the analyst asked for at import, kept so a refresh composes the- # same layer again rather than a differently dressed one.- "source_icons": bool(icons),- "created_at": _now(),- "updated_at": _now(),- "summary": summary,- "snapshot": _store(case, name, data, parsed, icons=bool(icons)),- }- if on_open is not None:- # Re-read the first time it is switched on in a session, which is what- # "subscribed" means; off leaves a layer that only moves on Refresh.- # Named for when it began as "on case open", kept so no case migrates.- spec["refresh"] = {"on_open": bool(on_open)}- _write_spec(case, name, spec)- _file_entity(case, name, spec)+ images = _pictograms(parsed, data, icons=bool(icons))+ with case.lock:+ name = _free_name(case, title or summary["title"])+ spec: dict[str, Any] = {+ "azimut_layer": SPEC_VERSION,+ "title": summary["title"],+ "source": source,+ "hidden": sorted(set(hidden) & live),+ # What the analyst asked for at import, kept so a refresh composes the+ # same layer again rather than a differently dressed one.+ "source_icons": bool(icons),+ "created_at": _now(),+ "updated_at": _now(),+ "summary": summary,+ "snapshot": _store(case, name, data, parsed, images),+ }+ if on_open is not None:+ # Re-read the first time it is switched on in a session, which is what+ # "subscribed" means; off leaves a layer that only moves on Refresh.+ # Named for when it began as "on case open", kept so no case migrates.+ spec["refresh"] = {"on_open": bool(on_open)}+ _write_spec(case, name, spec)+ _file_entity(case, name, spec)return row(name, spec)@@ -1888,9 +1992,14 @@ def refresh(case: "Case", name: str) -> dict[str, Any]:For GeoConfirmed the bytes are half of it: the factions that name thelegend are read beside the export, and a faction added since is a reasonto read the same bytes again.++ The read takes seconds and the case is not locked through it, so the analyst+ can hide a group, retitle the layer or delete it meanwhile. What the read+ brings back is therefore merged into the spec as it stands once the read is+ over, and a layer deleted meanwhile stays deleted."""- spec = _read_spec(case, name)- before = spec.get("source") or {}+ read = _read_spec(case, name)+ before = read.get("source") or {}if before.get("kind") not in FOLLOWED:raise LayerError("this layer came from a file, so there is nothing to refresh")@@ -1899,30 +2008,38 @@ def refresh(case: "Case", name: str) -> dict[str, Any]:from . import geoconfirmeddata, source = geoconfirmed.read_again(before)- spec["source"] = sourceelse:data, _ = fetch(str(before.get("url") or ""))- snapshot = spec.get("snapshot") or {}- now = _now()- if digest(data) == snapshot.get("sha256") and source == before:- spec["snapshot"] = {**snapshot, "checked_at": now}- else:+ unchanged = digest(data) == (read.get("snapshot") or {}).get("sha256") and source == before+ parsed = images = None+ if not unchanged:parsed = parse(data,- filename=_source_name(spec),- title=spec.get("title", ""),+ filename=_source_name(read),+ title=read.get("title", ""),reading=_reading(source),)- spec["summary"] = parsed["summary"]- spec["snapshot"] = {- **_store(case, name, data, parsed, icons=bool(spec.get("source_icons"))),- "checked_at": now,- }- # A category the source has since dropped is no longer a thing to hide.- live = {entry["name"] for entry in parsed["summary"]["categories"]}- spec["hidden"] = [name_ for name_ in spec.get("hidden") or [] if name_ in live]- spec["updated_at"] = now- _write_spec(case, name, spec)+ # Out of the archive only: a refresh never asks an icon host again.+ images = _pictograms(parsed, data, icons=bool(read.get("source_icons")), web=False)++ with case.lock:+ if not case.resolve_inside(layout.layer_spec_rel(name)).is_file():+ raise LayerError("this layer was removed while it was being read")+ spec = _read_spec(case, name)+ spec["source"] = source+ now = _now()+ if parsed is None:+ spec["snapshot"] = {**(spec.get("snapshot") or {}), "checked_at": now}+ else:+ spec["summary"] = parsed["summary"]+ if spec.get("source_icons"):+ images = {**_kept_web_icons(case, name, parsed), **(images or {})}+ spec["snapshot"] = {**_store(case, name, data, parsed, images or {}), "checked_at": now}+ # A category the source has since dropped is no longer a thing to hide.+ live = {entry["name"] for entry in parsed["summary"]["categories"]}+ spec["hidden"] = [name_ for name_ in spec.get("hidden") or [] if name_ in live]+ spec["updated_at"] = now+ _write_spec(case, name, spec)return row(name, spec)@@ -1946,6 +2063,21 @@ def update(Not the switch. Whether a layer is drawn lives in the page and starts off onevery load, so a layer that crashed the tab is not drawn again by the reload."""+ with case.lock:+ return _update_locked(+ case, name, hidden=hidden, period=period, on_open=on_open, title=title+ )+++def _update_locked(+ case: "Case",+ name: str,+ *,+ hidden: list[str] | None,+ period: tuple[str, str] | None,+ on_open: bool | None,+ title: str | None,+) -> dict[str, Any]:spec = _read_spec(case, name)if hidden is not None:live = {entry["name"] for entry in (spec.get("summary") or {}).get("categories", [])}diff --git a/src/azimut/engine/media.py b/src/azimut/engine/media.pyindex 47d6095..694f1a0 100644--- a/src/azimut/engine/media.py+++ b/src/azimut/engine/media.py@@ -22,7 +22,7 @@ from urllib.parse import urlsplitfrom PIL import Imagefrom .. import config, layout-from ..workspace import Case, CaseError, ensure_dir+from ..workspace import Case, CaseError, ensure_dir, write_text_atomicfrom . import enrich as enrich_enginefrom . import ffmpeg as ffmpeg_enginefrom . import links as link_engine@@ -1335,21 +1335,16 @@ def _replace_exact(value: Any, old: str, new: str) -> Any:def write_json_atomic(path: Path, data: dict[str, Any]) -> None:- ensure_dir(path.parent)- temporary = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")- try:- temporary.write_text(- json.dumps(data, indent=2, ensure_ascii=False) + "\n",- encoding="utf-8",- )- temporary.replace(path)- finally:- temporary.unlink(missing_ok=True)+ write_text_atomic(path, json.dumps(data, indent=2, ensure_ascii=False) + "\n")def rename_path(source: Path, destination: Path) -> None:- """Rename one file, including a case-only rename on Windows/macOS."""- if source == destination:+ """Rename one file, including a case-only rename on Windows/macOS.++ Compared as strings: a Windows path compares without regard to case, so+ `Roof.json == roof.json` there and the case-only rename would never run.+ """+ if str(source) == str(destination):returnensure_dir(destination.parent)if (diff --git a/src/azimut/engine/proofimport.py b/src/azimut/engine/proofimport.pyindex 5a2c7d0..6b5ab93 100644--- a/src/azimut/engine/proofimport.py+++ b/src/azimut/engine/proofimport.py@@ -297,11 +297,6 @@ def fill_files(return draft-def drop_for_url(case: Case, token: str, slot: str, url: str) -> dict[str, Any]:- """Let go of what one address put in a slot, files and all."""- return fill_files(case, token, slot, [], for_url=url)--def record_post(case: Case, token: str, post: dict[str, Any]) -> dict[str, Any]:"""Keep what the platform said about the post, and what its text states."""draft = read_draft(case, token)diff --git a/src/azimut/engine/sheetpass.py b/src/azimut/engine/sheetpass.pyindex 1f4fc4d..ae04d06 100644--- a/src/azimut/engine/sheetpass.py+++ b/src/azimut/engine/sheetpass.py@@ -41,16 +41,6 @@ from .sheetpromote import ACTIONS, JOIN, MAKE, UPDATEif TYPE_CHECKING:from ..workspace import Case-#: What a column may become. `ignore` is the default and the honest one: a worklist's-#: private notes have no business in the case's record of a subject, so a column travels-#: only when it was asked for.-MODES = ("ignore", "row", "value", "point", "addresses", "statement", "row-edges")--#: The modes that make something an edge can end at, in the order the join layer offers-#: them. `addresses` is absent on purpose: a bookmark already arrives holding a `mentions`-#: edge to the row's subject, so joining it a second time would state it twice.-POINTING = ("row", "value", "point")-class _Column:"""One column's declaration, after the door has read it."""diff --git a/src/azimut/engine/thumbnails.py b/src/azimut/engine/thumbnails.pyindex 05a21d2..9fdc8e3 100644--- a/src/azimut/engine/thumbnails.py+++ b/src/azimut/engine/thumbnails.py@@ -16,8 +16,8 @@ to the original file. This module owns their whole lifecycle.drained by the shared single worker (`engine/workqueue.py`), so several importsnever spawn several ffmpegs at once. A failed inline render is enqueued for theworker to retry.-- **Recovery**: a job left `running` by a crashed process is reclaimed on case- open (`Case.recover_jobs`), so work resumes instead of stalling.+- **Recovery**: a job left `running` by a crashed process is reclaimed at startup+ (`workqueue.recover_all`), so work resumes instead of stalling.- **Budget**: `prune_cache` evicts least-recently-used thumbnails past a sizebudget; it only ever touches the cache, never originals or database rows."""@@ -215,14 +215,6 @@ def _thumb_dir(case: "CaseType") -> Path:return case.subdir("media") / THUMB_DIR-def cache_size(case: "CaseType") -> int:- """Total bytes held by the thumbnail cache."""- thumbs = _thumb_dir(case)- if not thumbs.is_dir():- return 0- return sum(p.stat().st_size for p in thumbs.iterdir() if p.is_file())--def _proof_thumbs(case: "CaseType") -> set[str]:"""Thumbnails the saved proofs point at. Proofs are not media items, buttheir exports share this cache, so the sweep below has to count them asdiff --git a/src/azimut/engine/tilecache.py b/src/azimut/engine/tilecache.pyindex 58b9269..33d435c 100644--- a/src/azimut/engine/tilecache.py+++ b/src/azimut/engine/tilecache.py@@ -10,6 +10,7 @@ never a permanent offline imagery store.from __future__ import annotations+import osimport timefrom pathlib import Path@@ -55,3 +56,31 @@ def put(provider_id: str, z: int, x: int, y: int, content: bytes, media_type: st(base / f"{int(x)}_{int(y)}.{ext}").write_bytes(content)except OSError:pass+++def sweep(now: float | None = None) -> int:+ """Delete every entry past `TTL_DAYS`, read again or not. Returns how many went.++ `get` drops a stale entry only when it is asked for, and a tile of a date+ nobody asks for again (most of what a Detect sweep reads) would otherwise+ stay for good, which is the permanent imagery store this cache must not+ become. Never raises: a file another process holds is left for next time.+ """+ root = config.tile_cache_dir()+ cutoff = (time.time() if now is None else now) - TTL_DAYS * 86400+ dropped = 0+ for folder, _subfolders, files in os.walk(root, topdown=False):+ for name in files:+ path = Path(folder) / name+ try:+ if path.stat().st_mtime < cutoff:+ path.unlink()+ dropped += 1+ except OSError:+ continue+ if Path(folder) != root:+ try:+ Path(folder).rmdir() # refused while anything is left in it+ except OSError:+ pass+ return droppeddiff --git a/src/azimut/engine/tiles.py b/src/azimut/engine/tiles.pyindex ed763cf..361705a 100644--- a/src/azimut/engine/tiles.py+++ b/src/azimut/engine/tiles.py@@ -465,6 +465,26 @@ def is_placeholder_tile(content: bytes) -> bool:return hashlib.sha256(content).hexdigest() in PLACEHOLDER_TILE_SHA256+_ADDRESS = re.compile(r"https?://\S+")+++def upstream_failure(exc: BaseException) -> str:+ """What a failed provider call says in the browser, and never its address.++ An httpx error's text carries the URL it was sent to. For Sentinel Hub that+ URL holds the whole instance id, for Mapbox, Google or FIRMS the key, and a+ message lands in the page, the network log and the screenshot attached to a+ bug report. So the answer names what went wrong and nothing it was sent with.+ """+ if isinstance(exc, httpx.HTTPStatusError):+ return f"the provider answered {exc.response.status_code}"+ if isinstance(exc, httpx.TimeoutException):+ return "the provider did not answer in time"+ if isinstance(exc, httpx.HTTPError):+ return f"the provider could not be reached ({type(exc).__name__})"+ return _ADDRESS.sub("<address>", str(exc))++def resolve_url(provider: Provider) -> str:"""The provider's live XYZ template — session token substituted if needed."""if provider.session != "google":@@ -472,7 +492,7 @@ def resolve_url(provider: Provider) -> str:try:return google_tiles.resolve_template(provider.url)except Exception as exc:- raise TileFetchError(f"Google session token: {exc}") from exc+ raise TileFetchError(f"Google session token: {upstream_failure(exc)}") from excdef tile_url(url_template: str, z: int, x: int, y: int, zoom_offset: int = 0) -> str:diff --git a/src/azimut/engine/trash.py b/src/azimut/engine/trash.pyindex fc3eef1..6b78b48 100644--- a/src/azimut/engine/trash.py+++ b/src/azimut/engine/trash.py@@ -26,6 +26,7 @@ re-queues it.from __future__ import annotations+import jsonimport shutilfrom pathlib import Pathfrom typing import Any@@ -237,10 +238,50 @@ def restore(case: Case, group_id: str) -> dict[str, Any]:raise CaseError(f"'{occupied[0]}' is back in the case; rename or delete it before restoring")+ behind = _areas_in_the_trash(case, payload, root)+ if behind:+ raise CaseError(+ f"this routine draws on an area that is in the Trash; restore '{behind[0]}' first"+ )group = case.update_trash_group(group_id, state="restoring")return _finish_restore(case, group)+def _areas_in_the_trash(case: Case, payload: dict[str, Any], root: Path) -> list[str]:+ """The Trash groups holding a Detect area a routine being restored draws on.++ A routine reads its areas by reference, so restored alone it would come back+ as a file Detect cannot open. An area deleted for good is not asked for: the+ routine then opens without it, saying so, and can be given another.+ """+ moved = dict(_moved(payload))+ wanted: set[str] = set()+ for entity in payload.get("entities") or []:+ if entity.get("type") != "analysis-follow-up":+ continue+ slot = moved.get(str((entity.get("attrs") or {}).get("spec") or ""))+ try:+ spec = json.loads((root / slot).read_text(encoding="utf-8")) if slot else {}+ except (OSError, ValueError):+ continue+ for pair in spec.get("area_dates") or []:+ rel = f"{layout.ANALYSIS_DIR}/areas-{pair.get('area_id')}.json"+ try:+ present = case.resolve_inside(rel).exists()+ except CaseError:+ continue+ if rel not in moved and not present:+ wanted.add(rel)+ if not wanted:+ return []+ labels = []+ for listed in case.list_trash(): # listed without payloads, to stay bounded+ group = case.get_trash_group(listed["id"]) or {}+ if any(rel in wanted for rel, _slot in _moved(group.get("payload") or {})):+ labels.append(listed["label"])+ return labels++def purge(case: Case, group_id: str) -> None:"""Drop one group for good. The entity left the graph when it was deleted,so this is a directory and a row, never a second trip through the delete@@ -251,6 +292,7 @@ def purge(case: Case, group_id: str) -> None:raise CaseError(f"trash group '{group_id}' not found")_drop_dir(case, group_id)case.remove_trash_group(group_id)+ inspectwork.forget_legacy(case)def empty(case: Case) -> int:diff --git a/src/azimut/layout.py b/src/azimut/layout.pyindex cdb80c2..6e29d16 100644--- a/src/azimut/layout.py+++ b/src/azimut/layout.py@@ -244,6 +244,24 @@ def slugify(text: str | None, fallback: str, *, limit: int = MAX_SLUG) -> str:return value+def free_stem(taken: set[str], title: str | None, fallback: str) -> str:+ """`title` as a filename stem, numbered past whatever `taken` already holds.++ `taken` is casefolded: two stems differing only by case are one file on Windows+ and macOS, and a bundle refuses the pair.+ """+ base = slugify(title, fallback)+ if base.casefold() not in taken:+ return base+ n = 2+ while True:+ suffix = f" {n}"+ candidate = slugify(f"{base[: MAX_SLUG - len(suffix)]}{suffix}", fallback)+ if candidate.casefold() not in taken:+ return candidate+ n += 1++def visible_filename(title: str | None, suffix: str, fallback: str = "file") -> str:"""Canonical visible filename for ``title`` while preserving ``suffix``."""clean_suffix = suffix if suffix.startswith(".") else f".{suffix}" if suffix else ""@@ -485,10 +503,20 @@ def compare_session_rel(name: str) -> str:return f"{COMPARE_DIR}/{name}.json"+def analysis_rel(kind: str, ident: str) -> str:+ """One Detect record: an area, a zone set, a routine or a run."""+ return f"{ANALYSIS_DIR}/{kind}-{ident}.json"++def analysis_assets_rel(name: str) -> str:return f"{ANALYSIS_DIR}/{name}.assets"+def analysis_asset_rel(run_id: str, key: str) -> str:+ """One frame a run read, kept as its evidence under the run's own folder."""+ return f"{analysis_assets_rel(f'runs-{run_id}')}/{key}.png"++def grid_rel(name: str) -> str:return f"{SEARCH_DIR}/{name}.json"diff --git a/src/azimut/repository.py b/src/azimut/repository.pyindex eee20c8..667e335 100644--- a/src/azimut/repository.py+++ b/src/azimut/repository.py@@ -25,11 +25,6 @@ from typing import Any, Literal, Protocol, runtime_checkable#: `workspace` re-exports it for backward compatibility.EntityStatus = Literal["confirmed", "suggested"]-#: A durable job's lifecycle state (doc "Job states"). `queued` work is claimed-#: `running` by the single worker, then finishes `ready` or, past its retry-#: budget, `failed`; `cancelled` is an explicit stop.-JobState = Literal["queued", "running", "ready", "failed", "cancelled"]-@runtime_checkableclass CaseRepository(Protocol):diff --git a/src/azimut/server.py b/src/azimut/server.pyindex 513fb87..ca00241 100644--- a/src/azimut/server.py+++ b/src/azimut/server.py@@ -26,14 +26,25 @@ STATIC_DIR = Path(__file__).parent / "static"SERVE_PORT: int | None = None# The server binds localhost only, but that alone doesn't stop a web page the-# browser has open from reaching it — a page can hit 127.0.0.1 directly (its-# own Origin travels along), or point a name it controls at 127.0.0.1 (DNS-# rebinding, where the Host header becomes that name). Both are refused here:-# the Host must be a loopback name (defeats rebinding), and a cross-origin-# web Origin is turned away on every route except the token-gated ingest-# island, which opens itself to browser-extension origins on purpose.+# browser has open from reaching it. A page can hit 127.0.0.1 directly, or point+# a name it controls at 127.0.0.1 (DNS rebinding, where the Host header becomes+# that name). The Host must be a loopback name, which defeats rebinding. A+# cross-origin web Origin is turned away on every route except the token-gated+# ingest island, which opens itself to browser-extension origins on purpose.+# Origin alone is not enough: an <img>, a <script> or a link sends none on a GET,+# and a GET here can spend a provider's allowance or reach another host. The+# browser's `Sec-Fetch-Site` names the page that asked, so the API and the case+# files refuse one that is not this app's own (or a navigation typed by hand).LOCAL_HOSTNAMES = frozenset({"127.0.0.1", "localhost", "::1", "[::1]"})+#: `Sec-Fetch-Site` values naming another page: another site, or another port+#: or name of this machine.+FOREIGN_SITES = frozenset({"cross-site", "same-site"})+#: What a foreign page may not reach. The SPA itself stays open to a link, and+#: the ingest island answers only to its pairing token.+FENCED_PREFIXES = ("/api/", "/files/")+UNFENCED_PREFIXES = ("/api/ingest/",)+class BulkBodyLimit:"""Bound routes that carry browser-assembled files or documents before parsing.@@ -181,6 +192,13 @@ def install_local_guard(app: FastAPI) -> None:async def local_guard(request: Request, call_next):if not _is_local(_hostname(request.headers.get("host", ""))):return PlainTextResponse("invalid host header", status_code=400)+ path = request.url.path+ if (+ request.headers.get("sec-fetch-site", "").lower() in FOREIGN_SITES+ and path.startswith(FENCED_PREFIXES)+ and not path.startswith(UNFENCED_PREFIXES)+ ):+ return PlainTextResponse("cross-site request refused", status_code=403)origin = request.headers.get("origin")if origin and not _is_local(_hostname(origin)):ingest_extension = request.url.path.startswith(diff --git a/src/azimut/sqlite_backend.py b/src/azimut/sqlite_backend.pyindex bf6b6a0..f1d3634 100644--- a/src/azimut/sqlite_backend.py+++ b/src/azimut/sqlite_backend.py@@ -306,7 +306,6 @@ CREATE INDEX idx_temporal_kind ON temporal_items(kind);# `running`; it finishes `ready` or, past its retry budget, `failed`; an explicit# 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_STATES = ("queued", "running", "ready", "failed", "cancelled")_JOB_TERMINAL = frozenset({"ready", "failed", "cancelled"})T = TypeVar("T")diff --git a/src/azimut/workspace.py b/src/azimut/workspace.pyindex 3ab3e9b..7af3f1e 100644--- a/src/azimut/workspace.py+++ b/src/azimut/workspace.py@@ -174,6 +174,23 @@ def _replace_with_retry(src: Path, dst: Path) -> None:time.sleep(0.01)+def write_text_atomic(path: Path, text: str) -> None:+ """Replace a file's text whole: a reader, or a crash, sees the old or the new.++ `write_text` truncates first, so a process killed or a disk filling half way+ leaves an empty or cut file, which for a note is the analyst's text gone and+ for a spec is one that no longer parses. The scratch file sits beside the+ target so the rename never crosses a filesystem.+ """+ ensure_dir(path.parent)+ temporary = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")+ try:+ temporary.write_text(text, encoding="utf-8")+ _replace_with_retry(temporary, path)+ finally:+ temporary.unlink(missing_ok=True)++class CaseError(Exception):"""Raised for invalid case operations; maps to HTTP 4xx in the API layer."""@@ -771,7 +788,7 @@ class Case(CaseStore):return ""def write_notes(self, text: str) -> None:- self.notes_path.write_text(text, encoding="utf-8")+ write_text_atomic(self.notes_path, text)@propertydef note_dir(self) -> Path:@@ -863,8 +880,7 @@ class Case(CaseStore):)rel = self.note_target(folder, canonical)note_path = self.resolve_inside(rel)- ensure_dir(note_path.parent)- note_path.write_text(content, encoding="utf-8")+ write_text_atomic(note_path, content)return graph.update_entity(entity["id"], {"attrs": {"path": rel}})def read_note(self, entity_id: str) -> str:@@ -876,9 +892,7 @@ class Case(CaseStore):def write_note(self, entity_id: str, text: str) -> None:entity = self._note_entity(entity_id)- path = self._note_path(entity)- path.parent.mkdir(parents=True, exist_ok=True)- path.write_text(text, encoding="utf-8")+ write_text_atomic(self._note_path(entity), text)# -- lifecycle -----------------------------------------------------------@@ -1032,7 +1046,7 @@ class Case(CaseStore):applied: list[tuple[str, str]] = []try:for source, destination in moves:- if source.exists() and source != destination:+ if source.exists() and str(source) != str(destination):media_engine.rename_path(source, destination)moved.append((source, destination))for old, new in replacements:@@ -1135,6 +1149,23 @@ class Case(CaseStore):# -- helpers -------------------------------------------------------------+ def trashed_stems(self, directory: str) -> set[str]:+ """Casefolded names of the specs in `directory` that a delete moved to the Trash.++ A new artifact must not take one: the restore would find its path occupied+ and refuse, and anything that pointed at the old one by name (a kept image,+ a layer's files) would attach itself to the newcomer.+ """+ prefix = f"{directory}/"+ out = set()+ for head in self.list_trash():+ group = self.get_trash_group(head["id"]) or {}+ for rel in (group.get("payload") or {}).get("files") or []:+ rel = str(rel)+ if rel.startswith(prefix) and rel.endswith(".json") and "/" not in rel[len(prefix):]:+ out.add(Path(rel).stem.casefold())+ return out+def subdir(self, name: str) -> Path:try:directory = layout.subdir(self.path, name)@@ -1292,7 +1323,7 @@ def open_workspace() -> None:Imports are local because the modules below sit above this one; calling themat import time would close the circle."""- from .engine import bundles, scrapers, workqueue+ from .engine import bundles, scrapers, tilecache, workqueueconfig.ensure_workspace()scrapers.activate()@@ -1302,6 +1333,8 @@ def open_workspace() -> None:housekeeping()except Exception: # noqa: BLE001 - see the docstringlogger.warning("workspace housekeeping step failed", exc_info=True)+ # Off the startup path: a cache months of Detect sweeps filled is a long walk.+ threading.Thread(target=tilecache.sweep, name="tile-cache-sweep", daemon=True).start()def _one_work_per_file(case: Case) -> None:diff --git a/tests/casefold.py b/tests/casefold.pynew file mode 100644index 0000000..6d1d8c4--- /dev/null+++ b/tests/casefold.py@@ -0,0 +1,30 @@+"""Windows and macOS on a Linux run: two names that differ only by case are one file.++NTFS and APFS (as formatted by default) match names without regard to case, and+Windows' `Path.resolve()` answers with the case already on disk. `fold_names` makes+`Case.resolve_inside` do the same for the folders a test names, so a path that+differs from an existing file only by case resolves to that file, which is what an+unlink or a write through it reaches on those systems.+"""++from __future__ import annotations++from azimut import workspace+++def fold_names(monkeypatch, *directories: str) -> None:+ original = workspace.Case.resolve_inside++ def resolve(self, relative: str):+ path = original(self, relative)+ folded = relative.replace("\\", "/")+ if path.exists() or not path.parent.is_dir():+ return path+ if not any(folded.startswith(f"{d}/") for d in directories):+ return path+ for sibling in path.parent.iterdir():+ if sibling.name.casefold() == path.name.casefold():+ return sibling+ return path++ monkeypatch.setattr(workspace.Case, "resolve_inside", resolve)diff --git a/tests/test_analyzers.py b/tests/test_analyzers.pyindex 5858031..de957bb 100644--- a/tests/test_analyzers.py+++ b/tests/test_analyzers.py@@ -151,6 +151,39 @@ def test_keeping_a_candidate_is_the_only_thing_that_reaches_the_case(client, sceassert client.get(endpoint + "/preview").status_code == 404+def test_undoing_a_keep_takes_its_picture_along_and_the_trash_brings_all_back(client, scenario):+ case, body = scenario+ saved = run(client, case, body)+ endpoint = f"/api/cases/{case.id}/analysis/runs/{saved['id']}/results/{saved['results'][0]['id']}"++ # three hesitations leave nothing behind, however often the analyst changes their mind+ for _ in range(3):+ kept = client.post(endpoint + "/promote", json={"title": "Kept"}).json()+ undone = client.delete(endpoint + "/promote").json()+ assert case.find_entity(attr="path", value=kept["image"]) is None+ assert not case.resolve_inside(kept["image"]).exists()+ assert [e for e in case.list_entities() if e["type"] in ("place", "media")] == []++ group = undone["deleted"]["trash"]+ assert client.post(f"/api/cases/{case.id}/trash/{group}/restore").status_code == 200+ kinds = sorted(e["type"] for e in case.list_entities())+ assert "place" in kinds and "media" in kinds+++def test_undoing_a_keep_leaves_a_picture_a_proof_was_made_from(client, scenario):+ case, body = scenario+ saved = run(client, case, body)+ endpoint = f"/api/cases/{case.id}/analysis/runs/{saved['id']}/results/{saved['results'][0]['id']}"+ kept = client.post(endpoint + "/promote", json={"title": "Kept"}).json()+ picture = case.find_entity(attr="path", value=kept["image"])+ proof = case.add_entity("proof", "Built on it", attrs={}, by="user")+ case.add_link(proof["id"], picture["id"], "derived-from", by="user")++ client.delete(endpoint + "/promote")++ assert case.find_entity(attr="path", value=kept["image"]) is not None++def test_a_candidate_preview_is_enlarged_so_its_pixels_can_be_read(client, scenario):"""Legibility comes from whole-number nearest-neighbour zoom, not smoothing."""case, body = scenario@@ -694,12 +727,12 @@ def test_local_contrast_reads_a_target_against_its_own_patch_of_sea():water = np.ones((200, 200), bool)readings = []for patch in (calm, calm + 120):- empty, share = analyzers.local_contrast(patch, water, 61, 11)+ empty, share, _ = analyzers.local_contrast(patch, water, 61, 11)assert share.min() > 0.99assert abs(empty[100, 100]) < 4target = patch.copy()target[99:102, 99:102] += 100- contrast, _ = analyzers.local_contrast(target, water, 61, 11)+ contrast, _, _ = analyzers.local_contrast(target, water, 61, 11)readings.append(contrast[100, 100])assert min(readings) > 20assert abs(readings[0] - readings[1]) < 5@@ -709,7 +742,7 @@ def test_local_contrast_treats_land_in_the_ring_as_missing_background():values = np.full((160, 160), 20.0)water = np.zeros((160, 160), bool)water[:, :40] = True- _, share = analyzers.local_contrast(values, water, 61, 11)+ _, share, _ = analyzers.local_contrast(values, water, 61, 11)assert share[80, 5] > 0.9 # open seaassert share[80, 120] == 0 # inland, no water in the ring at allassert share[80, 60] < 0.5 # a shoreline is not somewhere a ship can bediff --git a/tests/test_artifacts.py b/tests/test_artifacts.pyindex 692a225..6e100f8 100644--- a/tests/test_artifacts.py+++ b/tests/test_artifacts.py@@ -49,6 +49,38 @@ def delete_everything(client, case_id: str) -> None:raise AssertionError("entities kept coming back")+STORAGE_DOC = Path(__file__).resolve().parent.parent / "docs" / "STORAGE_AND_PERFORMANCE.md"+++def documented_tree() -> set[str]:+ """The directories the published case tree draws, relative to `azimut/`."""+ text = STORAGE_DOC.read_text(encoding="utf-8")+ block = text.split("## The shape of a case", 1)[1].split("```text\n", 1)[1]+ block = block.split("```", 1)[0]+ stack: list[tuple[int, str]] = []+ out = set()+ for line in block.splitlines():+ name = line.split("#", 1)[0].strip()+ if not name.endswith("/"):+ continue+ depth = len(line) - len(line.lstrip())+ while stack and stack[-1][0] >= depth:+ stack.pop()+ stack.append((depth, name.rstrip("/")))+ parts = [part for _, part in stack]+ if parts[:2] == ["<case>", layout.TOOL_DIR] and len(parts) > 2:+ out.add("/".join(parts[2:]))+ return out+++def test_the_published_case_tree_draws_every_directory_a_case_is_born_with(tmp_path):+ born = {+ path.relative_to(layout.tool_root(tmp_path)).as_posix()+ for path in layout.content_dirs(tmp_path)+ }+ assert born - documented_tree() == set()++def test_deleting_everything_returns_the_case_to_its_birth_state(client):"""The gate. One artifact per tool goes in, everything is deleted, and whatis left has to be a fresh case — byte-for-byte in shape, if not in content.diff --git a/tests/test_bundles.py b/tests/test_bundles.pyindex b1c5f6b..4e18f16 100644--- a/tests/test_bundles.py+++ b/tests/test_bundles.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport jsonimport os+import shutilimport sqlite3import zipfilefrom contextlib import closing@@ -92,6 +93,109 @@ def test_plain_bundle_has_ordered_manifests_and_a_clean_database(bundle_case):).fetchone()[0] == 0+def _machine_strings(*folders: Path) -> set[bytes]:+ """How a folder of this machine would read inside a bundle, raw or JSON-escaped."""+ out = set()+ for folder in folders:+ text = str(folder)+ out |= {text.encode(), json.dumps(text)[1:-1].encode()}+ return out+++def _members_naming(bundle: Path, needles: set[bytes]) -> list[str]:+ with zipfile.ZipFile(bundle) as archive:+ return [+ name for name in archive.namelist()+ if any(needle in archive.read(name) for needle in needles)+ ]+++def _bundle_jobs(bundle: Path, case: Case) -> int:+ member = f"{bundles.BUNDLE_ROOT}/{case.db_path.relative_to(case.path).as_posix()}"+ extracted = config.bundles_dir() / "jobs-check.db"+ with zipfile.ZipFile(bundle) as archive:+ extracted.write_bytes(archive.read(member))+ with closing(sqlite3.connect(extracted)) as conn:+ count = conn.execute("SELECT COUNT(*) FROM jobs").fetchone()[0]+ extracted.unlink()+ return count+++def test_a_bundle_carries_no_job_and_no_folder_of_this_machine(bundle_case, tmp_path):+ # The first export's finished job, with its output path, sits in the database+ # the second export packs.+ for _ in range(2):+ job = bundles.queue_export(bundle_case)+ workqueue.drain(bundle_case)+ exported = Path(job["payload"]["output"])+ root = config.workspace_root()++ assert _members_naming(exported, _machine_strings(root)) == []+ assert _bundle_jobs(exported, bundle_case) == 0++ downloads = tmp_path / "Downloads"+ downloads.mkdir()+ received = downloads / exported.name+ shutil.copyfile(exported, received)+ imported, _ = bundles.queue_import(received)+ workqueue.drain(imported)+ imported = Case.open(imported.id)+ again = bundles.queue_export(imported)+ workqueue.drain(imported)+ reexported = Path(again["payload"]["output"])++ assert _members_naming(reexported, _machine_strings(root, downloads)) == []+ assert _bundle_jobs(reexported, imported) == 0+++def test_an_export_during_a_write_leaves_sqlites_journal_behind(bundle_case):+ writer = sqlite3.connect(bundle_case.db_path, isolation_level=None)+ try:+ writer.execute("BEGIN IMMEDIATE")+ writer.execute("INSERT INTO meta(key, value) VALUES('probe', 'x')")+ companions = [+ bundle_case.db_path.with_name(bundle_case.db_path.name + suffix)+ for suffix in bundles.DB_COMPANIONS+ ]+ assert any(path.exists() for path in companions)+ exported = bundles.export_case(bundle_case)+ finally:+ writer.execute("ROLLBACK")+ writer.close()++ with zipfile.ZipFile(exported) as archive:+ assert [n for n in archive.namelist() if n.endswith(bundles.DB_COMPANIONS)] == []+++def test_a_journal_in_a_received_bundle_never_lands_beside_the_database(bundle_case):+ """An Azimut before 0.3.1 could pack one; the bundle still imports, without it."""+ exported = bundles.export_case(bundle_case)+ db_member = f"{bundles.BUNDLE_ROOT}/{bundle_case.db_path.relative_to(bundle_case.path).as_posix()}"+ journal_member = f"{db_member}-journal"+ forged = config.bundles_dir() / "with-journal.azimut.zip"+ with zipfile.ZipFile(exported) as source:+ header = json.loads(source.read(bundles.HEADER_NAME))+ members = [+ (name, source.read(name)) for name in source.namelist()[1:-1]+ ] + [(journal_member, b"\xd9\xd5\x05\xf9\x20\xa1\x63\xd7" + b"\0" * 504)]+ header["total_size"] = sum(len(body) for _, body in members)+ records = []+ with zipfile.ZipFile(forged, "w") as archive:+ bundles._write_bytes(archive, bundles.HEADER_NAME, bundles._json_bytes(header), records)+ for name, body in members:+ bundles._write_bytes(archive, name, body, records)+ archive.writestr(+ bundles._zip_info(bundles.MANIFEST_NAME, compressed=True),+ bundles._json_bytes({"format_version": header["format_version"], "members": records}),+ )++ destination = Case.create("Journal import")+ imported = Case.open(bundles.import_into(destination, forged)["case_id"])++ assert [entity["label"] for entity in imported.list_entities()] == ["Witness"]+ assert not imported.db_path.with_name(imported.db_path.name + "-journal").exists()++def test_sealed_bundle_hides_the_zip_and_rejects_a_wrong_password(bundle_case):exported = bundles.export_case(bundle_case, password="correct horse")@@ -488,7 +592,8 @@ def test_bundle_member_names_are_safe_on_every_supported_os(names):def test_bundle_members_cannot_alias_on_case_insensitive_filesystems():- with pytest.raises(bundles.BundleError, match="collide"):+ # named, so the analyst knows which of the two to rename+ with pytest.raises(bundles.BundleError, match="'media/Photo.jpg' and 'media/photo.jpg' are one file"):bundles._validate_member_names(["media/Photo.jpg", "media/photo.jpg"])diff --git a/tests/test_compare_api.py b/tests/test_compare_api.pyindex e97062a..03ffc57 100644--- a/tests/test_compare_api.py+++ b/tests/test_compare_api.py@@ -7,7 +7,7 @@ import graph_readimport pytestfrom PIL import Image-from azimut import config+from azimut import config, layoutfrom azimut.api import compare as compare_apifrom azimut.api.compare import MAX_GIF_EDGE, _gif_frames, change_refusalfrom azimut.engine import links as link_engine@@ -606,3 +606,29 @@ def test_band_frame_validates_before_asking(client, monkeypatch):assert client.post("/api/compare/sentinel-frame", json={**FRAME_BODY, "width": 5000}).status_code == 422assert client.post("/api/compare/sentinel-frame", json=FRAME_BODY).status_code == 422assert config.month_usage("sentinelhub") == before++[email protected]("folded", [False, True], ids=["linux", "windows-macos"])+def test_a_change_of_case_renames_the_comparison_in_place(client, monkeypatch, folded):+ import casefold++ cid = _case(client, "Recased")+ _save(client, cid, "Harbour")+ if folded:+ casefold.fold_names(monkeypatch, layout.COMPARE_DIR)++ renamed = _save(client, cid, "harbour", rename_from="Harbour")++ assert renamed.status_code == 200, renamed.text+ folder = Case.open(cid).tool_root / layout.COMPARE_DIR+ assert [p.name for p in folder.glob("*.json")] == ["harbour.json"]+ assert client.get(f"/api/cases/{cid}/compare/sessions/harbour").status_code == 200+++def test_two_comparisons_differing_only_by_case_cannot_both_be_saved(client):+ cid = _case(client, "One name")+ _save(client, cid, "Harbour")++ assert _save(client, cid, "harbour").status_code == 409+ _save(client, cid, "Quay")+ assert _save(client, cid, "harbour", rename_from="Quay").status_code == 409diff --git a/tests/test_compare_saved_work.py b/tests/test_compare_saved_work.pyindex 8a28868..704c462 100644--- a/tests/test_compare_saved_work.py+++ b/tests/test_compare_saved_work.py@@ -152,3 +152,32 @@ def test_opening_a_case_from_an_earlier_build_places_its_comparisons(client):assert (placed["attrs"]["lat"], placed["attrs"]["lon"]) == (48.8584, 2.2945)# left for the Locate pass: a migration never waits on a geocoderassert "geo" not in placed["attrs"]+++def test_a_deleted_comparisons_kept_images_never_join_a_new_one_of_its_name(client):+ cid = _case(client, "Kept stay put")+ _save(client, cid, "Harbour")+ _keep(client, cid, "Harbour")+ group = client.delete(f"/api/cases/{cid}/compare/sessions/Harbour").json()["trash"]+ elsewhere = _spec()+ elsewhere["camera"] = {**elsewhere["camera"], "lat": -33.86, "lon": 151.2}++ fresh = _save(client, cid, "Harbour", elsewhere)++ assert fresh.status_code == 200, fresh.text+ assert fresh.json()["name"] != "Harbour", "a name in the Trash is not free"+ assert _row(client, cid, fresh.json()["name"])["kept"] == []+ # and the deleted one can still come back, with its image+ assert client.post(f"/api/cases/{cid}/trash/{group}/restore").status_code == 200+ assert len(_row(client, cid, "Harbour")["kept"]) == 1+++def test_a_rename_onto_a_name_in_the_trash_is_refused(client):+ cid = _case(client, "Trash names")+ _save(client, cid, "Harbour")+ client.delete(f"/api/cases/{cid}/compare/sessions/Harbour")+ _save(client, cid, "Quay")++ refused = _save(client, cid, "Harbour", rename_from="Quay")++ assert refused.status_code == 409 and "Trash" in refused.json()["detail"]diff --git a/tests/test_detect_rework.py b/tests/test_detect_rework.pyindex 3352cc4..b8333a7 100644--- a/tests/test_detect_rework.py+++ b/tests/test_detect_rework.py@@ -313,3 +313,45 @@ def test_single_image_methods_need_no_reference_and_pin_after_only(client, scenaassert pinned.json()["entity"]["attrs"]["geometry"]["type"] == "Point"with Image.open(case.resolve_inside(pinned.json()["image"])) as image:assert image.format == "PNG" and image.width <= 400+++def _routine_on_its_own_area(client, case, body, title="Harbour watch"):+ base = f"/api/cases/{case.id}/analysis"+ area = client.post(base + "/areas", json={**area_body(body["zones"][0]), "name": "Harbour"}).json()+ shared = {**body, "zones": [], "area_dates": [{"area_id": area["id"], "a": body["a"], "b": body["b"], "date_rule": "manual"}]}+ routine = client.post(base + "/followups", json={**shared, "title": title}).json()+ return base, area, routine+++def test_a_routine_is_not_restored_without_the_area_it_draws_on(client, scenario):+ case, body = scenario+ base, area, routine = _routine_on_its_own_area(client, case, body)+ routine_group = client.delete(base + "/followups/" + routine["id"]).json()["trash"]+ area_group = client.delete(base + "/areas/" + area["id"]).json()["trash"]++ refused = client.post(f"/api/cases/{case.id}/trash/{routine_group}/restore")+ assert refused.status_code == 409+ assert "Harbour" in refused.json()["detail"] and "restore" in refused.json()["detail"]+ assert client.get(base + "/followups").json() == []++ assert client.post(f"/api/cases/{case.id}/trash/{area_group}/restore").status_code == 200+ assert client.post(f"/api/cases/{case.id}/trash/{routine_group}/restore").status_code == 200+ assert [row["id"] for row in client.get(base + "/followups").json()] == [routine["id"]]+ opened = client.get(base + "/followups/" + routine["id"]).json()+ assert opened["zones"][0]["name"] == "Harbour" and "missing_areas" not in opened+++def test_a_routine_whose_area_is_gone_for_good_still_opens_and_says_so(client, scenario):+ case, body = scenario+ base, area, routine = _routine_on_its_own_area(client, case, body)+ routine_group = client.delete(base + "/followups/" + routine["id"]).json()["trash"]+ area_group = client.delete(base + "/areas/" + area["id"]).json()["trash"]+ assert client.delete(f"/api/cases/{case.id}/trash/{area_group}").status_code == 200++ assert client.post(f"/api/cases/{case.id}/trash/{routine_group}/restore").status_code == 200++ assert [row["id"] for row in client.get(base + "/followups").json()] == [routine["id"]]+ opened = client.get(base + "/followups/" + routine["id"]).json()+ assert opened["zones"] == [] and opened["missing_areas"] == [area["id"]]+ ran = client.post(base + "/followups/" + routine["id"] + "/run", json={})+ assert ran.status_code == 422 and "area" in ran.json()["detail"]diff --git a/tests/test_drafts_api.py b/tests/test_drafts_api.pyindex 5a0aba0..7eb8dc1 100644--- a/tests/test_drafts_api.py+++ b/tests/test_drafts_api.py@@ -177,3 +177,47 @@ def test_draft_rejects_unsafe_or_unbounded_paths(client, path):json={"title": "Bad path", "state": {"mediaPaths": [path]}},)assert response.status_code == 422+++def test_a_draft_named_with_a_hash_is_opened_and_deleted_on_its_own(client):+ from urllib.parse import quote++ cid = client.post("/api/cases", json={"name": "Drafts"}).json()["id"]+ for title in ("Thread", "Thread #2"):+ client.post(f"/api/cases/{cid}/drafts", json={"title": title, "state": STATE})++ assert client.get(f"/api/cases/{cid}/drafts/{quote('Thread #2', safe='')}").json()["title"] == "Thread #2"+ assert client.delete(f"/api/cases/{cid}/drafts/{quote('Thread #2', safe='')}").status_code == 200++ assert [row["title"] for row in client.get(f"/api/cases/{cid}/drafts").json()] == ["Thread"]++[email protected]("folded", [False, True], ids=["linux", "windows-macos"])+def test_a_change_of_case_renames_the_draft_in_place(client, monkeypatch, folded):+ import casefold++ from azimut import layout+ from azimut.workspace import Case++ cid = client.post("/api/cases", json={"name": "Drafts"}).json()["id"]+ client.post(f"/api/cases/{cid}/drafts", json={"title": "Thread", "state": STATE})+ if folded:+ casefold.fold_names(monkeypatch, layout.DRAFTS_DIR)++ renamed = client.post(+ f"/api/cases/{cid}/drafts", json={"title": "thread", "rename_from": "Thread", "state": STATE}+ )++ assert renamed.status_code == 200, renamed.text+ folder = Case.open(cid).tool_root / layout.DRAFTS_DIR+ assert [p.name for p in folder.glob("*.json")] == ["thread.json"]+ assert client.get(f"/api/cases/{cid}/drafts/thread").json()["state"]["place"] == STATE["place"]+++def test_two_drafts_differing_only_by_case_cannot_both_be_saved(client):+ cid = client.post("/api/cases", json={"name": "Drafts"}).json()["id"]+ client.post(f"/api/cases/{cid}/drafts", json={"title": "Thread", "state": STATE})++ again = client.post(f"/api/cases/{cid}/drafts", json={"title": "thread", "state": STATE})++ assert again.status_code == 409diff --git a/tests/test_entities.py b/tests/test_entities.pyindex ae9994d..9dda009 100644--- a/tests/test_entities.py+++ b/tests/test_entities.py@@ -5,12 +5,15 @@ make semantic sense. A new type therefore joins no connection accidentally. Thisfile locks the exact matrix exposed by the API and enforced on writes."""+from pathlib import Path+import pytestfrom azimut.engine import artifactsfrom azimut.engine import entitiesfrom azimut.engine import links as link_engine-from azimut.workspace import Case, CaseError+from azimut.sqlite_backend import SQLITE_SCHEMA+from azimut.workspace import CASE_SCHEMA, Case, CaseErrordef _new_case(client, name):@@ -177,6 +180,67 @@ def test_every_declared_type_says_what_it_is_for_when_the_case_is_drawn():assert entities.types_with_role(role), role+ONTOLOGY = Path(__file__).resolve().parent.parent / "docs" / "ONTOLOGY.md"+++def _doc_table(text: str, header: str) -> list[list[str]]:+ """The body rows of the Markdown table under `header`, cells unquoted."""+ lines = text.splitlines()+ start = lines.index(header) + 2 # past the header and its |---| rule+ rows = []+ for line in lines[start:]:+ if not line.startswith("|"):+ break+ rows.append([cell.strip().replace("`", "") for cell in line.strip("|").split("|")])+ return rows+++def _members(rows: list[list[str]]) -> dict[str, str]:+ return {member.strip(): row[0] for row in rows for member in row[2].split(",")}+++def test_the_filing_contract_lists_every_type_where_the_code_files_it():+ """ONTOLOGY.md is the contract a new tool files against, so a type the code+ declares and the document leaves out is one nobody learns the rules of."""+ text = ONTOLOGY.read_text(encoding="utf-8")+ families = _members(_doc_table(text, "| Family | Reads as | Members |"))+ roles = _members(_doc_table(text, "| Role | Reads as | Members | In the drawing |"))+ registry = {+ row[0]: (row[1], row[2])+ for row in _doc_table(+ text,+ "| Type | Family | Role | State | Produced by | Key `attrs` | File-backed |",+ )+ }+ for entry in entities.ENTITY_TYPES:+ assert families.get(entry.type) == entry.family, entry.type+ assert roles.get(entry.type) == entry.role, entry.type+ assert registry.get(entry.type) == (entry.family, entry.role), entry.type+++def test_a_type_is_shown_by_the_name_its_tool_gives_it(client):+ """The type id is storage and keeps its old word; the label is what Board, Files,+ Details and Trash print, so it follows the tool: Inspect keeps one work per file,+ Detect reruns a routine, and the areas serve Detect, not Compare."""+ rows = {row["type"]: row for row in client.get("/api/cases/entity-types").json()}++ assert rows["inspect-session"]["label"] == "Inspect work"+ assert rows["analysis-follow-up"]["label"] == "Detect routine"+ assert "Detect analyzer" in rows["analysis-zones"]["hint"]+ for row in rows.values():+ assert "session" not in row["label"].lower() or row["type"] == "compare-session"+ assert "watch" not in row["label"].lower(), row["type"]+ for type_ in ("analysis-zones", "analysis-area", "analysis-follow-up", "analysis-run"):+ assert "Compare" not in rows[type_]["hint"], type_+++def test_the_filing_contract_states_the_schemas_the_code_writes():+ text = " ".join(ONTOLOGY.read_text(encoding="utf-8").split())+ assert f"**Storage schema: `{CASE_SCHEMA}`.**" in text+ assert f'{{"azimut": {{"schema": {CASE_SCHEMA},' in text+ assert f"The internal SQLite schema is at version {SQLITE_SCHEMA}:" in text++def test_the_role_is_not_the_manual_flag_under_another_name():"""The two axes are independent, which is why an existing field could not bereused: `media` and `place` are tool-born subjects, `post` is tool-born and adiff --git a/tests/test_extension_signing.py b/tests/test_extension_signing.pyindex fed391a..32a228c 100644--- a/tests/test_extension_signing.py+++ b/tests/test_extension_signing.py@@ -203,6 +203,19 @@ def test_a_signer_failure_cannot_serialize_the_secret(monkeypatch, tmp_path):assert "synthetic-secret" not in str(error.value)+ "doc",+ [(REPO / "README.md").read_text(encoding="utf-8"), sign_extension.__doc__ or ""],+ ids=["README", "script docstring"],+)+def test_the_signing_instructions_never_put_the_secret_on_a_command_line(doc):+ # A secret typed at the prompt stays in the shell history, so the documented+ # road reads it from a private file instead.+ assert "export AMO_JWT_SECRET" not in doc+ assert "AMO_JWT_SECRET=" not in doc+ assert "source ~/.config/azimut/amo.env" in doc++def test_completed_delivery_cannot_pass_with_an_empty_update_list(monkeypatch, gecko):empty = json.dumps({"addons": {gecko["id"]: {"updates": []}}}).encode()monkeypatch.setattr(diff --git a/tests/test_files_api.py b/tests/test_files_api.pyindex 8382dab..f8885fe 100644--- a/tests/test_files_api.py+++ b/tests/test_files_api.py@@ -85,3 +85,58 @@ def test_a_name_holding_a_hash_is_served_under_its_encoded_url(client):# what the browser asked for before the encoding: the directory, not a fileassert client.get(f"/files/{cid}/media/").status_code == 404+++SCRIPTED_SVG = (+ b'<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10">'+ b"<script>fetch('/api/settings')</script><rect width='10' height='10'/></svg>"+)+++def _upload_bytes(client, cid, name, data, mime):+ res = client.post(+ f"/api/cases/{cid}/media/upload", files={"file": (name, io.BytesIO(data), mime)}+ )+ assert res.status_code == 200, res.text+ return res.json()["item"]+++def test_a_case_svg_is_served_sandboxed_so_its_script_never_runs_here(client):+ cid = client.post("/api/cases", json={"name": "Files"}).json()["id"]+ item = _upload_bytes(client, cid, "map.svg", SCRIPTED_SVG, "image/svg+xml")++ served = client.get(f"/files/{cid}/{item['path']}")++ assert served.status_code == 200+ assert served.headers["content-type"].startswith("image/svg+xml")+ policy = served.headers["content-security-policy"]+ assert policy.startswith("sandbox;") and "allow-scripts" not in policy+ assert "default-src 'none'" in policy+ assert served.headers["x-content-type-options"] == "nosniff"+ # still the file, so an <img> of it keeps drawing+ assert served.content == SCRIPTED_SVG++ again = client.get(f"/files/{cid}/{item['path']}", headers={"If-None-Match": served.headers["etag"]})+ assert again.status_code == 304+ assert again.headers["content-security-policy"] == policy+++def test_a_case_page_or_an_unnamed_type_is_sandboxed_too(client):+ cid = client.post("/api/cases", json={"name": "Files"}).json()["id"]+ page = _upload_bytes(client, cid, "saved.html", b"<script>alert(1)</script>", "text/html")+ odd = _upload_bytes(client, cid, "blob.weird", b"<script>alert(1)</script>", "application/octet-stream")++ for item in (page, odd):+ served = client.get(f"/files/{cid}/{item['path']}")+ assert served.headers["content-security-policy"].startswith("sandbox;")+ assert served.headers["x-content-type-options"] == "nosniff"+++def test_pictures_are_not_sandboxed_but_never_sniffed(client):+ cid = client.post("/api/cases", json={"name": "Files"}).json()["id"]+ item = _upload(client, cid)++ served = client.get(f"/files/{cid}/{item['path']}")++ assert "content-security-policy" not in served.headers+ assert served.headers["x-content-type-options"] == "nosniff"diff --git a/tests/test_inspect_work.py b/tests/test_inspect_work.pyindex 34ca02a..343511c 100644--- a/tests/test_inspect_work.py+++ b/tests/test_inspect_work.py@@ -10,6 +10,7 @@ from __future__ import annotationsimport ioimport json+import casefoldimport graph_readimport pytestfrom PIL import Image@@ -232,7 +233,7 @@ def test_a_name_the_app_derived_from_the_file_describes_nothing():long = "@Suriyak - The second phase of Operation: what the convoy footage shows, day 2"cut = layout.slugify(long, "Inspect")assert inspectwork._describes_nothing(cut, long)- assert inspectwork._describes_nothing(inspectwork._free_title({cut.casefold()}, long, "Inspect"), long)+ assert inspectwork._describes_nothing(layout.free_stem({cut.casefold()}, long, "Inspect"), long)assert inspectwork._describes_nothing(layout.slugify("Strike: day 2?", "Inspect"), "Strike: day 2?")assert inspectwork._describes_nothing("Roof 3", "Roof")assert not inspectwork._describes_nothing("Roof pass", "Roof")@@ -368,6 +369,29 @@ def test_renaming_a_collage_moves_its_file_and_keeps_its_entity(client):assert client.get(f"/api/cases/{cid}/collages/Strip").status_code == 404[email protected]("folded", [False, True], ids=["linux", "windows-macos"])+def test_a_change_of_case_renames_the_collage_and_keeps_it(client, monkeypatch, folded):+ cid = _case(client)+ photo = _upload(client, cid, "roof.png")+ _save_collage(client, cid, "Harbour strip", [_piece(photo)])+ [before] = _of_type(cid, "collage")+ if folded:+ casefold.fold_names(monkeypatch, layout.COLLAGE_DIR)++ renamed = _save_collage(client, cid, "harbour strip", [_piece(photo)], name="Harbour strip")++ assert renamed.status_code == 200, renamed.text+ assert renamed.json()["name"] == "harbour strip"+ folder = Case.open(cid).tool_root / layout.COLLAGE_DIR+ assert [p.name for p in folder.glob("*.json")] == ["harbour strip.json"]+ [after] = _of_type(cid, "collage")+ assert after["id"] == before["id"]+ assert after["attrs"]["spec"] == ".collages/harbour strip.json"+ loaded = client.get(f"/api/cases/{cid}/collages/harbour strip")+ assert loaded.status_code == 200+ assert [n["id"] for n in loaded.json()["spec"]["nodes"]] == ["nd_1"]++def test_a_collage_cannot_be_renamed_onto_another(client):cid = _case(client)photo = _upload(client, cid, "roof.png")@@ -637,3 +661,34 @@ def test_restoring_a_pre_0_3_1_session_from_the_trash_merges_it(client):assert [f["id"] for f in spec["frames"]] == ["fr_now", "fr_then"]assert [e["label"] for e in _of_type(cid, "collage")] == ["Old pass"]assert "Merged with “Old pass”." in work["attrs"]["notes"]+++def test_a_0_3_0_copy_leaves_with_its_file_and_never_travels(client):+ import zipfile++ from azimut.engine import bundles++ cid = _case(client)+ roof = _upload(client, cid, "roof.png", (1, 1, 1))+ gate = _upload(client, cid, "gate.png", (2, 2, 2))+ case = Case.open(cid)+ _legacy_session(case, "Roof pass", roof, frames=[_frame(roof)])+ _legacy_session(case, "Gate pass", gate, frames=[_frame(gate)])+ opened = _as_0_3_0(case)+ roof_copy = opened.resolve_inside(layout.legacy_session_rel("Roof pass"))+ gate_copy = opened.resolve_inside(layout.legacy_session_rel("Gate pass"))+ assert roof_copy.is_file() and gate_copy.is_file()++ exported = bundles.export_case(opened)+ with zipfile.ZipFile(exported) as archive:+ assert not [n for n in archive.namelist() if "/.inspect/.v1/" in n]++ photo = graph_read.entity(cid, path=roof)+ group = client.delete(f"/api/cases/{cid}/entities/{photo['id']}").json()["trash"]+ # still in the Trash: the file can come back, and so may the need to undo the merge+ assert roof_copy.is_file()++ assert client.delete(f"/api/cases/{cid}/trash/{group}").status_code == 200++ assert not roof_copy.exists()+ assert gate_copy.is_file(), "a file still in the case keeps its copy"diff --git a/tests/test_layout.py b/tests/test_layout.pyindex 56fa550..5351a6d 100644--- a/tests/test_layout.py+++ b/tests/test_layout.py@@ -16,6 +16,7 @@ import pytestfrom azimut import layoutfrom azimut.api.naming import slugify+from azimut.engine import analyzersfrom azimut.engine.media import safe_filenamefrom azimut.engine.thumbnails import THUMB_GENfrom azimut.layout import CASE_SUBDIRS, TRASH_DIR@@ -59,6 +60,7 @@ THUMB_NAME = 24 + len(f"-g{THUMB_GEN}") + len(".jpg")ASSET_NAME = 16 + len(".webp")TRASH_GROUP_ID = len("t_0123456789")TRASH_SLOT = 3 # "999" worth of artifacts in one delete+ANALYSIS_KEY = 32 # `analyzers._key`: a sha256 cut to 32 hexdef _branches() -> dict[str, int]:@@ -105,6 +107,9 @@ def _tool_relative(slug: int, media: int) -> dict[str, int]:"map layer snapshot": len(layout.layer_snapshot_rel(longest_name)),"map layer icons": len(layout.layer_icons_rel(longest_name)),"map layer cache": len(layout.layer_cache_rel(longest_name)),+ # Detect names its records and frames by id and hash, never by title+ "analysis item": max(len(layout.analysis_rel(kind, "a" * 12)) for kind in analyzers.KINDS),+ "analysis frame": len(layout.analysis_asset_rel("a" * 12, "k" * ANALYSIS_KEY)),"trash slot": len(f"{layout.TRASH_DIR}/") + TRASH_GROUP_ID + 1 + TRASH_SLOT,}diff --git a/tests/test_map_layers.py b/tests/test_map_layers.pyindex ccb43f3..4f7cd69 100644--- a/tests/test_map_layers.py+++ b/tests/test_map_layers.py@@ -1131,3 +1131,244 @@ def test_a_period_that_is_not_made_of_days_is_refused(client, case_id):assert client.patch(url, json={"period": {"start": "May", "end": ""}}).status_code == 422assert client.get(url).json()["period"] is None+++def test_a_name_with_a_hash_addresses_its_own_layer_once_encoded(client, case_id):+ """The browser cuts an unencoded "#" off as a fragment, which reached "Ops"."""+ from urllib.parse import quote++ add(client, case_id, KML, "a.kml", title="Ops")+ add(client, case_id, KML, "b.kml", title="Ops #2")+ base = f"/api/cases/{case_id}/map-layers"++ assert client.get(f"{base}/{quote('Ops #2', safe='')}/data").json()["type"] == "FeatureCollection"+ assert client.delete(f"{base}/{quote('Ops #2', safe='')}").status_code == 200++ assert [row["name"] for row in client.get(base).json()] == ["Ops"]+++# ---------------------------------------------------------------------------+# A refresh reads for seconds; the analyst keeps working meanwhile+# ---------------------------------------------------------------------------+++def _slow_refresh(client, case_id, monkeypatch, served: bytes):+ """Start a refresh whose read waits for `release`, and hand back its handles."""+ import threading++ monkeypatch.setattr(maplayers, "fetch", lambda url: (KML, "s.kml"))+ row = client.post(+ f"/api/cases/{case_id}/map-layers", json={"url": "https://example.test/s.kml"}+ ).json()+ reading, release = threading.Event(), threading.Event()++ def slow(url):+ reading.set()+ release.wait(10)+ return served, "s.kml"++ monkeypatch.setattr(maplayers, "fetch", slow)+ outcome: dict = {}++ def run():+ try:+ outcome["row"] = maplayers.refresh(Case.open(case_id), row["name"])+ except maplayers.LayerError as exc:+ outcome["error"] = str(exc)++ worker = threading.Thread(target=run)+ worker.start()+ assert reading.wait(10)+ return row, release, worker, outcome+++def test_a_setting_changed_while_a_refresh_reads_is_kept(client, case_id, monkeypatch):+ # new bytes, same groups: the refresh has something to write+ row, release, worker, outcome = _slow_refresh(client, case_id, monkeypatch, KML + b"\n")+ group = row["categories"][0]["name"]++ patched = client.patch(+ f"/api/cases/{case_id}/map-layers/{row['name']}",+ json={"hidden": [group], "title": "Renamed feed"},+ )+ release.set()+ worker.join(10)++ assert patched.status_code == 200+ assert outcome["row"]["sha256"] == maplayers.digest(KML + b"\n")+ [after] = client.get(f"/api/cases/{case_id}/map-layers").json()+ assert after["title"] == "Renamed feed"+ assert after["hidden"] == [group]+++def test_a_layer_deleted_while_a_refresh_reads_stays_deleted(client, case_id, monkeypatch):+ row, release, worker, outcome = _slow_refresh(client, case_id, monkeypatch, KML + b"\n")++ deleted = client.delete(f"/api/cases/{case_id}/map-layers/{row['name']}")+ release.set()+ worker.join(10)++ assert deleted.status_code == 200+ assert "removed while it was being read" in outcome["error"]+ assert client.get(f"/api/cases/{case_id}/map-layers").json() == []+ group = deleted.json()["trash"]+ restored = client.post(f"/api/cases/{case_id}/trash/{group}/restore")+ assert restored.status_code == 200, restored.text+ assert [r["name"] for r in client.get(f"/api/cases/{case_id}/map-layers").json()] == [row["name"]]+++def test_two_layers_differing_only_by_case_get_two_names_and_still_export(client, case_id):+ from azimut.engine import bundles++ first = add(client, case_id, KML, "a.kml", title="Roads")+ second = add(client, case_id, KML, "b.kml", title="roads")++ assert first["name"] == "Roads"+ assert second["name"].casefold() != "roads"+ bundles.export_case(Case.open(case_id))+++def test_a_new_layer_does_not_take_the_name_of_one_in_the_trash(client, case_id):+ first = add(client, case_id, KML, "a.kml", title="Roads")+ group = client.delete(f"/api/cases/{case_id}/map-layers/{first['name']}").json()["trash"]++ second = add(client, case_id, KML, "b.kml", title="Roads")++ assert second["name"] != "Roads"+ assert client.post(f"/api/cases/{case_id}/trash/{group}/restore").status_code == 200+++# ---------------------------------------------------------------------------+# An icons file somebody else made (it travels in bundles)+# ---------------------------------------------------------------------------+++def _forged_icons(client, case_id, members: dict[str, tuple[bytes, int]]) -> tuple[str, str]:+ row = add(client, case_id, KML, "s.kml")+ path = Case.open(case_id).resolve_inside(layout.layer_icons_rel(row["name"]))+ with zipfile.ZipFile(path, "w") as archive:+ for member, (data, method) in members.items():+ archive.writestr(member, data, compress_type=method)+ return row["name"], f"/api/cases/{case_id}/map-layers/{row['name']}/icons"+++def test_an_icon_that_inflates_past_its_bound_is_never_read(client, case_id):+ name, base = _forged_icons(client, case_id, {"abc.png": (b"\0" * (50 * 1024 * 1024), zipfile.ZIP_DEFLATED)})++ assert client.get(f"{base}/abc").status_code == 404+++def test_an_icon_that_is_not_a_png_this_app_made_is_never_served(client, case_id):+ tall = io.BytesIO()+ Image.new("RGBA", (4000, 10)).save(tall, "PNG")+ name, base = _forged_icons(client, case_id, {+ "aaa.png": (b"<svg onload=alert(1)>", zipfile.ZIP_STORED),+ "bbb.png": (tall.getvalue(), zipfile.ZIP_STORED),+ })++ assert client.get(f"{base}/aaa").status_code == 404+ assert client.get(f"{base}/bbb").status_code == 404+++def test_a_damaged_icons_file_is_a_missing_icon_and_not_a_crash(client, case_id):+ row = add(client, case_id, KML, "s.kml")+ path = Case.open(case_id).resolve_inside(layout.layer_icons_rel(row["name"]))+ icon = io.BytesIO()+ Image.new("RGBA", (32, 32), (255, 0, 0, 255)).save(icon, "PNG")+ with zipfile.ZipFile(path, "w") as archive:+ archive.writestr("abc.png", icon.getvalue() * 4, compress_type=zipfile.ZIP_DEFLATED)+ raw = bytearray(path.read_bytes())+ start = raw.index(b"abc.png") + len(b"abc.png")+ raw[start + 10 : start + 30] = b"\xff" * 20 # inside the deflate stream+ path.write_bytes(bytes(raw))++ answer = client.get(f"/api/cases/{case_id}/map-layers/{row['name']}/icons/abc")++ assert answer.status_code == 404+++def test_a_refresh_asks_no_icon_host_again_and_keeps_the_icons_it_has(client, case_id, monkeypatch):+ """SPEC §9: a layer's icons leave on the tick at import and never afterwards."""+ asked = []+ monkeypatch.setattr(maplayers, "_fetch_icon", lambda href: (asked.append(href), png())[1])+ served = [_many_icons(2, "https://icons.test/p.png")]+ monkeypatch.setattr(maplayers, "fetch", lambda url: (served[0], "s.kml"))+ row = client.post(+ f"/api/cases/{case_id}/map-layers", json={"url": "https://example.test/s.kml"}+ ).json()+ assert row["icons"] == 2 and len(asked) == 2++ served[0] = _many_icons(3, "https://icons.test/p.png") # moved, with one icon more+ moved = client.post(f"/api/cases/{case_id}/map-layers/{row['name']}/refresh").json()++ assert len(asked) == 2, "the refresh asked the icon host nothing"+ assert moved["icons"] == 2, "the two it had are kept, the new one is drawn as a shape"+++def test_a_received_followed_layer_reads_its_source_only_when_refreshed_here(client, case_id, monkeypatch):+ from azimut.engine import bundles++ monkeypatch.setattr(maplayers, "fetch", lambda url: (KML, "s.kml"))+ row = client.post(+ f"/api/cases/{case_id}/map-layers", json={"url": "https://sender.test/feed.kml"}+ ).json()+ assert row["refresh"]["on_open"] is True+ exported = bundles.export_case(Case.open(case_id))++ received = bundles.import_into(bundles.create_import_case("Received"), exported)++ [layer] = client.get(f"/api/cases/{received['case_id']}/map-layers").json()+ assert layer["refresh"]["on_open"] is False+ assert layer["source"]["url"] == "https://sender.test/feed.kml"+++# ---------------------------------------------------------------------------+# A damaged file is refused with a sentence, never a server error+# ---------------------------------------------------------------------------+++def _patched_kmz(*, method: int | None = None, flags: int | None = None, damage: bool = False,+ deflate: bool = False) -> bytes:+ import struct++ buffer = io.BytesIO()+ with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED if deflate else zipfile.ZIP_STORED) as archive:+ archive.writestr("doc.kml", KML * (20 if deflate else 1))+ raw = bytearray(buffer.getvalue())+ local = raw.index(b"PK\x03\x04")+ central = raw.index(b"PK\x01\x02")+ if method is not None:+ struct.pack_into("<H", raw, local + 8, method)+ struct.pack_into("<H", raw, central + 10, method)+ if flags is not None:+ struct.pack_into("<H", raw, local + 6, flags)+ struct.pack_into("<H", raw, central + 8, flags)+ if damage:+ start = local + 30 + len("doc.kml")+ raw[start + 8 : start + 40] = b"\xff" * 32+ return bytes(raw)+++ "data, filename",+ [+ (_patched_kmz(damage=True), "bad-crc.kmz"),+ (_patched_kmz(damage=True, deflate=True), "bad-deflate.kmz"),+ (_patched_kmz(method=9), "deflate64.kmz"),+ (_patched_kmz(flags=1), "encrypted.kmz"),+ # deep enough to exhaust the JSON decoder's recursion on every Python+ (b'{"type": "FeatureCollection", "features": ' + b"[" * 100_000 + b"]" * 100_000 + b"}", "deep.geojson"),+ ],+ ids=["bad-crc", "bad-deflate", "deflate64", "encrypted", "nested"],+)+def test_a_damaged_source_is_refused_with_a_sentence(client, case_id, data, filename):+ with pytest.raises(maplayers.LayerError):+ maplayers.parse(data, filename=filename)++ response = client.post(+ f"/api/cases/{case_id}/map-layers/upload",+ files={"file": (filename, io.BytesIO(data), "application/octet-stream")},+ data={"title": "", "icons": "false"},+ )+ assert response.status_code == 422, response.text+ assert response.json()["detail"]diff --git a/tests/test_proofs_api.py b/tests/test_proofs_api.pyindex 2eaf7cc..e5a148a 100644--- a/tests/test_proofs_api.py+++ b/tests/test_proofs_api.py@@ -1324,6 +1324,31 @@ def test_clearing_the_date_takes_it_off_the_entity(client):)[email protected]("cleared", ["", None])+def test_a_date_and_description_cleared_in_details_stay_cleared(client, cleared):+ cid = client.post("/api/cases", json={"name": "Cleared in Details"}).json()["id"]+ client.post(+ f"/api/cases/{cid}/proofs",+ json={"title": "Dated", "spec": {**SPEC, "when": "2024-05-01", "description": "Seen from the bridge"}},+ )+ proof = next(e for e in graph_read.entities(cid) if e["type"] == "proof")++ client.patch(+ f"/api/cases/{cid}/entities/{proof['id']}", json={"attrs": {"when": cleared, "notes": cleared}}+ )++ opened = client.get(f"/api/cases/{cid}/proofs/Dated").json()+ assert opened["when"] is None and opened["description"] is None+ # the composer saves what it opened, and the date must not come back with it+ client.post(f"/api/cases/{cid}/proofs", json={"rename_from": "Dated", "title": "Dated", "spec": opened})+ proof = next(e for e in graph_read.entities(cid) if e["type"] == "proof")+ assert proof["attrs"]["when"] == "" and proof["attrs"]["notes"] == ""+ assert (+ client.get(f"/api/cases/{cid}/timeline", params={"categories": "statement"}).json()["items"]+ == []+ )++def test_a_description_edited_in_the_graph_is_what_reopens(client):cid = client.post("/api/cases", json={"name": "Edited notes"}).json()["id"]client.post(@@ -1562,3 +1587,46 @@ def test_a_statement_reworded_by_hand_keeps_its_own_wording(client):restated = _claims(cid)[0]assert restated["label"] == "The convoy was filmed that morning"assert restated["attrs"]["when"] == "2024-03-12" # the date is still restated+++def test_a_proof_named_with_a_hash_is_opened_and_deleted_on_its_own(client):+ from urllib.parse import quote++ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]+ for title in ("Ops", "Ops #2"):+ client.post(f"/api/cases/{cid}/proofs", json={"title": title, "spec": SPEC, "png_base64": _png_b64()})++ assert client.get(f"/api/cases/{cid}/proofs/{quote('Ops #2', safe='')}").json()["title"] == "Ops #2"+ assert client.delete(f"/api/cases/{cid}/proofs/{quote('Ops #2', safe='')}").status_code == 200++ assert [row["name"] for row in client.get(f"/api/cases/{cid}/proofs").json()] == ["Ops"]++[email protected]("folded", [False, True], ids=["linux", "windows-macos"])+def test_a_change_of_case_renames_the_proof_and_its_picture_in_place(client, monkeypatch, folded):+ import casefold++ from azimut import layout+ from azimut.workspace import Case++ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]+ client.post(f"/api/cases/{cid}/proofs", json={"title": "Roof", "spec": SPEC, "png_base64": _png_b64()})+ if folded:+ casefold.fold_names(monkeypatch, "proofs")++ renamed = client.post(+ f"/api/cases/{cid}/proofs", json={"title": "roof", "rename_from": "Roof", "spec": SPEC}+ )++ assert renamed.status_code == 200, renamed.text+ case = Case.open(cid)+ assert [p.name for p in (case.tool_root / "proofs" / layout.META_DIR).glob("*.json")] == ["roof.json"]+ assert [p.name for p in (case.tool_root / "proofs").glob("*.png")] == ["roof.png"]+ assert client.get(f"/api/cases/{cid}/proofs/roof").json()["title"] == "roof"+++def test_two_proofs_differing_only_by_case_cannot_both_be_saved(client):+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]+ client.post(f"/api/cases/{cid}/proofs", json={"title": "Roof", "spec": SPEC})++ assert client.post(f"/api/cases/{cid}/proofs", json={"title": "roof", "spec": SPEC}).status_code == 409diff --git a/tests/test_regressions.py b/tests/test_regressions.pyindex 2ea9ac0..bcb699e 100644--- a/tests/test_regressions.py+++ b/tests/test_regressions.py@@ -293,3 +293,51 @@ def test_the_page_is_asked_for_again_on_every_visit(built_frontend, client):def test_workspace_module_exposes_the_guard_it_documents():# `Case.locate` is the only door to a case; keep the guard wired to it.assert workspace.layout.names_one_child is layout.names_one_child+++# -- a write cut short leaves the old text, never an empty file (AUD-017) --------+++def _interrupt_every_rename(monkeypatch):+ def refuse(self, target):+ raise OSError("the disk filled up")++ monkeypatch.setattr(workspace.Path, "replace", refuse)+++def test_a_note_save_cut_short_keeps_the_note_it_was_replacing(client, monkeypatch):+ cid = client.post("/api/cases", json={"name": "Cut short"}).json()["id"]+ note = client.post(+ f"/api/cases/{cid}/notes", json={"title": "Lead", "folder": "", "content": "# First lead"}+ ).json()+ case = Case.open(cid)+ path = case.resolve_inside(note["attrs"]["path"])++ _interrupt_every_rename(monkeypatch)+ with pytest.raises(OSError):+ case.write_note(note["id"], "half a sentence")+ with pytest.raises(OSError):+ case.write_notes("the case's own notes, half written")++ assert path.read_text(encoding="utf-8") == "# First lead"+ assert [p.name for p in path.parent.iterdir()] == [path.name], "no scratch file left behind"+++def test_a_spec_save_cut_short_keeps_the_spec_it_was_replacing(client, monkeypatch):+ from azimut.api import drafts, proofs++ cid = client.post("/api/cases", json={"name": "Cut short"}).json()["id"]+ case = Case.open(cid)+ spec = case.resolve_inside(layout.proof_spec_rel("Roof"))+ draft = case.resolve_inside(layout.draft_rel("Thread"))+ proofs._write_spec(spec, {"title": "Roof", "panels": []})+ client.post(f"/api/cases/{cid}/drafts", json={"title": "Thread", "state": {"tweet1": "kept"}})+ before = (spec.read_text(encoding="utf-8"), draft.read_text(encoding="utf-8"))++ _interrupt_every_rename(monkeypatch)+ with pytest.raises(OSError):+ proofs._write_spec(spec, {"title": "Roof", "panels": [{"id": "p1"}]})+ with pytest.raises(OSError):+ drafts.save_draft(cid, drafts.DraftIn(title="Thread", state={"tweet1": "lost"}))++ assert (spec.read_text(encoding="utf-8"), draft.read_text(encoding="utf-8")) == beforediff --git a/tests/test_release_gate.py b/tests/test_release_gate.pyindex 7993e55..90d81bb 100644--- a/tests/test_release_gate.py+++ b/tests/test_release_gate.py@@ -322,6 +322,22 @@ def test_release_binary_runs_the_application_smoke_test():assert f"ffmpeg_target: {target}" in workflow+def test_the_node_floor_for_the_frontend_build_is_the_one_vite_declares():+ """vite and rolldown refuse to start below their range, so the README and the+ frontend's own `engines` state that range rather than a rounder number."""+ import json++ root = Path(__file__).resolve().parent.parent+ readme = (root / "README.md").read_text(encoding="utf-8")+ package = json.loads((root / "frontend" / "package.json").read_text(encoding="utf-8"))+ lock = json.loads((root / "frontend" / "package-lock.json").read_text(encoding="utf-8"))++ vite = lock["packages"]["node_modules/vite"]["engines"]["node"]+ assert vite == "^20.19.0 || >=22.12.0"+ assert package["engines"]["node"] == vite+ assert "Node.js 20.19+ or 22.12+" in readme++def test_intel_macos_package_support_floor_matches_the_lock():root = Path(__file__).resolve().parent.parentreadme = (root / "README.md").read_text(encoding="utf-8")@@ -351,3 +367,53 @@ def test_intel_macos_package_support_floor_matches_the_lock():)assert "cryptography-48.0.1-cp311-abi3-macosx_10_9_universal2.whl" in lockassert "cryptography-50.0.0-cp311-abi3-macosx_11_0_arm64.whl" in lock+++def _glibc_floor():+ import importlib.util++ path = Path(__file__).resolve().parent.parent / "scripts" / "check_glibc_floor.py"+ spec = importlib.util.spec_from_file_location("check_glibc_floor", path)+ assert spec and spec.loader+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def test_the_linux_binary_states_and_holds_its_glibc_floor():+ """The binary carries the runner's own libstdc++, so the runner sets its floor.++ `ubuntu-latest` would move it without a word; the README says the floor, the+ workflow pins the image that gives it, and a step fails a build that asks more.+ """+ floor = _glibc_floor()+ root = Path(__file__).resolve().parent.parent+ workflow = (root / ".github" / "workflows" / "release.yml").read_text(encoding="utf-8")+ readme = (root / "README.md").read_text(encoding="utf-8")+ stated = ".".join(str(part) for part in floor.FLOOR)++ binaries = workflow.split(" binaries:\n", maxsplit=1)[1].split("\n artifacts:\n")[0]+ assert "- os: ubuntu-24.04" in binaries and "ubuntu-latest" not in binaries+ assert "scripts/check_glibc_floor.py dist-bin/azimut" in binaries+ assert f"| Linux (glibc {stated}+) |" in readme+ assert f"glibc {stated} or newer" in readme+++def test_the_glibc_floor_reads_versions_off_an_elf_image():+ floor = _glibc_floor()++ image = b"\x7fELF\0libc.so.6\0GLIBC_2.17\0GLIBC_2.34\0GLIBCXX_3.4.32\0GLIBC_2.3.4\0"+ assert floor.glibc_versions(image) == {(2, 17), (2, 34), (2, 3, 4)}+ newer = b"\x7fELF\0GLIBC_2.39\0"++ assert floor.over_floor(iter([("libstdc++.so.6", image)])) == []+ assert floor.over_floor(iter([("libstdc++.so.6", newer)])) == [("libstdc++.so.6", (2, 39))]+++def test_the_macos_first_run_makes_the_download_executable():+ """A browser download carries no exec bit, and right-click → Open left in macOS 15."""+ readme = (Path(__file__).resolve().parent.parent / "README.md").read_text(encoding="utf-8")+ macos = readme.split("- **macOS**:", maxsplit=1)[1].split("- **Windows**:", maxsplit=1)[0]++ assert "chmod +x azimut-macos-arm64" in macos+ assert "right-click" not in macosdiff --git a/tests/test_reveal.py b/tests/test_reveal.pyindex 1e308d9..f05271e 100644--- a/tests/test_reveal.py+++ b/tests/test_reveal.py@@ -230,21 +230,14 @@ def test_case_route_takes_no_path_from_the_caller(client, shown):assert not shown-def test_workspace_route_reveals_the_root(client, shown):- res = client.post("/api/settings/reveal-workspace")-- assert res.status_code == 200- assert res.json()["path"] == str(config.workspace_root())- assert shown == [config.workspace_root()]--def test_a_refusal_reaches_the_ui_as_a_reason(client, monkeypatch):def refuse(_path):raise reveal.RevealError("no file manager found (xdg-open is missing)")monkeypatch.setattr(reveal, "reveal", refuse)+ cid = client.post("/api/cases", json={"name": "Reveal refused"}).json()["id"]- res = client.post("/api/settings/reveal-workspace")+ res = client.post(f"/api/cases/{cid}/reveal")assert res.status_code == 409assert "xdg-open" in res.json()["detail"]diff --git a/tests/test_satellite_api.py b/tests/test_satellite_api.pyindex 38cb6f0..07c2a5d 100644--- a/tests/test_satellite_api.py+++ b/tests/test_satellite_api.py@@ -1364,3 +1364,108 @@ def test_a_denser_screen_states_the_ground_it_really_covers(client):assert drawn_1x == expected_1xassert drawn_2x == expected_2xassert drawn_1x != drawn_2x+++# -- a refused key never comes back in an error (AUD-019) --------------------------++INSTANCE = "a1b2c3d4-0000-4bad-beef-instance0secret"+MAPBOX = "pk.eyJ1IjoidGVzdCJ9.secret-mapbox-token"+++def _refusing(url, params=None, **_kwargs):+ import httpx++ return httpx.Response(401, request=httpx.Request("GET", url, params=params), text="denied")+++def keys_refused(monkeypatch):+ import httpx++ from azimut import config++ config.save_settings({**config.load_settings(), "api_keys": {"sentinelhub": INSTANCE, "mapbox": MAPBOX}})+ monkeypatch.setattr(httpx, "get", _refusing)+ monkeypatch.setattr(httpx, "post", lambda url, **kw: _refusing(url, **{k: v for k, v in kw.items() if k == "params"}))+++ "method, path, body",+ [+ ("get", "/api/satellite/sentinel/dates?lat=48.8&lon=2.3&start=2026-01-01&end=2026-02-01", None),+ ("get", "/api/satellite/sentinel/layers?check=true", None),+ ("post", "/api/satellite/sentinel1/layer", {}),+ ("get", "/api/satellite/sentinel/coverage?lat=48.8&lon=2.3&layer=TRUE-COLOR&date=2026-01-02", None),+ ],+)+def test_a_refused_sentinel_key_is_never_echoed(client, keys_refused, method, path, body):+ answer = getattr(client, method)(path, **({"json": body} if body is not None else {}))++ assert INSTANCE not in answer.text+ assert "https://" not in answer.text+++def test_a_refused_capture_key_is_never_echoed(client, keys_refused, monkeypatch):+ import httpx++ def refuse(_client, url):+ raise httpx.HTTPStatusError("401", request=httpx.Request("GET", url), response=httpx.Response(401))++ monkeypatch.setattr(tiles, "_default_fetch", lambda c, url: refuse(c, f"{url}?access_token={MAPBOX}"))+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]++ answer = client.post(+ f"/api/cases/{cid}/satellite/capture",+ json={"lat": 48.8584, "lon": 2.2945, "zoom": 16, "width": 256, "height": 256,+ "provider": "mapbox-satellite"},+ )++ assert answer.status_code == 502+ assert MAPBOX not in answer.text and "answered 401" in answer.text+++def test_an_upstream_failure_names_the_code_and_not_the_address():+ import httpx++ request = httpx.Request("GET", f"https://services.sentinel-hub.com/ogc/wfs/{INSTANCE}?x=1")+ refused = httpx.HTTPStatusError("x", request=request, response=httpx.Response(403, request=request))+ assert tiles.upstream_failure(refused) == "the provider answered 403"+ assert tiles.upstream_failure(httpx.ConnectTimeout("t", request=request)) == "the provider did not answer in time"+ assert INSTANCE not in tiles.upstream_failure(ValueError(f"bad reply from {request.url}"))+++# -- the tile cache expires what nobody reads again (AUD-024) ----------------------+++def test_the_tile_cache_sweep_drops_what_is_past_its_days_and_keeps_the_rest(tmp_workspace):+ import os+ import time++ from azimut import config+ from azimut.engine import tilecache++ tilecache.put("s2-2025-01-01", 12, 1, 2, b"old", "image/png")+ tilecache.put("s2-2026-09-01", 12, 1, 2, b"new", "image/png")+ root = config.tile_cache_dir()+ old = root / "s2-2025-01-01" / "12" / "1_2.png"+ past = time.time() - (tilecache.TTL_DAYS + 1) * 86400+ os.utime(old, (past, past))++ assert tilecache.sweep() == 1++ assert not old.exists() and not (root / "s2-2025-01-01").exists()+ assert tilecache.get("s2-2026-09-01", 12, 1, 2) == (b"new", "image/png")+++def test_opening_the_workspace_sweeps_the_tile_cache(tmp_workspace, monkeypatch):+ import threading++ from azimut import workspace+ from azimut.engine import tilecache++ swept = threading.Event()+ monkeypatch.setattr(tilecache, "sweep", lambda: swept.set())++ workspace.open_workspace()++ assert swept.wait(5)diff --git a/tests/test_server_guard.py b/tests/test_server_guard.pyindex f87bd1f..1e9197c 100644--- a/tests/test_server_guard.py+++ b/tests/test_server_guard.py@@ -4,12 +4,16 @@ The server binds localhost, but a page the browser already has open can stillreach 127.0.0.1 directly, or point a name it controls at it (DNS rebinding).The guard is the wall: the Host must be a loopback name, and a cross-origin webOrigin is turned away everywhere except the token-gated ingest island, which-opens itself to browser-extension origins on purpose.+opens itself to browser-extension origins on purpose. A GET from an <img> or a+link carries no Origin at all, so the browser's `Sec-Fetch-Site` is read too: a+foreign page reaches neither the API nor the case files.The shared ``client`` fixture already uses a loopback base_url, so per-requestheader overrides are exactly what the guard sees."""+import pytest+def test_loopback_host_is_allowed(client):for host in ("127.0.0.1", "127.0.0.1:8477", "localhost", "[::1]:8477"):@@ -62,3 +66,47 @@ def test_a_malformed_pairing_token_is_a_refusal_and_not_a_crash(client):answer = client.get("/api/ingest/ping", headers={"X-Azimut-Token": token})assert answer.status_code == 401, tokenassert answer.json()["detail"] == "missing or invalid pairing token"+++[email protected]("site", ["cross-site", "same-site"])[email protected]("path", ["/api/health", "/files/any-case/media/x.png"])+def test_a_foreign_page_without_an_origin_is_refused(client, site, path):+ r = client.get(path, headers={"sec-fetch-site": site})+ assert r.status_code == 403+ assert r.text == "cross-site request refused"++[email protected]("site", ["same-origin", "none"])+def test_the_apps_own_page_and_a_typed_address_are_served(client, site):+ assert client.get("/api/health", headers={"sec-fetch-site": site}).status_code == 200+++def test_a_link_from_elsewhere_still_opens_the_app_and_the_ingest_island_keeps_its_token(client):+ assert client.get("/", headers={"sec-fetch-site": "cross-site"}).status_code != 403+ # the extension's worker may be named cross-site; its pairing token is the wall+ assert client.get("/api/ingest/ping", headers={"sec-fetch-site": "cross-site"}).status_code == 401+++def test_a_foreign_tile_request_spends_nothing_and_reaches_no_provider(client, monkeypatch):+ import httpx++ from azimut import config+ from azimut.api import satellite++ reached: list[str] = []++ def handler(request: httpx.Request) -> httpx.Response:+ reached.append(str(request.url))+ return httpx.Response(200, content=b"", headers={"content-type": "image/png"})++ monkeypatch.setattr(satellite, "_tile_client", httpx.Client(transport=httpx.MockTransport(handler)))+ before = config.load_settings().get("usage")++ r = client.get(+ "/api/tiles/esri-world-imagery/15/16600/11278", headers={"sec-fetch-site": "cross-site"}+ )++ assert r.status_code == 403+ assert reached == []+ assert config.load_settings().get("usage") == beforediff --git a/tests/test_settings_api.py b/tests/test_settings_api.pyindex 81dac45..fd8580d 100644--- a/tests/test_settings_api.py+++ b/tests/test_settings_api.py@@ -510,7 +510,8 @@ def test_sentinel_layers_check_falls_back_to_the_catalogue_and_says_why(client,body = client.get("/api/satellite/sentinel/layers?check=true").json()# a failed discovery leaves a usable list rather than an empty dropdownassert body["source"] == "catalogue"- assert "offline" in body["detail"]+ # the reason is said, and never the address the instance id travels in+ assert body["detail"] == "could not read the instance's layers: the provider could not be reached (ConnectError)"def test_sentinel_dates_lists_passes_and_counts_the_request(client, monkeypatch):diff --git a/tests/test_updates.py b/tests/test_updates.pyindex 72a10c1..e8970e2 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 = "839ff8e1d14d98d6b19ca5a0e0be4610e8b31ac17cf7654caeb210aad724ef3b"+EXTENSION_PAYLOAD = "b3bcdad2bbc30c451e7ab9388dbfa26b5f7151f5b95fc89e868223a7893dd4f2"# The digest itself lives in engine/extinstall.py, because the update button# compares the same number: what the app ships against what the installed folder