Skip to content

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

JavaScript

M3: scale the local workspace (#26)

OsintMeThat0391cf9bf667
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index f1e5393..088dd17 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -89,3 +89,20 @@ jobs:
- run: npm run check
- run: npx vitest run
- run: npm run build
+
+ browser:
+ name: Browser canvas interactions
+ runs-on: ubuntu-latest
+ defaults:
+ run:
+ working-directory: frontend
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: "20"
+ cache: npm
+ cache-dependency-path: frontend/package-lock.json
+ - run: npm ci
+ - run: npx playwright install --with-deps chromium firefox
+ - run: npm run test:e2e
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index abf3211..816f71d 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -18,15 +18,17 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
- node-version: "20"
- - uses: actions/setup-python@v5
+ node-version: "20.20.2"
+ - uses: astral-sh/setup-uv@v5
with:
python-version: "3.12"
- name: Build frontend into the package
working-directory: frontend
run: npm ci && npm run build
- name: Build sdist + wheel
- run: pipx run build
+ run: |
+ uv sync --frozen --no-dev --group release --no-install-project
+ uv run --no-sync python -m build --no-isolation
- name: Sanity-check the wheel bundles the UI
run: |
python - <<'PY'
@@ -61,20 +63,19 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
- node-version: "20"
+ node-version: "20.20.2"
- uses: astral-sh/setup-uv@v5
with:
python-version: "3.12"
- name: Build frontend into the package
working-directory: frontend
run: npm ci && npm run build
- # The wheel only *declares* its dependencies, but the binary *contains*
- # them — this is the one artifact where the resolver's mood on build day
- # ships to users. Install from the lock so a tag rebuilds byte-for-byte.
- - name: Install locked deps + package + PyInstaller
+ # The wheel only declares its dependencies, but the binary contains them.
+ # Application and release tooling both come from the same lock.
+ - name: Install locked application and release tooling
run: |
- uv sync --frozen --no-dev
- uv pip install . pyinstaller
+ uv sync --frozen --no-dev --group release --no-install-project
+ uv sync --frozen --no-dev --group release --no-build-isolation --no-editable
# ffmpeg is a native program, not a Python dep, so it isn't in the wheel.
# Vendor a static ffmpeg + ffprobe per-OS so the binary works out of the
# box (packaging/azimut.spec picks them up; engine/ffmpeg.py finds them at
@@ -88,7 +89,7 @@ jobs:
# "latest" release tag always points at the newest static win64
# build, so pull ffmpeg.exe/ffprobe.exe out of its nested bin/.
curl -fL "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl.zip" -o ffmpeg.zip
- uv run python -c "
+ uv run --no-sync python -c "
import zipfile
zf = zipfile.ZipFile('ffmpeg.zip')
for n in zf.namelist():
@@ -104,19 +105,19 @@ jobs:
base="https://ffmpeg.martin-riedl.de/redirect/latest/$plat/release"
for tool in ffmpeg ffprobe; do
curl -fL "$base/$tool.zip" -o "$tool.zip"
- uv run python -c "import sys, zipfile; zipfile.ZipFile(sys.argv[1]).extractall('packaging/vendor')" "$tool.zip"
+ uv run --no-sync python -c "import sys, zipfile; zipfile.ZipFile(sys.argv[1]).extractall('packaging/vendor')" "$tool.zip"
done
fi
chmod +x packaging/vendor/* 2>/dev/null || true
ls -l packaging/vendor
- name: Build single-file binary
- run: uv run pyinstaller packaging/azimut.spec --distpath dist-bin --workpath build-bin
+ run: uv run --no-sync pyinstaller packaging/azimut.spec --distpath dist-bin --workpath build-bin
- name: Smoke-test the binary
shell: bash
run: |
BIN=dist-bin/azimut
[ "${{ runner.os }}" = "Windows" ] && BIN=dist-bin/azimut.exe
- "$BIN" --version
+ uv run --no-sync python scripts/smoke_binary.py "$BIN"
- name: Name the asset per-OS
shell: bash
run: |
diff --git a/.gitignore b/.gitignore
index 8a06605..f0eed81 100644
--- a/.gitignore
+++ b/.gitignore
@@ -21,6 +21,8 @@ dist/
# Node / JS
node_modules/
npm-debug.log*
+playwright-report/
+test-results/
# Editors / IDE
.idea/
@@ -32,6 +34,7 @@ Thumbs.db
# Workspace / OS
*.code-workspace
*.log
+.azimut-relaunch.json
# Misc
*.bak
diff --git a/README.md b/README.md
index 6d4c4c1..09e5958 100644
--- a/README.md
+++ b/README.md
@@ -1,24 +1,23 @@
# Azimut
-The OSINT investigator's workbench: one case, one folder, every tool.
-Local-first, so your media and your investigations stay on your machine.
+Azimut is a local OSINT workspace for reviewing media, building geolocation
+proofs and keeping case notes together.
-Built for the open-source-investigation community: GeoConfirmed contributors,
-journalists, researchers. Reopen a case months later and everything is still
-there, in one plain folder you can zip, git, or share.
+It is built for open-source investigators, journalists and researchers. Each
+case is a plain folder that can be reopened, archived or shared.
*The name is the French word for azimuth, the compass bearing you sight along
to fix a point on the map.*
-## v0.2.0 — Proof Studio & Post outputs
+## v0.2.0: Proof Studio and post outputs
| Tool | What it does |
|------|--------------|
| **Media Library** | Import local files or download by URL (X, Telegram, TikTok, YouTube, Instagram and more via yt-dlp, with a gallery-dl fallback for image-only posts). Each item gets a clean local file, metadata and a SHA-256. Multi-photo posts open a picker. |
| **Inspect** | A scratch workspace over any photo or video: frame adjustments, editable crop, sharpest-frame capture, hand-made collage with per-piece warp/scale/rotate, and auto-stitch to solve a panorama's layout for you. Nothing enters the case until you save. |
| **Satellite** | Coordinates or a place name become an imagery crop, with select-area capture, map rotation, measurement tools and reference-image overlays. Esri/OSM by default; add a Mapbox or Google key for more basemaps. |
-| **Proof Composer** | Start a named proof from a reusable house style, select case panels with search, compose them in a grid or free layout, annotate with colored shapes/freehand/text, and export `proof.png` plus a re-editable spec. |
-| **Post Composer** | Turn a proof into a prepared thread for X, Bluesky, or Mastodon: coordinates, plus code, attribution, target-specific character counts, media, and Markdown report output. |
+| **Geo Proof** | Start a named proof from a reusable house style, select case panels with search, compose them in a grid or free layout, annotate with colored shapes/freehand/text, and export `proof.png` plus a re-editable spec. |
+| **Geo Report** | Turn a proof into a prepared thread for X, Bluesky, or Mastodon: coordinates, plus code, attribution, target-specific character counts, media, and a structured Markdown case note with linked evidence. |
Every tool works one-shot (a scratch session, no setup) or inside a case, a
plain directory holding the whole investigation.
@@ -29,10 +28,12 @@ New in v0.2.0:
skeletons. Proof templates cover background, spacing, text, footer, signature
placement, and preferred colours; post templates cover the mention, tweet-1
fields, media tweet, and extra tweets.
-- Proof Composer can start a named proof, search and filter case panels, apply a
+- Geo Proof can start a named proof, search and filter case panels, apply a
template, arrange panels horizontally or vertically, and draw freehand marks.
-- Post Composer prepares the same thread for X, Bluesky, or Mastodon, groups
- selected media safely, and copies a compact Markdown report.
+- Geo Report prepares the same thread for X, Bluesky, or Mastodon, groups
+ selected media safely, and saves a structured Markdown case note with
+ clickable case entities and embedded local evidence. Its save confirmation
+ includes an `OPEN` action for the new note.
- Draft and template storage validates bounds and paths before writing, with
atomic template saves and efficient multi-source link updates.
@@ -44,9 +45,8 @@ azimut # starts on http://127.0.0.1:8477 and opens a browser tab
```
Update with `pipx upgrade azimut`, remove with `pipx uninstall azimut`. Your
-cases and settings live under `~/Azimut` and are left untouched by both — an
-upgrade never makes you redo an investigation, and an uninstall never deletes
-your data (delete `~/Azimut` by hand if you also want the data gone).
+cases and settings live under `~/Azimut`; upgrades and uninstalling the app do
+not remove them. Delete `~/Azimut` manually if you also want to remove the data.
Azimut runs in a normal browser tab (Firefox/Chrome); there is no separate
window. Closing the terminal it prints its URL into stops the app.
@@ -61,8 +61,12 @@ opens Azimut in your browser.
|----|-------|
| Windows | `azimut-windows-x86_64.exe` |
| macOS (Apple Silicon) | `azimut-macos-arm64` |
+| macOS (Intel) | No standalone binary; install with `pipx` or `pip` |
| Linux | `azimut-linux-x86_64` |
+Intel Macs are supported through the Python package. They do not have a
+downloadable standalone binary.
+
First run, the binaries are **unsigned**, so the OS warns before letting them
open:
- **macOS**: right-click the file → **Open** → **Open** (Gatekeeper only
@@ -80,19 +84,48 @@ open unchanged in the new version.
The downloadable binaries bundle a static **ffmpeg** (and ffprobe), so video
thumbnails, frame scans, video enhancement, and downloads that merge separate
audio+video streams work out of the box. If you `pip install azimut` instead,
-put ffmpeg on your `PATH` for those features — everything else works without it.
+put ffmpeg on your `PATH` for those features. Everything else works without it.
The bundled ffmpeg is redistributed under its own license; see
[ffmpeg.org/legal.html](https://ffmpeg.org/legal.html).
From source:
+Requires Python 3.11+ and Node.js 20+ for the frontend build.
+
+macOS and Linux:
+
```bash
git clone https://github.com/OsintMeThat/azimut && cd azimut
python3 -m venv .venv && .venv/bin/pip install -e ".[dev]"
-cd frontend && npm install && npm run build && cd ..
+cd frontend && npm ci && npm run build && cd ..
.venv/bin/azimut
```
+Windows PowerShell:
+
+```powershell
+git clone https://github.com/OsintMeThat/azimut
+Set-Location azimut
+py -3.11 -m venv .venv
+.venv\Scripts\python -m pip install -e ".[dev]"
+Set-Location frontend
+npm ci
+npm run build
+Set-Location ..
+.venv\Scripts\azimut.exe
+```
+
+Rebuild and relaunch the local app with the cross-platform helper:
+
+```bash
+python3 scripts/relaunch.py # macOS / Linux
+py scripts\relaunch.py # Windows
+```
+
+The tool rebuilds the frontend, stops the previous Azimut instance started
+through the same tool, and launches the fresh build. It never kills unrelated
+processes by name. Use `--no-browser` to keep it from opening a new tab.
+
Frontend development (hot reload, proxied API):
```bash
@@ -126,9 +159,10 @@ bundled into the Python wheel via hatchling `artifacts`. So `npm run build`
```bash
cd frontend && npm run build && cd .. # refresh the bundled UI
-uv sync --frozen # the exact deps CI tested
-pipx run build # wheel + sdist (UI included)
-uv run pyinstaller packaging/azimut.spec # optional: standalone binary
+uv sync --frozen --no-dev --group release --no-install-project
+uv sync --frozen --no-dev --group release --no-build-isolation --no-editable
+uv run --no-sync python -m build --no-isolation
+uv run --no-sync pyinstaller packaging/azimut.spec
```
### Dependencies
@@ -173,8 +207,9 @@ One-time setup: register the repo as a
1. **Local-first, privacy-first.** No account, no telemetry, no upload; the
server binds to `127.0.0.1` only, and Azimut never posts anywhere on your
behalf.
-2. **The case is the product.** Plain JSON + media files, versionable,
- portable.
+2. **The case is the product.** Media and notes stay as files and the graph lives
+ in per-case SQLite. A closed case folder is complete and portable; a ZIP
+ import/export workflow is planned.
3. One tab = one tool, useful in 30 seconds.
4. **Orchestrator, not replacer.** Integrate specialized services rather than
cloning them.
diff --git a/bench/case_baseline.py b/bench/case_baseline.py
new file mode 100644
index 0000000..b2146e3
--- /dev/null
+++ b/bench/case_baseline.py
@@ -0,0 +1,149 @@
+#!/usr/bin/env python3
+"""JSON-store baseline for the storage/performance migration (Step 0).
+
+Builds the synthetic large case (tests/bigcase.py) and times the operations the
+migration is meant to make cheap, on the current monolithic ``case.json``. The
+numbers are the "before" this work is measured against; capture them on the
+reference machine described in docs/STORAGE_AND_PERFORMANCE.md before changing
+anything.
+
+Standard library only, and it lives outside ``src/azimut`` so it is never
+packaged into the wheel or the frozen binaries. Run it, don't ship it:
+
+ python bench/case_baseline.py # default 10k/20k/5k
+ python bench/case_baseline.py --no-media-files # graph only, faster
+ python bench/case_baseline.py --entities 2000 --links 4000 --media 1000
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import shutil
+import statistics
+import sys
+import tempfile
+import time
+from pathlib import Path
+
+_TESTS = Path(__file__).resolve().parent.parent / "tests"
+sys.path.insert(0, str(_TESTS))
+
+
+def _time(fn, iterations: int) -> float:
+ """Median wall-clock milliseconds over ``iterations`` calls of ``fn``."""
+ samples = []
+ for _ in range(iterations):
+ start = time.perf_counter()
+ fn()
+ samples.append((time.perf_counter() - start) * 1000)
+ return statistics.median(samples)
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__)
+ ap.add_argument("--entities", type=int, default=10_000)
+ ap.add_argument("--links", type=int, default=20_000)
+ ap.add_argument("--media", type=int, default=5_000)
+ ap.add_argument("--notes", type=int, default=200)
+ ap.add_argument("--artifacts", type=int, default=300)
+ ap.add_argument("--seed", type=int, default=1234)
+ ap.add_argument("--iterations", type=int, default=25)
+ ap.add_argument("--no-media-files", action="store_true",
+ help="skip writing placeholder media/sidecars (graph-only timing)")
+ ap.add_argument("--home", type=Path, default=None,
+ help="workspace root to build in (default: a temp dir, removed after)")
+ ap.add_argument("--keep", action="store_true", help="keep the temp workspace")
+ args = ap.parse_args()
+
+ home = args.home or Path(tempfile.mkdtemp(prefix="azimut-bench-"))
+ os.environ["AZIMUT_HOME"] = str(home)
+
+ # imported after AZIMUT_HOME is set; config reads the env at call time
+ from azimut.engine import links as link_engine
+ from bigcase import build_big_case
+
+ print(f"workspace: {home}")
+ print(f"building {args.entities} entities / {args.links} links / {args.media} media …")
+ t0 = time.perf_counter()
+ case, summary = build_big_case(
+ entities=args.entities, links=args.links, media=args.media,
+ notes=args.notes, artifacts=args.artifacts, seed=args.seed,
+ write_media_files=not args.no_media_files,
+ )
+ build_ms = (time.perf_counter() - t0) * 1000
+
+ data = case.read()
+ ids = [e["id"] for e in data["entities"]]
+ json_bytes = case.json_path.stat().st_size
+ payload_bytes = len(json.dumps({"id": case.id, **data}))
+ a, b = ids[0], ids[1]
+ subject = next(lk["to"] for lk in data["links"] if lk["type"] == "depends-on")
+ mid = ids[len(ids) // 2]
+
+ it = args.iterations
+
+ def op_add_entity():
+ case.add_entity("domain", "bench-probe", {"note": "x"}, by="user")
+
+ def op_add_link():
+ case.add_link(a, b, "mentions", by="user")
+
+ def op_update_entity():
+ case.update_entity(mid, {"attrs": {"touched": time.time()}})
+
+ def op_filter_scan():
+ d = case.read()
+ _ = [e for e in d["entities"] if e.get("type") == "media"]
+ _ = [e for e in d["entities"] if "42" in e.get("label", "")]
+
+ def op_plan_delete():
+ link_engine.plan_delete(case, subject)
+
+ def op_remove_entity():
+ e = case.add_entity("domain", "bench-remove", by="user")
+ start = time.perf_counter()
+ case.remove_entity(e["id"])
+ op_remove_entity.last = (time.perf_counter() - start) * 1000
+
+ def timed_remove():
+ op_remove_entity()
+ return op_remove_entity.last
+
+ results = [
+ ("read (open case)", it, _time(case.read, it)),
+ ("filter/search scan", it, _time(op_filter_scan, it)),
+ ("plan_delete (dialog)", it, _time(op_plan_delete, it)),
+ ("add_entity (1 write)", it, _time(op_add_entity, it)),
+ ("add_link (1 write)", it, _time(op_add_link, it)),
+ ("update_entity (1 write)", it, _time(op_update_entity, it)),
+ ("remove_entity (1 write)", it,
+ statistics.median([timed_remove() for _ in range(it)])),
+ ]
+
+ print()
+ print(f" entities={summary.entities} links={summary.links} "
+ f"media={summary.media} ({summary.media_files_missing} missing files) "
+ f"notes={summary.notes} artifacts={summary.artifacts} "
+ f"folders={summary.folders} tombstoned={summary.tombstoned}")
+ print(f" case.json on disk : {json_bytes / 1e6:8.2f} MB")
+ print(f" case-open payload : {payload_bytes / 1e6:8.2f} MB (shipped to the browser)")
+ print(f" fixture build : {build_ms / 1000:8.2f} s")
+ print()
+ print(f" {'operation':<26}{'iters':>7}{'median ms':>14}")
+ print(f" {'-' * 26}{'-' * 7}{'-' * 14}")
+ for name, iters, ms in results:
+ print(f" {name:<26}{iters:>7}{ms:>14.3f}")
+ print()
+ print(" Every *_write op above is a full read-modify-write of case.json: its")
+ print(" cost scales with the whole case, which is the ceiling this work lifts.")
+
+ if not args.keep and args.home is None:
+ shutil.rmtree(home, ignore_errors=True)
+ elif args.keep:
+ print(f"\n kept workspace at {home}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/docs/IMAGERY_PROVIDERS.md b/docs/IMAGERY_PROVIDERS.md
index c386297..853a2a8 100644
--- a/docs/IMAGERY_PROVIDERS.md
+++ b/docs/IMAGERY_PROVIDERS.md
@@ -1,16 +1,14 @@
-# Keyed imagery providers — Mapbox, Google (tiles & Maps JS) & Sentinel Hub
+# Keyed imagery providers
-> Azimut ships optional user-keyed basemaps alongside the key-less defaults
-> (Esri, OSM, OpenTopoMap). The rules below are why their code looks the way it does — they come
-> from Google's and Mapbox's terms, not from taste. Read alongside SPEC.md §6
-> "v1 notes → Tile providers" (legal-only policy).
+> Azimut offers optional Mapbox, Google and Sentinel Hub providers alongside the
+> keyless defaults. Their legal and technical constraints define the implementation.
>
> Implemented in [`engine/tiles.py`](../src/azimut/engine/tiles.py),
> [`engine/google_tiles.py`](../src/azimut/engine/google_tiles.py),
> [`engine/tilecache.py`](../src/azimut/engine/tilecache.py) and
> [`api/settings.py`](../src/azimut/api/settings.py).
-## Legal rules (decided — do not relax)
+## Legal rules
| Rule | Why |
|------|-----|
@@ -18,7 +16,7 @@
| Core features never require a key. Key-less providers (Esri, OSM, OpenTopoMap) stay the default. | Principle 7. |
| **Never** ship/suggest/document unofficial endpoints (`mt1.google.com`, `khms*`, …). Only official APIs. | Legal-only policy. |
| **Google tiles must NOT be cached to disk.** | Google's Map Tiles API forbids pre-fetch/store/cache/offline use of tiles ([policies](https://developers.google.com/maps/documentation/tile/policies)). |
-| A Google **capture** is allowed only as a **flattened, attributed screenshot** (single PNG, attribution burned in) — never a store of raw tiles. | Google Geo Guidelines permit screenshots in reports/periodicals ≤5,000 copies **with attribution**; the anti-cache clause forbids tile hoarding. Two different acts. |
+| A Google **capture** is a flattened, attributed PNG, never stored raw tiles. | Google permits attributed screenshots in reports and periodicals up to 5,000 copies; its anti-cache rule still forbids tile storage. |
| Every capture keeps provider **attribution** (Google/Mapbox + data providers, e.g. Maxar) unmodified. For Google it is **burned into the image footer**. | Attribution is a condition of the allowed use, not a courtesy. |
### Per-provider capability matrix
@@ -38,91 +36,86 @@ caching/redistribution limits vary, so the cache stays modest (30-day TTL) and
attribution always on.
² Free for any use, commercial included, *provided* the attribution line stays
-visible — CC-BY-SA makes it a licence condition, not a courtesy. The tile
+visible. CC-BY-SA makes it a licence condition. The tile
policy's only real limit is "no mass downloads", which a single-user workbench
never approaches. Topographic, so `imagery=false` (the labels overlay would
double its own labels). Its tile server stops at **z17** and answers deeper
-zooms with a constant "max zoom layer = 17" placard — registered in
+zooms with a constant "max zoom layer = 17" placard. It is registered in
`PLACEHOLDER_TILE_SHA256`, and the live map caps its zoom at the provider max
so it is never requested. Verified 2026-07.
-³ Open data (Copernicus free/full/open licence) — the licence asks only for
+³ Open data under the Copernicus free, full and open licence. It requires
attribution, so no capture or cache restriction. The constraint is quota, not law.
The instance ID is the **whole credential**: OGC needs no OAuth token on top of it
-(verified 2026-07 — a wrong id answers `400 Invalid instance id`, never a 401). It
+(verified 2026-07: a wrong id answers `400 Invalid instance id`, never a 401). It
is still the user's quota identity, so it lives in `api_keys` like any other key.
⁴ A Maps JS key is client-side **by design** (referrer-restricted, not secret), so
-shipping it to the browser in the loader URL is the intended use — unlike every
+shipping it to the browser in the loader URL is intended. Every
tile key, which stays server-side behind the proxy.
-## Google in the EEA (2025-07-08) — why there are two Google entries
+## Google in the EEA since 2025-07-08
Google stopped serving **satellite tiles** (Map Tiles API *and* Static Maps API)
to projects with an **EEA billing address**: 403 `PERMISSION_DENIED` with the
explanation in the error body ([Map Tiles notice](https://developers.google.com/maps/comms/eea/map-tiles),
-[Static notice](https://developers.google.com/maps/comms/eea/maps-static) — a
-Bundeskartellamt outcome, not a bug). Applies to projects created after that date
+[Static notice](https://developers.google.com/maps/comms/eea/maps-static)). This
+applies to projects created after that date
or that later left "Unmodified State". Non-EEA accounts keep the tile pipeline.
-The one official Google satellite route left in the EEA is the **Maps JavaScript
-API widget** — so Azimut ships both:
+The Maps JavaScript API widget remains the official Google satellite route in the
+EEA, so Azimut supports both products:
| | Google Satellite (tiles) | Google Satellite (Maps JS) |
|---|---|---|
| Works in the EEA | **no** (403) | yes |
| Rendering | XYZ tiles through our proxy | a real `google.maps.Map` under Leaflet (GoogleMutant plugin, Beerware licence) |
-| Captures | stitched crop, attribution burned | **screen pixels only** — same Capture button, modes and frame; the crop comes from one tab screenshot taken by the **capture extension** (Settings → Capture extension; the button gates on it). Attribution burned, `method:"screenshot"` + `framed:true` |
-| Capture frame | any size (tiles are fetched) | can't exceed the map view — screen pixels are the ceiling, so no resolution multiplier |
+| Captures | stitched crop, attribution burned | **screen pixels only** from one tab screenshot taken by the capture extension; attribution burned, `method:"screenshot"`, `framed:true` |
+| Capture frame | any size (tiles are fetched) | limited to the map view; no resolution multiplier |
| Rotation / oversample / marquee | yes | **rotation + marquee yes**, oversample no |
-| Meter | tiles | **map loads** (~10k free/month) — the widget layer is created once per *page life* and reused across tab and basemap switches, since every instantiation bills a load; this is also why eco mode is pinned off for it. Reloading the app is therefore a real +1, which is why the counter climbs while developing |
-| Key test | `createSession` server-side | in-browser only (`gm_authFailure`), from Settings; a *changed* key needs an app reload — Google's script binds one key per page life. **Costs a map load** and reports it to the meter (a rejected key is free) |
+| Meter | tiles | **map loads** (~10k free/month); one widget instance per page life, reused across tabs and basemap switches; eco mode disabled because a replacement instance bills another load |
+| Key test | `createSession` server-side | in-browser `gm_authFailure`; a changed key requires reload; an accepted key test bills and records one map load |
Both keys can be saved at once: each lights its own basemap, and the EEA failure
path benches the tiles one automatically (below) leaving the widget on offer.
Leaflet keeps all interaction, so measure tools, places, reference windows and
the labels overlay work unchanged over the widget.
-### The widget is a normal basemap, with one seam
+### Maps JS widget behavior
-GoogleMutant runs a **hidden** `google.maps.Map` and clones its `<img>` tiles into
-an ordinary Leaflet `GridLayer`. Two consequences worth knowing:
+GoogleMutant runs a hidden `google.maps.Map` and clones its `<img>` tiles into a
+Leaflet `GridLayer`.
- **Rotation works.** The visible tiles are Leaflet tiles in the rotatable tile
pane, and leaflet-rotate already asks the grid for the rotated bounding box.
- The only catch is coverage: the hidden map renders the *unrotated* viewport, so
- a turned view wants corner tiles that were never rendered — blank corners.
+ The hidden map renders the unrotated viewport, so a turned view can otherwise
+ expose blank corners.
`lib/gmaps.js` sizes the hidden map to a **square of the container's diagonal,
centred**, which covers every bearing at once. Extra tile renders inside one
map load are free; the billing is per `google.maps.Map`.
-- **Those cloned tiles are still off-limits.** Reading them back (canvas,
- html2canvas, refetching the URLs) is exactly the programmatic extraction
- Google's terms forbid — the fact that they sit in our DOM changes nothing. The
+- **Cloned tiles remain off-limits.** Reading them through canvas, html2canvas or
+ their URLs is programmatic extraction forbidden by Google's terms. The
capture path therefore goes through the **capture extension** (`extension/`,
installed from Settings): one `tabs.captureVisibleTab` behind the user's
- click — the browser-blessed tab screenshot. No share prompt, no sharing bar,
- and fullscreen survives, which the earlier `getDisplayMedia` route broke
- (the share prompt drops fullscreen and relayouts the map under a
- just-measured frame). Without the extension the Capture button explains and
- points at Settings — never a half-working fallback.
+ click. This avoids the share prompt and preserves fullscreen, unlike the earlier
+ `getDisplayMedia` route. Without the extension, Capture directs the user to
+ Settings and does not offer a fallback.
What the screen-pixel route still forces, whatever supplies the frame:
| Trap | Rule |
|---|---|
-| The tab frame is the **whole viewport** — our HUD, control clusters and reference windows paint *over* the map and would land in the crop | `.map-wrap.grabbing` hides our chrome for the grab (`:global`, or the reference windows — a child component — slip through scoped CSS). The marker stays: the tile path burns one in, so a screen crop keeps its own |
-| A frame can silently be the **wrong surface** (browser zoom changed mid-flight, a stale frame from before a resize) and the crop math is one scale factor — it would crop real pixels off the wrong place and look fine doing it | Check registration (`lib/screenCrop.js isRegistered`, viewport aspect) on **every frame** before cropping; refuse on mismatch |
-| `captureVisibleTab` needs **activeTab or `<all_urls>`** — host permissions are NOT enough (verified: both browsers refuse), so a page-initiated capture fails on a fresh tab | One extension click (icon or `Alt+Shift+A`) grants activeTab **for the tab's whole life** (the app is an SPA — no navigation, so once per session). The app turns the refusal into a "click the icon once" toast, and the popup pings back so the app can say "press Capture again". Never `<all_urls>` |
+| The tab frame covers the whole viewport, including Azimut chrome | `.map-wrap.grabbing` hides the HUD, controls and child reference windows through `:global`. The marker stays because tile captures burn one into their output too. |
+| Browser zoom or resize can make a frame belong to the wrong surface | Validate every frame with `lib/screenCrop.js isRegistered` and the viewport aspect; refuse mismatches. |
+| `captureVisibleTab` needs `activeTab` or `<all_urls>`; host permission is insufficient | One extension click grants `activeTab` for the SPA tab's life. The app explains this once. Never request `<all_urls>`. |
-**Provenance:** `framed` says what the coordinates mean. `true` — the crop was
-taken through the capture frame, so lat/lon is the crop centre. `false` — a
-pasted/dropped image, so lat/lon is only the map view when it was filed.
+**Provenance:** `framed:true` means lat/lon is the registered crop centre.
+`framed:false` means lat/lon records only the map view used while filing a pasted
+or dropped image.
-**A failed capture is never downgraded into an import.** A frame that can't be
-registered is refused with an error and nothing is filed — the paste dialog is a
-deliberate choice from the capture menu, never an escape hatch offered after a
-failure. Quietly proposing to file *some other image* instead is how an
-unregistered picture ends up wearing a capture's provenance.
+A frame that fails registration is refused and nothing is filed. Importing a
+pasted screenshot remains a separate capture-menu action so it cannot inherit
+registered-frame provenance.
### The capture extension (`extension/`, api/ingest.py)
@@ -131,20 +124,17 @@ One MV3 extension (Chrome/Edge + Firefox), two flows:
| | Azimut's Maps JS basemap | External map sites |
|---|---|---|
| Trigger | the app's own Capture button (bridge content script relays) | toolbar click / `Alt+Shift+A` → popup → drag an area |
-| Sites | localhost only | Google Maps/Earth, Bing, Yandex, OSM, Apple Maps, Zoom Earth, Satellites.pro, Copernicus Browser — **refuses non-map sites**, enforced by the endpoint too |
-| Metadata | the app's own view (registered crop, `framed:true`) | parsed from the page **URL only**, never the DOM — coordinates, zoom, bearing, place name (→ title), imagery date where the URL carries one (Copernicus `toTime`, Zoom Earth `/date=`); correctable in the popup; may be empty |
-| Filing | the app files same-origin — no pairing | `POST /api/ingest/screenshot`, gated by a **pairing token** (Settings → copy, extension options → paste) + CORS open to extension origins only; an SSE nudge (`/api/events`) makes the capture appear in any open app tab without a reload |
+| Sites | localhost only | Google Maps/Earth, Bing, Yandex, OSM, Apple Maps, Zoom Earth, Satellites.pro and Copernicus Browser; endpoint also refuses non-map sites |
+| Metadata | app view (`framed:true`) | parsed only from the URL: coordinates, zoom, bearing, place name and any encoded imagery date; correctable in the popup; may be empty |
+| Filing | same-origin, no pairing | token-gated `POST /api/ingest/screenshot`, CORS limited to extension origins; `/api/events` refreshes open app tabs |
| Attribution | burned by the app | burned server-side per site (`api/ingest.py ATTRIBUTIONS`), source URL + site + timestamp always in provenance |
-**The extension is deliberately dumb** (owner decision, same logic as the
-unbounded yt-dlp ranges): it screenshots and sends the URL, and every URL
-format rule lives in `engine/mapsites.py` — the popup's prefill is
+The extension only screenshots and sends the URL. Every URL format rule lives in
+`engine/mapsites.py`; the popup prefill is
`GET /api/ingest/parse`, and the POST re-derives site/attribution/metadata
from the URL itself, trusting the client for nothing but its own corrections.
-URL formats race sites that change without notice, and the extension is the
-one component that can't be updated remotely (loaded unpacked, no store) —
-so a changed format must cost an app update, never a hand reinstall on every
-machine. Don't add site knowledge to the extension.
+The unpacked extension cannot update remotely, while the app can. Keep site
+knowledge in the app so format changes do not require reinstalling the extension.
Legal rails, encoded in both the extension and the endpoint: one screenshot per
explicit user action (nothing schedulable), URL-only metadata, on-screen
@@ -156,7 +146,7 @@ credits ride along inside the pixels, attribution burned on top.
by: the Settings key test (every provider), a `createSession` refusal or a tile
401/403 that survives the re-mint retry (with Google's own sentence as the
reason), and the browser's `gm_authFailure` for the JS key. **Never** by plain
-network errors — a timeout says nothing about the key. A key marked bad is
+network errors; a timeout says nothing about the key. A key marked bad is
withheld from `all_providers()`, so the basemap vanishes from the selector (the
live map falls back to Esri) until the key changes (verdict cleared) or a test
passes. Settings shows the stored reason inline.
@@ -166,13 +156,13 @@ passes. Settings shows the stored reason inline.
`eco_max_zooms` in settings.json lets each tile basemap carry its own eco
threshold (blank = provider default, else the global one; 0 = eco off for it).
Needed because one global value can't fit both a z22 basemap and Sentinel-2's
-z14 ceiling — and the JS widget is excluded entirely (a swap re-bills a load).
+z14 ceiling. The JS widget is excluded because replacing it bills another load.
## Sentinel-2 is a dated mosaic, not a basemap
-Use the **OGC WMTS** endpoint — not Catalog (STAC metadata only, no pixels) and not
-the Process API (POST + evalscript; buys band math, fits nothing in the XYZ
-pipeline — deferred with Satellite Compare).
+Use the OGC WMTS endpoint. Catalog provides STAC metadata but no pixels. The
+Process API requires POST and evalscript, so band math remains deferred with
+Satellite Compare.
```
https://sh.dataspace.copernicus.eu/ogc/wmts/{key}?SERVICE=WMTS&REQUEST=GetTile
@@ -180,69 +170,73 @@ https://sh.dataspace.copernicus.eu/ogc/wmts/{key}?SERVICE=WMTS&REQUEST=GetTile
&TILEMATRIX={z}&TILECOL={x}&TILEROW={y}&FORMAT=image/jpeg
```
-`{key}` is a **configuration instance** UUID (Dashboard → Configuration Utility),
-built from the **Simple Sentinel-2 L2A template** — that template is what makes
-`TRUE_COLOR` exist. L2A (bottom-of-atmosphere) over L1C: corrected colour, and the
-120 m mosaic / 20 m Europe-only templates are too coarse or too regional to be a
-basemap at all. **"Show logo" and "Show warnings" must be off in the instance** —
-both are burned into every tile server-side, which would tile the map with
-Copernicus logos and put one inside evidence captures.
+`{key}` is a configuration-instance UUID from Dashboard → Configuration Utility.
+Use the Simple Sentinel-2 L2A template, which defines `TRUE_COLOR`. L2A provides
+corrected bottom-of-atmosphere colour; the 120 m mosaic and 20 m Europe-only
+templates are unsuitable as basemaps. Turn off **Show logo** and **Show warnings**
+because the server burns both into every tile.
`TIME` is a **mosaicking window**, so this layer is "mosaic over range X", not "the
imagery". Omitted, the layer's own default applies (the most recent pass).
-**The layer and the window ride on the provider id** — `sentinel2~SWIR~2026-05-01~2026-05-31`
+The provider id carries the layer and window:
+`sentinel2~SWIR~2026-05-01~2026-05-31`
(`engine/sentinel.py`, mirrored in `frontend/src/lib/sentinel.js`). That is what
solves the cache trap this section used to warn about: the disk cache keys on
`provider.id`, so a window in the id *is* a window in the cache key and two dates
can never collide. It also means the tile proxy, `fetch_crop` and a capture's
-provenance all inherit the choice for free — none of them can render from one
+provenance all inherit the choice. None can render from one
window and file under another. `tiles.get_provider()` parses the variant;
`parse_variant` is the validation boundary (the id becomes a URL path segment
*and* a cache directory, so the shape is an allowlist).
| Choice | UI | Notes |
|--------|----|-------|
-| Layer | picker, populated from **GetCapabilities** on first open | `LAYERS` in `engine/sentinel.py` is a 4-entry *fallback*; the instance is the authority on what it serves — offering a layer it lacks just 400s on selection |
-| Date | a **calendar**: only days with a real pass are selectable, coloured by cloud | one day, not a range — a range is a mosaic of several passes and can't be dated. Sent as `TIME=day/day` |
+| Layer | picker populated from **GetCapabilities** on first open | `LAYERS` in `engine/sentinel.py` is a four-entry fallback; the instance is authoritative, so unsupported layers are not offered |
+| Date | a **calendar**: candidate pass days are coloured by cloud, then checked at the crosshair | one day, not a range. Sent as `TIME=day/day` |
### Dates come from WFS, and cost one request
`GET /ogc/wfs/{instance}?TYPENAMES=DSS2&TIME=…&BBOX=…&OUTPUTFORMAT=application/json`
-— same instance credential, no OAuth (Catalog would need one). `DSS2` is L2A: a
+uses the same instance credential and no OAuth. `DSS2` is L2A; a
date list from L1C would be a plausible lie about a different collection.
`SRSNAME=EPSG:4326` puts **latitude first** in the BBOX.
Billed at **0.01 PU but one whole request**, so `record_usage` counts it as 1:
-both quotas are 30k, the meter tracks requests exactly and over-states PU
-slightly — the conservative direction. Hence the meter's unit is "request", not
+both quotas are 30k. The meter tracks requests exactly and slightly overstates PU,
+so its unit is "request", not
"tile" (`meterUnit`).
**Granule footprints are checked against the point** (`_covers`). A granule's
bounding box is a square; its data is the slice of orbit swath inside it. WFS
-answers on the box, so without the check a day gets listed, pinned, and renders
-**black** — exactly the failure a date list exists to prevent. The footprint is
+answers on the box, so without the check a listed day can render black. The footprint is
tested under both axis orders: read backwards, every granule on Earth would be
rejected.
+WFS dates are still candidates. Before changing the map, the picker sends an
+8×8 WMS `dataMask` check for the selected layer and day. A failed check leaves
+the current map in place and marks the date unavailable at that location. The
+result is cached by layer, date and rounded coordinates. Moving the map disables
+the old dates until the list refreshes. A successful check counts as one more
+Sentinel Hub request.
+
**Its levels are numbered by resolution, not by grid width.** `TILEMATRIX=14` is
-9.55 m/px on an 8192-wide grid — the same imagery Mapbox calls z13. Tile indices
+9.55 m/px on an 8192-wide grid, equivalent to Mapbox z13. Tile indices
stay at the repo's `tile_z` either way, so only the level's *name* differs:
-`Provider.zoom_offset=1` re-adds what `z_shift` took off. Getting this wrong is not
-subtle — the service answers `400 Invalid TILECOL`.
+`Provider.zoom_offset=1` re-adds what `z_shift` took off. A wrong offset returns
+`400 Invalid TILECOL`.
**Eco mode needs its own threshold here** (`Provider.eco_max_zoom=11`). The global
default (z15) is tuned for basemaps that run to z22; Sentinel-2's imagery stops at
-z14, so sharing it would swap the layer away at most zooms it can serve. At z11 and out a
-Sentinel-2 pixel is ~40 m of ground and Esri shows the same scene for free — the
-swap costs a known date for an unknown one, which only pays where the resolution
-adds nothing anyway.
+z14, so sharing it would replace the layer at most supported zooms. At z11 and
+out, one Sentinel-2 pixel covers about 40 m and free Esri imagery has comparable
+detail. The swap is limited to those low-detail views.
| Limit | Value | Consequence |
|-------|-------|-------------|
-| Native resolution | 10 m/px ≈ 9.55 m/px at `TILEMATRIX=14` | `max_native_zoom=14` — deeper is Sentinel Hub upsampling we'd pay full price for |
-| Useful zoom | z18 | `max_zoom=18`, on **magnified native tiles** — see below |
-| Free quota | **30 000 requests + 30 000 PU/month** (Copernicus General) | `meter="sentinelhub"`; per-account and **editable in Settings** — see below |
+| Native resolution | 10 m/px ≈ 9.55 m/px at `TILEMATRIX=14` | `max_native_zoom=14`; deeper requests only buy server-side upsampling |
+| Useful zoom | z18 | `max_zoom=18` on magnified native tiles |
+| Free quota | **30 000 requests + 30 000 PU/month** (Copernicus General) | `meter="sentinelhub"`; per-account and editable in Settings |
| Rate | 300 req/min, 300 PU/min | why tiles stay 512 |
| PU cost | 512×512, 3 bands, 8-bit = **exactly 1 PU** | one tile = 1 request = 1 PU, so the counter is faithful |
@@ -254,14 +248,13 @@ Google's big-tile trick buys nothing here. 512 wins on the requests/min limit al
`max_native_zoom` (14) and `max_zoom` (18) are different questions: where the
imagery *stops*, and where looking at it stops being useful. You cannot read a
ship at 10 m/px from three levels out, so the view runs to z18 while requests
-stop at 14 and the last native tile is magnified — same pixels, larger, **zero
-extra requests**. Asking Sentinel Hub for z18 would buy its upsampling of those
-same pixels at 16× the tiles, every one billed: the identical image, paid for.
+stop at 14 and magnify the last native tile without extra requests. Asking
+Sentinel Hub for z18 would bill 16 times as many tiles for server-side upsampling.
Leaflet's `maxNativeZoom` does it on the live map; `fetch_crop` mirrors it so a
capture matches the screen, and records `native_zoom` +
-`native_meters_per_pixel` next to `zoom` — the image is real, its resolution is
-not what the zoom implies, and a reader has to be able to tell. The tile proxy
+`native_meters_per_pixel` next to `zoom`. This records that the native resolution
+is lower than the display zoom implies. The tile proxy
refuses to fetch past the ceiling at all (`_native_grid_zoom`), for anything
that isn't the live map.
@@ -271,9 +264,8 @@ Copernicus **documents 10 000** PU/month and **provisions 30 000** (observed
2026-07, `copernicus-general-quota`). So `config.FREE_TIER` is a *default*, and
`free_tiers` in settings.json overrides any meter (`config.free_tier()`,
editable per provider under Settings → Usage). A hardcoded number makes the
-gauge and the 90% soft block lie about someone else's account — and the block
-pausing a provider that is nowhere near its limit is a real failure, not a
-cosmetic one.
+gauge and 90% soft block can match the user's account rather than a global
+assumption.
[Quotas](https://documentation.dataspace.copernicus.eu/Quotas.html) ·
[PU definition](https://documentation.dataspace.copernicus.eu/APIs/SentinelHub/Overview/ProcessingUnit.html)
@@ -298,27 +290,26 @@ The **token** may be cached; tiles may not.
**Tile sizes.** Mapbox serves **512px** tiles: it bills 256px tiles 4× vs 512px for
the same ground area at the same m/px. Google serves **1024px hi-DPI** tiles
(`scale=scaleFactor4x, highDpi=true`): it bills per *request* regardless of tile
-size, so one request covers sixteen 256px tiles' worth of ground at the same m/px —
-verified pixel-identical. Mapbox's `@2x` equivalent is *upsampled* (softer), which
+size, so one request covers sixteen 256px tiles' worth of ground at the same m/px;
+the output was verified pixel-identical. Mapbox's `@2x` equivalent is upsampled, so
is why Mapbox stays at 512.
**Oversampling.** The live map oversamples Google 2× (1024px tiles in 512px cells,
one zoom deeper) because Google's mid-zoom mosaics are verifiably softer than its
-deep ones — net ¼ the cost of plain 256px tiles. The z17 view alone boosts to 4×
+deep ones, at one quarter the request cost of plain 256px tiles. The z17 view boosts to 4×
(z19 detail): the z18 mosaic it would otherwise show is often an older/hazier
-collection than the z19+ aerial. Captures stay 1:1 provider pixels — no resampling
+collection than the z19+ aerial. Captures retain provider pixels without resampling
in evidence imagery.
-**Billing units.** Both bill **per tile served** — Google's 2D Map Tiles SKU is
+**Billing units.** Both bill per tile served. Google's 2D Map Tiles SKU is
"Request that returns a 2D map tile" (session and viewport requests are free);
Mapbox Static Tiles bills per tile request when used with Leaflet. Free tiers:
Google 100k/month then $0.60/1k (plus hard limits of 15k tiles/day and 6k/min per
-project), Mapbox 200k/month then $0.50/1k (no hard cap — alerts only). Metered
+project), Mapbox 200k/month then $0.50/1k (alerts only, no hard cap). Metered
tiles are proxied through the backend so the counter matches billing exactly;
browser cache hits never re-count.
## Deliberately not basemaps
-Street View and Google Photorealistic 3D Tiles are keyed Google products but not
-tile providers — a ground-imagery tool and a 3D scene respectively. They live in the
-SPEC backlog, not here.
+Street View and Google Photorealistic 3D Tiles are not basemap providers. They
+remain separate ground-imagery and 3D-scene roadmap items.
diff --git a/docs/ONTOLOGY.md b/docs/ONTOLOGY.md
index a9e25c2..164ca64 100644
--- a/docs/ONTOLOGY.md
+++ b/docs/ONTOLOGY.md
@@ -1,13 +1,13 @@
# Azimut ontology (case data model)
-> The contract every tool files against. Companion to [SPEC.md §5](SPEC.md); the
-> spec stays a summary, this is the precise vocabulary. Keep it small, coherent,
-> extensible, **versioned** — grown from real tool needs, never a whiteboard
-> taxonomy. Nothing enters a case without a human click (SPEC principle 5).
+> This is the filing contract for every tool and the detailed companion to
+> [SPEC.md §5](SPEC.md). Extend and version it only when implemented tools need
+> new vocabulary. Nothing enters a case without analyst confirmation.
-**Schema version: `1`** (what `case.json` carries as `{"azimut": {"schema": 1}}`;
-aligns with spec v0.2). Bump on any breaking change to entity/link shape; ship a
-migration when you do.
+**Storage schema: `3`.** The manifest carries `{"azimut": {"schema": 3,
+"storage": "sqlite"}}`; schema 3 moved the graph from `case.json` to per-case
+`case.db`. The entity/link shape is unchanged since v1. Breaking changes require
+a schema bump and migration.
Legend: ✅ implemented in code · 🔶 machinery exists, unused · ⬜ proposed.
@@ -15,20 +15,19 @@ Legend: ✅ implemented in code · 🔶 machinery exists, unused · ⬜ proposed
## 1. Where it lives
-`case.json` is the single source of truth for the graph:
+`case.db` (SQLite) is the source of truth for the graph; the storage boundary
+presents it as this logical shape:
```jsonc
{ "entities": [ … ], "links": [ … ], "folders": [ … ] }
```
-- **Entities** = the nodes (files, points, proofs, people…). ✅
-- **Links** = typed directed edges between nodes. ✅ (every save states what its
- output was made from; see §3.)
-- **Folders** = the analyst's own `/`-nested buckets (`attrs.folder`), an
- organisational overlay, **not** semantic links. ✅
-- Rich per-media metadata (kind, size, uploader, duration, thumbnail…) lives in a
- **media sidecar**, not on the entity — the entity carries only what the graph
- needs to point and dedupe.
+- **Entities** are nodes such as files, points, proofs and people. ✅
+- **Links** are typed directed edges. Every save records its inputs; see §3. ✅
+- **Folders** are `/`-nested analyst buckets in `attrs.folder`, not semantic
+ links. ✅
+- Media sidecars hold kind, size, uploader, duration and thumbnail data. Entities
+ retain only what the graph needs for identity, links and deduplication.
## 2. Entity
@@ -41,9 +40,8 @@ Legend: ✅ implemented in code · 🔶 machinery exists, unused · ⬜ proposed
"status": "confirmed", "source": "https://…" } }
```
-Rules: `type` is extensible — unknown strings are accepted and stored; the UI
-just doesn't get a custom renderer for them (SPEC §5 escape hatch, keep it).
-`label` is always editable and never load-bearing for identity.
+`type` is extensible: unknown strings are stored but receive no custom renderer.
+`label` is editable and never defines identity.
### Entity type registry
@@ -55,7 +53,7 @@ just doesn't get a custom renderer for them (SPEC §5 escape hatch, keep it).
| `proof` | ✅ | proof-composer | `spec` (json), `path` (png) | yes |
| `post` | ✅ | post-composer | `draft` (json) | yes |
| `inspect-session` | ✅ | inspect | `spec` (json) | yes |
-| `note` | ✅ | (manual) | free | no |
+| `note` | ✅ | notebook | `path`, `folder?` | yes (Markdown) |
| `person` | ⬜ | manual / future | name attrs | no |
| `organization` | ⬜ | manual / future | | no |
| `alias` / `account` | ⬜ | future orchestrator | `platform`, `handle`, `url` | no |
@@ -66,9 +64,8 @@ just doesn't get a custom renderer for them (SPEC §5 escape hatch, keep it).
New types coming from the roadmap (declare here when built): `panorama`,
`ground-image`, `map-board`, `report`.
-Per-type **attribute schemas** are the main open work: fix a controlled vocab of
-attr keys per type so tools read each other's output reliably. Today attrs are
-convention, not contract.
+Per-type attribute schemas remain open work. Today attribute keys are conventions,
+not a validated contract between tools.
## 3. Link
@@ -78,9 +75,8 @@ convention, not contract.
"provenance": { "by": "proof-composer", "at": "…", "status": "confirmed" } }
```
-Directed: read as **`from` → `type` → `to`**. Removing an entity drops every
-link touching it (`remove_entity`, ✅) — but *what* gets removed is decided
-first, by link type (see "Delete" below).
+Read a directed link as **`from` → `type` → `to`**. Removing an entity drops its
+incident links. The link type decides whether dependent entities also disappear.
### Link type registry (proposed core)
@@ -95,12 +91,11 @@ first, by link type (see "Delete" below).
| `posted` | account → media/post | authorship | ⬜ |
| `mentions` | media/note → any | referenced, weaker than depicts | ⬜ |
-### Delete: the policy is the link type, not the tool
+### Delete policy
-A new tool inherits the right behaviour by picking a link type, so this never
-needs re-deciding per tool. The test:
+A tool selects one of two deletion behaviours through its link type:
-> **Delete the target — is anything usable left in my file?**
+> **After deleting the target, is the holder still usable?**
> Yes → `derived-from`. No → `depends-on`.
| | `derived-from` | `depends-on` |
@@ -109,23 +104,21 @@ needs re-deciding per tool. The test:
| Holds | its own pixels/text | only a reference |
| Target deleted | **survives**, + tombstone | **deleted with it**, transitively |
-- **Never cascade into an output.** A post keeps its coordinates and text when
- its proof goes; a frame keeps its pixels when its video goes.
-- **Tombstone** = `attrs.lost_sources[]`, `{label, type, path, sha256,
- source_url, at}` — the sha256 and URL are what keep the loss auditable six
- months later. Keyed by path, never stacked. Additive: schema stays 0.
-- **One door.** Every delete (sidebar, Media Library, a tool's own list) routes
- through the chokepoint, so the rules cannot be sidestepped by where you click.
- The confirm dialog states both lists before the click.
-- A **secondary** reference never cascades: losing one collage piece leaves a
- placeholder, it does not void the session. Only the subject does.
+- `derived-from` never cascades into an output. A post keeps its text when its
+ proof is deleted; a frame keeps its pixels when its video is deleted.
+- `attrs.lost_sources[]` stores `{label, type, path, sha256, source_url, at}`.
+ Tombstones are keyed by path and never stacked.
+- Every UI deletion uses the same dependency-aware service. The confirmation
+ lists cascading deletions and surviving outputs before the action.
+- Losing a secondary source leaves a placeholder. Only losing the subject can
+ invalidate a dependent session.
-Free-typed labels stay allowed (SPEC §5) — the registry is the well-known set the
-UI understands, not a closed list.
+Free-typed labels remain valid. The registry defines what the UI understands,
+not a closed list.
### The derivation chain
-The chain, filed at save time — same click, no new ceremony (principle 3):
+The chain is filed with the save action:
```
post ──derived-from──▶ proof ──derived-from──▶ capture ──(provenance: provider,zoom,bearing)
@@ -138,10 +131,9 @@ How it is wired (`engine/links.py`):
- Sources are recorded as **case paths** (a proof's panels, a session's
`spec.source`, a derivative's sidecar `source.from`/`sources`); the link layer
resolves path → entity and emits the edge.
-- **Every save restates them** (`sync`): a panel dropped from a proof drops its
- edge, a proof saved three times still carries one edge per panel.
-- A path that resolves to nothing (its source was deleted while the tool was
- open) cannot be linked — it leaves a tombstone instead. Never lost in silence.
+- Every save restates sources through `sync`. Removing a panel removes its edge;
+ repeated saves keep one edge per panel.
+- A missing source path produces a tombstone instead of a link.
- Media derivatives are all filed through one registration point, so any future
tool producing imagery gets its chain for free. A derivative that **dedupes**
onto an existing entity still records its derivation: the same frame really
@@ -152,33 +144,31 @@ How it is wired (`engine/links.py`):
## 4. Provenance, confidence, identity
-- **Provenance** (on every entity *and* link): `by` (tool id — `media-library`,
- `satellite`, `proof-composer`, `post-composer`, `inspect`, or `manual`), `at`
- (UTC), `status`, optional `source` (a URL). Borrow the *shape* of W3C PROV
- (entity/activity/agent) conceptually — don't adopt the standard wholesale.
+- **Provenance** (on every entity and link): `by` (tool id: `media-library`,
+ `satellite`, `proof-composer`, `post-composer`, `inspect`, or `user`), `at`
+ (UTC), `status` and optional source URL. It borrows the entity/activity/agent
+ shape of W3C PROV without implementing the full standard.
- **Confidence** = `status`: `confirmed` (analyst-made or analyst-accepted) vs
`suggested` (a tool proposed it, awaiting a click). 🔶 `suggested` has no
- producer yet — the sidebar section and the PATCH validator exist, but no tool
- emits it until the v2 EXIF/OCR tools land. ✅ Binary on purpose —
- honest and simple; resist finer grading until a tool truly needs it.
+ producer yet. The sidebar and PATCH validator exist, but no tool emits it until
+ the v3 EXIF/OCR tools land. Keep the status binary until a real workflow needs
+ finer grading. ✅
**A derivation is `confirmed`**: `derived-from`/`depends-on` record what the
analyst's own click just made, not what a tool inferred. `suggested` is for
- inference — OCR reading a street name, EXIF proposing a `place` (see §5.2).
-- **`same-as` / merge** (⬜ open, SPEC §9): when two entities are one real thing,
+ inference, such as OCR reading a street name or EXIF proposing a `place`.
+- **`same-as` / merge** (⬜ open, SPEC §10): when two entities are one real thing,
link `same-as` rather than destructively merging; a resolver treats a `same-as`
- cluster as one node in views and unions their attrs/links. Keeps it reversible
- and auditable. Decide the collapse rules before the first orchestrator tool
- produces duplicate accounts.
+ cluster as one node in views and unions its attributes and links. Collapse rules
+ must be defined before an orchestrator creates duplicate accounts.
## 5. Design rules
-1. **Extensible core, not complete taxonomy.** Small well-known set + free-string
- escape hatch. Grow from real tool needs.
-2. **Nothing without a click.** Tools emit `suggested`; the analyst confirms
- (principle 5). Inferred links are `suggested` too — but a derivation filed at
- save time is `confirmed`: it states what the click did, it does not guess (§4).
+1. Keep a small known vocabulary and allow free-string extensions required by
+ implemented tools.
+2. Tools emit `suggested`; the analyst confirms. Derivations filed during save are
+ `confirmed` because they record the action rather than an inference.
3. **Two-way delete.** An artifact and its entity are one thing; deleting either
drops the other and its links (SPEC §6 delete/edit sync). What that takes
with it is the link type's call, never the tool's (§3).
-4. **Version the schema.** This file's version travels with `case.json`; a bump
- ships a migration. Do the formalisation now, while the corpus is tiny.
+4. Version graph-shape and storage-format changes in the case manifest and ship a
+ migration with each bump.
diff --git a/docs/SPEC.md b/docs/SPEC.md
index b072e6f..6cddaff 100644
--- a/docs/SPEC.md
+++ b/docs/SPEC.md
@@ -1,74 +1,68 @@
-# Azimut — the OSINT investigator's workbench
+# Azimut product overview
-> One case, one folder, every tool. Local-first: your media and your
-> investigations never leave your machine. Built for the open-source-investigation
-> community (GeoConfirmed contributors, journalists, researchers).
-
-Status: **spec v0.3** (2026-07-18). Reads top to bottom as: the story → what
-ships today (Done) → the roadmap (v2+) → loose ideas. Shipped-tool detail lives
-in code + tests; imagery in [IMAGERY_PROVIDERS.md](IMAGERY_PROVIDERS.md), UI in
-[UI.md](UI.md), entities in [ONTOLOGY.md](ONTOLOGY.md).
+Status: **spec v0.3** (2026-07-18). Read in order: Done → Roadmap → Loose ideas.
+Implementation detail belongs in code and tests; see
+[IMAGERY_PROVIDERS.md](IMAGERY_PROVIDERS.md), [UI.md](UI.md),
+[ONTOLOGY.md](ONTOLOGY.md) and
+[STORAGE_AND_PERFORMANCE.md](STORAGE_AND_PERFORMANCE.md).
---
-## 1. The story
-
-Azimut is **the desk where an OSINT investigation lives**. GEOINT (geolocation
-proofs) is the flagship pillar and the v1 focus, but media, people, places,
-timelines, evidence and reports all belong in the same case.
-
-> **Close Azimut. Reopen the case six months later. Everything is there:** the
-> media, the annotated proofs, the entities and their links, the timeline, the
-> notes, the exports — in one plain folder you can zip, git, or share.
+## 1. Product
-Every design decision is tested against that sentence. Today an investigation is
-scattered across 50 tabs, three folders, Obsidian, Draw.io, Google Earth and a
-notepad; Azimut bundles the daily gestures into one installable app and files
-their outputs into the case.
+Azimut is a local OSINT workspace. It keeps source media, geolocation work,
+proofs, notes and exports in one portable case folder.
## 2. Principles
-1. **Local-first, privacy-first.** No account, no telemetry, no upload. Network
- only when a tool inherently needs it (tiles, geocoding, download), always to
- third parties directly, never through an Azimut server. One exception: an
- opt-out check to GitHub's public releases feed on load, so binary users hear
- about updates (Settings → Updates turns it off).
-2. **The case is the product.** Tools are how you work; the case folder is what
- you keep — plain JSON + media, human-readable, versionable, portable.
-3. **One tab = one tool, useful in 30 seconds.** Every tool works one-shot with
- no case open (a silent scratch case, discardable or promotable).
-4. **Orchestrator, not replacer.** Azimut launches specialized services and files
- what the analyst picks as entities with provenance; it never clones them.
-5. **Tools emit facts, the analyst decides.** Tools suggest entities/links but
- nothing enters the case without a human click. No automated geolocation magic.
-6. **Honest, auditable output.** Every artifact records how it was produced;
- hints are labeled as hints.
-7. **Free and open source.** Free APIs and local computation only; user keys are
- optional extras (e.g. official Google imagery), never a requirement.
-8. **English UI**, international community.
+1. **Local-first.** No account, telemetry or upload. Network access follows a
+ network-dependent action, except for the optional startup release check.
+2. **Portable cases.** Files hold media, notes and proofs; per-case SQLite holds
+ the 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
+ scratch case.
+4. **Orchestration.** Specialized services stay external; selected results enter
+ the case with provenance.
+5. **Analyst control.** Tools may suggest entities or links, but only an analyst
+ action confirms them.
+6. **Auditable output.** Artifacts record how they were produced and label hints.
+7. **Free core.** Local computation and keyless services cover core workflows;
+ user-supplied keys add optional providers.
+8. **English interface.**
+
+Key constraints:
+
+- **Legal-only imagery.** Built-in providers are Esri, OSM, OpenTopoMap and
+ Sentinel-2. Keyed providers need the user's own key.
+ Unofficial key-less endpoints of keyed services (`mt1.google.com`) are never
+ shipped. Custom XYZ templates stay supported.
+- **Two-way delete/edit sync.** An artifact and its sidebar entity are one thing;
+ deleting either removes the other. One capture ⇄ one `capture` entity.
## 3. The case workspace
A directory per investigation (`~/Azimut/cases/<case>/` by default):
```
-case.json # metadata + entities + links (schema from v1)
+case.json # small manifest: name, dates, storage format + schema
+case.db # authoritative SQLite graph: entities, links, folders
notes.md # free-form case notes (markdown)
+notes/ # filed note bodies (Markdown)
media/ # source + captured + extracted media, with metadata + sha256
proofs/ # composed proofs: exported PNGs + editable JSON specs
exports/ # post drafts, reports, shared bundles
-evidence.jsonl # append-only journal (v3)
+evidence.jsonl # append-only journal (v4)
inspect/ # saved Inspect session specs
```
-Every tool reads and writes here. Plain files first; SQLite only for rebuildable
-indexes. One-shot mode = a scratch case in a temp/inbox location, same code path,
-promotable to a named case or reaped when idle.
+Tools use `CaseRepository` for structured state. Media, notes and proofs remain
+files. Legacy JSON graphs migrate to SQLite on open with a retained backup.
+One-shot work uses the same code path in a promotable scratch case.
-## 4. Data model — entities & links
+## 4. Data model
-The schema exists from **v1** so early tools file their outputs correctly and to
-avoid painful migrations. Full vocabulary in [ONTOLOGY.md](ONTOLOGY.md).
+The entity/link schema has existed since v1. Full vocabulary lives in
+[ONTOLOGY.md](ONTOLOGY.md).
- **Entity types** (extensible): person, organization, alias/username, account,
email, phone, domain, ip, vehicle, place, event, media, proof.
@@ -77,112 +71,90 @@ avoid painful migrations. Full vocabulary in [ONTOLOGY.md](ONTOLOGY.md).
- **Provenance on everything**: which tool/action, source, when, confidence
(`confirmed` by analyst vs `suggested` by a tool).
-Enrichment loop: a tool runs → suggests entities/links → the analyst confirms or
-dismisses → the case graph grows. UI progression: v1 a sidebar list; v3 adds the
-Relations, graph, map and timeline views.
+Tools suggest entities and links; analyst confirmation adds them to the graph.
+Relations, graph, map and timeline views are planned for v4.
---
-## 5. Done — v1 Proof Studio (shipped as GitHub `v0.1.0`)
+## 5. Done
-The end-to-end daily gesture, GeoConfirmed-style: media in → annotate the match →
-publish the proof. Milestones M0–M7 delivered it (AGPL-3.0, frontend bundled in
-the wheel, cross-platform binaries, tag-driven release CI).
+### v1 Proof Studio (shipped as GitHub `v0.1.0+`)
+
+The first complete workflow: collect media → annotate the match → prepare the
+proof for publication.
| Tool | What it does |
|------|--------------|
-| ✅ **Media Library** | Case media shelf. Import (drag & drop) or download by URL (yt-dlp + gallery-dl fallback + Telegram photo scraper) → clean file + metadata + sha256, each a `media` entity. Multi-attachment picker, facet bar (type/source + virtual folders), per-item notes, lightbox, provenance modal. |
-| ✅ **Inspect** | Scratch workspace over any photo/video, nothing saved until Save. Sharpest-frame scan, per-frame adjustments, view-only zoom/pan/rotate, editable crop, multi-piece warp collage with auto-stitch (planar/cylindrical/spherical), ELA hint, reopenable sessions. |
-| ✅ **Satellite** | Coordinate map over an XYZ tile abstraction. Save a `place` or capture a sourced crop (→ `capture`, filed in `media/`). Standard-size or marquee capture, resolution multiplier, marker styles, map rotation, move-pin, dual dates, measure, OSM overlay, reference windows, external-map links. |
-| ✅ **Proof Composer** | The v1 heart. Start a named proof with independent template and searchable case-panel selection. Multi-row grid or free layout; resize, tweet-crop guide, magic tweet-fit; editable shapes/freehand/text, per-color legend, captions, traced Coordinates + Source, signature. Export `proof.png` + re-editable JSON spec. |
-| ✅ **Post Composer** | GeoConfirmed thread from a proof: place + plus code, decimal coords, mention, source, optional media tweet, extra tweets, char counts. Save drafts, publish (opens X prefilled — never posts for you). |
-| ✅ **Case sidebar** | Resizable. Case notes, suggestions inbox, nested "My work" folders + Unfiled, a details/selection editor, two-way delete sync, and the case switcher (create/open/promote/rename/delete, unique names). |
-
-**Also shipped** (folded in from the old backlog): Sentinel-2 (user-keyed, layer
-picker + pass calendar), OpenTopoMap, OSM overlay, Google Maps JS basemap for the
-EEA, Esri overzoom, keyed Mapbox/Google with monthly usage counters + eco mode +
-cost controls, the capture browser extension, the settings tabs
-(Preferences/Imagery/About) + settings backup, scraper self-update, the launcher,
-server security hardening, and the two-regime dependency setup.
-
-**Shipped since** (first v2 tools landed on `main`):
+| ✅ **Media Library** | Imports or downloads case media with metadata, SHA-256, notes, provenance and multi-attachment selection. |
+| ✅ **Inspect** | Reviews images and video, including saved orientation (±90°/±180°), frame selection, adjustments, crops, collages, auto-stitch, ELA hints and sessions. |
+| ✅ **Satellite** | Saves places and attributed map captures with provider, date, rotation, measure and reference tools. |
+| ✅ **Geo Proof** | Composes templated grid or free-layout panels with annotations and exports a PNG with an editable spec. |
+| ✅ **Geo Report** | Prepares sourced proof threads and saved drafts without posting automatically. |
+| ✅ **Case sidebar** | Manages cases, notes, suggestions, folders, details and synchronized artifact deletion. |
+| ✅ **Imagery providers** | Supports Esri, OSM, OpenTopoMap, Sentinel-2 and optional Mapbox/Google with usage controls. |
+| ✅ **Capture extension** | Files user-initiated map screenshots with URL metadata, attribution and provenance. |
+| ✅ **Distribution** | Bundles the browser UI, launcher, cross-platform binaries, ffmpeg, locked builds and server hardening. |
+
+### v2 GEOINT suite (shipped as GitHub `v0.2.0+`)
| Tool | What it does |
|------|--------------|
-| ✅ **Coordinates** | Map-workspace tab: paste a point in any notation (decimal, DDM, DMS, UTM, MGRS, plus code, geohash) → read it back in every other with copy; the nine external-map links; opt-in Nominatim place name. |
-| ✅ **Reverse Search** | Collect-workspace launcher: pick a case image (or scrub a video to a frame), tweak brightness/contrast/saturation/grayscale → copy to the clipboard for Google Lens or save the PNG to drag into Yandex/Bing/TinEye, each opened key-less. Orchestrates, never queries itself. |
-| ✅ **Grid Search** | Satellite mode: overlay a custom metric grid on an area of interest — drag a box or draw a polygon, reshape either after the fact — and sweep it cell by cell. Fly-to-review with keyboard marks, cleared/flagged coverage; every action auto-saves. A case holds several named grids you switch between; promote a hit to a `place`. In-app only, no export. |
-| ✅ **Templates** | Reusable house styles, workspace-level: a proof style (background, panel margins, text sizes, footer, signature placement, preferred colours) and a post-thread skeleton (mention, which tweet-1 lines, media tweet, extra tweets). Built and edited in Settings → Templates, applied from the Proof/Post Composer. |
-| ✅ **Post outputs** | Prepare one thread for X, Bluesky or Mastodon, hand it to the selected composer, or copy a Markdown report. |
-
-**Key constraints** (carried forward):
+| ✅ **Coordinates** | Converts common coordinate formats, copies results and opens map or geocoding links. |
+| ✅ **Reverse Search** | Prepares image or video frames for keyless reverse-image services without uploading automatically. |
+| ✅ **Grid Search** | Saves editable AOI grids with keyboard review states and place promotion. |
+| ✅ **Templates** | Stores reusable proof styles and post-thread structures at workspace level. |
+| ✅ **Geo Report outputs** | Targets X, Bluesky or Mastodon and saves structured Markdown notes with evidence links. |
+| ✅ **Case Notebook** | Edits tabbed Markdown notes with local media, entity links, broken-reference markers and PDF output. |
+| ✅ **Canvas tests** | Exercises Leaflet and Konva interactions in Chromium and Firefox. |
+| ✅ **Storage platform** | Uses per-case SQLite, bounded catalog queries and a durable one-worker job queue. |
-- **Legal-only imagery**: built-in providers are Esri (default, key-less), OSM,
- OpenTopoMap and Sentinel-2 only. Keyed providers need the user's own key.
- Unofficial key-less endpoints of keyed services (`mt1.google.com`) are never
- shipped. Custom XYZ templates stay supported.
-- **Two-way delete/edit sync**: an artifact and its sidebar entity are one thing;
- deleting either removes the other. One capture ⇄ one `capture` entity.
-- **Frame-geolocator engine is not reused**; v1 is a fresh implementation.
---
## 6. Roadmap
-Each version must deliver **one complete workflow people use daily**, not a
-spread of half-tools. Ideas that firm up get promoted into these tables (§7);
-new tools land as tabs/modes inside an existing workspace (see [UI.md](UI.md)),
-never as new rail entries. Releases ship as GitHub `v0.x` tags.
+Each version delivers one complete daily workflow. Firm ideas move here from
+§7. New tools become tabs or modes in an existing workspace (see
+[UI.md](UI.md)). Releases ship as GitHub `v0.x` tags.
-### v2 — GEOINT suite
+### v3: GEOINT expansion
| Tool | What it does |
|------|--------------|
| **Satellite Compare** | Same coords across providers (Esri / Sentinel-2 date slider / Bing / keyed), synced pan/zoom. Copernicus easy link. |
-| **Image Compare** | Overlay two images with opacity/swipe + pixel diff. Sat-vs-screen alignment aid (assist, never a verdict). |
+| **Image Compare** | Overlay two images with opacity, swipe and pixel diff. Assist satellite-to-screen alignment without presenting a verdict. |
| **EXIF & Metadata** | GPS/timestamps/device/codecs parsed locally + a "what was stripped" hint; suggests place/event. |
-| **Shadow Clock** | Mark a shadow → possible capture times (sun-position math, local); sun times + solar azimuth readout at coords+date. Pairs with weather/METAR history. |
+| **Shadow Clock** | Mark a shadow to estimate possible capture times; show sun times and azimuth for a place and date; pair with weather/METAR history. |
| **OCR** | Read signs/plates (tesseract), detect script/language. |
-| **Audio Transcript** | Transcribe speech (Whisper) + acoustic context hints (bells/adhan/aircraft/language); auto-translate → English (offline). |
+| **Audio Transcript** | Transcribe and translate speech offline; flag acoustic context such as bells, adhan, aircraft or language. |
| **Ground Imagery** | Ground-level photos: Panoramax/Mapillary/KartaView key-less first; Street View easy link, optional keyed in-app view. |
| **Panorama** | Stitch a video window / frame set. Auto-stitch already in Inspect; still to do: sample a video window directly, seam blending. |
-| **Proof annotation** | Grow the Proof Composer toolbox: shape fill + dashed strokes, numbered markers, a redaction/blur box; a document-level free layer so shapes cross panels and reach the margins; callout / zoom insets. |
-| **Case Notebook** | A full notes page, not just raw `notes.md`: write, paste screenshots and images, embed links to places/entities; a writer pane + a reader pane. |
-
-Also toward v2: GIF maker, curated tools-links page, command palette (Ctrl+K),
-full-text case search, timezone + local-time readout at coords, clipboard
-capture (paste an image or a URL anywhere → filed as media with provenance),
-scale bar + north arrow + optional graticule burned into captures
-(preference-toggled auto-inclusion, extension/widget capture path included),
-read EXIF/GPS at media import → suggest place/time.
+| **Proof annotation** | Grow the Geo Proof toolbox: shape fill + dashed strokes, numbered markers, a redaction/blur box; a document-level free layer so shapes cross panels and reach the margins; callout / zoom insets. |
-Engineering toward v2: split Satellite and Proof Composer into focused modules;
-add Playwright coverage for canvas interactions that unit tests cannot exercise;
-follow the [case storage and performance migration](STORAGE_AND_PERFORMANCE.md)
-so large cases stay responsive on modest hardware.
+Toward v3: GIF maker; curated tool links; command palette (Ctrl+K); full-text
+case search; timezone and local time at coordinates; clipboard image/URL capture
+with provenance; preference-controlled scale bar, north arrow and graticule on
+app or extension captures; EXIF/GPS import suggestions for place and time.
-### v3 — investigation layer
+### v4: investigation layer
| Tool | What it does |
|------|--------------|
| **Case Board / Relations** | Browse/create/merge entities; typed links; graph/timeline/map views over the schema filling since v1. |
| **Map Board (MyMaps-style)** | Editable case map: custom pins + notes/links, shapes, layers; import/export KML/KMZ/GeoJSON; pins bind to `place`. |
-| **Evidence Locker** | Per-item sha256/timestamps/source/notes; Wayback archiving; exportable chain-of-custody (`evidence.jsonl`). |
+| **Evidence Locker** | Track SHA-256, timestamps, source and notes; archive with Wayback and export `evidence.jsonl`. |
| **Timeline Builder** | Timestamped events from mixed sources aligned on timeline + map. |
| **Report Builder** | Assemble proofs/maps/timeline/entities/notes into HTML/PDF. |
-Also toward v3: dependency-aware delete (partly done), downloader cookies,
-archive-on-download + archive time machine (Wayback CDX snapshot timeline +
-diff), web-page save extension, case bundle export/import, an editable/filterable
-places table (CSV/GeoJSON export), temporal change detection over imagery dates, a pattern-of-life map (a source's
-extractable locations on map + timeline), a full chronolocation solver
-(shadow + sun + weather → dated window), auto-hash + timestamp on every export
-(proof.png etc.) recorded in the evidence journal, cross-case global search (a
-handle/coordinate/face across all cases, distinct from the in-case full-text
-search), optional X/Twitter API key in Settings (with quota) to auto-publish
-Post Composer threads when enabled.
+Toward v4: dependency-aware delete (partly done); downloader cookies;
+archive-on-download and a Wayback CDX snapshot timeline with diff; web-page save
+extension; case bundle import/export; editable places table with CSV/GeoJSON;
+imagery-date change detection; source location pattern-of-life map and timeline;
+shadow/sun/weather chronolocation solver; journaled hashes and timestamps for
+every export; cross-case handle/coordinate/face search; optional quota-aware X
+publishing.
-### v4 — orchestration & advanced
+### v5: orchestration and advanced
| Tool | What it does |
|------|--------------|
@@ -192,48 +164,38 @@ Post Composer threads when enabled.
| **Camera Resection (GCP)** | Mark matching points photo↔map → solve camera position, viewing azimuth and rough FOV (OpenCV solvePnP); saves the match as evidence. Inverse of Viewshed. |
| **Map Measures** | Distance, bearing/azimuth, area, FOV cone; includes measure-on-imagery. |
| **Déjà Vu** | Perceptual-hash index flags recycled footage (local first; community index later). |
-| **Manipulation Hints** | ELA (in Inspect), JPEG quantization, noise, AI-media detector — all labeled as hints. |
+| **Manipulation Hints** | Add JPEG quantization, noise and AI-media hints alongside Inspect's ELA. |
| **Channel Monitor** | Watch Telegram channels, auto-archive media, queue for geolocation (rate limits, ToS care). |
-Also toward v4: skyline/horizon matching against a DEM (semi-auto geoloc from a
-terrain silhouette), photogrammetric measurement from a resected photo (real
-sizes via the GCP camera pose), road-topology search via Overpass (sketch a
-junction → candidate spots), satellite-pass finder (public TLEs → who imaged a
-place+time).
+Toward v5: DEM skyline matching from a terrain silhouette; real-world
+measurement from a resected photo and its GCP camera pose; Overpass road-topology
+search from a junction sketch; satellite-pass search from public TLEs.
### After the MapLibre migration
-Leaflet → MapLibre GL. **Phase 1** = 2D iso-functional parity (same providers and
-captures, zero 3D; existing capture tests stay green, asserting the captured
-pixels). **Phase 2** = pitch + terrain + oblique **3D capture**, pitch recorded in
-provenance alongside bearing. Then: 3D satellite capture, Google Photorealistic
-3D Tiles (user-keyed).
+Phase 1 replaces Leaflet with MapLibre GL at 2D feature parity, with no 3D and
+capture tests that verify the pixels. Phase 2 adds pitch, terrain and oblique 3D
+capture, with pitch and bearing in provenance. Later work covers 3D satellite
+capture and user-keyed Google Photorealistic 3D Tiles.
## 7. Loose ideas
-No version yet — one line each. Promote into a roadmap table when a workflow
-firms up; delete when it stops making sense.
+No version yet. Promote an idea when its workflow is clear; delete it when it
+stops making sense.
-- **Free-form montage editor** — likely unneeded once the free overlay layer
- lands; only with a crisp boundary vs Proof Composer + Inspect collage.
-- **In-app OSINT assistant** — a local-model assist layer, no API key and
- no-cloud by default: a chat panel (or opt-in bridge to the user's existing
- LLM chat session) plus a local vision model that *suggests* features/entities
- in a photo (signs, vehicles, landmarks, script) for the analyst to confirm.
-- _(add ideas here — keep them one-liners)_
+- **Free-form montage editor:** consider only if it stays distinct from Geo Proof and Inspect collage.
+- **In-app OSINT assistant:** local chat and vision suggestions for analyst confirmation, with no cloud or API key by default.
## 8. Explicit non-goals
- No cloud, accounts, hosted service, or telemetry.
-- No automated geolocation "magic button" — Azimut files facts, the analyst decides.
-- No rebuilding specialized OSINT services — orchestrate them (principle 4).
-- No block-evasion scraping; yt-dlp/gallery-dl as-is. Own session cookies = auth
- (in scope); third-party downloader proxies (ssstwitter & co) are out — they
- re-encode media and leak the target.
+- No automated geolocation verdict; Azimut files facts for the analyst.
+- No rebuilding specialized OSINT services; Azimut orchestrates them.
+- No block-evasion scraping. User session cookies are in scope; third-party
+ downloader proxies are not because they re-encode media and expose targets.
- No auto-posting by default. An optional, opt-in X/Twitter API key (Settings,
- like the imagery keys) may enable auto-publish from Post Composer, quota
- shown alongside it; Post Composer's default opens X prefilled and never
- posts on its own. No paid API dependency, ever, for core features.
+ with quota shown) may enable Geo Report publishing. Core features never
+ require a paid API.
## 9. Architecture
@@ -242,29 +204,36 @@ firms up; delete when it stops making sense.
- **Frontend**: Svelte + Leaflet (→ MapLibre) + Konva/canvas, served by the
backend, opened in the default browser. Rail = workspaces in pipeline order,
tools are tabs inside them (see [UI.md](UI.md)).
-- **Settings & secrets** ✅: in-app tabs (Preferences / Imagery / About), keys
+- **Settings and secrets:** in-app tabs (Preferences / Imagery / About), keys
stored locally and never bundled into a shared case, monthly usage counters,
backup export/import, opt-out "new release is live" pop-up on load (per-version
- "don't show again"). Display prefs are presentation only — artifacts keep
+ "don't show again"). Display preferences affect presentation only; artifacts keep
decimal degrees + metres on disk.
-- **Distribution** ✅: `pip install azimut` + PyInstaller single-file binaries
+- **Distribution:** `pip install azimut` plus PyInstaller single-file binaries
(Windows/Linux/macOS) that bundle a static ffmpeg/ffprobe (works out of the
box; pip installs still want ffmpeg on `PATH`) and carry the app icon on the
Windows `.exe`.
-- **Dependencies** ✅: ranges in `pyproject.toml`, exact pins in `uv.lock`; yt-dlp
+- **Dependencies:** ranges in `pyproject.toml`, exact pins in `uv.lock`; yt-dlp
+ gallery-dl unbounded on purpose; scraper self-update keeps an old binary useful.
-- **Storage**: plain files (§3); SQLite only for rebuildable caches.
-- **Security posture** ✅ (single-user localhost): `127.0.0.1` bind + Host/Origin
+- **Storage:** per-case SQLite `case.db` is the authoritative graph (files for
+ media/notes/proofs; a closed folder is a complete copy); legacy `case.json` cases migrate
+ on open; case open and lists use bounded, cursor-paged queries; thumbnails and
+ background work run through a durable, 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, 100 MP Pillow clamp, token-gated ingest
island for the extension. Accepted risks recorded here: cleartext keys over
localhost, the hash-verified scraper updater, and tile/media URL fetches (SSRF
only matters if the localhost assumption breaks). The startup update check is
- the one on-mount network call — opt-out, read-only against GitHub's releases
- feed, notes rendered as text (no HTML injection).
+ the one on-mount network call: opt-out and read-only against GitHub's releases
+ feed, notes rendered as text (no HTML injection). Remote images embedded in a
+ Notebook note contact their host whenever the preview opens; Notebook warns
+ about that behavior and local Case media avoids it.
## 10. Open questions
-- Entity attribute vocabularies, `same-as` merge semantics, confidence levels —
- freeze at v1 release.
-- Déjà Vu community index: needs infra + moderation, out of scope until v4.
+- Define entity attribute vocabularies, `same-as` merge semantics and confidence
+ levels before Relations ships.
+- Déjà Vu community index: needs infrastructure and moderation; out of scope
+ until v5.
- Name/handle availability: GitHub org/repo `azimut`, x.com handle, domain.
diff --git a/docs/STORAGE_AND_PERFORMANCE.md b/docs/STORAGE_AND_PERFORMANCE.md
index 67f9c1b..e11d1ba 100644
--- a/docs/STORAGE_AND_PERFORMANCE.md
+++ b/docs/STORAGE_AND_PERFORMANCE.md
@@ -1,70 +1,53 @@
-# Case storage and performance migration
+# Case storage and performance
-This document plans the move from a monolithic `case.json` to a per-case
-SQLite database. The goal is to keep every existing workflow intact while
-making large cases comfortable on modest computers.
+This document describes current case storage and the controls that keep large
+cases responsive. The migration from a monolithic `case.json` graph to per-case
+SQLite is complete.
-The migration changes structured case data only. Images, videos, proof PNGs,
-drafts and saved Inspect sessions remain ordinary files inside the case
-folder.
+Structured case data lives in SQLite. Images, videos, proof PNGs, drafts, saved
+Inspect sessions and note bodies remain ordinary files inside the case folder.
-## Goals
-
-- Open a case without loading its full catalog into Python or the browser.
-- Keep metadata edits fast as the number of entities and links grows.
-- Bound CPU and memory use during thumbnail generation and media analysis.
-- Preserve the current local-first, portable case folder.
-- Migrate old cases automatically without moving or rewriting their media.
-- Give future EXIF, OCR, transcript, timeline, map and evidence tools one
- durable storage and job model.
-- Keep unknown entity and link types readable so the ontology remains
- extensible.
-
-## Non-goals
-
-- Media bytes do not move into SQLite.
-- Migration does not change image or video codecs.
-- SQLite is not a reason to load every row and render every card at once.
-- This work does not add cloud storage, telemetry or background network calls.
-- The first migration does not need to implement every future entity
- attribute. It must leave room for versioned additions.
-
-## Target case layout
+## The shape of a case
```text
-case.json # small manifest: name, dates, format and compatibility
-case.db # entities, links, folders, catalog, jobs and events
-notes.md # current case notes; later indexed for Case Notebook
-media/ # imported, downloaded and derived media
+case.json # small manifest: name, dates, storage format and schema
+case.db # entities, links, folders, catalog and jobs (SQLite)
+notes.md # case-wide Markdown note
+notes/ # filed Markdown note bodies (one file per note entity)
+media/ # imported, downloaded and derived media + sidecars
+ .dl/ # in-progress downloads (transient)
+ .thumbs/ # disposable thumbnail cache
proofs/ # editable proof specs and rendered PNGs
-exports/ # post drafts, reports and case bundles
+exports/ # post drafts and reports
inspect/ # saved Inspect session specs
-.thumbs/ # disposable thumbnail cache
-evidence.jsonl # future portable evidence journal
+search/ # saved Grid Search state
```
-`case.json` remains the discovery manifest. It owns the case name, creation
-date and storage compatibility fields. It no longer contains the entity graph.
-Keeping this small file lets the case switcher identify a case without opening
-its database.
+`case.json` is the discovery manifest: name, creation date, and the storage and
+schema fields. It no longer holds the graph, so the case switcher can identify a
+case without opening its database. `case.db` is the source of truth for mutable
+structured state (entities, links, folders, jobs). The files under `media/`,
+`proofs/`, `exports/`, `inspect/` and `notes/` are the source of truth for their
+own content.
-`case.db` becomes the source of truth for mutable structured state. The files
-under `media/`, `proofs/`, `exports/` and `inspect/` remain the source of truth
-for their content.
+Every mutation used to re-read and rewrite the whole `case.json` under a per-case
+lock. At 10k entities that rewrote megabytes per edit and shipped the entire
+graph to the browser on open. SQLite removes both ceilings: a single edit touches
+one row in one short transaction, and case open ships a manifest instead of a
+graph.
-Media sidecars keep immutable acquisition and technical metadata that belongs
-with a file. Mutable catalog fields such as title, notes and folder move to
-the database. The migration imports existing values and the storage layer
-becomes the only code allowed to change them.
+## Source of truth
-This is a deliberate change to the current SPEC rule that limits SQLite to
-rebuildable caches. `docs/SPEC.md` and `docs/ONTOLOGY.md` must be updated in the
-implementation change that activates the new format.
+`case.db` owns the graph. Portability currently means copying the complete case
+folder while it is closed; rollback journaling leaves no WAL checkpoint outside
+that folder. Media, proofs and note bodies remain inspectable files. A future
+case ZIP workflow will package and import this same folder without creating a
+second writable copy.
## Ownership rules
-Each value has one owner. Cached copies may exist, but they must be disposable
-and carry enough information to detect when they are stale.
+Each value has one owner. Cached copies may exist, but they are disposable and
+carry enough information to detect staleness.
| Data | Owner | Notes |
|---|---|---|
@@ -74,304 +57,234 @@ and carry enough information to detect when they are stale.
| Image, video and audio bytes | Filesystem | Never stored as database blobs |
| Proof and session content | Their JSON/PNG files | Registered as artifacts in the database |
| Acquisition provenance | Media sidecar | Immutable after registration |
-| Search rows | SQLite index tables | Rebuildable from owned data |
-| Thumbnails | `.thumbs/` | Cache; safe to remove at any time |
-| Cross-case search | Workspace index | Rebuildable from each case |
-| Evidence export | `evidence.jsonl` | Produced from committed event records |
+| Background jobs | `case.db` (`jobs`) | Durable, recoverable, one worker |
+| Thumbnails | `media/.thumbs/` | Cache; safe to remove at any time |
+| Note bodies | `notes.md`, `notes/<id>.md` | Graph keeps only id, title, folder, path |
+
+## Packaging and frozen-binary constraints
+
+The same storage layer serves `pip install azimut` and PyInstaller binaries for
+Windows, macOS and Linux:
+
+- **No runtime dependency was added.** SQLite is the stdlib `sqlite3` module,
+ already bundled by PyInstaller; the durable queue and thumbnail worker use only
+ `threading`/`subprocess`/`sqlite3` plus the already-declared Pillow. The three
+ binaries build unchanged. `tests/test_release_gate.py` guards this.
+- **Feature availability is per-binary, not per-Python.** `sqlite3` links whatever
+ SQLite the build environment provides, so FTS5, JSON1 and RTree can be present
+ on the dev machine yet missing from a shipped binary. The store stays on core
+ SQL: `find_entity` scans and matches attributes in Python rather than relying on
+ JSON1. Any future indexed projection (geo, time, full-text) is probed at runtime
+ with a `LIKE`/scan fallback before it enters the contract.
+- **`case.db` lives under the workspace root**, inside the case folder, never
+ beside the frozen executable, which may sit on read-only media.
+- **Dev-only tooling stays out of the artifact.** The synthetic fixture
+ (`tests/bigcase.py`) and the benchmark harness (`bench/case_baseline.py`) live
+ outside `src/azimut/`, so hatchling never packages them, and use only the
+ standard library.
+
+## The storage boundary
+
+`repository.py` defines `CaseRepository`, the one interface every tool and route
+uses to read and mutate a case's graph, catalog and jobs. Nothing outside the
+implementation reaches into a raw `case.json` shape. `workspace.Case` is the
+filesystem shell (manifest, notes, media, lifecycle, path resolution) and
+delegates every graph, catalog and job method to a `SqliteCase`
+(`sqlite_backend.py`) over `case.db`. `engine/links.py` and `api/cases.py` read
+through `get_entity` / `links_of` / `snapshot`, never the file.
+
+`snapshot()` returns the whole graph for delete planning, export, migration checks
+and test assertions.
+`overview()` is the case-open view: the manifest and folder list, without the
+entity/link arrays. Direct storage access outside `Case`/`SqliteCase` should fail
+review.
## Database shape
-The first schema should stay small. New roadmap tools add migrations when they
-need new indexed concepts.
+`case.db` is at SQLite schema 3. The schema counter is independent of the JSON
+`CASE_SCHEMA`: the manifest's `azimut.storage` field selects the backend, and each
+format counts its own shape upgrades.
-### Core tables
+### Tables
`meta`
-: Database schema version, ontology version and creation information.
+: Schema version, case name and timestamps.
`schema_migrations`
-: Every applied migration, its version and completion time.
+: Every applied SQLite-schema migration and its completion time.
`entities`
-: `id`, `type`, `label`, `attrs_json`, provenance fields and status. Unknown
- types and attributes remain valid.
+: `id`, `type`, `label`, `attrs_json`, an indexed `folder` (denormalised from
+ `attrs.folder`), provenance fields and status. Unknown types and attributes stay
+ valid.
`links`
-: `id`, source entity, target entity, type, provenance fields and status.
- Foreign keys prevent links to missing entities. Delete policy remains in the
- existing dependency-aware service rather than in a blind SQL cascade.
+: `id`, source, target, `type`, provenance and status. Foreign keys forbid a link
+ to a missing entity. The delete policy lives in the dependency-aware service
+ (`engine/links.py`), not in a blind SQL cascade.
`folders`
-: Normalized logical paths for the analyst's organisation. These are not
- filesystem directories and are not semantic links.
-
-`artifacts`
-: Entity, safe relative path, media kind, MIME type, size, SHA-256 and source
- metadata needed by catalog queries. Paths are unique within a case.
+: Normalized `/`-separated logical paths for the analyst's organisation. Not
+ filesystem directories, not semantic links.
`jobs`
-: Durable local work such as thumbnails, EXIF extraction, OCR, transcription
- and video analysis. Stores state, progress, retry count and a short error.
-
-`events`
-: Committed case changes that can feed the future Evidence Locker and its
- `evidence.jsonl` export. An event identifier makes export idempotent.
+: Durable local background work: `id`, `kind`, an optional `job_key`, `state`,
+ `attempts`, `max_attempts`, `payload_json`, `error` and timestamps. See
+ "Thumbnails and background jobs".
-### Indexes
+### Indexes and migrations
-The initial schema needs indexes for:
+Indexes cover entity type/status/folder and link source/target/type, plus job
+state and a partial unique index on `(kind, job_key)` that keeps a keyed job from
+being enqueued twice. `SqliteCase.open` upgrades an older `case.db` in place
+through `_SQLITE_MIGRATIONS`, each step in its own immediate transaction, re-reading
+the version inside the transaction so a raced second opener applies nothing; a
+newer schema is refused rather than mangled. The two shipped migrations add the
+indexed `folder` column (1→2) and the `jobs` table (2→3).
-- entity type, status and creation time;
-- link source, target and type;
-- artifact path, hash and media kind;
-- folder path;
-- job state and requested time.
-
-Full-text search is added over labels, notes and selected metadata. Geographic
-and temporal projections should be added when the first map and timeline
-queries land. Generic attributes stay in JSON until a real workflow needs an
-indexed, typed field.
-
-Use the SQLite support shipped with Python. Any reliance on FTS5, JSON or RTree
-must be tested on the Windows, Linux and macOS release matrix before it becomes
-part of the storage contract.
+Geographic, temporal and full-text projections are deferred until a query needs
+them. Each projection requires its own migration and tests.
### Connection policy
-- Enable foreign keys on every connection.
-- Set a bounded busy timeout instead of failing immediately on a short write.
-- Keep transactions short. File hashing and ffmpeg work happen outside them.
-- Start with SQLite's rollback journal and `synchronous=FULL`. The app is
- single-user and portability matters more than speculative write concurrency.
-- Benchmark WAL before adopting it. If WAL is ever enabled, case close and
- export must checkpoint it so a copied case is complete.
-- Create live backups through SQLite's backup API. A manual folder copy is only
- guaranteed when the case is closed.
-- Apply restrictive file permissions through the existing workspace helpers.
-
-## Storage boundary before migration
-
-The first implementation step is not SQL. Introduce one repository boundary
-for every case operation:
-
-- read case summary;
-- list, get, add, update and remove entities;
-- list, add and remove links;
-- manage folders;
-- register and update artifacts;
-- resolve paths to entities;
-- plan and apply dependency-aware deletion;
-- enqueue and update local jobs.
-
-The API and tools call this boundary. They no longer read or rewrite
-`case.json` directly. A JSON-backed repository keeps the current behavior while
-the boundary is introduced. The SQLite implementation then replaces it without
-requiring every tool to change at once.
-
-Direct storage access should fail review after this phase. Tests may inspect
-fixtures and migration output, but production tools use the repository.
-
-## Automatic migration
-
-The conversion is one-way for normal use. A backup makes it recoverable, and
-the legacy importer remains available indefinitely.
-
-### Format versioning
-
-Storage format and ontology version become separate concepts. The new manifest
-must still carry a higher compatibility schema so an older Azimut refuses to
-open it instead of treating it as an empty case.
-
-The new application supports:
-
-- opening and migrating legacy JSON cases;
-- opening current SQLite cases;
-- refusing a database created by a newer unsupported schema;
-- importing a retained legacy backup for recovery.
-
-It does not dual-write JSON and SQLite in production. Dual writes create two
-authoritative copies and make crash recovery ambiguous.
-
-### Conversion sequence
-
-1. Acquire the existing per-case lock.
-2. Read and validate the legacy `case.json`.
-3. Check free disk space for the small database and its temporary copy.
-4. Create a uniquely named, versioned JSON backup without overwriting an older
- backup.
-5. Build `case.db.tmp` with the target schema.
-6. Import entities, links, folders and artifact references in one database
- transaction.
-7. Import mutable media fields from existing sidecars.
-8. Validate row counts, identifiers, relative paths and link endpoints.
-9. Run `foreign_key_check` and `integrity_check`.
-10. Commit and close the temporary database.
-11. Atomically rename the temporary database to `case.db`.
-12. Atomically replace `case.json` with the new manifest.
-13. Reopen the case through the normal SQLite repository and compare its
- summary with the migration report.
-
-The manifest changes last. A crash before that point leaves the legacy case as
-the active format. A complete but unreferenced temporary database can be
-validated and reused or safely replaced on the next attempt.
-
-Do not rehash every large video during migration. Import the recorded hash,
-verify file existence and offer a separate integrity scan. Forced rehashing
-would make the first launch unexpectedly expensive on a slow disk.
-
-### Migration validation
-
-The migration report records:
-
-- entity, link and folder counts;
-- artifact and sidecar counts;
-- missing files and unresolved paths;
-- duplicate identifiers or paths;
-- links whose endpoints are missing;
-- database integrity results.
-
-Missing media is reported but does not erase its entity or provenance. Existing
-dependency and tombstone rules remain in force.
-
-If validation fails, the manifest is not changed. The user sees a short error
-with the recovery location, and the legacy case remains available.
-
-## API and frontend migration
-
-SQLite only helps the interface when queries and rendering are bounded.
-
-### Compatibility pass
-
-First, keep current API responses unchanged and run them against both storage
-implementations. This isolates storage regressions from UI changes.
-
-### Bounded catalog API
-
-Add cursor-based endpoints for entities, media and links with:
-
-- stable ordering;
-- a default and maximum page size;
-- type, folder, status and date filters;
-- server-side search;
-- summary counts returned separately;
-- direct lookup by identifier.
-
-Cursor pagination avoids shifting pages when an import adds a new item. Offset
-pagination is acceptable only for small, static lists.
-
-Once every consumer has moved, the case-open response stops embedding the full
-entity and link arrays. It returns the manifest, counts and the first data
-needed by the active view.
-
-### Bounded rendering
-
-- Fetch the first page only when a tool becomes visible.
-- Keep a small in-memory cache keyed by entity identifier.
-- Load more rows as the user approaches the end of the visible list.
-- Limit mounted media cards. Add simple windowing if progressive pages still
- leave too many DOM nodes.
-- Preserve selection by identifier, not by list position.
-- Run filters and full-text search in the backend.
-- Cancel stale requests when the user changes case or query.
-
-This work must not introduce a frontend dependency unless it has compatible
-prebuilt support requirements and earns its maintenance cost. A small local
-list window is preferable if it covers the current layouts.
-
-## Thumbnail and background-job model
-
-Thumbnails are disposable. A broken thumbnail must never block access to the
-original file.
-
-### Cache identity
-
-A thumbnail key includes:
-
-- original artifact identifier and SHA-256;
-- requested size or variant;
-- thumbnail generator version.
-
-Changing the original file or generator therefore schedules a new result
-instead of serving stale pixels.
-
-### Job states
-
-Use at least `queued`, `running`, `ready`, `failed` and `cancelled`. A job also
-stores attempts, timestamps, progress where available and a short diagnostic.
-On startup, an interrupted `running` job returns to `queued` or `failed`
-according to its retry policy.
-
-### Generation rules
-
-- Generate visible and newly imported items first. Do not rebuild the entire
- case during open.
-- Default to one CPU-heavy worker on modest hardware. A preference may allow
- more, but foreground interaction keeps priority.
-- Bound ffmpeg execution time and remove partial output after failure.
-- Decode images through the existing pixel clamp.
-- Write to a unique temporary file, validate the result, then rename it into
- `.thumbs/` atomically.
-- Store a concise error and retry with a limit. Never loop forever.
-- Provide a manual regenerate action for one item or the whole cache.
-- Apply a configurable cache-size budget and evict least-recently-used results.
- Eviction never touches originals or database records.
-
-### UI failure behavior
-
-- Use lazy image loading and asynchronous browser decoding.
-- Show a type-specific placeholder while queued or after failure.
-- A failed `<img>` request switches to the placeholder and reports the stale
- cache entry once. It does not retry on every render.
-- Keep title, provenance and actions usable without a thumbnail.
-- Expose retry without turning a technical failure into a blocking dialog.
-
-The same durable queue later runs EXIF parsing, OCR, transcripts, perceptual
-hashes and other local analysis. Each job begins only after a user action that
-requires it; opening a tab does not create network work.
+- Foreign keys on every connection; a bounded `busy_timeout` instead of failing a
+ short write immediately.
+- Transactions are short. File hashing and ffmpeg work happen outside them.
+- Rollback journal with `synchronous=FULL` (not WAL): the app is single-user and
+ portability matters more than write concurrency, so a plain folder copy of a
+ closed case is always complete with nothing to checkpoint.
+- A fresh connection per operation, closed before any rename, so Windows' rules
+ for open files and directory replacement are respected. Writes run in one
+ `BEGIN IMMEDIATE`..`COMMIT` and roll back on error.
+
+## Automatic migration of legacy cases
+
+Legacy json cases still open. `Case.open` runs `migrate`: it applies the json-shape
+migrations up to `JSON_SCHEMA`, materializes any inline note bodies to files, then
+`convert_json_to_sqlite` builds `case.db` and the manifest is flipped to
+`{"schema": 3, "storage": "sqlite"}` **last**. A crash before the flip leaves the
+legacy json case active. A `case.pre-migrate-v<n>.json` backup is taken once before
+the first rewrite and never overwritten, so the conversion is recoverable.
+
+The converter builds `case.db.tmp`, imports the whole graph in one transaction,
+runs `foreign_key_check` and `integrity_check`, then atomically renames into place;
+any failure removes the temp file and leaves the target untouched. A link to a
+missing endpoint is reported (`MigrationReport.missing_endpoints`) and dropped,
+never erasing an entity. Recorded media hashes are imported as-is; migration does
+not rehash large videos; an integrity scan is a separate, explicit action.
+
+The live in-file JSON graph backend has been removed. `Case.create` always makes a
+`case.db`; no code path writes an entity/link graph back into `case.json`. The only
+JSON code left is the one-way importer and the on-open migration.
+
+## Bounded catalog API
+
+SQLite only helps the interface when queries and rendering are bounded. Case open
+ships `overview()` (manifest + folders), and the catalog loads through cursor-paged
+endpoints:
+
+- `GET /api/cases/{id}/catalog/entities` returns `{items, next_cursor}` in stable
+ insertion order, with a clamped page size and server-side filters: a
+ comma-separated `type` set, `status`, a label substring `q`, and folder
+ (`unfiled=true` or an exact `folder` path). The cursor keys on `rowid`, so a
+ background import appending rows never shifts a page already scrolled past, and a
+ deletion before the cursor never skips a live row.
+- `GET /api/cases/{id}/catalog/summary` returns `{total, by_type, by_status,
+ by_folder}` without shipping the graph.
+- `GET /api/cases/{id}/entities/{id}/chain` (neighbour derivation),
+ `GET /entities/lookup` (one entity by attribute), and
+ `GET /entities/{id}/derivation` (transitive `derived-from` closure) are the
+ bounded single-entity reads, each built on `links_of` rather than the whole
+ graph.
+
+The sidebar pages the catalog through `buildCatalogQuery` and uses a generation
+guard, so a stale page never lands after a case or filter switch.
+`fetchAllEntities` walks the pages server-side for the whole-slice cases and
+accepts an `AbortController` signal; `lookupEntity` and `fetchDerivation` cover
+the single-entity and closure cases. These helpers live in
+`frontend/src/lib/catalog.js`. The sidebar, `Files`, `Notebook`, `Satellite`,
+`Media Library`, `Inspector` and the composers use them; none loads
+`caseState.current.entities`/`.links`, which no longer exist on the case-open
+response.
+
+Deferred to their first consumer: date filters (a timeline filter), links
+pagination (a relations/graph view), and notes/label full-text search (gated on
+per-binary FTS5).
+
+## Thumbnails and background jobs
+
+Thumbnails are disposable pixels: a broken or missing one never blocks access to
+the original. `engine/thumbnails.py` owns their whole lifecycle, and the durable
+`jobs` table is the general background-work model behind it (EXIF, OCR and
+transcripts will reuse it).
+
+### Cache identity, atomic generation
+
+A thumbnail's file name folds in the original's SHA-256 and the generator version
+(`THUMB_GEN`): `media/.thumbs/<sha[:24]>-g<gen>.jpg`. A changed original or a
+bumped generator therefore maps to a *new* file rather than serving stale pixels;
+the superseded ones become orphans that `repair` sweeps. Pixels are rendered to a
+unique temp file, validated, then renamed into `.thumbs/`. Readers never see a
+half-written thumbnail, and the Windows rename rules hold. Images decode through
+the process-wide Pillow pixel clamp.
+
+### Inline for cheap, queued for heavy
+
+A registered image gets its thumbnail rendered inline with Pillow. Videos use the
+CPU-heavy ffmpeg path and are queued, as are images whose inline render fails.
+Jobs are keyed on media path, so retrying or regenerating does not stack duplicates.
+
+### One worker, recoverable
+
+A single background worker drains thumbnail jobs, so only one ffmpeg process runs
+at a time.
+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 is
+gone). 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.
+
+### Budget, repair, retry states
+
+`prune_cache` evicts least-recently-used thumbnails (by mtime) past a size budget;
+`repair` removes abandoned temp files and orphaned thumbnails no live sidecar
+references. Both only ever touch the cache, never originals or database rows. A
+content-addressed thumbnail can be shared by identical-bytes captures, so deleting
+one media file drops the cached thumbnail only when no surviving sidecar still
+points at it.
+
+The media listing tags each item with a `thumb_state` (`ready`, `queued`,
+`running`, `failed`, or `none`). The Media Library renders the image when ready
+(lazy-loaded, async-decoded, with an `onerror` fallback to the type icon that
+reports once and does not retry per render), a "Generating…" placeholder while
+queued, and a retry affordance on failure. `POST
+/api/cases/{id}/media/thumbnails/regenerate` re-queues one item (the per-card
+retry) or every missing/failed one; the grid polls the listing while anything is
+pending, and stops on its own once nothing is.
## Filesystem and database consistency
-SQLite cannot atomically commit a filesystem rename. File-backed operations
-therefore follow a recoverable sequence.
-
-For creation:
-
-1. Produce the file under a unique temporary name.
-2. Validate and hash it.
-3. Rename it to its final path.
-4. Register it in a short database transaction.
-5. Reconciliation removes abandoned temporary files and registers or reports
- untracked final files according to the operation journal.
-
-For deletion, first rename the file into a case-local trash/staging directory,
-then commit the database deletion, then remove it. A crash leaves a recoverable
-staged file. This also follows Windows rules for open files and directory
-replacement.
-
-An inexpensive reconciliation pass checks pending operations when a case
-opens. Full hashing and media probing stay behind an explicit integrity scan.
-
-## Performance budgets
-
-Performance work needs a repeatable fixture and a reference machine. Use a
-modest profile such as four logical CPU cores, 8 GB of RAM, integrated graphics
-and a SATA-class drive. Keep the exact machine and software versions in the
-benchmark report.
+SQLite cannot atomically commit a filesystem rename, so file-backed operations are
+recoverable. Creation produces a file under a unique temp name, validates it,
+renames it to its final path, then registers it in a short transaction. Deletion
+removes the file and sidecar, then settles the database. Thumbnail generation
+follows the same temp-then-rename discipline. The rollback journal means a copied
+closed case is always complete.
-The initial large-case fixture should contain:
+## Performance
-- 10,000 entities;
-- 20,000 links;
-- 5,000 registered media items and sidecars;
-- nested folders, notes, suggestions and unknown entity types;
-- ready, missing, corrupt and failed thumbnails;
-- proof, post and Inspect artifacts;
-- missing source files and dependency tombstones.
+The reference profile for absolute timings is a modest machine (four logical
+cores, 8 GB RAM, integrated graphics, SATA-class drive); the exact machine and
+versions belong in the benchmark report. The large-case fixture
+(`tests/bigcase.py` `build_big_case`, driven by `bench/case_baseline.py`, standard
+library only, outside the wheel) builds 10k entities / 20k links / 5k media with
+nested folders, notes, suggestions, unknown types, mixed thumbnail states, proof/
+post/Inspect artifacts, missing files and tombstones. It writes `case.json` in one
+pass (the per-item path is the O(n²) cost being measured) and is seeded, so the
+same arguments produce byte-identical rows.
-Large binaries can be sparse fixtures or small synthetic files. Separate
-benchmarks cover real image decoding and video thumbnail extraction.
-
-Initial interaction targets on the reference machine:
+Interaction budgets on the reference machine:
| Operation | Target |
|---|---:|
@@ -382,154 +295,68 @@ Initial interaction targets on the reference machine:
| Mounted catalog rows/cards | 300 or fewer |
| Default CPU-heavy background jobs | 1 at a time |
-These are starting budgets, not release claims. Record the current JSON
-baseline first, calibrate the reference device, then make regressions fail CI
-using stable relative thresholds. Absolute timings remain a manual release
-check because shared CI hardware varies.
-
-Also track peak backend memory, browser memory, query count, long browser tasks
-and thumbnail queue depth. Memory use for the first page must not grow linearly
-with the total case catalog.
-
-## Test plan
-
-### Characterization
-
-Pin current behavior before changing storage:
-
-- case creation, rename, promotion and deletion;
-- entity and link CRUD;
-- unknown entity and link types;
-- folders and unfiled items;
-- suggested and confirmed status;
-- media import, download, deduplication and sidecars;
-- proof, post and Inspect save/reopen;
-- dependency-aware delete and tombstones;
-- concurrent media registration;
-- notes and provenance updates.
-
-### Migration fixtures
-
-Keep small legacy cases in the test suite with Unicode, unusual paths, absent
-optional fields, unknown types, missing files and valid derivation chains.
-Compare their public API results before and after migration.
-
-Test failure after every conversion stage. Reopening must either finish the
-migration or leave the JSON case untouched. It must never expose a half-filled
-database as current.
-
-### Database behavior
-
-- constraints and foreign keys;
-- rollback on failed writes;
-- concurrent readers and short writers;
-- unsupported newer schema refusal;
-- sequential schema upgrades;
-- backup and restore;
-- corruption detection;
-- cross-platform path handling and permissions.
-
-### Frontend and load tests
-
-- first-page rendering without a full-case fetch;
-- pagination stability while imports arrive;
-- selection across page loads;
-- fast case switching with stale-request cancellation;
-- broken and missing thumbnail fallbacks;
-- bounded DOM and memory use;
-- no network request merely from opening a case or tab.
-
-Run the backend suite on Python 3.11 and the three release operating systems.
-Run frontend unit tests, checks, the production build and targeted Playwright
-coverage for scrolling, selection and thumbnail failure.
+These are starting budgets, not release claims: absolute timings are a manual
+release check because shared CI hardware varies, while relative regressions can be
+made to fail CI against a recorded baseline.
+
+### Captured baselines (fast dev machine, not the reference profile)
+
+Read the shape, not the absolute milliseconds. At the default size (10k / 20k /
+5k), the old monolithic `case.json` was **8.4 MB** and case open shipped **~6 MB**
+of graph to the browser; every single mutation was **~244 ms** because it
+read-modify-wrote the whole file (linear in case size). On the SQLite backend a
+single `add_entity` is **~5.5 ms** (one durable row, roughly flat with case size),
+a `get_entity` is a **0.15 ms** indexed read, and converting a 5k-entity case runs
+once in **~233 ms**. Case open no longer ships the graph at all. The
+reference-machine capture remains a manual release step.
+
+## How it is verified
+
+- **Graph contract** (`tests/test_repository.py`): entity/link/folder CRUD,
+ dedupe, `sync_links` id preservation, folder subtree removal, cursor paging and
+ summaries, the derivation closure, and the durable job queue (idempotent
+ enqueue, claim, retry-then-fail, recover, prune) held against `Case`
+ (SQLite-backed).
+- **Store specifics** (`tests/test_sqlite_backend.py`): create/open, newer-schema
+ refusal, foreign keys, rollback, the in-place schema upgrade through every
+ migration, keyset paging, and the atomic converter (roundtrip, dangling-link
+ report, failure leaves no db, large-case integrity).
+- **Migration** (`tests/test_migrations.py`): legacy json → sqlite on open, backup
+ recoverability, a failed activation leaving the json case usable, forward-compat
+ refusal.
+- **Thumbnails and jobs** (`tests/test_thumbnails.py`, `tests/test_media_api.py`):
+ inline vs queued, atomic generation with no partial/temp on failure, content-key
+ by generator version, drain + retry-then-fail, cancel on missing media, LRU
+ budget eviction, orphan/temp repair, shared-thumbnail delete safety, the
+ background worker, startup recovery, and the `thumb_state` + regenerate API.
+- **Release gate** (`tests/test_release_gate.py`): a legacy case migrates and every
+ workflow answers, a closed-case folder copy opens identically, a large migrated
+ case opens through bounded queries, and the frozen-binary packaging constraints
+ hold.
+- **Frontend** (vitest + svelte-check + the production build): first-page paging,
+ request cancellation on case switch, and the thumbnail placeholder/failure/retry
+ markup.
+
+The backend suite runs on Python 3.11 and the three release operating systems.
+
+## Manual release steps
+
+Two parts of the release gate are inherently manual and are done at release time,
+not in CI:
+
+- Record the reference-machine numbers (the profile above) and calibrate the
+ relative CI thresholds against them.
+- Migrate several disposable real-world case copies end to end and confirm every
+ workflow before tagging.
## Roadmap compatibility
-The storage work is successful only if later tools reuse it.
-
-| Roadmap work | Storage support |
-|---|---|
-| EXIF and metadata | Local jobs emit suggested place/event entities |
-| OCR and transcript | Durable jobs, text artifacts and full-text index |
-| Case Notebook | File-backed content with indexed text and entity references |
-| Case Board / Relations | Indexed entities, typed links and reversible `same-as` |
-| Map Board | Place entities plus indexed geographic projections |
-| Timeline Builder | Event entities plus indexed time projections |
-| Evidence Locker | Committed events exported idempotently to `evidence.jsonl` |
-| Report Builder | Stable artifact identifiers and derivation links |
-| Cross-case search | Rebuildable workspace index over closed case summaries |
-| Search Orchestrator | Durable jobs and analyst-confirmed suggestions |
-| Déjà Vu | Perceptual hashes indexed without loading media bytes |
-| Channel Monitor | Bounded persistent queue with explicit network actions |
-
-Do not pre-build all of these tables now. Add typed projections when the first
-real query needs them, with a schema migration and tests. The core identifiers,
-provenance and link rules must remain stable.
-
-## Delivery sequence
-
-### 1. Baseline and contract
-
-- Add the large synthetic fixture and benchmark commands.
-- Capture current JSON timings and memory.
-- Finalize ownership and compatibility fields.
-- Add characterization tests where behavior is not already pinned.
-
-### 2. Repository boundary
-
-- Add the storage interface and JSON implementation.
-- Move all case graph and catalog access behind it.
-- Keep API responses and frontend behavior unchanged.
-
-### 3. SQLite implementation
-
-- Add schema creation, migrations, indexes and backup helpers.
-- Run the same repository contract tests against JSON and SQLite.
-- Add the converter and crash/failure tests.
-
-### 4. Safe activation
-
-- Enable migration on case open.
-- Keep the legacy importer and JSON backup.
-- Update SPEC, ONTOLOGY, UI documentation and case-tree examples.
-- Verify Windows, Linux, macOS and Python 3.11.
-
-### 5. Bounded loading
-
-- Add paginated endpoints and server-side filters.
-- Change frontend stores to summary plus page caches.
-- Add progressive loading, request cancellation and DOM bounds.
-
-### 6. Job and thumbnail hardening
-
-- Add the durable queue and one-worker default.
-- Make thumbnail generation lazy, atomic and recoverable.
-- Add cache budgeting, repair and visible retry states.
-
-### 7. Release gate
-
-- Run functional, migration, load and packaging tests.
-- Test copies, backups and case bundles.
-- Migrate several disposable real-world case copies.
-- Record the reference-machine results.
-- Ship only when the new format matches all current workflows and meets the
- agreed performance budgets.
-
-The legacy importer is permanent. The JSON writer can be removed after the
-SQLite release is stable, but opening an untouched old case must continue to
-work.
-
-## Completion criteria
-
-The migration is complete when:
-
-- existing cases migrate automatically with a retained backup;
-- no production tool reads or writes the old graph arrays directly;
-- all current workflows pass unchanged;
-- older applications refuse the new format safely;
-- a failed migration leaves the original case usable;
-- case opening and lists use bounded queries and bounded rendering;
-- thumbnail failures never block media access;
-- the large-case fixture meets the reference performance budgets;
-- the documented v2, v3 and v4 workflows fit the storage, job and event model;
-- the full frontend and backend validation paths pass on supported platforms.
+Later tools reuse this storage, job and event model rather than inventing their
+own: EXIF/OCR/transcript jobs on the durable queue with text artifacts and a
+future full-text index; the Notebook's file-backed content with indexed text and
+entity references; Board/Relations over indexed entities and typed links; Map and
+Timeline over geographic and temporal projections added when their first query
+lands; the Evidence Locker exporting committed events idempotently to
+`evidence.jsonl`; cross-case search over a rebuildable workspace index. New typed
+projections arrive with their own migration and tests; the core identifiers,
+provenance and link rules stay stable.
diff --git a/docs/UI.md b/docs/UI.md
index f12b745..e77e11e 100644
--- a/docs/UI.md
+++ b/docs/UI.md
@@ -1,8 +1,7 @@
-# Azimut — UI & UX reference
+# Azimut UI and UX reference
-How the interface is organized (UX) and styled (UI). This is the contract new
-tools and future works follow — not a roadmap. Feature phasing lives in
-[SPEC.md](SPEC.md).
+This document defines the interface structure and visual language. Feature
+phasing lives in [SPEC.md](SPEC.md).
## Layout anatomy
@@ -15,72 +14,86 @@ tools and future works follow — not a roadmap. Feature phasing lives in
## Workspace model (UX)
-The rail holds a **fixed set of activity workspaces in investigation-pipeline
-order**. Tools are tabs inside a workspace — **a new tool never adds a rail
-entry**; it registers in `frontend/src/lib/workspaces.js`.
+The rail holds a fixed set of workspaces in investigation order. Tools register
+in `frontend/src/lib/workspaces.js` and appear as tabs, never as new rail entries.
| Workspace | Tools today | Future tools land here |
|---|---|---|
-| **Collect** | Media Library, Files, Reverse Search | Channel Monitor, Evidence Locker |
+| **Sources** | Media Library, Files, Reverse Search | Channel Monitor, Evidence Locker |
| **Examine** | Inspect (Selection / Frame / Collage / Analyze) | EXIF, OCR, Image Compare, Hints, Shadow Clock, audio |
| **Map** | Satellite, Coordinates | **one map, many modes**: Compare, Ground Imagery, Measures, Viewshed, OSM Query, Map Board |
-| **Compose** | Proof Composer, Post Composer | Report Builder, GIF maker |
-| *(Case)* | — sidebar covers it | v3: Notes, Relations, Timeline, Orchestrator |
+| **Compose** | Geo Proof, Geo Report, Notebook | Report Builder, GIF maker |
+| *(Case)* | Sidebar | v4: Notes, Relations, Timeline; v5: Orchestrator |
Rules:
-- **Max two levels** (workspace → tab), preserving SPEC principle 3.
-- **`uiState.tool` is the single source of truth**; the active workspace is
- derived from it, so cross-tool handoffs (`uiState.tool = 'proof'`) never
- care about workspaces. Clicking a workspace returns to its last-used tab.
-- **Deep links**: `#<tool>` (stable), `#<workspace>`, `#<workspace>/<tool>`.
-- **Navigation follows the object too**: from any artifact — open in tool,
- locate on map, add to proof. The rail is for starting; objects continue.
+- Use at most two levels: workspace → tab.
+- `uiState.tool` is authoritative. The active workspace is derived from it, so
+ cross-tool handoffs do not need workspace logic. Each workspace remembers its
+ last-used tab.
+- Deep links use `#<tool>`, `#<workspace>` or `#<workspace>/<tool>`.
+- Artifact actions can open a tool, locate a place or add an item to a proof.
- Settings is app plumbing: behind the topbar gear, not on the rail.
## Case sidebar
-Four sections; tools list (and delete) their own saved artifacts via their
-Open lists / shelves — the sidebar never duplicates a by-tool listing.
-Its left edge is a drag handle (240–640 px, capped at half the window;
-double-click resets, width persists).
-
-- **Case Notes** — `notes.md`.
-- **Suggestions** — tool-suggested entities; confirm or dismiss (only shown
- when non-empty).
-- **My work** — every saved artifact: the analyst's nested folders (the only
- user-owned taxonomy) plus an **Unfiled** inbox for the rest. File by
- dragging a row onto a folder or from the details panel (folder field).
- Unfiling deletes nothing. The **Files** tab (Collect) opens this same tree
- as a desktop surface — small tiles, rubber-band select, drag several at once,
- right-click a file or folder for Move to Unfiled / Delete.
-- **Details** — selection editor for any artifact: preview, title/notes,
- provenance (created by/at, source), the derivation chain (made-from /
- used-by), My-work folder, open-in-tool / open-file / go-to-coords, Delete
- everywhere (danger confirm). One shared body (`EntityDetails.svelte`) — the
- sidebar panel and the Media Library's info modal render the same editor.
+The sidebar has four sections. Tools keep their own saved-artifact lists; the
+sidebar does not duplicate them. Its left edge resizes from 240 to 640 px, capped
+at half the window. Double-click resets the persisted width.
+
+The sidebar defaults to collapsed in Map and open elsewhere. Open state is
+remembered per workspace for the current session. Reloading restores the defaults.
+
+- **Case Notes** opens `notes.md` in the Notebook. Filed notes open there too.
+- **Suggestions** lists tool-proposed entities for confirmation or dismissal and
+ stays hidden when empty.
+- **My work** contains nested analyst folders and an **Unfiled** inbox. Rows can
+ be filed by drag-and-drop or through Details. Unfiling does not delete data.
+ The **Files** tab presents the same tree with tiles, multi-select and context
+ actions.
+- **Details** edits an artifact's preview, title, notes, provenance, derivation
+ chain and folder. It also provides open, locate and delete actions. The sidebar
+ and Media Library modal share `EntityDetails.svelte`.
+
+## Notebook
+
+The Notebook places a GitHub-flavored Markdown editor beside its preview. The
+resizable split is stored locally, and Preview-only hides the editor. A note
+with a remote inline image warns that its host is contacted on every open;
+adding the image to the Case keeps it local. Markdown
+help covers supported syntax, image layout and aligned text. The Preview toolbar
+opens an A4 print view that keeps local images and omits remote media.
+
+Case Notes stays pinned while filed notes open in session tabs. Paste, drop or
+pick case media to insert it; the reference menu links case entities. Deleted
+references remain as broken markers. External captures and bookmarks open their
+source page. Internal captures restore their Satellite view and provider. A saved
+Geo Report exposes an `OPEN` action for its new note.
## Visual language (UI)
-Tokens live in `frontend/src/app.css`; components never hardcode colors.
-Reference points: QGIS, Google Earth Pro, Resolve, Lightroom — dense, flat,
-sober instruments.
+Tokens live in `frontend/src/app.css`. The interface follows the dense, flat
+instrument style of QGIS, Google Earth Pro, Resolve and Lightroom.
-- **Type**: one workhorse font (system stack); mono for data (coords, hashes,
- dates); few weights; uppercase micro-labels only as panel-section headers.
+- **Type**: system font for interface copy, monospace for coordinates, hashes and
+ dates, and uppercase micro-labels only for panel sections.
- **Palette**: neutral gray darks (`--bg-0…3`), white-alpha borders, muted
- status colors. **One accent (azimuth amber), three roles only**: the single
- primary action per view, selection (picker borders, focus rings), and 2px
- active-edge indicators on rail/tabs. Never as a background wash, never as
- decoration, no glows.
+ status colors. Azimuth amber is reserved for the primary action, selection and
+ 2 px active-edge indicators. It is not a decorative background or glow.
+- **Theme**: dark by default, with a light daylight palette toggled from the
+ foot of the rail. Both are the same tokens: `:root` holds dark, a
+ `:root[data-theme='light']` block flips the colour tokens, and `lib/theme.js`
+ stamps `data-theme` on `<html>` (remembered in `localStorage`, applied in
+ `index.html` before first paint). The amber accent and the annotation palette
+ stay fixed across themes. Surfaces over imagery remain dark through
+ `.dark-surface`. New chrome must use tokens; hardcoded light colours are limited
+ to text on dark image scrims.
- **Shape**: radii 3/4/6px, flat panels with 1px borders, rectangular badges.
- **Motion**: none. Color-only transitions ≤0.15s; no entrance animations,
no hover lifts. Transient functional feedback (locate-flash) is the one
exception.
-- **Copy**: no slogans or self-explanation in chrome; empty states are one
- short sentence; **no em-dashes in visible UI strings** (use `·`, `:`, or a
- period; hover tooltips are tolerated); "(one-shot mode)" style parentheses
- over dash suffixes.
+- **Copy**: no slogans or self-explanation in chrome. Empty states use one short
+ sentence. Visible UI strings use `·`, `:` or a period instead of em dashes.
- **Brand**: compass rose (`Logo.svelte`) + vector wordmark
(`Wordmark.svelte`), both extracted from
`frontend/src/assets/logo-source.svg`; favicon derives from the same rose.
@@ -88,9 +101,8 @@ sober instruments.
## Adding a tool (checklist for future work)
-1. Add the component under `frontend/src/tools/`, register it in
- `App.svelte`'s `TOOLS` and in its workspace's `tools` array
- (`lib/workspaces.js`) — rail and deep links follow automatically.
+1. Add the component under `frontend/src/tools/`. Register it in `App.svelte`
+ and the workspace's `tools` array in `lib/workspaces.js`.
2. Consume tokens and shared primitives (`.btn`, `.input`, `.card`,
`.tool-header`); respect the accent roles above.
3. The tool owns its artifacts: list, reopen and delete them in-tool; file
diff --git a/extension/background.js b/extension/background.js
index 271a047..75290ef 100644
--- a/extension/background.js
+++ b/extension/background.js
@@ -48,7 +48,7 @@ async function cropDataUrl(dataUrl, rect, viewportW) {
/** File one screenshot with the backend (POST /api/ingest/screenshot). */
async function ingest(blob, meta) {
const { backendUrl, token } = await settings();
- if (!token) throw new Error("not paired — open the extension options and paste the token from Azimut Settings");
+ if (!token) throw new Error("not paired. Open the extension options and paste the token from Azimut Settings");
// Thin on purpose: image + URL is a complete capture — the app parses the
// URL itself (site, coordinates, title, imagery date). Everything else here
// is either the user's popup corrections or plain context.
@@ -70,9 +70,9 @@ async function ingest(blob, meta) {
body: form,
});
} catch {
- throw new Error(`Azimut is not reachable at ${backendUrl} — is the app running?`);
+ throw new Error(`Azimut is not reachable at ${backendUrl}. Is the app running?`);
}
- if (r.status === 401) throw new Error("pairing token rejected — re-pair in the extension options");
+ if (r.status === 401) throw new Error("pairing token rejected. Pair again in the extension options");
if (!r.ok) throw new Error(`Azimut refused the capture (${r.status}): ${(await r.text()).slice(0, 200)}`);
const body = await r.json();
// Remember where this capture landed — including a freshly minted scratch
diff --git a/extension/options.html b/extension/options.html
index 52f4855..45c5dec 100644
--- a/extension/options.html
+++ b/extension/options.html
@@ -9,7 +9,7 @@
<p class="muted">
In Azimut open <strong>Settings → Capture extension</strong>, copy the
pairing token, and paste it here. The token only lets this extension file
- captures into your local Azimut — nothing leaves your machine.
+ captures into your local Azimut. Nothing leaves your machine.
</p>
<div class="row">
<label for="backendUrl">Azimut URL</label>
diff --git a/extension/options.js b/extension/options.js
index 9ba2498..c6efe05 100644
--- a/extension/options.js
+++ b/extension/options.js
@@ -27,13 +27,13 @@ async function init() {
headers: { "X-Azimut-Token": token },
});
if (r.status === 401) {
- status("Azimut answered but rejected the token — copy it again from Settings.", "error");
+ status("Azimut answered but rejected the token. Copy it again from Settings.", "error");
return;
}
const body = await r.json();
- status(`Paired with Azimut ${body.version} — you're set.`, "ok");
+ status(`Paired with Azimut ${body.version}.`, "ok");
} catch {
- status(`No Azimut at ${backendUrl} — is the app running?`, "error");
+ status(`No Azimut at ${backendUrl}. Is the app running?`, "error");
}
});
}
diff --git a/extension/overlay.js b/extension/overlay.js
index f422d1f..744491f 100644
--- a/extension/overlay.js
+++ b/extension/overlay.js
@@ -21,7 +21,7 @@
"position:fixed;display:none;border:1.5px dashed #e8a33d;background:rgba(232,163,61,0.10);" +
"box-shadow:0 0 0 100vmax rgba(10,10,10,0.35);pointer-events:none";
const hint = document.createElement("div");
- hint.textContent = "Drag to select the area to capture — Esc to cancel";
+ hint.textContent = "Drag to select the capture area. Press Esc to cancel";
hint.style.cssText =
"position:fixed;top:14px;left:50%;transform:translateX(-50%);padding:6px 12px;" +
"background:#141414;color:#e6e6e6;font:13px system-ui,sans-serif;border-radius:6px;" +
diff --git a/extension/popup.html b/extension/popup.html
index 52f678d..34cf840 100644
--- a/extension/popup.html
+++ b/extension/popup.html
@@ -13,7 +13,7 @@
<!-- one of these three states shows at a time -->
<section id="state-nomap" hidden>
- <p>Not a map site — no screenshot here.</p>
+ <p>This is not a supported map site.</p>
<p class="muted">
Screen capture is maps only (Google Maps/Earth, Bing, Yandex, OSM, Apple
Maps, Zoom Earth, Copernicus). You can still file this page as a bookmark:
@@ -33,11 +33,11 @@
</section>
<section id="state-azimut" hidden>
- <p>This is Azimut itself — you're set. Use the app's own <strong>Capture</strong> button.</p>
+ <p>This is Azimut. Use the app's own <strong>Capture</strong> button.</p>
<p class="muted">
Opening this popup granted the capture permission for this tab (browsers
require one click on the extension before it may screenshot a tab). It
- lasts until the tab is closed — you won't need to come back here.
+ lasts until the tab is closed. You will not need to return here.
</p>
</section>
@@ -61,7 +61,7 @@
<input id="title" type="text" placeholder="optional" />
</div>
<p id="coords-note" class="muted" hidden>
- No coordinates in this URL — the capture files without them (fixable later
+ No coordinates were found in this URL. The capture is filed without them and can be fixed later
in Azimut's sidebar).
</p>
<div class="actions">
diff --git a/extension/popup.js b/extension/popup.js
index 49a3ecd..c573058 100644
--- a/extension/popup.js
+++ b/extension/popup.js
@@ -46,11 +46,11 @@ async function loadCases(select, stored) {
if (r.status === 401) throw new Error("unpaired");
cases = await r.json();
} catch (e) {
- select.replaceChildren(new Option("Azimut unreachable — check options", ""));
+ select.replaceChildren(new Option("Azimut unreachable. Check options", ""));
status(
e.message === "unpaired"
? "Not paired: open the extension options and paste the token from Azimut Settings."
- : `Cannot reach Azimut at ${backendUrl} — is the app running?`,
+ : `Cannot reach Azimut at ${backendUrl}. Is the app running?`,
"error"
);
return false;
@@ -109,7 +109,7 @@ async function init() {
}
parsed = await r.json();
} catch {
- status(`Cannot reach Azimut at ${stored.backendUrl} — is the app running?`, "error");
+ status(`Cannot reach Azimut at ${stored.backendUrl}. Is the app running?`, "error");
return;
}
@@ -160,7 +160,7 @@ async function init() {
if (!paired) return;
// half a coordinate would 422 server-side; catch it where it's fixable
if ((numOrNull("lat") === null) !== (numOrNull("lon") === null)) {
- status("Latitude and longitude go together — fill both or neither.", "error");
+ status("Latitude and longitude go together. Fill both or neither.", "error");
return;
}
const r = await api.runtime.sendMessage({
diff --git a/frontend/e2e/app.fixture.js b/frontend/e2e/app.fixture.js
new file mode 100644
index 0000000..2244735
--- /dev/null
+++ b/frontend/e2e/app.fixture.js
@@ -0,0 +1,179 @@
+import { expect } from '@playwright/test';
+
+export const CASE_ID = 'browser-test';
+export const PANEL_PATH = 'media/panel.svg';
+
+const PANEL_SVG = `
+ <svg xmlns="http://www.w3.org/2000/svg" width="640" height="360">
+ <rect width="640" height="360" fill="#304b65"/>
+ <path d="M0 300L180 150L300 250L450 90L640 280V360H0Z" fill="#6c8f55"/>
+ <circle cx="520" cy="76" r="34" fill="#f4c95d"/>
+ </svg>`;
+
+const TILE_SVG = `
+ <svg xmlns="http://www.w3.org/2000/svg" width="256" height="256">
+ <rect width="256" height="256" fill="#243747"/>
+ <path d="M0 190L70 120L140 175L210 80L256 140V256H0Z" fill="#4f7047"/>
+ </svg>`;
+
+const media = [{
+ path: PANEL_PATH,
+ filename: 'panel.svg',
+ kind: 'image',
+ width: 640,
+ height: 360,
+ source: { type: 'upload' },
+ thumbnail: null,
+ folder: '',
+ notes: '',
+}];
+
+const caseOverview = {
+ id: CASE_ID,
+ name: 'Browser Test',
+ scratch: false,
+ entities: [],
+ links: [],
+ folders: [],
+};
+
+const settings = {
+ coord_format: 'dd',
+ units: 'metric',
+ home_view: { lat: 48.8584, lon: 2.2945, zoom: 16 },
+ post_mention: '@GeoConfirmed',
+ post_target: 'x',
+ signature_handle: '',
+ update_check_on_start: false,
+ update_dismissed_version: '',
+ usage: {},
+ usage_overrides: {},
+ eco_zoom_fallback: true,
+ eco_max_zoom: 15,
+ free_tier: {},
+ month: '2026-07',
+};
+
+const providers = [{
+ id: 'esri-world-imagery',
+ label: 'Esri World Imagery',
+ url: 'https://tiles.invalid/{z}/{x}/{y}.png',
+ attribution: 'Browser fixture',
+ max_zoom: 19,
+ tile_size: 256,
+ oversample: 1,
+ imagery: true,
+ capturable: true,
+}];
+
+function json(route, body, status = 200) {
+ return route.fulfill({ status, contentType: 'application/json', body: JSON.stringify(body) });
+}
+
+/**
+ * Run the real Svelte, Konva and Leaflet code while replacing only Azimut's
+ * local API and files with deterministic fixtures. Any unexpected request is
+ * recorded so a passing interaction test cannot silently depend on the network.
+ */
+export async function installAppFixture(page) {
+ const unexpected = [];
+ const captures = [];
+ const proofSaves = [];
+
+ await page.addInitScript((caseId) => {
+ localStorage.setItem('azimut:lastCase', caseId);
+ localStorage.setItem('azimut:theme', 'dark');
+ }, CASE_ID);
+
+ await page.route('**/*', async (route) => {
+ const request = route.request();
+ const url = new URL(request.url());
+ const path = url.pathname;
+
+ if (url.hostname !== '127.0.0.1') {
+ unexpected.push(`${request.method()} ${request.url()}`);
+ return route.abort('blockedbyclient');
+ }
+
+ if (path.startsWith('/@') || path.startsWith('/src/') || path.startsWith('/node_modules/') ||
+ path === '/' || path === '/index.html' || path === '/favicon.svg') {
+ return route.continue();
+ }
+
+ if (path === `/files/${CASE_ID}/${PANEL_PATH}`) {
+ return route.fulfill({ contentType: 'image/svg+xml', body: PANEL_SVG });
+ }
+ if (path.startsWith('/api/tiles/')) {
+ return route.fulfill({ contentType: 'image/svg+xml', body: TILE_SVG });
+ }
+ if (path === '/api/events') {
+ return route.fulfill({ contentType: 'text/event-stream', body: '' });
+ }
+ if (path === '/api/settings/signature.png') {
+ return route.fulfill({ status: 404, body: '' });
+ }
+ if (path === '/api/settings') return json(route, settings);
+ if (path === '/api/templates') return json(route, { proof: [], post: [] });
+ if (path === '/api/cases') return json(route, [{ ...caseOverview, entity_count: 1 }]);
+ if (path === `/api/cases/${CASE_ID}`) return json(route, caseOverview);
+ if (path === `/api/cases/${CASE_ID}/media`) return json(route, media);
+ if (path === `/api/cases/${CASE_ID}/satellite`) return json(route, []);
+ if (path === `/api/cases/${CASE_ID}/notes`) return json(route, { text: '' });
+ if (path === `/api/cases/${CASE_ID}/catalog/summary`) {
+ return json(route, { total: 1, by_type: { media: 1 }, by_status: { confirmed: 1 }, by_folder: {} });
+ }
+ if (path === `/api/cases/${CASE_ID}/catalog/entities`) {
+ return json(route, { items: [], next_cursor: null });
+ }
+ if (path === `/api/cases/${CASE_ID}/entities/lookup`) {
+ return json(route, { entity: null });
+ }
+ if (path === '/api/satellite/providers') return json(route, providers);
+ if (path === `/api/cases/${CASE_ID}/search-grids`) return json(route, []);
+ if (path === '/api/satellite/imagery-date') {
+ return json(route, { supported: false, date: null, source: null });
+ }
+ if (path === `/api/cases/${CASE_ID}/satellite/capture` && request.method() === 'POST') {
+ const payload = request.postDataJSON();
+ captures.push(payload);
+ return json(route, {
+ path: `media/capture-${captures.length}.png`,
+ title: `Capture ${captures.length}`,
+ ...payload,
+ provider_label: 'Esri World Imagery',
+ attribution: 'Browser fixture',
+ fetched_at: '2026-07-21T00:00:00Z',
+ tiles_missing: 0,
+ tiles_upscaled: 0,
+ });
+ }
+ if (path === `/api/cases/${CASE_ID}/proofs` && request.method() === 'POST') {
+ const payload = request.postDataJSON();
+ proofSaves.push(payload);
+ return json(route, { name: 'browser-proof', png: 'proofs/browser-proof.png' });
+ }
+
+ unexpected.push(`${request.method()} ${path}`);
+ return json(route, { detail: `Unhandled browser fixture request: ${path}` }, 404);
+ });
+
+ return {
+ captures,
+ proofSaves,
+ expectNoUnexpectedRequests: () => expect(unexpected).toEqual([]),
+ };
+}
+
+export async function openProofWithPanel(page) {
+ await page.goto('/#proof');
+ await expect(page.getByRole('heading', { name: 'Geo Proof' })).toBeVisible();
+ await page.getByRole('button', { name: 'New proof' }).first().click();
+ await expect(page.getByRole('heading', { name: 'Create proof' })).toBeVisible();
+ await page.locator('.selectable-pick').click();
+ await page.getByRole('button', { name: 'Create proof' }).click();
+ await expect(page.locator('.konva canvas')).toHaveCount(2);
+ await expect(page.locator('.panel-row')).toHaveCount(1);
+ await page.evaluate(() => new Promise((resolve) => {
+ requestAnimationFrame(() => requestAnimationFrame(resolve));
+ }));
+}
diff --git a/frontend/e2e/proof-canvas.spec.js b/frontend/e2e/proof-canvas.spec.js
new file mode 100644
index 0000000..c6630f7
--- /dev/null
+++ b/frontend/e2e/proof-canvas.spec.js
@@ -0,0 +1,63 @@
+import { test, expect } from '@playwright/test';
+import { installAppFixture, openProofWithPanel } from './app.fixture.js';
+
+test('a real Konva panel remains interactive after click and drag', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await openProofWithPanel(page);
+
+ const canvas = page.locator('.konva canvas').first();
+ const box = await canvas.boundingBox();
+ expect(box).not.toBeNull();
+ // The stage fills the full tool height while the fitted 16:9 panel sits near
+ // its top. Use a point well inside that image, away from its footer.
+ const x = box.x + box.width / 2;
+ const y = box.y + Math.min(180, box.height / 3);
+
+ await page.mouse.click(x, y);
+ await expect(page.locator('.panel-row')).toHaveClass(/selected/);
+
+ await page.getByTitle('Free layout: drag panels anywhere').click();
+ // Changing layout intentionally clears selection. The first click above
+ // covers the canvas selection regression; use the deterministic side control
+ // to select the panel for the separate free-layout drag assertion.
+ await page.evaluate(() => new Promise((resolve) => {
+ requestAnimationFrame(() => requestAnimationFrame(resolve));
+ }));
+ await page.locator('.panel-thumb').click();
+ await expect(page.locator('.panel-row')).toHaveClass(/selected/);
+ await page.mouse.move(x, y);
+ await page.mouse.down();
+ await page.mouse.move(x + 45, y + 28, { steps: 6 });
+ await page.mouse.up();
+
+ await page.getByRole('button', { name: 'Save', exact: true }).click();
+ await expect.poll(() => fixture.proofSaves.length).toBe(1);
+ const savedPanel = fixture.proofSaves[0].spec.panels[0];
+ expect(Number.isFinite(savedPanel.x)).toBe(true);
+ expect(Number.isFinite(savedPanel.y)).toBe(true);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('draws a real Konva annotation and round-trips undo and redo', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await openProofWithPanel(page);
+
+ const canvas = page.locator('.konva canvas').first();
+ const box = await canvas.boundingBox();
+ expect(box).not.toBeNull();
+ const x = box.x + box.width / 2 - 40;
+ const y = box.y + box.height / 2 - 25;
+
+ await page.getByTitle('Box (r)').click();
+ await page.mouse.move(x, y);
+ await page.mouse.down();
+ await page.mouse.move(x + 90, y + 65, { steps: 6 });
+ await page.mouse.up();
+ await expect(page.locator('.shape-row')).toHaveCount(1);
+
+ await page.getByTitle('Undo (Ctrl+Z)').click();
+ await expect(page.locator('.shape-row')).toHaveCount(0);
+ await page.getByTitle('Redo (Ctrl+Shift+Z / Ctrl+Y)').click();
+ await expect(page.locator('.shape-row')).toHaveCount(1);
+ fixture.expectNoUnexpectedRequests();
+});
diff --git a/frontend/e2e/satellite-canvas.spec.js b/frontend/e2e/satellite-canvas.spec.js
new file mode 100644
index 0000000..c23533b
--- /dev/null
+++ b/frontend/e2e/satellite-canvas.spec.js
@@ -0,0 +1,77 @@
+import { test, expect } from '@playwright/test';
+import { installAppFixture } from './app.fixture.js';
+
+test('opens Map with the case sidebar collapsed and lets the user reopen it', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await page.goto('/#satellite');
+ await expect(page.locator('.map')).toHaveClass(/leaflet-container/);
+
+ await expect(page.locator('.sidebar')).toHaveCount(0);
+ await page.getByTitle('Toggle case sidebar').click();
+ await expect(page.locator('.sidebar')).toBeVisible();
+
+ await page.getByRole('button', { name: 'Examine', exact: true }).click();
+ await expect(page.locator('.sidebar')).toBeVisible();
+ await page.getByTitle('Toggle case sidebar').click();
+ await expect(page.locator('.sidebar')).toHaveCount(0);
+
+ await page.getByRole('button', { name: 'Map', exact: true }).click();
+ await expect(page.locator('.sidebar')).toBeVisible();
+ await page.getByTitle('Toggle case sidebar').click();
+ await expect(page.locator('.sidebar')).toHaveCount(0);
+
+ await page.getByRole('button', { name: 'Examine', exact: true }).click();
+ await expect(page.locator('.sidebar')).toHaveCount(0);
+
+ await page.getByRole('button', { name: 'Map', exact: true }).click();
+ await expect(page.locator('.sidebar')).toHaveCount(0);
+ await page.getByTitle('Toggle case sidebar').click();
+ await expect(page.locator('.sidebar')).toBeVisible();
+ await page.reload();
+ await expect(page.locator('.map')).toHaveClass(/leaflet-container/);
+ await expect(page.locator('.sidebar')).toHaveCount(0);
+
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('rotates the real Leaflet map with a middle-button gesture', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await page.goto('/#satellite');
+ const map = page.locator('.map');
+ await expect(map).toHaveClass(/leaflet-container/);
+ const box = await map.boundingBox();
+ expect(box).not.toBeNull();
+
+ const x = box.x + box.width / 2;
+ const y = box.y + box.height / 2;
+ await page.mouse.move(x, y);
+ await page.mouse.down({ button: 'middle' });
+ await page.mouse.move(x + 100, y + 55, { steps: 8 });
+ await page.mouse.up({ button: 'middle' });
+
+ await expect(page.locator('.deg')).not.toHaveText('0°');
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('captures a marquee drawn on the real Leaflet surface', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await page.goto('/#satellite');
+ const map = page.locator('.map');
+ await expect(map).toHaveClass(/leaflet-container/);
+
+ await page.getByRole('button', { name: 'Capture options' }).click();
+ await page.getByRole('button', { name: 'Select area', exact: true }).click();
+ await page.locator('.capture-main').click();
+
+ const box = await map.boundingBox();
+ expect(box).not.toBeNull();
+ await page.mouse.move(box.x + 120, box.y + 110);
+ await page.mouse.down();
+ await page.mouse.move(box.x + 330, box.y + 250, { steps: 8 });
+ await page.mouse.up();
+
+ await expect.poll(() => fixture.captures.length).toBe(1);
+ expect(fixture.captures[0].width).toBeGreaterThan(150);
+ expect(fixture.captures[0].height).toBeGreaterThan(100);
+ fixture.expectNoUnexpectedRequests();
+});
diff --git a/frontend/index.html b/frontend/index.html
index 77adc9d..bb596b9 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -5,6 +5,16 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Azimut</title>
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <script>
+ // Stamp the saved theme before first paint so light-mode users never see
+ // a dark flash. Mirrors lib/theme.js; dark is the default.
+ try {
+ var t = localStorage.getItem('azimut:theme');
+ document.documentElement.dataset.theme = t === 'light' ? 'light' : 'dark';
+ } catch (e) {
+ document.documentElement.dataset.theme = 'dark';
+ }
+ </script>
</head>
<body>
<div id="app"></div>
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index f20a756..be2685c 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -9,12 +9,15 @@
"version": "0.1.2",
"dependencies": {
"@fontsource/oxanium": "^5.2.8",
+ "dompurify": "^3.4.12",
"konva": "^9.3.0",
"leaflet": "^1.9.4",
"leaflet-rotate": "^0.2.8",
- "leaflet.gridlayer.googlemutant": "^0.16.0"
+ "leaflet.gridlayer.googlemutant": "^0.16.0",
+ "marked": "^17.0.6"
},
"devDependencies": {
+ "@playwright/test": "^1.61.1",
"@sveltejs/vite-plugin-svelte": "^7.2.0",
"happy-dom": "^20.10.6",
"svelte": "^5.0.0",
@@ -146,6 +149,22 @@
"url": "https://github.com/sponsors/Boshen"
}
},
+ "node_modules/@playwright/test": {
+ "version": "1.61.1",
+ "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.61.1.tgz",
+ "integrity": "sha512-8nKv6+0RJSL9FE4jYOEGXnPeM/Hg12qZpmqzZjRh3qM0Y7c3z1mrOTfFLids72RDQYVh9WpLEfR5WdpNX4fkig==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "playwright": "1.61.1"
+ },
+ "bin": {
+ "playwright": "cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/@rolldown/binding-android-arm64": {
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.1.5.tgz",
@@ -507,7 +526,7 @@
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
"integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
- "dev": true,
+ "devOptional": true,
"license": "MIT"
},
"node_modules/@types/whatwg-mimetype": {
@@ -766,6 +785,15 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/dompurify": {
+ "version": "3.4.12",
+ "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.12.tgz",
+ "integrity": "sha512-zQvGet8Z2sWbQhCmfFz/T5QWH2oBmjnqK3qvOjaqaNLrLEF912WamU+ohnTp0TCep/MFVHpdJuCZEdFOdTnEFg==",
+ "license": "(MPL-2.0 OR Apache-2.0)",
+ "optionalDependencies": {
+ "@types/trusted-types": "^2.0.7"
+ }
+ },
"node_modules/entities": {
"version": "7.0.1",
"resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",
@@ -1212,6 +1240,18 @@
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
+ "node_modules/marked": {
+ "version": "17.0.6",
+ "resolved": "https://registry.npmjs.org/marked/-/marked-17.0.6.tgz",
+ "integrity": "sha512-gB0gkNafnonOw0obSTEGZTT86IuhILt2Wfx0mWH/1Au83kybTayroZ/V6nS25mN7u8ASy+5fMhgB3XPNrOZdmA==",
+ "license": "MIT",
+ "bin": {
+ "marked": "bin/marked.js"
+ },
+ "engines": {
+ "node": ">= 20"
+ }
+ },
"node_modules/mri": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz",
@@ -1282,6 +1322,53 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
+ "node_modules/playwright": {
+ "version": "1.61.1",
+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.61.1.tgz",
+ "integrity": "sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "playwright-core": "1.61.1"
+ },
+ "bin": {
+ "playwright": "cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "fsevents": "2.3.2"
+ }
+ },
+ "node_modules/playwright-core": {
+ "version": "1.61.1",
+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.61.1.tgz",
+ "integrity": "sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "playwright-core": "cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/playwright/node_modules/fsevents": {
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
+ "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
"node_modules/postcss": {
"version": "8.5.16",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.16.tgz",
diff --git a/frontend/package.json b/frontend/package.json
index 9c483ba..a751045 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -8,9 +8,12 @@
"build": "vite build",
"preview": "vite preview",
"test": "vitest run",
- "check": "svelte-check --output human --threshold error"
+ "test:e2e": "playwright test",
+ "test:e2e:headed": "playwright test --headed",
+ "check": "svelte-check --output human --threshold warning"
},
"devDependencies": {
+ "@playwright/test": "^1.61.1",
"@sveltejs/vite-plugin-svelte": "^7.2.0",
"happy-dom": "^20.10.6",
"svelte": "^5.0.0",
@@ -21,9 +24,11 @@
},
"dependencies": {
"@fontsource/oxanium": "^5.2.8",
+ "dompurify": "^3.4.12",
"konva": "^9.3.0",
"leaflet": "^1.9.4",
"leaflet-rotate": "^0.2.8",
- "leaflet.gridlayer.googlemutant": "^0.16.0"
+ "leaflet.gridlayer.googlemutant": "^0.16.0",
+ "marked": "^17.0.6"
}
}
diff --git a/frontend/playwright.config.js b/frontend/playwright.config.js
new file mode 100644
index 0000000..ebfc808
--- /dev/null
+++ b/frontend/playwright.config.js
@@ -0,0 +1,25 @@
+import { defineConfig, devices } from '@playwright/test';
+
+export default defineConfig({
+ testDir: './e2e',
+ fullyParallel: false,
+ forbidOnly: !!process.env.CI,
+ retries: process.env.CI ? 1 : 0,
+ workers: process.env.CI ? 1 : undefined,
+ reporter: process.env.CI ? 'github' : 'list',
+ use: {
+ baseURL: 'http://127.0.0.1:18477',
+ screenshot: 'only-on-failure',
+ trace: 'retain-on-failure',
+ },
+ webServer: {
+ command: 'npm run dev -- --host 127.0.0.1 --port 18477',
+ url: 'http://127.0.0.1:18477',
+ reuseExistingServer: !process.env.CI,
+ timeout: 120_000,
+ },
+ projects: [
+ { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
+ { name: 'firefox', use: { ...devices['Desktop Firefox'] } },
+ ],
+});
diff --git a/frontend/src/App.svelte b/frontend/src/App.svelte
index 62d28f8..e90094a 100644
--- a/frontend/src/App.svelte
+++ b/frontend/src/App.svelte
@@ -7,43 +7,46 @@
toast,
updateState,
checkForUpdateOnStart,
+ toggleTheme,
} from './lib/state.svelte.js';
import { startEvents, onEvent } from './lib/events.js';
- import { WORKSPACES, workspaceOf, toolFromHash } from './lib/workspaces.js';
+ import {
+ WORKSPACES,
+ TOOL_LABELS,
+ sidebarOpenForWorkspace,
+ workspaceOf,
+ toolFromHash,
+ } from './lib/workspaces.js';
+ import { createToolLoader } from './lib/toolLoader.js';
import Icon from './components/Icon.svelte';
import Logo from './components/Logo.svelte';
import Wordmark from './components/Wordmark.svelte';
import CaseSwitcher from './components/CaseSwitcher.svelte';
import CaseSidebar from './components/CaseSidebar.svelte';
import Toasts from './components/Toasts.svelte';
- import MediaLibrary from './tools/MediaLibrary.svelte';
- import Files from './tools/Files.svelte';
- import ReverseSearch from './tools/ReverseSearch.svelte';
- import Satellite from './tools/Satellite.svelte';
- import Coordinates from './tools/Coordinates.svelte';
- import ProofComposer from './tools/ProofComposer.svelte';
- import PostComposer from './tools/PostComposer.svelte';
- import Inspector from './tools/Inspector.svelte';
- import Settings from './tools/Settings.svelte';
import UpdateModal from './components/UpdateModal.svelte';
// The rail holds workspaces (docs/UI.md §3); tools are tabs inside them.
// Settings lives behind the topbar gear instead — app plumbing, not part
// of the working flow.
const TOOLS = [
- { id: 'media', label: 'Media', component: MediaLibrary },
- { id: 'files', label: 'Files', component: Files },
- { id: 'reverse', label: 'Reverse Search', component: ReverseSearch },
- { id: 'inspect', label: 'Inspect', component: Inspector },
- { id: 'satellite', label: 'Satellite', component: Satellite },
- { id: 'coordinates', label: 'Coordinates', component: Coordinates },
- { id: 'proof', label: 'Proof', component: ProofComposer },
- { id: 'post', label: 'Post', component: PostComposer },
+ { id: 'media', label: TOOL_LABELS.media, load: () => import('./tools/MediaLibrary.svelte') },
+ { id: 'files', label: TOOL_LABELS.files, load: () => import('./tools/Files.svelte') },
+ { id: 'reverse', label: TOOL_LABELS.reverse, load: () => import('./tools/ReverseSearch.svelte') },
+ { id: 'inspect', label: TOOL_LABELS.inspect, load: () => import('./tools/Inspector.svelte') },
+ { id: 'satellite', label: TOOL_LABELS.satellite, load: () => import('./tools/Satellite.svelte') },
+ { id: 'coordinates', label: TOOL_LABELS.coordinates, load: () => import('./tools/Coordinates.svelte') },
+ { id: 'proof', label: TOOL_LABELS.proof, load: () => import('./tools/ProofComposer.svelte') },
+ { id: 'post', label: TOOL_LABELS.post, load: () => import('./tools/PostComposer.svelte') },
+ { id: 'notebook', label: TOOL_LABELS.notebook, load: () => import('./tools/Notebook.svelte') },
];
const ALL_TOOLS = [
...TOOLS,
- { id: 'settings', label: 'Settings', component: Settings },
+ { id: 'settings', label: TOOL_LABELS.settings, load: () => import('./tools/Settings.svelte') },
];
+ const loader = createToolLoader(Object.fromEntries(ALL_TOOLS.map((tool) => [tool.id, tool.load])));
+ let toolComponents = $state.raw({});
+ let toolErrors = $state.raw({});
const TOOL_IDS = ALL_TOOLS.map((t) => t.id);
const toolLabel = (id) => ALL_TOOLS.find((t) => t.id === id)?.label ?? id;
@@ -58,20 +61,48 @@
// Workspace navigation: clicking a workspace returns to its last-used tab.
const activeWs = $derived(workspaceOf(uiState.tool));
const lastTool = $state({});
+ const sidebarOpenByWorkspace = $state({});
+ let previousTool = null;
$effect(() => {
const ws = workspaceOf(uiState.tool);
if (ws) lastTool[ws.id] = uiState.tool;
});
+ $effect(() => {
+ const nextTool = uiState.tool;
+ const previousWs = workspaceOf(previousTool);
+ const nextWs = workspaceOf(nextTool);
+ if (nextWs && previousWs?.id !== nextWs.id) {
+ uiState.sidebarOpen = sidebarOpenForWorkspace(nextWs.id, sidebarOpenByWorkspace);
+ }
+ previousTool = nextTool;
+ });
function openWorkspace(ws) {
uiState.tool = lastTool[ws.id] ?? ws.tools[0];
}
+ function toggleSidebar() {
+ const open = !uiState.sidebarOpen;
+ const ws = workspaceOf(uiState.tool);
+ if (ws) sidebarOpenByWorkspace[ws.id] = open;
+ uiState.sidebarOpen = open;
+ }
// Tools mount lazily on first visit, then stay mounted (hidden via CSS) so
// unsaved editor state — a half-composed proof, a collage in progress —
// survives switching tabs to grab another capture or media.
const visited = $state({ [uiState.tool]: true });
+ async function ensureTool(id) {
+ try {
+ const component = await loader.load(id);
+ toolComponents = { ...toolComponents, [id]: component };
+ if (toolErrors[id]) toolErrors = { ...toolErrors, [id]: null };
+ } catch (error) {
+ toolErrors = { ...toolErrors, [id]: error?.message ?? 'Could not load this tool' };
+ }
+ }
$effect(() => {
- visited[uiState.tool] = true;
+ const id = uiState.tool;
+ visited[id] = true;
+ void ensureTool(id);
});
// Load the case list and reopen the last-used case (survives reloads), then
@@ -115,7 +146,7 @@
<button
class="btn btn-ghost btn-sm"
title="Toggle case sidebar"
- onclick={() => (uiState.sidebarOpen = !uiState.sidebarOpen)}
+ onclick={toggleSidebar}
>
<Icon name="panelRight" size={16} />
</button>
@@ -134,6 +165,14 @@
<span>{ws.label}</span>
</button>
{/each}
+ <button
+ class="rail-btn theme-toggle"
+ onclick={toggleTheme}
+ title={uiState.theme === 'light' ? 'Switch to dark theme' : 'Switch to light theme'}
+ >
+ <Icon name={uiState.theme === 'light' ? 'moon' : 'sun'} size={19} />
+ <span>{uiState.theme === 'light' ? 'Dark' : 'Light'}</span>
+ </button>
</nav>
<main class="canvas">
@@ -153,8 +192,18 @@
<div class="canvas-body">
{#each ALL_TOOLS as tool (tool.id)}
{#if visited[tool.id]}
+ {@const ToolComponent = toolComponents[tool.id]}
<div class="tool-host" class:hidden={uiState.tool !== tool.id}>
- <tool.component />
+ {#if ToolComponent}
+ <ToolComponent />
+ {:else if toolErrors[tool.id]}
+ <div class="tool-loading">
+ <p>{toolErrors[tool.id]}</p>
+ <button class="btn btn-sm" onclick={() => ensureTool(tool.id)}>Retry</button>
+ </div>
+ {:else}
+ <div class="tool-loading">Loading {tool.label}…</div>
+ {/if}
</div>
{/if}
{/each}
@@ -244,6 +293,10 @@
color: var(--text-1);
border-left-color: var(--accent);
}
+ /* pinned to the foot of the rail, away from the workspace switches */
+ .theme-toggle {
+ margin-top: auto;
+ }
.canvas {
flex: 1;
min-width: 0;
@@ -284,4 +337,14 @@
.tool-host.hidden {
display: none;
}
+ .tool-loading {
+ width: 100%;
+ height: 100%;
+ display: grid;
+ place-content: center;
+ justify-items: center;
+ gap: 10px;
+ color: var(--text-3);
+ font-size: var(--fs-sm);
+ }
</style>
diff --git a/frontend/src/app.css b/frontend/src/app.css
index b7cb55d..a8ce6a1 100644
--- a/frontend/src/app.css
+++ b/frontend/src/app.css
@@ -66,6 +66,78 @@
color-scheme: dark;
}
+/* -- light theme -------------------------------------------------
+ Same tokens, daylight palette. Toggled by stamping data-theme="light"
+ on <html> (lib/theme.js); dark is the default and lives in :root above.
+ Only the colour tokens flip — typography, geometry and the annotation
+ palette (which must stay high-contrast over imagery) are shared.
+ The bg ramp keeps its meaning: bg-0 is the working canvas, bg-1 the
+ surrounding chrome, bg-2 raised surfaces, bg-3 hover/active. */
+:root[data-theme='light'] {
+ --bg-0: #f5f5f3; /* app / canvas — soft warm paper */
+ --bg-1: #ffffff; /* panels, sidebar, topbar — clean white chrome */
+ --bg-2: #ffffff; /* raised: cards, inputs (separated by --border) */
+ --bg-3: #e9e9e6; /* hover states, active rows */
+ --border: rgba(0, 0, 0, 0.11);
+ --border-strong: rgba(0, 0, 0, 0.22);
+
+ --text-1: #1e1e1e; /* primary text */
+ --text-2: #5c5c5c; /* secondary text */
+ --text-3: #8a8a8a; /* hints, placeholders */
+
+ --accent: #e8a33d; /* azimuth amber — brand-stable across themes */
+ --accent-hover: #d68f24;
+ --accent-soft: rgba(232, 163, 61, 0.2);
+ --accent-text: #201400; /* text on accent */
+
+ /* status hues deepened so they read as text on white */
+ --ok: #3f9d5a;
+ --ok-soft: rgba(63, 157, 90, 0.13);
+ --warn: #b5811f;
+ --danger: #c0392b;
+ --danger-soft: rgba(192, 57, 43, 0.12);
+ --info: #3b73b8;
+ --info-soft: rgba(59, 115, 184, 0.12);
+
+ --shadow-1: 0 1px 3px rgba(0, 0, 0, 0.12);
+ --shadow-2: 0 8px 28px rgba(0, 0, 0, 0.16);
+
+ /* Brand marks read light-on-dark by default; on white the cream lettering
+ and compass highlights need a dark ink instead (Logo/Wordmark fall back to
+ the cream when this is unset). */
+ --brand-ink: #23262b;
+
+ color-scheme: light;
+}
+
+/* Surfaces that sit *over imagery* — the Satellite map with its Leaflet
+ controls (zoom, scale, attribution) and floating tool clusters — were tuned
+ for the dark palette and must stay dark in every theme, or they clash with
+ the tiles beneath them. Opt in with class="dark-surface": it re-pins the
+ dark tokens locally, so it's a no-op in dark mode and a hard revert in light.
+ Values mirror the :root dark palette above — keep them in step. */
+:root[data-theme='light'] .dark-surface {
+ --bg-0: #151515;
+ --bg-1: #1c1c1c;
+ --bg-2: #252525;
+ --bg-3: #2f2f2f;
+ --border: rgba(255, 255, 255, 0.09);
+ --border-strong: rgba(255, 255, 255, 0.18);
+ --text-1: #e3e3e3;
+ --text-2: #9f9f9f;
+ --text-3: #6c6c6c;
+ --accent-text: #141414;
+ --ok: #66b578;
+ --ok-soft: rgba(102, 181, 120, 0.12);
+ --warn: #d9a53f;
+ --danger: #d97070;
+ --danger-soft: rgba(217, 112, 112, 0.12);
+ --info: #6f9fd8;
+ --info-soft: rgba(111, 159, 216, 0.12);
+ --shadow-1: 0 1px 3px rgba(0, 0, 0, 0.4);
+ --shadow-2: 0 8px 28px rgba(0, 0, 0, 0.5);
+}
+
/* -- reset ------------------------------------------------------ */
*,
*::before,
diff --git a/frontend/src/components/CaseSidebar.svelte b/frontend/src/components/CaseSidebar.svelte
index c95f126..00c7be7 100644
--- a/frontend/src/components/CaseSidebar.svelte
+++ b/frontend/src/components/CaseSidebar.svelte
@@ -1,4 +1,5 @@
<script>
+ import { untrack } from 'svelte';
import { api } from '../lib/api.js';
import {
caseState,
@@ -9,14 +10,16 @@
persistSidebarWidth,
} from '../lib/state.svelte.js';
import { DEFAULT_W } from '../lib/sidebar.js';
- import { buildTree, subtreeCount, flattenPaths, folderOf } from '../lib/folderTree.js';
+ import { buildTree, subtreeCountFrom, flattenPaths, folderOf } from '../lib/folderTree.js';
+ import { buildCatalogQuery, settleCatalogSummary } from '../lib/catalog.js';
import { assignFolder as fileEntity } from '../lib/filing.js';
- import { deletePlan } from '../lib/chain.js';
- import { openEntity, gotoCapture, ENTITY_TOOL } from '../lib/navigate.js';
+ import { createNote } from '../lib/notes.js';
+ import { openEntity, gotoCapture, openNotebook, ENTITY_TOOL } from '../lib/navigate.js';
import Icon from './Icon.svelte';
import Modal from './Modal.svelte';
import ConfirmDialog from './ConfirmDialog.svelte';
import EntityDetails from './EntityDetails.svelte';
+ import FolderSelect from './FolderSelect.svelte';
const ENTITY_ICONS = {
person: 'user',
@@ -38,9 +41,6 @@
'inspect-session': 'inspect',
};
- // Entity types backed by a file on disk — deleting them everywhere drops the file.
- const FILE_BACKED = new Set(['media', 'capture', 'proof', 'post', 'inspect-session']);
-
const VIDEO_EXTS = new Set(['mp4', 'mov', 'webm', 'mkv', 'avi', 'm4v']);
// 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
@@ -52,44 +52,100 @@
}
const entityIcon = (e) => (e.type === 'media' && isVideo(e) ? 'video' : ENTITY_ICONS[e.type] ?? 'note');
- // ── case notes (single notes.md) ─────────────────────────────────────────
- let caseNotes = $state('');
- let caseNotesLoadedFor = $state(null);
- let saveTimer;
- let saved = $state(true);
let section = $state({ notes: false, suggestions: true, mywork: true });
- $effect(() => {
- const id = caseState.current?.id;
- if (id && id !== caseNotesLoadedFor) {
- caseNotesLoadedFor = id;
- api.get(`/api/cases/${id}/notes`).then((r) => (caseNotes = r.text));
- } else if (!id) {
- caseNotesLoadedFor = null;
- caseNotes = '';
+ // ── bounded catalog loading (docs/STORAGE_AND_PERFORMANCE.md, Step 5) ───────
+ // The sidebar no longer holds the whole graph. It builds the folder tree from
+ // the (small) folder list plus the summary's folder keys, takes its badge
+ // counts from the summary, and loads entities a page at a time per section:
+ // Suggestions, Unfiled, and each folder on expand. `seq` guards a stale
+ // response from landing after the case or a mutation moved on.
+ const CATALOG_PAGE = 200;
+ const emptySection = () => ({ items: [], cursor: null, done: false, loading: false, loaded: false });
+
+ let summary = $state(null); // { total, by_type, by_status, by_folder }
+ let suggestedData = $state(emptySection());
+ let unfiledData = $state(emptySection());
+ let folderData = $state({}); // path -> section
+ let seq = 0;
+ let loadedCaseId = null;
+
+ const byFolder = $derived(summary?.by_folder ?? {});
+ const suggestedCount = $derived(summary?.by_status?.suggested ?? 0);
+ const confirmedCount = $derived(Math.max(0, (summary?.total ?? 0) - suggestedCount));
+
+ async function loadSection(sec, params, { id, mySeq, more = false } = {}) {
+ id ??= caseState.current?.id;
+ mySeq ??= seq;
+ if (!id) return;
+ if (more && (sec.loading || sec.done)) return; // don't stack a "show more"
+ sec.loading = true;
+ try {
+ const page = await api.get(
+ buildCatalogQuery(id, { ...params, limit: CATALOG_PAGE, cursor: more ? sec.cursor : null })
+ );
+ if (mySeq !== seq) return; // a case switch or reload superseded us
+ sec.items = more ? [...sec.items, ...(page.items ?? [])] : page.items ?? [];
+ sec.cursor = page.next_cursor ?? null;
+ sec.done = !sec.cursor;
+ sec.loaded = true;
+ sec.loading = false;
+ } catch (e) {
+ if (mySeq !== seq) return;
+ sec.loading = false;
+ toast(e.message, 'danger');
}
- });
+ }
+
+ const loadSuggested = (more = false) => loadSection(suggestedData, { status: 'suggested' }, { more });
+ const loadUnfiled = (more = false) =>
+ loadSection(unfiledData, { status: 'confirmed', unfiled: true }, { more });
+ function loadFolder(path, more = false) {
+ if (!folderData[path]) folderData[path] = emptySection();
+ return loadSection(folderData[path], { status: 'confirmed', folder: path }, { more });
+ }
+
+ async function loadSummary(id, mySeq) {
+ try {
+ const s = await api.get(`/api/cases/${id}/catalog/summary`);
+ summary = settleCatalogSummary(summary, s, mySeq === seq);
+ } catch {
+ summary = settleCatalogSummary(summary, null, mySeq === seq);
+ /* counts are a nicety; an empty summary just shows zeroes */
+ }
+ }
+
+ // Reload the summary and every open section. Runs on case change (full reset
+ // first) and on every reloadCase() (caseState.rev), so a mutation anywhere is
+ // reflected without re-reading the whole graph.
+ function refreshAll(id) {
+ seq++;
+ if (id !== loadedCaseId) {
+ loadedCaseId = id;
+ summary = null;
+ expanded = {};
+ folderData = {};
+ unfiledOpen = false;
+ addingUnder = undefined;
+ infoEntity = null;
+ suggestedData = emptySection();
+ unfiledData = emptySection();
+ }
+ if (!id) {
+ summary = null;
+ return;
+ }
+ loadSummary(id, seq);
+ loadSuggested();
+ loadUnfiled();
+ for (const path of Object.keys(expanded)) if (expanded[path]) loadFolder(path);
+ }
- function onCaseNotesInput() {
- saved = false;
- clearTimeout(saveTimer);
+ $effect(() => {
const id = caseState.current?.id;
- saveTimer = setTimeout(async () => {
- if (!id) return;
- try {
- await api.put(`/api/cases/${id}/notes`, { text: caseNotes });
- saved = true;
- } catch (e) {
- toast(`Notes not saved: ${e.message}`, 'danger');
- }
- }, 700);
- }
-
- // ── entities ─────────────────────────────────────────────────────────────
- const entities = $derived(caseState.current?.entities ?? []);
- const links = $derived(caseState.current?.links ?? []);
- const suggested = $derived(entities.filter((e) => e.provenance?.status === 'suggested'));
- const confirmed = $derived(entities.filter((e) => e.provenance?.status !== 'suggested'));
+ caseState.rev; // re-run on every reload (a mutation elsewhere or our own)
+ untrack(() => refreshAll(id));
+ });
async function confirmEntity(entity) {
await api.patch(`/api/cases/${caseState.current.id}/entities/${entity.id}`, {
@@ -105,10 +161,8 @@
toast(`Dismissed "${entity.label}"`, 'info');
}
- // clicking a row: notes open the editor, captures open their image, places
- // navigate the map — everything else opens its tool
+ // Clicking a row opens its owning workspace; notes share the Notebook.
function onEntityActivate(entity) {
- if (entity.type === 'note') return openEditNote(entity);
if (entity.type === 'capture') return openInfo(entity);
openEntity(entity);
}
@@ -121,40 +175,24 @@
let addingUnder = $state(undefined); // folder path currently gaining a child
let newSubName = $state('');
let expanded = $state({}); // path -> bool (absent = collapsed)
- let dragEntityId = $state(null);
+ let dragEntityId = $state(null); // for the dragging visual
+ let dragEntity = null; // the entity being dragged (no full-graph lookup on drop)
let dragOverFolder = $state(undefined); // folder path being hovered
const caseFolders = $derived(caseState.current?.folders ?? []);
- const tree = $derived(buildTree(caseFolders, confirmed));
+ // Structure only: the tree is built from folders plus any folder a summary
+ // count refers to (an entity filed into a path that was never an explicit
+ // folder still gets a node), with no entities attached — those load per node.
+ const tree = $derived(buildTree([...new Set([...caseFolders, ...Object.keys(byFolder)])], []));
const allFolders = $derived(flattenPaths(tree));
- // everything not yet filed — the inbox you file (or inspect) items from
- const unfiled = $derived(confirmed.filter((e) => !folderOf(e)));
let unfiledOpen = $state(false);
- let unfiledTypeFilter = $state(null);
- const TYPE_LABEL = {
- media: 'Media', capture: 'Satellite', note: 'Notes', proof: 'Proofs',
- post: 'Posts', place: 'Places', 'inspect-session': 'Inspect',
- };
- // chip counts, in a stable order (declaration order of TYPE_LABEL, then anything unmapped)
- const unfiledTypes = $derived.by(() => {
- const counts = new Map();
- for (const e of unfiled) counts.set(e.type, (counts.get(e.type) ?? 0) + 1);
- return Object.keys(TYPE_LABEL)
- .filter((t) => counts.has(t))
- .concat([...counts.keys()].filter((t) => !(t in TYPE_LABEL)))
- .map((t) => ({ type: t, label: TYPE_LABEL[t] ?? t, count: counts.get(t) }));
- });
- const unfiledFiltered = $derived(
- unfiledTypeFilter ? unfiled.filter((e) => e.type === unfiledTypeFilter) : unfiled
- );
- $effect(() => {
- // drop a stale filter when its type disappears from Unfiled (e.g. filed away)
- if (unfiledTypeFilter && !unfiled.some((e) => e.type === unfiledTypeFilter)) unfiledTypeFilter = null;
- });
const isExpanded = (path) => expanded[path] === true;
- function toggle(path) { expanded[path] = !isExpanded(path); }
+ function toggle(path) {
+ expanded[path] = !isExpanded(path);
+ if (expanded[path]) loadFolder(path);
+ }
function focus(node) { node.focus(); }
async function createFolder(fullName) {
@@ -196,14 +234,16 @@
// drag & drop wiring
function onDragStart(ev, entity) {
dragEntityId = entity.id;
+ dragEntity = entity;
ev.dataTransfer.effectAllowed = 'move';
ev.dataTransfer.setData('text/plain', entity.id);
}
function onDropFolder(ev, folder) {
ev.preventDefault();
dragOverFolder = undefined;
- const entity = entities.find((e) => e.id === dragEntityId);
+ const entity = dragEntity;
dragEntityId = null;
+ dragEntity = null;
if (entity) assignFolder(entity, folder).catch((e) => toast(e.message, 'danger'));
}
@@ -225,32 +265,6 @@
}
}
- // Delete everywhere: removes the entity and its underlying file(s). Used from
- // the details panel (and the note modal) — irreversible, danger tone.
- //
- // Whatever hangs off the entity is spelled out before the click: sessions that
- // cannot outlive it go too, outputs made from it stay and keep a record of
- // what they lost. Nothing cascades into an output — ever (ONTOLOGY §3).
- function askDeleteEverywhere(entity, onDone) {
- confirmState = {
- title: 'Delete everywhere?',
- message: `“${entity.label}” will be removed from the case and its tool.`,
- detail: FILE_BACKED.has(entity.type)
- ? 'This permanently deletes the underlying file(s) on disk — it cannot be undone.'
- : 'This permanently removes it from the case — it cannot be undone.',
- consequences: deletePlan(entities, links, entity.id),
- confirmLabel: 'Delete everywhere',
- tone: 'danger',
- icon: 'trash',
- action: async () => {
- await api.del(`/api/cases/${caseState.current.id}/entities/${entity.id}`);
- await reloadCase();
- toast(`Deleted "${entity.label}"`, 'info');
- onDone?.();
- },
- };
- }
-
// Remove from My work: just clears the filing. The item stays in its tool.
function askRemoveFromMyWork(entity) {
confirmState = {
@@ -266,10 +280,6 @@
function askDeleteFolder(path) {
const prefix = path + '/';
- const inside = entities.filter((e) => {
- const f = folderOf(e);
- return f === path || (f && f.startsWith(prefix));
- });
const subs = allFolders.filter((f) => f.startsWith(prefix)).length;
confirmState = {
title: 'Remove this folder?',
@@ -280,8 +290,9 @@
confirmLabel: 'Remove folder',
tone: 'default',
icon: 'folderMinus',
+ // The backend unfiles every entity under the removed subtree, so this
+ // does not enumerate the graph — it just drops the folder and refreshes.
action: async () => {
- for (const e of inside) await assignFolder(e, '');
await api.del(
`/api/cases/${caseState.current.id}/folders?name=${encodeURIComponent(path)}`
);
@@ -308,38 +319,19 @@
let noteModalSaving = $state(false);
function openNewNote() {
- noteModal = { entity: null, title: '', folder: '', content: '' };
- }
-
- function openEditNote(entity) {
- noteModal = {
- entity,
- title: entity.label,
- folder: entity.attrs?.folder ?? '',
- content: entity.attrs?.content ?? '',
- };
+ noteModal = { title: '', folder: '' };
}
async function saveNote() {
if (!noteModal) return;
- const { entity, title, folder, content } = noteModal;
+ const { title, folder } = noteModal;
if (!title.trim()) { toast('Title required', 'warn'); return; }
noteModalSaving = true;
try {
- const attrs = { content, folder: folder.trim() };
- if (!entity) {
- await api.post(`/api/cases/${caseState.current.id}/entities`, {
- type: 'note', label: title.trim(), attrs,
- });
- toast('Note created', 'ok', 1600);
- } else {
- await api.patch(`/api/cases/${caseState.current.id}/entities/${entity.id}`, {
- label: title.trim(), attrs,
- });
- toast('Note saved', 'ok', 1600);
- }
+ const note = await createNote(caseState.current.id, { title, folder });
await reloadCase();
noteModal = null;
+ openNotebook(note.id);
} catch (e) {
toast(e.message, 'danger');
} finally {
@@ -420,29 +412,21 @@
<div class="sections">
<!-- 1 · Case Notes (single notes.md) -->
- <button class="section-head" onclick={() => (section.notes = !section.notes)}>
- <Icon name={section.notes ? 'chevronDown' : 'chevronRight'} size={13} />
+ <button class="section-head" onclick={() => openNotebook()}>
+ <Icon name="note" size={13} />
<span>Case Notes</span>
- {#if !saved}<span class="badge">saving…</span>{/if}
+ <span class="open-note">Open</span>
</button>
- {#if section.notes}
- <textarea
- class="textarea notes mono"
- bind:value={caseNotes}
- oninput={onCaseNotesInput}
- placeholder="Case notes (markdown)…"
- ></textarea>
- {/if}
<!-- 2 · Suggestions (tool-suggested entities: confirm or dismiss) -->
- {#if suggested.length > 0}
+ {#if suggestedCount > 0}
<button class="section-head" onclick={() => (section.suggestions = !section.suggestions)}>
<Icon name={section.suggestions ? 'chevronDown' : 'chevronRight'} size={13} />
<span>Suggestions</span>
- <span class="count">{suggested.length}</span>
+ <span class="count">{suggestedCount}</span>
</button>
{#if section.suggestions}
- {#each suggested as e (e.id)}
+ {#each suggestedData.items as e (e.id)}
<div class="entity suggested">
<Icon name={entityIcon(e)} size={14} />
<div class="e-body">
@@ -457,6 +441,11 @@
</button>
</div>
{/each}
+ {#if !suggestedData.done}
+ <button class="more" onclick={() => loadSuggested(true)} disabled={suggestedData.loading}>
+ Show more
+ </button>
+ {/if}
{/if}
{/if}
@@ -465,7 +454,7 @@
<button class="section-head" onclick={() => (section.mywork = !section.mywork)}>
<Icon name={section.mywork ? 'chevronDown' : 'chevronRight'} size={13} />
<span>My work</span>
- <span class="count">{confirmed.length}</span>
+ <span class="count">{confirmedCount}</span>
</button>
<button class="btn btn-ghost btn-sm new-note-btn" title="New note" onclick={openNewNote}>
<Icon name="plus" size={13} /><Icon name="note" size={13} />
@@ -486,7 +475,7 @@
{@render folderNode(node, 0)}
{/each}
- {#if unfiled.length > 0}
+ {#if unfiledData.items.length > 0}
<div
class="frow"
role="button"
@@ -497,29 +486,21 @@
<Icon name={unfiledOpen ? 'chevronDown' : 'chevronRight'} size={12} />
<Icon name="layers" size={13} />
<span class="fname">Unfiled</span>
- <span class="fcount">{unfiled.length}</span>
+ <span class="fcount">{unfiledData.items.length}{unfiledData.done ? '' : '+'}</span>
</div>
{#if unfiledOpen}
- {#if unfiledTypes.length > 1}
- <div class="chip-row">
- {#each unfiledTypes as t (t.type)}
- <button
- class="chip"
- class:active={unfiledTypeFilter === t.type}
- onclick={() => (unfiledTypeFilter = unfiledTypeFilter === t.type ? null : t.type)}
- >
- {t.label}<span class="chip-count">{t.count}</span>
- </button>
- {/each}
- </div>
- {/if}
- {#each unfiledFiltered as e (e.id)}
+ {#each unfiledData.items as e (e.id)}
{@render entityRow(e, 1)}
{/each}
+ {#if !unfiledData.done}
+ <button class="more" onclick={() => loadUnfiled(true)} disabled={unfiledData.loading}>
+ Show more
+ </button>
+ {/if}
{/if}
{/if}
- {#if tree.length === 0 && unfiled.length === 0}
+ {#if tree.length === 0 && unfiledData.items.length === 0}
<div class="none">
Everything you save lands here; create folders to organize it.
</div>
@@ -571,7 +552,7 @@
<Icon name={isExpanded(node.path) ? 'chevronDown' : 'chevronRight'} size={12} />
<Icon name={isExpanded(node.path) ? 'folderOpen' : 'folder'} size={13} />
<span class="fname">{node.name}</span>
- <span class="fcount">{subtreeCount(node)}</span>
+ <span class="fcount">{subtreeCountFrom(node, byFolder)}</span>
<span
class="fact"
role="button"
@@ -615,15 +596,30 @@
{#each node.children as child (child.path)}
{@render folderNode(child, depth + 1)}
{/each}
- {#each node.entities as e (e.id)}
- {@render entityRow(e, depth + 1)}
- {/each}
+ {@const sec = folderData[node.path]}
+ {#if sec}
+ {#each sec.items as e (e.id)}
+ {@render entityRow(e, depth + 1)}
+ {/each}
+ {#if !sec.done}
+ <button
+ class="more"
+ style="margin-left: {8 + (depth + 1) * 14}px"
+ onclick={() => loadFolder(node.path, true)}
+ disabled={sec.loading}
+ >
+ Show more
+ </button>
+ {/if}
+ {/if}
{/if}
{/snippet}
<!-- one entity row (My work): activate, info, unfile -->
{#snippet entityRow(e, depth)}
{@const isClickable = e.type === 'note' || e.type === 'capture' || !!ENTITY_TOOL[e.type]}
+ <!-- The role and tab stop deliberately exist only for activatable entity types. -->
+ <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
<div
class="entity"
class:clickable={isClickable}
@@ -631,7 +627,7 @@
style="padding-left: {8 + depth * 14}px"
draggable="true"
ondragstart={(ev) => onDragStart(ev, e)}
- ondragend={() => { dragEntityId = null; dragOverFolder = undefined; }}
+ ondragend={() => { dragEntityId = null; dragEntity = null; dragOverFolder = undefined; }}
onclick={() => onEntityActivate(e)}
role={isClickable ? 'button' : undefined}
tabindex={isClickable ? 0 : undefined}
@@ -686,7 +682,7 @@
<!-- Note edit / create modal -->
{#if noteModal}
<Modal
- title={noteModal.entity ? 'Edit note' : 'New note'}
+ title="New note"
onclose={() => (noteModal = null)}
width="580px"
>
@@ -698,48 +694,21 @@
bind:value={noteModal.title}
/>
- <label class="modal-label" for="note-folder" style="margin-top:10px">Folder (in My work)</label>
- <input
- id="note-folder"
- class="input"
- placeholder="e.g. research, timeline, sources…"
- bind:value={noteModal.folder}
- list="note-folder-suggestions"
- />
- <datalist id="note-folder-suggestions">
- {#each allFolders as f (f)}<option value={f}></option>{/each}
- </datalist>
-
- <label class="modal-label" for="note-content" style="margin-top:10px">Content</label>
- <textarea
- id="note-content"
- class="textarea note-content"
- rows="14"
- placeholder="Write your notes in markdown…"
- bind:value={noteModal.content}
- ></textarea>
+ <span class="modal-label" style="margin-top:10px">Folder (in My work)</span>
+ <FolderSelect bind:value={noteModal.folder} folders={allFolders} emptyLabel="My work (root)" />
<div class="modal-row">
- {#if noteModal.entity}
- <button
- class="btn btn-ghost btn-sm"
- style="color:var(--danger,#e55)"
- onclick={() => askDeleteEverywhere(noteModal.entity, () => (noteModal = null))}
- >
- <Icon name="trash" size={13} /> Delete note
- </button>
- {/if}
<div style="flex:1"></div>
<button class="btn" onclick={() => (noteModal = null)}>Cancel</button>
<button class="btn btn-primary" onclick={saveNote} disabled={noteModalSaving}>
- {noteModalSaving ? 'Saving…' : noteModal.entity ? 'Save' : 'Create'}
+ {noteModalSaving ? 'Creating…' : 'Create'}
</button>
</div>
</Modal>
{/if}
-<!-- Confirmation dialog (delete everywhere / remove from My work / remove folder) -->
+<!-- Confirmation dialog (remove from My work / remove folder) -->
{#if confirmState}
<ConfirmDialog
title={confirmState.title}
@@ -825,13 +794,8 @@
gap: 2px;
}
.new-note-btn:hover { color: var(--accent); }
+ .open-note { margin-left: auto; color: var(--text-3); font-weight: 600; }
.count { margin-left: auto; color: var(--text-3); font-weight: 600; }
- .notes {
- min-height: 130px;
- font-size: var(--fs-xs);
- margin: 0 4px 10px;
- width: calc(100% - 8px);
- }
/* tool group header (Saved work) */
/* folder tree */
.new-folder { display: flex; gap: 6px; padding: 2px 8px 8px; }
@@ -859,22 +823,20 @@
.fact { opacity: 0; color: var(--text-3); display: flex; padding: 2px; border-radius: 4px; flex-shrink: 0; }
.fact:hover { color: var(--text-1); }
.fdel:hover { color: var(--danger, #e55); }
- .chip-row { display: flex; flex-wrap: wrap; gap: 4px; padding: 2px 8px 6px 22px; }
- .chip {
- display: inline-flex;
- align-items: center;
- gap: 4px;
- padding: 2px 7px;
- border-radius: var(--r-sm);
+ .more {
+ align-self: flex-start;
+ margin: 2px 8px 6px;
+ padding: 3px 10px;
font-size: var(--fs-xs);
- font-weight: 500;
- background: var(--bg-2);
+ font-weight: 600;
color: var(--text-2);
- border: 1px solid transparent;
+ background: var(--bg-2);
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ cursor: pointer;
}
- .chip:hover { color: var(--text-1); }
- .chip.active { background: var(--accent-soft); color: var(--accent); border-color: var(--accent); }
- .chip-count { color: inherit; opacity: 0.65; font-weight: 600; }
+ .more:hover { color: var(--text-1); border-color: var(--border-strong); }
+ .more:disabled { opacity: 0.5; cursor: default; }
.frow:hover .fact { opacity: 1; }
/* entities */
.entity {
@@ -921,6 +883,5 @@
border-bottom: 1px solid var(--border);
font-size: var(--fs-sm);
}
- .note-content { width: 100%; resize: vertical; font-family: var(--font-mono); font-size: var(--fs-xs); }
.modal-row { display: flex; align-items: center; gap: 8px; margin-top: 14px; }
</style>
diff --git a/frontend/src/components/CaseSwitcher.svelte b/frontend/src/components/CaseSwitcher.svelte
index d0680a8..61c78e1 100644
--- a/frontend/src/components/CaseSwitcher.svelte
+++ b/frontend/src/components/CaseSwitcher.svelte
@@ -204,12 +204,12 @@
<input
id="case-name"
class="input"
- placeholder="e.g. Kharkiv strike — March 2026"
+ placeholder="e.g. March 2026 incident"
bind:value={nameInput}
autofocus
/>
{#if nameTaken}
- <p class="err">A case with this name already exists — pick another.</p>
+ <p class="err">A case with this name already exists. Pick another.</p>
{/if}
<div class="actions">
<button type="button" class="btn" onclick={() => (modal = null)}>Cancel</button>
@@ -234,9 +234,8 @@
You will lose everything in “{delTarget.name}”.
</p>
<p class="warn-body">
- This permanently deletes the whole case folder and all its contents —
- media, satellite crops, proofs, exports and notes. This cannot be
- undone.
+ This permanently deletes the whole case folder, including its media,
+ satellite crops, proofs, exports and notes. It cannot be undone.
</p>
</div>
</div>
@@ -374,10 +373,6 @@
.item:hover {
background: var(--bg-2);
}
- .item.active {
- background: var(--bg-3);
- color: var(--text-1);
- }
.warn {
display: flex;
gap: 13px;
diff --git a/frontend/src/components/ConfirmDialog.svelte b/frontend/src/components/ConfirmDialog.svelte
index 700f0ef..d1a982a 100644
--- a/frontend/src/components/ConfirmDialog.svelte
+++ b/frontend/src/components/ConfirmDialog.svelte
@@ -55,7 +55,7 @@
<div class="conseq danger">
<div class="conseq-h">
<Icon name="trash" size={12} />
- <span>Goes with it — nothing is left of these without it</span>
+ <span>Deleted with it because they cannot stand alone</span>
</div>
<ul>
{#each consequences.cascade as item (item.id ?? item.label)}
@@ -68,7 +68,7 @@
<div class="conseq">
<div class="conseq-h">
<Icon name="check" size={12} />
- <span>Kept — each keeps a record of what it was made from</span>
+ <span>Kept with a record of its missing source</span>
</div>
<ul>
{#each consequences.tombstone as item (item.id ?? item.label)}
diff --git a/frontend/src/components/EntityDetails.svelte b/frontend/src/components/EntityDetails.svelte
index f91440f..62abd7f 100644
--- a/frontend/src/components/EntityDetails.svelte
+++ b/frontend/src/components/EntityDetails.svelte
@@ -14,10 +14,11 @@
import { caseState, reloadCase, toast } from '../lib/state.svelte.js';
import { buildTree, flattenPaths, folderOf } from '../lib/folderTree.js';
import { assignFolder as fileEntity } from '../lib/filing.js';
- import { chainOf, deletePlan, DEPENDS_ON } from '../lib/chain.js';
+ import { DEPENDS_ON } from '../lib/chain.js';
import { openEntity, gotoCapture, ENTITY_TOOL } from '../lib/navigate.js';
import Icon from './Icon.svelte';
import ConfirmDialog from './ConfirmDialog.svelte';
+ import FolderSelect from './FolderSelect.svelte';
let { entityId, onclose, ondeleted } = $props();
@@ -33,15 +34,34 @@
});
const currentId = $derived(walkedId ?? entityId);
- const entities = $derived(caseState.current?.entities ?? []);
- const links = $derived(caseState.current?.links ?? []);
- const entity = $derived(entities.find((e) => e.id === currentId) ?? null);
+ // The entity and its derivation chain come from the bounded chain endpoint
+ // (Step 5), not the whole graph: fetched for the selected/walked id and
+ // refetched after a reload, guarded so a stale response can't overwrite a
+ // newer selection.
+ let chainData = $state(null); // { entity, sources, lost, dependents, empty }
+ let chainSeq = 0;
+ const entity = $derived(chainData?.entity ?? null);
+ const chain = $derived(chainData);
- const confirmed = $derived(entities.filter((e) => e.provenance?.status !== 'suggested'));
- const allFolders = $derived(flattenPaths(buildTree(caseState.current?.folders ?? [], confirmed)));
+ $effect(() => {
+ const id = currentId;
+ const cid = caseState.current?.id;
+ caseState.rev; // refetch after a save / delete / folder move
+ const mySeq = ++chainSeq;
+ if (!id || !cid) {
+ chainData = null;
+ return;
+ }
+ api
+ .get(`/api/cases/${cid}/entities/${id}/chain`)
+ .then((c) => { if (mySeq === chainSeq) chainData = c; })
+ .catch(() => { if (mySeq === chainSeq) chainData = null; });
+ });
+
+ const allFolders = $derived(flattenPaths(buildTree(caseState.current?.folders ?? [], [])));
// Entity types backed by a file on disk — deleting them drops the file.
- const FILE_BACKED = new Set(['media', 'capture', 'proof', 'post', 'inspect-session']);
+ const FILE_BACKED = new Set(['media', 'capture', 'proof', 'post', 'inspect-session', 'note']);
// Every artifact type gets the title/notes editor. Media/captures go through
// their sidecar PATCH; the rest edit the entity itself.
const EDITABLE = new Set(['capture', 'place', 'media', 'proof', 'post', 'inspect-session', 'note', 'bookmark']);
@@ -50,8 +70,6 @@
post: 'post', 'inspect-session': 'inspect', note: 'note', bookmark: 'link',
};
- const chain = $derived(entity ? chainOf(entities, links, entity.id) : null);
-
// ── resolved listing item (media/satellite) + editable fields ──────────────
let infoData = $state(null);
let infoLoading = $state(false);
@@ -140,16 +158,26 @@
let confirmState = $state(null);
let confirmBusy = $state(false);
- function askDeleteEverywhere() {
+ async function askDeleteEverywhere() {
const e = entity;
if (!e) return;
+ // The authoritative plan is the backend's; the preview reads its dependents
+ // endpoint rather than mirroring the whole graph client-side.
+ let consequences = { cascade: [], tombstone: [] };
+ try {
+ consequences = await api.get(
+ `/api/cases/${caseState.current.id}/entities/${e.id}/dependents`
+ );
+ } catch {
+ /* no preview — the delete still enforces the plan server-side */
+ }
confirmState = {
title: 'Delete everywhere?',
message: `“${e.label}” will be removed from the case and its tool.`,
detail: FILE_BACKED.has(e.type)
- ? 'This permanently deletes the underlying file(s) on disk — it cannot be undone.'
- : 'This permanently removes it from the case — it cannot be undone.',
- consequences: deletePlan(entities, links, e.id),
+ ? 'This permanently deletes the underlying file(s) on disk. It cannot be undone.'
+ : 'This permanently removes it from the case. It cannot be undone.',
+ consequences,
action: async () => {
await api.del(`/api/cases/${caseState.current.id}/entities/${e.id}`);
await reloadCase();
@@ -265,8 +293,6 @@
<span class="info-k">URL</span>
<a class="mono src" href={entity.attrs.url} target="_blank" rel="noreferrer">{entity.attrs.url}</a>
</div>
- {:else if entity.attrs?.content}
- <div class="info-note-body">{entity.attrs.content}</div>
{/if}
{#if entity.attrs?.coords}
<div class="info-row"><span class="info-k">Coords</span><span class="mono">{entity.attrs.coords}</span></div>
@@ -283,7 +309,7 @@
<Icon name={ENTITY_ICON[src.type] ?? 'file'} size={12} />
<span class="chain-label">{src.label}</span>
{#if type === DEPENDS_ON}
- <span class="chain-tag" title="This is a view over that item — it cannot outlive it">needs</span>
+ <span class="chain-tag" title="This view cannot outlive that item">needs</span>
{/if}
</button>
{/each}
@@ -320,11 +346,8 @@
<textarea id="ed-notes" class="textarea" rows="3" bind:value={infoNotes} placeholder="Add observations, links, context…"></textarea>
{/if}
- <label class="modal-label" for="ed-folder">Folder (My work)</label>
- <input id="ed-folder" class="input" bind:value={infoFolder} placeholder="none" list="ed-folder-suggestions" />
- <datalist id="ed-folder-suggestions">
- {#each allFolders as f (f)}<option value={f}></option>{/each}
- </datalist>
+ <span class="modal-label">Folder (My work)</span>
+ <FolderSelect bind:value={infoFolder} folders={allFolders} emptyLabel="None" />
<div class="details-actions">
{#if detailsFilePath}
@@ -337,9 +360,9 @@
<Icon name="external" size={13} /> Open link
</a>
{/if}
- {#if ENTITY_TOOL[entity.type]}
+ {#if ENTITY_TOOL[entity.type] || entity.type === 'note'}
<button class="btn btn-ghost btn-sm" onclick={() => { openEntity(entity); onclose?.(); }}>
- <Icon name="arrowRight" size={13} /> Open in tool
+ <Icon name="arrowRight" size={13} /> {entity.type === 'note' ? 'Open note' : 'Open in tool'}
</button>
{/if}
{#if entity.type === 'capture' && entity.attrs?.lat != null}
@@ -351,7 +374,7 @@
<div class="details-actions">
<button
class="btn btn-ghost btn-sm del"
- title="Delete everywhere: removes the item and its file(s) from the case"
+ title="Delete this item and its case files"
onclick={askDeleteEverywhere}
>
<Icon name="trash" size={13} /> Delete
@@ -465,11 +488,6 @@
max-height: 8.5em;
overflow-y: auto;
}
- .info-note-body {
- white-space: pre-wrap;
- font-size: var(--fs-sm);
- color: var(--text-2);
- }
.textarea {
width: 100%;
resize: vertical;
diff --git a/frontend/src/components/FolderSelect.svelte b/frontend/src/components/FolderSelect.svelte
new file mode 100644
index 0000000..8cdab7f
--- /dev/null
+++ b/frontend/src/components/FolderSelect.svelte
@@ -0,0 +1,222 @@
+<script>
+ import Icon from './Icon.svelte';
+ import { buildTree, flattenPaths } from '../lib/folderTree.js';
+ import { portal } from '../lib/fullscreen.js';
+
+ // A folder picker that only lets you choose an existing My-work folder or
+ // deliberately create a new one — no free-typing a stray path by accident.
+ let {
+ value = $bindable(''),
+ folders = [],
+ emptyLabel = 'No folder',
+ allowCreate = true,
+ id = undefined,
+ } = $props();
+
+ let open = $state(false);
+ let creating = $state(false);
+ let newName = $state('');
+ let triggerEl = $state(null);
+ // The menu is portaled to <body> (so a modal's overflow can't clip it) and
+ // fixed-positioned onto the trigger. These hold the computed placement.
+ let menuStyle = $state('');
+
+ const GAP = 4; // px between trigger and menu
+ const MARGIN = 12; // keep the menu this far from the viewport edge
+
+ function openMenu() {
+ const r = triggerEl?.getBoundingClientRect();
+ if (r) {
+ const below = window.innerHeight - r.bottom;
+ // Open upward when the field sits near the bottom (e.g. a modal footer).
+ const up = below < 300 && r.top > below;
+ const space = (up ? r.top : below) - GAP - MARGIN;
+ const vpos = up
+ ? `bottom:${window.innerHeight - r.top + GAP}px`
+ : `top:${r.bottom + GAP}px`;
+ menuStyle = `left:${r.left}px; width:${r.width}px; ${vpos}; max-height:${Math.round(space)}px`;
+ }
+ open = true;
+ }
+
+ // Depth-first, so children sit under their parent; depth drives indentation.
+ const options = $derived(
+ flattenPaths(buildTree(folders ?? [], [])).map((p) => ({
+ path: p,
+ name: p.split('/').pop(),
+ depth: p.split('/').length - 1,
+ }))
+ );
+
+ function close() {
+ open = false;
+ creating = false;
+ newName = '';
+ }
+ function pick(p) {
+ value = p;
+ close();
+ }
+ function commitNew() {
+ // Trim and drop leading/trailing slashes; nested paths (a/b) are allowed.
+ const name = newName.trim().replace(/^\/+|\/+$/g, '');
+ if (!name) return;
+ pick(name);
+ }
+</script>
+
+<div class="folder-select">
+ <button
+ type="button"
+ class="trigger"
+ {id}
+ bind:this={triggerEl}
+ onclick={() => (open ? close() : openMenu())}
+ aria-haspopup="listbox"
+ aria-expanded={open}
+ >
+ <Icon name={value ? 'folder' : 'folderMinus'} size={14} />
+ <span class="cur" class:none={!value}>{value || emptyLabel}</span>
+ <Icon name="chevronDown" size={14} />
+ </button>
+
+ {#if open}
+ <button class="backdrop" onclick={close} aria-label="Close folder picker" use:portal></button>
+ <div class="menu card" role="listbox" use:portal style={menuStyle}>
+ <button class="opt" class:active={!value} onclick={() => pick('')}>
+ <Icon name="folderMinus" size={14} />
+ <span class="grow">{emptyLabel}</span>
+ {#if !value}<Icon name="check" size={14} />{/if}
+ </button>
+
+ {#if options.length}
+ <div class="sep"></div>
+ {#each options as o (o.path)}
+ <button
+ class="opt"
+ class:active={value === o.path}
+ style:padding-left={`${10 + o.depth * 14}px`}
+ onclick={() => pick(o.path)}
+ title={o.path}
+ >
+ <Icon name="folder" size={14} />
+ <span class="grow">{o.name}</span>
+ {#if value === o.path}<Icon name="check" size={14} />{/if}
+ </button>
+ {/each}
+ {/if}
+
+ {#if allowCreate}
+ <div class="sep"></div>
+ {#if creating}
+ <form
+ class="create"
+ onsubmit={(e) => {
+ e.preventDefault();
+ commitNew();
+ }}
+ >
+ <!-- svelte-ignore a11y_autofocus -->
+ <input class="input" placeholder="New folder name…" bind:value={newName} autofocus />
+ <button type="submit" class="btn btn-primary btn-sm" disabled={!newName.trim()}>
+ Add
+ </button>
+ </form>
+ {:else}
+ <button class="opt new" onclick={() => (creating = true)}>
+ <Icon name="plus" size={14} /> New folder…
+ </button>
+ {/if}
+ {/if}
+ </div>
+ {/if}
+</div>
+
+<style>
+ .folder-select {
+ position: relative;
+ }
+ .trigger {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ padding: 6px 8px;
+ background: var(--bg-2);
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ color: var(--text-1);
+ font-size: var(--fs-sm);
+ text-align: left;
+ }
+ .trigger:hover {
+ border-color: var(--border-strong);
+ }
+ .cur {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .cur.none {
+ color: var(--text-3);
+ }
+ /* Portaled to <body>, so they sit above the modal overlay (z-index 900). */
+ .backdrop {
+ position: fixed;
+ inset: 0;
+ z-index: 940;
+ cursor: default;
+ }
+ .menu {
+ position: fixed;
+ min-width: 220px;
+ overflow: auto;
+ z-index: 950;
+ box-shadow: var(--shadow-2);
+ padding: 5px;
+ }
+ .opt {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ padding: 7px 10px;
+ border-radius: var(--r-sm);
+ font-size: var(--fs-sm);
+ color: var(--text-1);
+ text-align: left;
+ }
+ .opt:hover {
+ background: var(--bg-2);
+ }
+ .opt.active {
+ background: var(--bg-3);
+ }
+ .opt.new {
+ color: var(--accent);
+ font-weight: 600;
+ }
+ .grow {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .sep {
+ height: 1px;
+ background: var(--border);
+ margin: 5px 0;
+ }
+ .create {
+ display: flex;
+ gap: 6px;
+ padding: 4px;
+ }
+ .create .input {
+ flex: 1;
+ min-width: 0;
+ }
+</style>
diff --git a/frontend/src/components/FolderSelect.test.js b/frontend/src/components/FolderSelect.test.js
new file mode 100644
index 0000000..4506bf8
--- /dev/null
+++ b/frontend/src/components/FolderSelect.test.js
@@ -0,0 +1,17 @@
+import { describe, expect, it } from 'vitest';
+import { render } from 'svelte/server';
+import FolderSelect from './FolderSelect.svelte';
+
+describe('FolderSelect trigger', () => {
+ it('shows the empty label when nothing is picked', () => {
+ const { body } = render(FolderSelect, { props: { value: '', emptyLabel: 'Unfiled' } });
+ expect(body).toContain('Unfiled');
+ });
+
+ it('shows the picked folder path on the trigger', () => {
+ const { body } = render(FolderSelect, {
+ props: { value: 'research/sources', folders: ['research', 'research/sources'] },
+ });
+ expect(body).toContain('research/sources');
+ });
+});
diff --git a/frontend/src/components/Icon.svelte b/frontend/src/components/Icon.svelte
index 416ea30..f00883d 100644
--- a/frontend/src/components/Icon.svelte
+++ b/frontend/src/components/Icon.svelte
@@ -47,7 +47,12 @@
external: 'M14 4h6v6m0-6L10 14M9 5H6a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h11a2 2 0 0 0 2-2v-3',
grip: 'M9 6h.01M9 12h.01M9 18h.01M15 6h.01M15 12h.01M15 18h.01',
alert: 'M12 3 2.5 19.5h19L12 3Zm0 7v4m0 3.5h.01',
+ info: 'M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20Zm0-11v6m0-10h.01',
clock: 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18Zm0 4v5l3.5 2',
+ play: 'm8 5 11 7-11 7V5Z',
+ pause: 'M8 5v14m8-14v14',
+ volume: 'M5 10v4h3l4 4V6L8 10H5Zm11-2a6 6 0 0 1 0 8m2.5-10.5a9 9 0 0 1 0 13',
+ volumeOff: 'M5 10v4h3l4 4V6L8 10H5m8.5.5 5 5m0-5-5 5',
eye: 'M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12Zm9.5-3a3 3 0 1 1 0 6 3 3 0 0 1 0-6Z',
eyeOff: 'M9.9 9.9a3 3 0 1 0 4.2 4.2M10.7 5.7A9.8 9.8 0 0 1 12 5.5c6 0 9.5 6.5 9.5 6.5a17.8 17.8 0 0 1-2.2 3M6.6 6.6C4 8.4 2.5 12 2.5 12S6 18.5 12 18.5c1.5 0 2.9-.4 4.1-1.1M3 3l18 18',
key: 'm21 2-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777Zm0 0L15.5 7.5m0 0 3 3L22 7l-3-3m-3.5 3.5L19 4',
@@ -74,6 +79,8 @@
ruler: 'M4 15.5 15.5 4l4.5 4.5L8.5 20 4 15.5Zm3.5-.5 1.5 1.5m1-4.5 1.5 1.5m1-4.5L14 11',
polygon: 'M12 3.5 20 9.5l-3 9.5H7L4 9.5l8-6Z',
angle: 'M5 4v15h15M5 19 20 6',
+ sun: 'M12 7a5 5 0 1 0 0 10 5 5 0 0 0 0-10ZM12 1v3M12 20v3M4.2 4.2l2.1 2.1M17.7 17.7l2.1 2.1M1 12h3M20 12h3M4.2 19.8l2.1-2.1M17.7 6.3l2.1-2.1',
+ moon: 'M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8Z',
};
</script>
diff --git a/frontend/src/components/Logo.svelte b/frontend/src/components/Logo.svelte
index 3aca4fb..d5ec8e1 100644
--- a/frontend/src/components/Logo.svelte
+++ b/frontend/src/components/Logo.svelte
@@ -24,10 +24,10 @@
<path fill="rgb(47,48,51)" d="M 683.889 769.546 C 700.993 768.842 722.491 769.394 739.895 769.462 C 758.503 769.535 792.856 768.305 810.571 770.899 L 811.104 772.567 L 809.671 773.004 C 775.959 776.654 742.332 774.638 708.41 775.181 C 704.001 775.251 682.502 775.588 679.619 773.975 L 679.443 772.324 C 681.597 769.303 680.177 770.221 683.889 769.546 z" />
<path fill="rgb(47,48,51)" d="M 1262.95 769.419 C 1286.17 768.587 1310.69 770.197 1334.09 769.441 C 1344.57 769.103 1358.15 769.121 1368.41 770.211 L 1369.61 772.23 C 1364.26 776.087 1359.84 775.295 1353.3 775.148 C 1338.95 774.996 1251.54 776.456 1244.38 773.492 C 1248.98 769.403 1256.95 769.609 1262.95 769.419 z" />
<path fill="rgb(174,145,110)" d="M 1048.47 465.87 C 1114.42 465.733 1185.21 498.054 1234.21 541.356 C 1293.6 594.557 1329.33 669.24 1333.5 748.867 C 1319.01 748.611 1304.06 748.785 1289.53 748.773 C 1287.61 696.749 1262.7 636.812 1228.29 598.112 C 1178.68 542.309 1121.51 515.963 1048.46 510.187 C 1048.37 495.415 1048.37 480.642 1048.47 465.87 z" />
- <path fill="rgb(203,193,181)" d="M 997.517 467.424 C 1000.49 467.14 999.299 466.671 1001.38 468.216 C 1002.96 475.01 1002.18 503.418 1002.1 511.662 C 954.811 515.143 901.995 536.481 864.837 565.599 C 803.873 613.372 771.809 673.186 761.809 748.875 C 749.319 748.64 736.283 748.838 723.75 748.858 L 720.18 748.447 C 717.043 743.897 721.456 723.766 722.664 717.553 C 732.187 667.784 753.917 621.158 785.905 581.859 C 838.343 517.001 914.534 475.798 997.517 467.424 z" />
+ <path fill="var(--brand-ink, rgb(203,193,181))" d="M 997.517 467.424 C 1000.49 467.14 999.299 466.671 1001.38 468.216 C 1002.96 475.01 1002.18 503.418 1002.1 511.662 C 954.811 515.143 901.995 536.481 864.837 565.599 C 803.873 613.372 771.809 673.186 761.809 748.875 C 749.319 748.64 736.283 748.838 723.75 748.858 L 720.18 748.447 C 717.043 743.897 721.456 723.766 722.664 717.553 C 732.187 667.784 753.917 621.158 785.905 581.859 C 838.343 517.001 914.534 475.798 997.517 467.424 z" />
<path fill="url(#az-rose-se)" d="M 1289.25 795.949 L 1332.89 796.039 C 1327.48 849.421 1311.73 897.547 1281.23 942.11 C 1235.69 1008.94 1165.38 1054.85 1085.87 1069.67 C 1074.09 1072.12 1060.39 1073.61 1048.41 1074.67 C 1048.49 1060.14 1048.48 1045.62 1048.38 1031.09 C 1180.01 1018.19 1273.05 926.957 1289.25 795.949 z" />
<path fill="url(#az-rose-sw)" d="M 718.719 795.968 L 762.601 796.01 C 765.423 844.66 791.223 900.082 822.425 937.046 C 867.523 990.852 932.188 1024.49 1002.13 1030.52 L 1002.09 1074.18 C 943.935 1071.36 879.034 1044.96 834.217 1008.63 C 765.319 952.789 728.817 882.792 718.719 795.968 z" />
- <path fill="rgb(203,193,181)" d="M 849.463 955.024 L 848.074 955.646 L 847.678 954.653 C 852.011 944.457 871.897 911.572 878.066 900.781 C 899.33 863.039 920.906 825.474 942.791 788.088 C 948.342 778.607 954.574 768.415 959.813 758.717 C 965.567 748.067 969.999 738.042 977.087 728.115 C 986.729 714.612 1003.31 712.43 1016.1 704.241 C 1034.59 692.406 1203.03 583.022 1204.46 582.805 L 1203.93 585.09 C 1199.65 595.348 1183.1 622.104 1176.81 632.84 C 1162.47 657.73 1148.37 682.755 1134.51 707.912 C 1121.46 731.261 1108.42 754.609 1095.45 778.029 C 1088.53 790.523 1083.97 804.712 1074.93 815.709 C 1063.27 829.904 1049.73 832.35 1034.49 840.724 C 1025.89 845.455 1015.6 852.163 1007.06 857.461 L 905.739 920.454 C 895.621 926.841 856.923 952.607 849.463 955.024 z" />
+ <path fill="var(--brand-ink, rgb(203,193,181))" d="M 849.463 955.024 L 848.074 955.646 L 847.678 954.653 C 852.011 944.457 871.897 911.572 878.066 900.781 C 899.33 863.039 920.906 825.474 942.791 788.088 C 948.342 778.607 954.574 768.415 959.813 758.717 C 965.567 748.067 969.999 738.042 977.087 728.115 C 986.729 714.612 1003.31 712.43 1016.1 704.241 C 1034.59 692.406 1203.03 583.022 1204.46 582.805 L 1203.93 585.09 C 1199.65 595.348 1183.1 622.104 1176.81 632.84 C 1162.47 657.73 1148.37 682.755 1134.51 707.912 C 1121.46 731.261 1108.42 754.609 1095.45 778.029 C 1088.53 790.523 1083.97 804.712 1074.93 815.709 C 1063.27 829.904 1049.73 832.35 1034.49 840.724 C 1025.89 845.455 1015.6 852.163 1007.06 857.461 L 905.739 920.454 C 895.621 926.841 856.923 952.607 849.463 955.024 z" />
<path fill="url(#az-rose-needle)" d="M 1110.53 682.315 L 1111.19 684.205 C 1108.86 686.868 1106.8 688.065 1106.87 690.69 C 1109.72 692.169 1115.29 694.969 1117.65 696.855 C 1123.16 701.261 1123.27 710.06 1130.9 710.092 L 1134.51 707.912 C 1121.46 731.261 1108.42 754.609 1095.45 778.029 C 1088.53 790.523 1083.97 804.712 1074.93 815.709 C 1063.27 829.904 1049.73 832.35 1034.49 840.724 C 1025.89 845.455 1015.6 852.163 1007.06 857.461 L 905.739 920.454 C 895.621 926.841 856.923 952.607 849.463 955.024 C 854.952 946.492 878.753 922.785 887.184 913.778 C 924.329 874.425 961.711 835.297 999.328 796.395 C 988.514 784.1 988.27 766.925 997.429 753.613 C 1002.93 745.462 1011.57 739.958 1021.28 738.411 C 1032.51 736.675 1040 739.991 1048.71 746.165 C 1069.04 725.375 1089.49 702.188 1110.53 682.315 z" />
<path fill="rgb(125,118,108)" d="M 1110.53 682.315 C 1114.69 675.669 1144.02 646.116 1151.08 639.522 C 1167.15 624.497 1187.5 598.081 1203.93 585.09 C 1199.65 595.348 1183.1 622.104 1176.81 632.84 C 1162.47 657.73 1148.37 682.755 1134.51 707.912 L 1130.9 710.092 C 1123.27 710.06 1123.16 701.261 1117.65 696.855 C 1115.29 694.969 1109.72 692.169 1106.87 690.69 C 1106.8 688.065 1108.86 686.868 1111.19 684.205 L 1110.53 682.315 z" />
<path fill="rgb(13,17,21)" d="M 999.328 796.395 C 988.514 784.1 988.27 766.925 997.429 753.613 C 1002.93 745.462 1011.57 739.958 1021.28 738.411 C 1032.51 736.675 1040 739.991 1048.71 746.165 C 1057.76 757.154 1059.87 762.696 1058.49 777.494 C 1052.5 795.549 1040.57 806.652 1020.62 805.792 C 1015.97 803.196 1010.81 806.377 999.328 796.395 z" />
diff --git a/frontend/src/components/Toasts.svelte b/frontend/src/components/Toasts.svelte
index 00db5c9..3d4f4e4 100644
--- a/frontend/src/components/Toasts.svelte
+++ b/frontend/src/components/Toasts.svelte
@@ -4,6 +4,15 @@
import { portal } from '../lib/fullscreen.js';
const icons = { info: 'compass', ok: 'check', danger: 'alert', warn: 'alert' };
+
+ function activate(t) {
+ try {
+ t.action?.onClick?.();
+ } finally {
+ const index = uiState.toasts.findIndex((item) => item.id === t.id);
+ if (index !== -1) uiState.toasts.splice(index, 1);
+ }
+ }
</script>
<div class="toasts" use:portal>
@@ -11,6 +20,11 @@
<div class="toast {t.kind}">
<Icon name={icons[t.kind] ?? 'compass'} size={15} />
<span>{t.message}</span>
+ {#if t.action}
+ <button class="toast-action" type="button" onclick={() => activate(t)}>
+ {t.action.label}
+ </button>
+ {/if}
</div>
{/each}
</div>
@@ -53,4 +67,23 @@
border-color: var(--warn);
color: var(--warn);
}
+ .toast-action {
+ pointer-events: auto;
+ margin-left: 4px;
+ padding: 2px 0;
+ border: 0;
+ background: transparent;
+ color: inherit;
+ font: inherit;
+ font-size: var(--fs-xs);
+ font-weight: 700;
+ letter-spacing: 0.08em;
+ text-decoration: underline;
+ text-underline-offset: 3px;
+ cursor: pointer;
+ }
+ .toast-action:hover,
+ .toast-action:focus-visible {
+ color: var(--text);
+ }
</style>
diff --git a/frontend/src/components/Toasts.test.js b/frontend/src/components/Toasts.test.js
new file mode 100644
index 0000000..c1969a4
--- /dev/null
+++ b/frontend/src/components/Toasts.test.js
@@ -0,0 +1,25 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { render } from 'svelte/server';
+import { uiState } from '../lib/state.svelte.js';
+import Toasts from './Toasts.svelte';
+
+afterEach(() => {
+ uiState.toasts = [];
+});
+
+describe('Toasts', () => {
+ it('renders an action as an explicit clickable button', () => {
+ uiState.toasts = [{
+ id: 1,
+ message: 'Report saved as a note',
+ kind: 'ok',
+ action: { label: 'OPEN', onClick: vi.fn() },
+ }];
+
+ const { body } = render(Toasts);
+
+ expect(body).toContain('Report saved as a note');
+ expect(body).toContain('>OPEN</button>');
+ expect(body).toContain('toast-action');
+ });
+});
diff --git a/frontend/src/components/Wordmark.svelte b/frontend/src/components/Wordmark.svelte
index 7b3b399..c8e4108 100644
--- a/frontend/src/components/Wordmark.svelte
+++ b/frontend/src/components/Wordmark.svelte
@@ -5,7 +5,7 @@
<!-- AZIMUT lettering from the brand logo (frontend/src/assets/logo-source.svg),
kept as vector so it scales with the mark. Coordinates verbatim from the source. -->
<svg {height} viewBox="285 1200 1225 194" aria-label="Azimut">
- <g fill="rgb(203,193,181)">
+ <g fill="var(--brand-ink, rgb(203,193,181))">
<path d="M 386.806 1206.85 L 406.791 1206.65 C 438.322 1267.19 471.856 1327.3 502.947 1387.95 L 476.826 1388 L 399.896 1244.09 C 398.633 1241.84 398.212 1241.38 396.679 1239.3 C 394.17 1241.25 322.694 1375.93 316.247 1388.03 L 290.282 1388 C 322.057 1327.4 354.232 1267.02 386.806 1206.85 z" />
<path transform="translate(-35 0)" d="M 593.024 1206.88 C 645.808 1205.92 701.57 1206.88 754.594 1206.92 L 754.545 1221.64 C 712.636 1269.72 668.106 1318.07 625.616 1365.98 L 755.368 1366.15 L 755.514 1388.04 C 700.985 1387 643.129 1388.01 588.33 1388.08 L 588.281 1373.82 C 630.958 1325.33 673.893 1277.08 717.085 1229.05 C 676.116 1228.57 634.048 1228.98 593.005 1228.97 L 593.024 1206.88 z" />
<path transform="translate(-92 0)" d="M 862.025 1206.82 L 884.691 1206.83 L 884.787 1387.97 L 862.017 1387.98 L 862.025 1206.82 z" />
diff --git a/frontend/src/lib/api.js b/frontend/src/lib/api.js
index 8b8a11d..04a832c 100644
--- a/frontend/src/lib/api.js
+++ b/frontend/src/lib/api.js
@@ -30,7 +30,9 @@ async function request(method, path, body, opts = {}) {
}
export const api = {
- get: (path) => request('GET', path),
+ // `opts` reaches fetch (e.g. `{ signal }`) so a caller can cancel a stale
+ // request — the bounded catalog aborts an in-flight page on case/filter change.
+ get: (path, opts) => request('GET', path, undefined, opts),
post: (path, body) => request('POST', path, body),
put: (path, body) => request('PUT', path, body),
patch: (path, body) => request('PATCH', path, body),
diff --git a/frontend/src/lib/catalog.js b/frontend/src/lib/catalog.js
new file mode 100644
index 0000000..9ac6ea0
--- /dev/null
+++ b/frontend/src/lib/catalog.js
@@ -0,0 +1,66 @@
+/** Bounded catalog helpers shared by the case tools and sidebar. */
+import { api } from './api.js';
+
+/** Apply a summary response only while its request still belongs to the active case. */
+export function settleCatalogSummary(current, next, isCurrent) {
+ return isCurrent ? next : current;
+}
+
+/** Build the catalog request path. Only the filters that are set appear.
+ * `unfiled` (no folder) wins over an exact `folder` path when both are given. */
+export function buildCatalogQuery(
+ caseId,
+ { cursor, limit, types, status, query, folder, unfiled } = {}
+) {
+ const params = new URLSearchParams();
+ if (limit != null) params.set('limit', String(limit));
+ if (cursor) params.set('cursor', cursor);
+ if (types && types.length) params.set('type', types.join(','));
+ if (status) params.set('status', status);
+ if (query) params.set('q', query);
+ if (unfiled) params.set('unfiled', 'true');
+ else if (folder != null) params.set('folder', folder);
+ const qs = params.toString();
+ return `/api/cases/${caseId}/catalog/entities${qs ? `?${qs}` : ''}`;
+}
+
+/**
+ * Walk every page of the catalog and return the whole filtered list.
+ *
+ * The bounded read for a tool that genuinely needs a full slice — the Files
+ * finder tree, the Notebook mention list, the map's saved places — off the
+ * catalog endpoint instead of the case-open payload. It pages server-side
+ * (largest page the API allows) so the graph never ships in one response, and a
+ * caller can still window the returned rows. `signal` cancels a case switch.
+ */
+export async function fetchAllEntities(
+ caseId,
+ { types, status, query, get = api.get, signal, pageSize = 500 } = {}
+) {
+ if (!caseId) return [];
+ const out = [];
+ let cursor = null;
+ do {
+ const path = buildCatalogQuery(caseId, { cursor, limit: pageSize, types, status, query });
+ const page = await get(path, signal ? { signal } : undefined);
+ out.push(...(page.items ?? []));
+ cursor = page.next_cursor ?? null;
+ } while (cursor);
+ return out;
+}
+
+/** Resolve one entity by an `attrs` value (`path`, `spec`, `draft`), or null.
+ * The bounded replacement for scanning the whole graph for a single file. */
+export async function lookupEntity(caseId, attr, value, { get = api.get } = {}) {
+ if (!caseId) return null;
+ const params = new URLSearchParams({ attr, value });
+ const res = await get(`/api/cases/${caseId}/entities/lookup?${params}`);
+ return res?.entity ?? null;
+}
+
+/** The transitive `derived-from` closure rooted at an entity, as
+ * `{ entities, links }` — the Post composer's proof-to-source-media trace. */
+export async function fetchDerivation(caseId, entityId, { get = api.get } = {}) {
+ if (!caseId || !entityId) return { entities: [], links: [] };
+ return get(`/api/cases/${caseId}/entities/${entityId}/derivation`);
+}
diff --git a/frontend/src/lib/catalog.test.js b/frontend/src/lib/catalog.test.js
new file mode 100644
index 0000000..0388174
--- /dev/null
+++ b/frontend/src/lib/catalog.test.js
@@ -0,0 +1,89 @@
+import { describe, expect, it } from 'vitest';
+import {
+ buildCatalogQuery, fetchAllEntities, lookupEntity, fetchDerivation, settleCatalogSummary,
+} from './catalog.js';
+
+describe('buildCatalogQuery', () => {
+ it('omits unset filters and joins a type set', () => {
+ expect(buildCatalogQuery('c1', {})).toBe('/api/cases/c1/catalog/entities');
+ expect(
+ buildCatalogQuery('c1', {
+ limit: 50,
+ cursor: '12',
+ types: ['media', 'capture'],
+ status: 'suggested',
+ query: 'ada',
+ })
+ ).toBe(
+ '/api/cases/c1/catalog/entities?limit=50&cursor=12&type=media%2Ccapture&status=suggested&q=ada'
+ );
+ });
+
+ it('carries a folder path, and lets unfiled win over it', () => {
+ expect(buildCatalogQuery('c1', { folder: 'Sources/Telegram' })).toBe(
+ '/api/cases/c1/catalog/entities?folder=Sources%2FTelegram'
+ );
+ expect(buildCatalogQuery('c1', { unfiled: true, folder: 'ignored' })).toBe(
+ '/api/cases/c1/catalog/entities?unfiled=true'
+ );
+ });
+});
+
+describe('settleCatalogSummary', () => {
+ it('clears a current failed request and ignores a stale response', () => {
+ const previous = { total: 12 };
+ expect(settleCatalogSummary(previous, null, true)).toBe(null);
+ expect(settleCatalogSummary(previous, { total: 3 }, false)).toBe(previous);
+ });
+});
+
+/** A stand-in backend that pages a fixed id list the way the API does. */
+function fakeBackend(ids) {
+ return async (path) => {
+ if (path.includes('/catalog/summary')) {
+ return { total: ids.length, by_type: {}, by_status: {} };
+ }
+ const url = new URL(path, 'http://x');
+ const cursor = Number(url.searchParams.get('cursor') ?? 0);
+ const limit = Number(url.searchParams.get('limit') ?? 100);
+ const slice = ids.slice(cursor, cursor + limit).map((id) => ({ id, type: 'person', label: id }));
+ const nextCursor = cursor + limit < ids.length ? String(cursor + limit) : null;
+ return { items: slice, next_cursor: nextCursor };
+ };
+}
+
+describe('fetchAllEntities — the full bounded slice', () => {
+ it('walks every page and returns the whole list', async () => {
+ const get = fakeBackend(['a', 'b', 'c', 'd', 'e']);
+ const all = await fetchAllEntities('c1', { pageSize: 2, get });
+ expect(all.map((e) => e.id)).toEqual(['a', 'b', 'c', 'd', 'e']);
+ });
+
+ it('passes filters through and is empty without a case', async () => {
+ const paths = [];
+ const get = async (path) => {
+ paths.push(path);
+ return { items: [], next_cursor: null };
+ };
+ await fetchAllEntities('c1', { types: ['place'], status: 'confirmed', get });
+ expect(paths[0]).toContain('type=place');
+ expect(paths[0]).toContain('status=confirmed');
+ expect(await fetchAllEntities(null, { get })).toEqual([]);
+ });
+});
+
+describe('lookupEntity / fetchDerivation', () => {
+ it('resolves an entity by attr, or null', async () => {
+ const get = async (path) =>
+ path.includes('value=media%2Fa.jpg') ? { entity: { id: 'e1' } } : { entity: null };
+ expect((await lookupEntity('c1', 'path', 'media/a.jpg', { get })).id).toBe('e1');
+ expect(await lookupEntity('c1', 'path', 'media/none.jpg', { get })).toBe(null);
+ expect(await lookupEntity(null, 'path', 'x', { get })).toBe(null);
+ });
+
+ it('fetches a derivation subgraph, empty without ids', async () => {
+ const get = async () => ({ entities: [{ id: 'p' }], links: [{ from: 'p', to: 'm' }] });
+ expect((await fetchDerivation('c1', 'p', { get })).entities).toHaveLength(1);
+ expect(await fetchDerivation('c1', null, { get })).toEqual({ entities: [], links: [] });
+ });
+});
diff --git a/frontend/src/lib/folderTree.js b/frontend/src/lib/folderTree.js
index 94f59d0..c8ff009 100644
--- a/frontend/src/lib/folderTree.js
+++ b/frontend/src/lib/folderTree.js
@@ -6,6 +6,12 @@
export const folderOf = (e) => e.attrs?.folder || null;
+/** True when an entity belongs to `folder` or one of its descendants. */
+export function isInFolderSubtree(entity, folder) {
+ const entityFolder = folderOf(entity);
+ return entityFolder === folder || entityFolder?.startsWith(`${folder}/`) || false;
+}
+
/** Build the nested tree. Folders exist even when empty; entities attach
* to their exact folder node. Children are sorted case-insensitively. */
export function buildTree(folders, items) {
@@ -38,6 +44,16 @@ export function subtreeCount(node) {
return node.entities.length + node.children.reduce((s, c) => s + subtreeCount(c), 0);
}
+/**
+ * A node's subtree count from a `{ path: count }` map (the catalog summary's
+ * `by_folder`), for a tree whose nodes carry no entities — the bounded sidebar
+ * builds structure from folders alone and counts from the summary.
+ */
+export function subtreeCountFrom(node, byFolder) {
+ const own = byFolder[node.path] ?? 0;
+ return own + node.children.reduce((s, c) => s + subtreeCountFrom(c, byFolder), 0);
+}
+
/** Every folder path in the tree, depth-first (folder pickers). */
export function flattenPaths(nodes) {
return nodes.flatMap((n) => [n.path, ...flattenPaths(n.children)]);
diff --git a/frontend/src/lib/folderTree.test.js b/frontend/src/lib/folderTree.test.js
index 9718186..aa05a94 100644
--- a/frontend/src/lib/folderTree.test.js
+++ b/frontend/src/lib/folderTree.test.js
@@ -1,5 +1,7 @@
import { describe, it, expect } from 'vitest';
-import { buildTree, subtreeCount, flattenPaths, folderOf } from './folderTree.js';
+import {
+ buildTree, subtreeCount, subtreeCountFrom, flattenPaths, folderOf, isInFolderSubtree,
+} from './folderTree.js';
const ent = (id, folder) => ({ id, attrs: folder ? { folder } : {} });
@@ -11,6 +13,16 @@ describe('folderOf', () => {
});
});
+describe('isInFolderSubtree', () => {
+ it('includes a folder and its descendants, but not sibling or similarly named folders', () => {
+ expect(isInFolderSubtree(ent('a', 'Sources'), 'Sources')).toBe(true);
+ expect(isInFolderSubtree(ent('b', 'Sources/Telegram'), 'Sources')).toBe(true);
+ expect(isInFolderSubtree(ent('c', 'SourcesElse'), 'Sources')).toBe(false);
+ expect(isInFolderSubtree(ent('d', 'Timeline'), 'Sources')).toBe(false);
+ expect(isInFolderSubtree(ent('e'), 'Sources')).toBe(false);
+ });
+});
+
describe('buildTree', () => {
it('nests /-separated paths and keeps empty folders', () => {
const tree = buildTree(['Sources/Telegram', 'Timeline'], []);
@@ -41,3 +53,13 @@ describe('buildTree', () => {
expect(a.children.map((n) => n.name)).toEqual(['B', 'c']);
});
});
+
+describe('subtreeCountFrom', () => {
+ it('sums a folder and its descendants from a by_folder count map', () => {
+ const tree = buildTree(['Sources/Telegram', 'Sources/Signal', 'Timeline'], []);
+ const byFolder = { Sources: 1, 'Sources/Telegram': 3, Timeline: 2 };
+ const sources = tree.find((n) => n.name === 'Sources');
+ expect(subtreeCountFrom(sources, byFolder)).toBe(4); // 1 own + 3 Telegram + 0 Signal
+ expect(subtreeCountFrom(tree.find((n) => n.name === 'Timeline'), byFolder)).toBe(2);
+ });
+});
diff --git a/frontend/src/lib/inspect.js b/frontend/src/lib/inspect.js
index c7a3876..a3c0564 100644
--- a/frontend/src/lib/inspect.js
+++ b/frontend/src/lib/inspect.js
@@ -25,6 +25,20 @@ export function adjustDefaults(filters) {
// tuned video inherits them so it looks like it came from the modified clip.
export const VIDEO_ADJUST_IDS = ['brightness', 'contrast', 'saturation', 'gamma', 'grayscale', 'invert'];
+// Video orientation is deliberately discrete: right-angle turns keep the full
+// frame and map directly to ffmpeg's geometry filters.
+export const RIGHT_ANGLE_ROTATIONS = [-180, -90, 0, 90, 180];
+
+export function normalizeRightAngleRotation(value) {
+ const angle = Number(value);
+ return RIGHT_ANGLE_ROTATIONS.includes(angle) ? angle : 0;
+}
+
+export function rotationOps(value) {
+ const angle = normalizeRightAngleRotation(value);
+ return angle ? [{ op: 'rotate', params: { angle } }] : [];
+}
+
/** Seed a new frame's adjust values from the current video-gear values. */
export function videoSeed(filters, videoAdjust) {
const out = adjustDefaults(filters);
@@ -56,6 +70,10 @@ export function isNeutral(filters, values) {
return filters.every((f) => (values[f.id] ?? defaultOf(f)) === defaultOf(f));
}
+export function hasVideoEdits(filters, values, rotation) {
+ return normalizeRightAngleRotation(rotation) !== 0 || !isNeutral(filters, values);
+}
+
/** Turn slider values (+ optional fractional crop) into the backend op pipeline. */
export function buildOps(filters, values, crop = null) {
values = values ?? {};
@@ -69,6 +87,15 @@ export function buildOps(filters, values, crop = null) {
return ops;
}
+/** Build the full recipe for a captured frame, including its video orientation. */
+export function buildFrameOps(filters, frame) {
+ return [
+ ...(frame?.sourceOps ?? []),
+ ...rotationOps(frame?.rotation),
+ ...buildOps(filters, frame?.adjust, frame?.crop),
+ ];
+}
+
/**
* A collage piece's recipe stripped back to its unprojected pixels.
*
diff --git a/frontend/src/lib/inspect.test.js b/frontend/src/lib/inspect.test.js
index 31591ba..2b2f641 100644
--- a/frontend/src/lib/inspect.test.js
+++ b/frontend/src/lib/inspect.test.js
@@ -3,10 +3,41 @@ import {
clampCrop, moveCrop, resizeCropByHandle,
QUAD_SIDES, quadEdgeMidpoints, moveQuadEdge, quadCentroid,
quadsBounds, translateQuad, moveQuads, rotateQuads, scaleQuads, pinholeOps,
+ buildFrameOps, hasVideoEdits, normalizeRightAngleRotation, rotationOps,
} from './inspect.js';
const near = (a, b, eps = 1e-6) => Math.abs(a - b) < eps;
+describe('video orientation', () => {
+ const filters = [{ id: 'brightness', params: [{ name: 'amount', default: 1 }] }];
+
+ it('accepts only the supported right-angle orientations', () => {
+ expect([-180, -90, 0, 90, 180].map(normalizeRightAngleRotation)).toEqual([-180, -90, 0, 90, 180]);
+ expect(normalizeRightAngleRotation(45)).toBe(0);
+ expect(normalizeRightAngleRotation('bad')).toBe(0);
+ });
+
+ it('makes a rotation-only video saveable', () => {
+ expect(hasVideoEdits(filters, { brightness: 1 }, 90)).toBe(true);
+ expect(hasVideoEdits(filters, { brightness: 1 }, 0)).toBe(false);
+ expect(hasVideoEdits(filters, { brightness: 1.2 }, 0)).toBe(true);
+ });
+
+ it('carries the video orientation into captured-frame recipes', () => {
+ const frame = {
+ sourceOps: rotationOps(-90),
+ rotation: 180,
+ adjust: { brightness: 1.2 },
+ crop: null,
+ };
+ expect(buildFrameOps(filters, frame)).toEqual([
+ { op: 'rotate', params: { angle: -90 } },
+ { op: 'rotate', params: { angle: 180 } },
+ { op: 'brightness', params: { amount: 1.2 } },
+ ]);
+ });
+});
+
describe('pinholeOps', () => {
const remap = { op: 'remap', params: { warp: 'cylindrical' } };
const bright = { op: 'brightness', params: { amount: 1.2 } };
diff --git a/frontend/src/lib/markdown.js b/frontend/src/lib/markdown.js
new file mode 100644
index 0000000..21247d3
--- /dev/null
+++ b/frontend/src/lib/markdown.js
@@ -0,0 +1,166 @@
+import DOMPurify from 'dompurify';
+import { marked, Renderer } from 'marked';
+
+const ENTITY_REF = /\[\[entity:([A-Za-z0-9_-]+)\|([^\]]+)\]\]/g;
+const MEDIA_REF = /\[\[media:([A-Za-z0-9_-]+)\|([^\]]+)\]\](?:\{([^}\n]+)\})?/g;
+const IMAGE_ATTRS = /!\[([^\]]*)\]\((\S+?)(?:\s+["']([^"']*)["'])?\)\s*\{([^}\n]+)\}/g;
+const ALIGNMENT_BLOCK = /^:::\s*(left|center|right)\s*\n([\s\S]*?)^:::\s*$/gm;
+const ATTR_PARAM = '__azimut_attrs';
+const purify = typeof window === 'undefined' ? null : DOMPurify(window);
+
+function sanitize(rendered) {
+ if (purify) return purify.sanitize(rendered, {
+ ADD_TAGS: ['video', 'source'],
+ ADD_ATTR: ['controls', 'target', 'data-entity-id'],
+ });
+ // The preview only runs in a browser. This small fallback keeps server-side
+ // callers and unit tests safe without requiring a DOM implementation.
+ return rendered
+ .replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, '')
+ .replace(/\s(?:href|src)=(['"]?)javascript:[^\s>]*\1/gi, '');
+}
+
+/** Markdown source for a portable, clickable reference to an entity in this case. */
+export function entityReference(entity) {
+ return `[[entity:${entity.id}|${entity.label.replace(/[\[\]]/g, '')}]]`;
+}
+
+export function mediaReference(entity) {
+ return `[[media:${entity.id}|${entity.label.replace(/[\[\]]/g, '')}]]`;
+}
+
+/** Remote inline images contact their host whenever the preview is rendered. */
+export function remoteImageUrls(text = '') {
+ const urls = new Set();
+ const tokens = marked.lexer(sourceWithCaseReferences(text), { gfm: true });
+ marked.walkTokens(tokens, (token) => {
+ if (token.type !== 'image') return;
+ const href = imageOptions(token.href).href;
+ const url = new URL(href, 'https://notebook.invalid');
+ if ((url.protocol === 'http:' || url.protocol === 'https:')
+ && url.origin !== 'https://notebook.invalid') {
+ urls.add(url.toString());
+ }
+ });
+ return [...urls];
+}
+
+function withImageAttributes(source) {
+ return source.replace(IMAGE_ATTRS, (_match, alt, href, title, attributes) => {
+ const separator = href.includes('?') ? '&' : '?';
+ const annotated = `${href}${separator}${ATTR_PARAM}=${encodeURIComponent(attributes)}`;
+ return `![${alt}](${annotated}${title ? ` "${title}"` : ''})`;
+ });
+}
+
+function sourceWithCaseReferences(text) {
+ return withImageAttributes(String(text))
+ .replace(ENTITY_REF, (_match, id, label) => `[${label}](azimut://entity/${id})`)
+ .replace(MEDIA_REF, (_match, id, label, attributes) => {
+ const query = attributes ? `?${ATTR_PARAM}=${encodeURIComponent(attributes)}` : '';
+ return `![${label}](azimut://media/${id}${query})`;
+ });
+}
+
+function broken(kind, label) {
+ return `<span class="broken-ref" title="Deleted from this case">${kind}: ${label}</span>`;
+}
+
+function localMediaPath(href, caseId) {
+ const prefix = `/files/${caseId}/`;
+ return caseId && href.startsWith(prefix) ? href.slice(prefix.length) : null;
+}
+
+function imageOptions(href) {
+ const url = new URL(href, 'https://notebook.invalid');
+ const attributes = url.searchParams.get(ATTR_PARAM) ?? '';
+ url.searchParams.delete(ATTR_PARAM);
+ const source = url.origin === 'https://notebook.invalid'
+ ? `${url.pathname}${url.search}${url.hash}`
+ : url.toString();
+ const values = Object.fromEntries([...attributes.matchAll(/\b(width|align)\s*=\s*([\w.%+-]+)/g)]
+ .map(([, key, value]) => [key, value]));
+ const width = /^(?:[1-9]\d?(?:\.\d+)?|100(?:\.0+)?)%$/.test(values.width ?? '')
+ || /^(?:[2-9]\d|[1-9]\d{2}|1[0-5]\d{2}|1600)px$/.test(values.width ?? '')
+ ? values.width : '';
+ const align = ['left', 'center', 'right'].includes(values.align) ? values.align : 'left';
+ return { href: source, width, align };
+}
+
+function imageMarkup({ href, alt, title, width, align }) {
+ const attrs = `${title ? ` title="${title}"` : ''}${width ? ` style="width: ${width}"` : ''}`;
+ return { attrs, className: `markdown-image align-${align}` };
+}
+
+function renderer({ entities, caseId }) {
+ const byId = new Map(entities.map((entity) => [entity.id, entity]));
+ const mediaByPath = new Map(entities
+ .filter((entity) => (entity.type === 'media' || entity.type === 'capture') && entity.attrs?.path)
+ .map((entity) => [entity.attrs.path, entity]));
+ const value = new Renderer();
+
+ value.link = function link(token) {
+ const body = this.parser.parseInline(token.tokens);
+ const entityMatch = /^azimut:\/\/entity\/([A-Za-z0-9_-]+)$/.exec(token.href);
+ if (entityMatch) {
+ return byId.has(entityMatch[1])
+ ? `<a href="#" data-entity-id="${entityMatch[1]}" class="entity-ref">${body}</a>`
+ : broken('Reference unavailable', body);
+ }
+ const mediaMatch = /^azimut:\/\/media\/([A-Za-z0-9_-]+)$/.exec(token.href);
+ if (mediaMatch) {
+ const entity = byId.get(mediaMatch[1]);
+ if (!entity?.attrs?.path) return broken('Media unavailable', body);
+ const url = `/files/${caseId}/${entity.attrs.path}`;
+ return entity.attrs.kind === 'video'
+ ? `<video controls src="${url}">${body}</video>`
+ : `<img src="${url}" alt="${entity.label}">`;
+ }
+ const title = token.title ? ` title="${token.title}"` : '';
+ return `<a href="${token.href}"${title} target="_blank" rel="noreferrer">${body}</a>`;
+ };
+
+ value.image = (token) => {
+ const options = imageOptions(token.href);
+ const path = localMediaPath(options.href, caseId);
+ if (path && !mediaByPath.has(path)) return broken('Media unavailable', token.text);
+ const mediaUrl = new URL(options.href, 'https://notebook.invalid');
+ if (mediaUrl.protocol === 'azimut:' && mediaUrl.hostname === 'media') {
+ const entity = byId.get(mediaUrl.pathname.slice(1));
+ if (!entity?.attrs?.path) return broken('Media unavailable', token.text);
+ const url = `/files/${caseId}/${entity.attrs.path}`;
+ const markup = imageMarkup({ href: url, alt: entity.label, title: token.title, ...options });
+ return entity.attrs.kind === 'video'
+ ? `<video controls src="${url}" class="${markup.className}"${markup.attrs}>${token.text}</video>`
+ : `<img src="${url}" alt="${entity.label}" class="${markup.className}"${markup.attrs}>`;
+ }
+ const markup = imageMarkup({ href: options.href, alt: token.text, title: token.title, ...options });
+ return `<img src="${options.href}" alt="${token.text}" class="${markup.className}"${markup.attrs}>`;
+ };
+ return value;
+}
+
+function renderAlignmentBlocks(source, options) {
+ const blocks = [];
+ const main = source.replace(ALIGNMENT_BLOCK, (_match, align, contents) => {
+ const token = `AZIMUT_ALIGNMENT_BLOCK_${blocks.length}`;
+ blocks.push({ token, align, contents });
+ return token;
+ });
+ const rendered = marked.parse(main, options);
+ return blocks.reduce((html, block) => html.replace(
+ `<p>${block.token}</p>`,
+ `<div class="markdown-align align-${block.align}">${marked.parse(block.contents, options)}</div>`,
+ ), rendered);
+}
+
+/** Render GitHub-flavored Markdown, then remove unsafe HTML before previewing it. */
+export function markdownHtml(text = '', { entities = [], caseId = '' } = {}) {
+ const options = {
+ gfm: true,
+ breaks: false,
+ renderer: renderer({ entities, caseId }),
+ };
+ const rendered = renderAlignmentBlocks(sourceWithCaseReferences(text), options);
+ return sanitize(rendered);
+}
diff --git a/frontend/src/lib/markdown.test.js b/frontend/src/lib/markdown.test.js
new file mode 100644
index 0000000..13eb62c
--- /dev/null
+++ b/frontend/src/lib/markdown.test.js
@@ -0,0 +1,73 @@
+import { describe, expect, it } from 'vitest';
+import { entityReference, markdownHtml, remoteImageUrls } from './markdown.js';
+
+describe('markdownHtml', () => {
+ it('renders GitHub-flavored tables, task lists and fenced code', () => {
+ const html = markdownHtml('| Name | Value |\n| --- | --- |\n| A | B |\n\n- [x] done\n\n```js\nconst x = 1;\n```');
+ expect(html).toContain('<table>');
+ expect(html).toContain('type="checkbox"');
+ expect(html).toContain('<pre><code class="language-js">');
+ });
+
+ it('removes unsafe HTML and URL schemes', () => {
+ const html = markdownHtml('<script>alert(1)</script>\n\n[bad](javascript:alert(1))');
+ expect(html).not.toContain('<script>');
+ expect(html).not.toContain('javascript:');
+ });
+
+ it('renders entity references as clickable local links', () => {
+ const source = entityReference({ id: 'e_lead', label: 'Lead' });
+ expect(source).toBe('[[entity:e_lead|Lead]]');
+ expect(markdownHtml(source, { entities: [{ id: 'e_lead', label: 'Lead' }] }))
+ .toContain('data-entity-id="e_lead"');
+ });
+
+ it('keeps deleted case references visible as broken', () => {
+ expect(markdownHtml('[[entity:e_gone|Deleted lead]]')).toContain('Reference unavailable: Deleted lead');
+ expect(markdownHtml('![Deleted image](/files/case-1/media/gone.png)', { caseId: 'case-1' }))
+ .toContain('Media unavailable: Deleted image');
+ });
+
+ it('sizes and aligns images without allowing unsafe values', () => {
+ const html = markdownHtml('![Map](/map.png){width=50% align=center}');
+ expect(html).toContain('class="markdown-image align-center"');
+ expect(html).toContain('style="width: 50%"');
+
+ const invalid = markdownHtml('![Map](/map.png){width=99999px align=diagonal}');
+ expect(invalid).toContain('class="markdown-image align-left"');
+ expect(invalid).not.toContain('width:');
+ });
+
+ it('applies alignment blocks to rendered Markdown content', () => {
+ const html = markdownHtml('::: center\n**Centred text**\n:::');
+ expect(html).toContain('<div class="markdown-align align-center">');
+ expect(html).toContain('<strong>Centred text</strong>');
+ });
+
+ it('applies image options to case media', () => {
+ const html = markdownHtml('[[media:e_image|Map]]{width=320px align=right}', {
+ caseId: 'case-1',
+ entities: [{ id: 'e_image', label: 'Map', type: 'media', attrs: { path: 'media/map.png', kind: 'image' } }],
+ });
+ expect(html).toContain('src="/files/case-1/media/map.png"');
+ expect(html).toContain('class="markdown-image align-right"');
+ expect(html).toContain('style="width: 320px"');
+ });
+});
+
+describe('remoteImageUrls', () => {
+ it('reports external inline images but not links or case media', () => {
+ const source = [
+ '[Website](https://example.com/page)',
+ '![Tracker](https://images.example/pixel.png)',
+ '![Local](/files/case-1/media/local.png)',
+ '[[media:e_local|Filed image]]',
+ ].join('\n\n');
+ expect(remoteImageUrls(source)).toEqual(['https://images.example/pixel.png']);
+ });
+
+ it('deduplicates remote images and recognizes protocol-relative URLs', () => {
+ const source = '![A](//images.example/a.png)\n![A again](https://images.example/a.png)';
+ expect(remoteImageUrls(source)).toEqual(['https://images.example/a.png']);
+ });
+});
diff --git a/frontend/src/lib/navigate.js b/frontend/src/lib/navigate.js
index ea7b2bb..aa41648 100644
--- a/frontend/src/lib/navigate.js
+++ b/frontend/src/lib/navigate.js
@@ -17,6 +17,11 @@ export const ENTITY_TOOL = {
/** Reopen an artifact in its tool, loading whatever spec/draft it carries. */
export function openEntity(entity) {
+ if (entity.type === 'note') {
+ uiState.openNotebook = { noteId: entity.id };
+ uiState.tool = 'notebook';
+ return;
+ }
if (entity.type === 'proof') {
const spec = entity.attrs?.spec ?? '';
const name = spec.replace(/^proofs\//, '').replace(/\.json$/, '');
@@ -52,6 +57,30 @@ export function openEntity(entity) {
uiState.tool = 'satellite';
return;
}
+ if (entity.type === 'bookmark' && entity.attrs?.url) {
+ window.open(entity.attrs.url, '_blank', 'noopener,noreferrer');
+ return;
+ }
+ if (entity.type === 'capture') {
+ if (entity.attrs?.source_url) {
+ window.open(entity.attrs.source_url, '_blank', 'noopener,noreferrer');
+ return;
+ }
+ const lat = Number(entity.attrs?.lat);
+ const lon = Number(entity.attrs?.lon);
+ if (Number.isFinite(lat) && Number.isFinite(lon)) {
+ uiState.gotoCoords = {
+ lat,
+ lon,
+ zoom: Number(entity.attrs?.zoom),
+ bearing: Number(entity.attrs?.bearing),
+ provider: entity.attrs?.provider,
+ };
+ uiState.focusCapture = entity.attrs?.path ?? null;
+ uiState.tool = 'satellite';
+ }
+ return;
+ }
if (entity.type === 'media') {
if (entity.attrs?.path) uiState.focusMedia = entity.attrs.path;
uiState.tool = 'media';
@@ -61,6 +90,12 @@ export function openEntity(entity) {
if (tool) uiState.tool = tool;
}
+/** Open the case-wide note (null) or one filed note in the shared Notebook. */
+export function openNotebook(noteId = null) {
+ uiState.openNotebook = { noteId };
+ uiState.tool = 'notebook';
+}
+
/** Fly the Satellite map to a capture's recorded coordinates (its marker). */
export function gotoCapture(entity) {
const lat = Number(entity.attrs?.lat);
diff --git a/frontend/src/lib/navigate.test.js b/frontend/src/lib/navigate.test.js
new file mode 100644
index 0000000..200b8ab
--- /dev/null
+++ b/frontend/src/lib/navigate.test.js
@@ -0,0 +1,33 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { uiState } from './state.svelte.js';
+import { openEntity } from './navigate.js';
+
+beforeEach(() => {
+ uiState.tool = 'media';
+ uiState.gotoCoords = null;
+ uiState.focusCapture = null;
+ vi.stubGlobal('window', { open: vi.fn() });
+});
+
+describe('openEntity', () => {
+ it('opens bookmarks and external captures in a new browser tab', () => {
+ openEntity({ type: 'bookmark', attrs: { url: 'https://example.test/bookmark' } });
+ openEntity({ type: 'capture', attrs: { source_url: 'https://maps.example.test/view' } });
+
+ expect(window.open).toHaveBeenNthCalledWith(1, 'https://example.test/bookmark', '_blank', 'noopener,noreferrer');
+ expect(window.open).toHaveBeenNthCalledWith(2, 'https://maps.example.test/view', '_blank', 'noopener,noreferrer');
+ });
+
+ it('returns an internal capture to its recorded Satellite view', () => {
+ openEntity({ type: 'capture', attrs: {
+ path: 'media/crop.png', lat: 48.8584, lon: 2.2945, zoom: 17, bearing: 30,
+ provider: 'esri-world-imagery',
+ } });
+
+ expect(uiState.tool).toBe('satellite');
+ expect(uiState.focusCapture).toBe('media/crop.png');
+ expect(uiState.gotoCoords).toEqual({
+ lat: 48.8584, lon: 2.2945, zoom: 17, bearing: 30, provider: 'esri-world-imagery',
+ });
+ });
+});
diff --git a/frontend/src/lib/notebook.js b/frontend/src/lib/notebook.js
new file mode 100644
index 0000000..bfb22f8
--- /dev/null
+++ b/frontend/src/lib/notebook.js
@@ -0,0 +1,52 @@
+export const NOTEBOOK_MIN_PANE = 280;
+export const NOTEBOOK_MIN_SPLIT = 30;
+export const NOTEBOOK_MAX_SPLIT = 70;
+export const NOTEBOOK_DEFAULT_SPLIT = 50;
+export const NOTEBOOK_HELP_MARGIN = 12;
+
+const KEY = 'azimut:notebookSplit';
+
+/** Load one note without letting a response land after the active key changed. */
+export async function loadNotebookText(requestedKey, endpoint, { get, currentKey }) {
+ const result = await get(endpoint);
+ return {
+ accepted: currentKey() === requestedKey,
+ text: result.text,
+ };
+}
+
+export function clampNotebookSplit(value, containerWidth = Infinity) {
+ if (!Number.isFinite(value)) return NOTEBOOK_DEFAULT_SPLIT;
+ const paneFloor = Number.isFinite(containerWidth) && containerWidth > 0
+ ? Math.min(50, (NOTEBOOK_MIN_PANE / containerWidth) * 100)
+ : 0;
+ const min = Math.max(NOTEBOOK_MIN_SPLIT, paneFloor);
+ const max = Math.min(NOTEBOOK_MAX_SPLIT, 100 - paneFloor);
+ return Math.round(Math.min(max, Math.max(min, value)) * 10) / 10;
+}
+
+export function clampNotebookHelpPosition(x, y, panelWidth, panelHeight, containerWidth, containerHeight) {
+ const maxX = Math.max(NOTEBOOK_HELP_MARGIN, containerWidth - panelWidth - NOTEBOOK_HELP_MARGIN);
+ const maxY = Math.max(NOTEBOOK_HELP_MARGIN, containerHeight - panelHeight - NOTEBOOK_HELP_MARGIN);
+ return {
+ x: Math.round(Math.min(maxX, Math.max(NOTEBOOK_HELP_MARGIN, x))),
+ y: Math.round(Math.min(maxY, Math.max(NOTEBOOK_HELP_MARGIN, y))),
+ };
+}
+
+export function loadNotebookSplit() {
+ try {
+ const stored = localStorage.getItem(KEY);
+ return stored === null ? NOTEBOOK_DEFAULT_SPLIT : clampNotebookSplit(Number(stored));
+ } catch {
+ return NOTEBOOK_DEFAULT_SPLIT;
+ }
+}
+
+export function saveNotebookSplit(split) {
+ try {
+ localStorage.setItem(KEY, String(clampNotebookSplit(split)));
+ } catch {
+ /* localStorage may be unavailable. */
+ }
+}
diff --git a/frontend/src/lib/notebook.test.js b/frontend/src/lib/notebook.test.js
new file mode 100644
index 0000000..5c01576
--- /dev/null
+++ b/frontend/src/lib/notebook.test.js
@@ -0,0 +1,73 @@
+import { describe, expect, it, vi, afterEach } from 'vitest';
+import {
+ clampNotebookHelpPosition, clampNotebookSplit, loadNotebookSplit, saveNotebookSplit,
+ loadNotebookText, NOTEBOOK_DEFAULT_SPLIT,
+} from './notebook.js';
+
+afterEach(() => vi.unstubAllGlobals());
+
+describe('clampNotebookSplit', () => {
+ it('keeps the writer between the configured limits', () => {
+ expect(clampNotebookSplit(5, 1400)).toBe(30);
+ expect(clampNotebookSplit(90, 1400)).toBe(70);
+ });
+
+ it('makes room for both 280px panes in a narrower Notebook', () => {
+ expect(clampNotebookSplit(30, 700)).toBe(40);
+ expect(clampNotebookSplit(70, 700)).toBe(60);
+ });
+});
+
+describe('loadNotebookText', () => {
+ it('rejects a late response after another note becomes active', async () => {
+ let activeKey = 'case-1:a';
+ let resolveA;
+ const requestA = loadNotebookText('case-1:a', '/notes/a', {
+ get: () => new Promise((resolve) => { resolveA = resolve; }),
+ currentKey: () => activeKey,
+ });
+
+ activeKey = 'case-1:b';
+ const requestB = loadNotebookText('case-1:b', '/notes/b', {
+ get: async () => ({ text: 'Note B' }),
+ currentKey: () => activeKey,
+ });
+ expect(await requestB).toEqual({ accepted: true, text: 'Note B' });
+
+ resolveA({ text: 'Late note A' });
+ expect(await requestA).toEqual({ accepted: false, text: 'Late note A' });
+ });
+});
+
+describe('Notebook split persistence', () => {
+ it('round-trips a split value', () => {
+ const values = {};
+ vi.stubGlobal('localStorage', {
+ getItem: (key) => values[key] ?? null,
+ setItem: (key, value) => { values[key] = value; },
+ });
+ saveNotebookSplit(61.4);
+ expect(loadNotebookSplit()).toBe(61.4);
+ });
+
+ it('uses the default when storage is unavailable', () => {
+ vi.stubGlobal('localStorage', { getItem: () => { throw new Error('denied'); } });
+ expect(loadNotebookSplit()).toBe(NOTEBOOK_DEFAULT_SPLIT);
+ });
+});
+
+describe('clampNotebookHelpPosition', () => {
+ it('keeps the Markdown helper inside the Notebook', () => {
+ expect(clampNotebookHelpPosition(-40, 900, 720, 540, 1200, 800)).toEqual({ x: 12, y: 248 });
+ expect(clampNotebookHelpPosition(240, 80, 720, 540, 1200, 800)).toEqual({ x: 240, y: 80 });
+ });
+
+ it('anchors an oversized helper to the viewport margin', () => {
+ expect(clampNotebookHelpPosition(100, 100, 720, 540, 600, 400)).toEqual({ x: 12, y: 12 });
+ });
+
+ it('reclamps the helper after expanding from its collapsed title bar', () => {
+ expect(clampNotebookHelpPosition(600, 700, 380, 48, 1000, 800)).toEqual({ x: 600, y: 700 });
+ expect(clampNotebookHelpPosition(600, 700, 760, 540, 1000, 800)).toEqual({ x: 228, y: 248 });
+ });
+});
diff --git a/frontend/src/lib/notebookContent.js b/frontend/src/lib/notebookContent.js
new file mode 100644
index 0000000..b8971a9
--- /dev/null
+++ b/frontend/src/lib/notebookContent.js
@@ -0,0 +1,15 @@
+export function insertNotebookText(text, value, start = text.length, end = start) {
+ const before = text.slice(0, start);
+ const after = text.slice(end);
+ return { text: `${before}${value}${after}`, cursor: before.length + value.length };
+}
+
+import { mediaReference } from './markdown.js';
+
+export function notebookImageMarkdown(_caseId, item, entity) {
+ return entity ? mediaReference(entity) : `![${item.filename}](/files/${_caseId}/${item.path})`;
+}
+
+export function notebookMediaMarkdown(_caseId, entity) {
+ return mediaReference(entity);
+}
diff --git a/frontend/src/lib/notebookContent.test.js b/frontend/src/lib/notebookContent.test.js
new file mode 100644
index 0000000..f587b99
--- /dev/null
+++ b/frontend/src/lib/notebookContent.test.js
@@ -0,0 +1,20 @@
+import { describe, expect, it } from 'vitest';
+import { insertNotebookText, notebookImageMarkdown, notebookMediaMarkdown } from './notebookContent.js';
+
+describe('Notebook content helpers', () => {
+ it('inserts a reference at the current selection', () => {
+ expect(insertNotebookText('Before after', 'middle ', 7, 7)).toEqual({
+ text: 'Before middle after', cursor: 14,
+ });
+ });
+
+ it('writes a case-local Markdown image reference', () => {
+ expect(notebookImageMarkdown('case-1', { filename: 'frame.png', path: 'media/frame.png' }, { id: 'e_frame', label: 'frame.png' }))
+ .toBe('[[media:e_frame|frame.png]]');
+ });
+
+ it('records a video as a case media reference', () => {
+ expect(notebookMediaMarkdown('case-1', { id: 'e_clip', label: 'clip.mp4', attrs: { path: 'media/clip.mp4', kind: 'video' } }))
+ .toBe('[[media:e_clip|clip.mp4]]');
+ });
+});
diff --git a/frontend/src/lib/notebookPdf.js b/frontend/src/lib/notebookPdf.js
new file mode 100644
index 0000000..a3198a6
--- /dev/null
+++ b/frontend/src/lib/notebookPdf.js
@@ -0,0 +1,122 @@
+function escapeHtml(value) {
+ return String(value)
+ .replaceAll('&', '&amp;')
+ .replaceAll('<', '&lt;')
+ .replaceAll('>', '&gt;')
+ .replaceAll('"', '&quot;')
+ .replaceAll("'", '&#39;');
+}
+
+function mediaNote(document, message) {
+ const note = document.createElement('p');
+ note.className = 'pdf-media-note';
+ note.textContent = message;
+ return note;
+}
+
+/** Keep PDF export local: local images print, while remote media never loads. */
+export function prepareNotebookPdfContent(content, origin, document = globalThis.document) {
+ const wrapper = document.createElement('div');
+ wrapper.innerHTML = content;
+
+ for (const source of wrapper.querySelectorAll('source')) source.remove();
+ for (const element of wrapper.querySelectorAll('[srcset]')) element.removeAttribute('srcset');
+ for (const element of wrapper.querySelectorAll('[style]')) {
+ if (/url\s*\(/i.test(element.getAttribute('style'))) element.removeAttribute('style');
+ }
+
+ for (const video of wrapper.querySelectorAll('video, audio')) {
+ video.replaceWith(mediaNote(document, 'Video not included in PDF.'));
+ }
+
+ for (const image of wrapper.querySelectorAll('img')) {
+ const source = image.getAttribute('src');
+ let isLocal = false;
+ try {
+ isLocal = new URL(source, origin).origin === origin;
+ } catch {
+ // An invalid source cannot be part of the export.
+ }
+ if (!isLocal) image.replaceWith(mediaNote(document, 'External image not included in PDF.'));
+ }
+
+ return wrapper.innerHTML;
+}
+
+export function notebookPdfHtml({ title, content, origin, document = globalThis.document }) {
+ const safeTitle = escapeHtml(title || 'Case Notes');
+ const body = prepareNotebookPdfContent(content, origin, document);
+ return `<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8">
+ <base href="${escapeHtml(origin)}/">
+ <title>${safeTitle}</title>
+ <style>
+ @page { size: A4; margin: 18mm 16mm 20mm; }
+ :root { color-scheme: light; }
+ * { box-sizing: border-box; }
+ body { margin: 0; color: #202124; background: #fff; font: 10.5pt/1.6 Georgia, 'Times New Roman', serif; }
+ .document-header { margin-bottom: 11mm; padding-bottom: 5mm; border-bottom: 1.5pt solid #bd7a25; }
+ .document-kicker { margin: 0 0 2mm; color: #8a5a1a; font: 600 8pt/1.2 Arial, sans-serif; letter-spacing: .12em; text-transform: uppercase; }
+ h1 { margin: 0; color: #181818; font: 700 25pt/1.12 Arial, sans-serif; letter-spacing: -.025em; }
+ h1, h2, h3, h4, h5, h6 { break-after: avoid; page-break-after: avoid; }
+ h2 { margin: 9mm 0 3mm; color: #202124; font: 700 16pt/1.2 Arial, sans-serif; }
+ h3 { margin: 7mm 0 2mm; font: 700 12pt/1.25 Arial, sans-serif; }
+ h4, h5, h6 { margin: 5mm 0 2mm; font: 700 10.5pt/1.3 Arial, sans-serif; }
+ p, ul, ol, blockquote, pre, table { margin: 0 0 4mm; }
+ ul, ol { padding-left: 6mm; }
+ li + li { margin-top: 1mm; }
+ a { color: #6d4515; text-decoration-color: #bd7a25; }
+ blockquote { padding: 1mm 0 1mm 4mm; border-left: 2pt solid #bd7a25; color: #555; }
+ code { padding: .15em .35em; border-radius: 2pt; background: #f4f1ed; font: 8.8pt/1.45 'SFMono-Regular', Consolas, monospace; }
+ pre { overflow: hidden; padding: 3mm; border: .5pt solid #ddd6cc; border-radius: 2pt; background: #f8f6f3; white-space: pre-wrap; }
+ pre code { padding: 0; background: transparent; }
+ table { width: 100%; border-collapse: collapse; font-size: 9pt; break-inside: avoid; page-break-inside: avoid; }
+ th, td { padding: 2mm 2.5mm; border: .5pt solid #d8d1c8; text-align: left; vertical-align: top; }
+ th { background: #f1ece5; font-family: Arial, sans-serif; }
+ tr { break-inside: avoid; page-break-inside: avoid; }
+ img { display: block; max-width: 100%; height: auto; margin: 0 0 4mm; border-radius: 2pt; break-inside: avoid; page-break-inside: avoid; }
+ .markdown-image.align-center { margin-right: auto; margin-left: auto; }
+ .markdown-image.align-right { margin-right: 0; margin-left: auto; }
+ .markdown-align.align-center { text-align: center; }
+ .markdown-align.align-right { text-align: right; }
+ .entity-ref { color: #6d4515; font-weight: 700; }
+ .broken-ref, .pdf-media-note { color: #777; font-style: italic; }
+ .pdf-media-note { padding: 2mm 3mm; border-left: 2pt solid #d8d1c8; background: #faf8f5; }
+ .document-footer { position: fixed; right: 0; bottom: -13mm; left: 0; color: #777; font: 8pt Arial, sans-serif; }
+ @media print { a { color: inherit; } }
+ </style>
+ </head>
+ <body>
+ <header class="document-header"><p class="document-kicker">Azimut notes</p><h1>${safeTitle}</h1></header>
+ <main>${body}</main>
+ <footer class="document-footer">Generated locally from case notes</footer>
+ </body>
+</html>`;
+}
+
+/** Open the browser's Save-as-PDF flow from a user gesture. */
+export function downloadNotebookPdf({ title, content }) {
+ const printWindow = window.open('', '_blank');
+ if (!printWindow) return false;
+
+ const origin = window.location.origin;
+ printWindow.document.open();
+ printWindow.addEventListener('load', () => {
+ const images = Array.from(printWindow.document.images ?? []);
+ Promise.all(images.map((image) => image.complete
+ ? Promise.resolve()
+ : new Promise((resolve) => {
+ image.addEventListener('load', resolve, { once: true });
+ image.addEventListener('error', resolve, { once: true });
+ })))
+ .then(() => {
+ printWindow.focus();
+ printWindow.print();
+ });
+ }, { once: true });
+ printWindow.document.write(notebookPdfHtml({ title, content, origin, document: printWindow.document }));
+ printWindow.document.close();
+ return true;
+}
diff --git a/frontend/src/lib/notebookPdf.test.js b/frontend/src/lib/notebookPdf.test.js
new file mode 100644
index 0000000..0ed6439
--- /dev/null
+++ b/frontend/src/lib/notebookPdf.test.js
@@ -0,0 +1,60 @@
+import { Window } from 'happy-dom';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { downloadNotebookPdf, notebookPdfHtml, prepareNotebookPdfContent } from './notebookPdf.js';
+
+const origin = 'http://127.0.0.1:8477';
+
+afterEach(() => vi.unstubAllGlobals());
+
+describe('notebook PDF export', () => {
+ it('keeps local case images and omits remote media', () => {
+ const document = new Window().document;
+ const content = prepareNotebookPdfContent(
+ '<img src="/files/case-1/media/map.png" srcset="https://example.test/[email protected] 2x"><img src="https://example.test/map.png"><video src="/files/case-1/media/clip.mp4"></video>',
+ origin,
+ document,
+ );
+
+ expect(content).toContain('/files/case-1/media/map.png');
+ expect(content).not.toContain('srcset=');
+ expect(content).not.toContain('https://example.test/map.png');
+ expect(content).toContain('External image not included in PDF.');
+ expect(content).toContain('Video not included in PDF.');
+ });
+
+ it('builds a print-ready A4 document with the note title', () => {
+ const document = new Window().document;
+ const html = notebookPdfHtml({
+ title: 'Field Notes',
+ content: '<h2>Finding</h2><p>Confirmed.</p>',
+ origin,
+ document,
+ });
+
+ expect(html).toContain('@page { size: A4;');
+ expect(html).toContain('<title>Field Notes</title>');
+ expect(html).toContain('<h1>Field Notes</h1>');
+ expect(html).toContain('<h2>Finding</h2>');
+ });
+
+ it('opens a print window from the download action', async () => {
+ const document = new Window().document;
+ let onLoad;
+ const printWindow = {
+ document,
+ addEventListener: (_type, callback) => { onLoad = callback; },
+ focus: vi.fn(),
+ print: vi.fn(),
+ };
+ const open = vi.fn(() => printWindow);
+ vi.stubGlobal('window', { location: { origin }, open });
+
+ expect(downloadNotebookPdf({ title: 'Case Notes', content: '<p>Ready.</p>' })).toBe(true);
+ expect(open).toHaveBeenCalledWith('', '_blank');
+
+ onLoad();
+ await Promise.resolve();
+ expect(printWindow.focus).toHaveBeenCalledOnce();
+ expect(printWindow.print).toHaveBeenCalledOnce();
+ });
+});
diff --git a/frontend/src/lib/notebookTabs.js b/frontend/src/lib/notebookTabs.js
new file mode 100644
index 0000000..d19e278
--- /dev/null
+++ b/frontend/src/lib/notebookTabs.js
@@ -0,0 +1,19 @@
+export function caseTab() {
+ return { id: 'case', noteId: null };
+}
+
+export function openNotebookTab(tabs, noteId = null) {
+ const id = noteId ?? 'case';
+ return {
+ tabs: tabs.some((tab) => tab.id === id) ? tabs : [...tabs, { id, noteId }],
+ activeId: id,
+ };
+}
+
+export function closeNotebookTab(tabs, activeId, id) {
+ if (id === 'case') return { tabs, activeId };
+ const index = tabs.findIndex((tab) => tab.id === id);
+ const nextTabs = tabs.filter((tab) => tab.id !== id);
+ if (activeId !== id) return { tabs: nextTabs, activeId };
+ return { tabs: nextTabs, activeId: (nextTabs[Math.max(0, index - 1)] ?? caseTab()).id };
+}
diff --git a/frontend/src/lib/notebookTabs.test.js b/frontend/src/lib/notebookTabs.test.js
new file mode 100644
index 0000000..3734e35
--- /dev/null
+++ b/frontend/src/lib/notebookTabs.test.js
@@ -0,0 +1,19 @@
+import { describe, expect, it } from 'vitest';
+import { caseTab, closeNotebookTab, openNotebookTab } from './notebookTabs.js';
+
+describe('Notebook tabs', () => {
+ it('opens a filed note once and focuses its tab', () => {
+ const first = openNotebookTab([caseTab()], 'e_lead');
+ const second = openNotebookTab(first.tabs, 'e_lead');
+ expect(second.tabs).toHaveLength(2);
+ expect(second.activeId).toBe('e_lead');
+ });
+
+ it('keeps case notes pinned and focuses the previous tab when closing', () => {
+ const tabs = [caseTab(), { id: 'e_lead', noteId: 'e_lead' }, { id: 'e_time', noteId: 'e_time' }];
+ expect(closeNotebookTab(tabs, 'e_time', 'e_time')).toEqual({
+ tabs: [caseTab(), { id: 'e_lead', noteId: 'e_lead' }], activeId: 'e_lead',
+ });
+ expect(closeNotebookTab(tabs, 'case', 'case')).toEqual({ tabs, activeId: 'case' });
+ });
+});
diff --git a/frontend/src/lib/notes.js b/frontend/src/lib/notes.js
index bc74db5..6858bcb 100644
--- a/frontend/src/lib/notes.js
+++ b/frontend/src/lib/notes.js
@@ -1,8 +1,7 @@
/**
- * Creating a note entity. A note is just an entity of type `note` whose body
- * lives in `attrs.content`; `attrs.folder` files it into a My-work folder
- * (''=unfiled). Lifted out of the case sidebar so the desktop organizer's
- * right-click menu can create notes the same way.
+ * Creating a filed Markdown note. Its title and folder stay on the entity;
+ * its body is written to notes/<entity id>.md by the case API. Lifted out of
+ * the case sidebar so the desktop organizer can create notes the same way.
*
* Does not reload the case: the caller refetches once it returns.
*/
@@ -11,9 +10,17 @@ import { api } from './api.js';
export async function createNote(caseId, { title, folder = '', content = '' }) {
const label = (title ?? '').trim();
if (!label) throw new Error('Title required');
- await api.post(`/api/cases/${caseId}/entities`, {
- type: 'note',
- label,
- attrs: { content: content ?? '', folder: (folder ?? '').trim() },
+ return api.post(`/api/cases/${caseId}/notes`, {
+ title: label,
+ folder: (folder ?? '').trim(),
+ content: content ?? '',
});
}
+
+export function resetCaseNotes(caseId) {
+ return api.put(`/api/cases/${caseId}/notes`, { text: '' });
+}
+
+export function deleteNote(caseId, noteId) {
+ return api.del(`/api/cases/${caseId}/entities/${noteId}`);
+}
diff --git a/frontend/src/lib/notes.test.js b/frontend/src/lib/notes.test.js
index 90d33eb..3ec0e52 100644
--- a/frontend/src/lib/notes.test.js
+++ b/frontend/src/lib/notes.test.js
@@ -1,36 +1,40 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { api } from './api.js';
-import { createNote } from './notes.js';
+import { createNote, deleteNote, resetCaseNotes } from './notes.js';
-vi.mock('./api.js', () => ({ api: { post: vi.fn(async () => ({})) } }));
+vi.mock('./api.js', () => ({
+ api: {
+ post: vi.fn(async () => ({})),
+ put: vi.fn(async () => ({})),
+ del: vi.fn(async () => ({})),
+ },
+}));
-beforeEach(() => api.post.mockClear());
+beforeEach(() => {
+ api.post.mockClear();
+ api.put.mockClear();
+ api.del.mockClear();
+});
describe('createNote', () => {
- it('posts a note entity with content and filing folder', async () => {
+ it('posts a filed Markdown note with content and folder', async () => {
await createNote('case-1', { title: 'Lead', folder: 'Research', content: 'body' });
- expect(api.post).toHaveBeenCalledWith('/api/cases/case-1/entities', {
- type: 'note',
- label: 'Lead',
- attrs: { content: 'body', folder: 'Research' },
+ expect(api.post).toHaveBeenCalledWith('/api/cases/case-1/notes', {
+ title: 'Lead', folder: 'Research', content: 'body',
});
});
it('trims the title and folder, and defaults content to empty', async () => {
await createNote('case-1', { title: ' Lead ', folder: ' Research ' });
- expect(api.post).toHaveBeenCalledWith('/api/cases/case-1/entities', {
- type: 'note',
- label: 'Lead',
- attrs: { content: '', folder: 'Research' },
+ expect(api.post).toHaveBeenCalledWith('/api/cases/case-1/notes', {
+ title: 'Lead', folder: 'Research', content: '',
});
});
it('leaves the note unfiled when no folder is given', async () => {
await createNote('case-1', { title: 'Lead' });
- expect(api.post).toHaveBeenCalledWith('/api/cases/case-1/entities', {
- type: 'note',
- label: 'Lead',
- attrs: { content: '', folder: '' },
+ expect(api.post).toHaveBeenCalledWith('/api/cases/case-1/notes', {
+ title: 'Lead', folder: '', content: '',
});
});
@@ -39,3 +43,17 @@ describe('createNote', () => {
expect(api.post).not.toHaveBeenCalled();
});
});
+
+describe('case note actions', () => {
+ it('resets the case-wide note through its notes endpoint', async () => {
+ await resetCaseNotes('case-1');
+
+ expect(api.put).toHaveBeenCalledWith('/api/cases/case-1/notes', { text: '' });
+ });
+
+ it('deletes a filed note through the entity delete endpoint', async () => {
+ await deleteNote('case-1', 'note-1');
+
+ expect(api.del).toHaveBeenCalledWith('/api/cases/case-1/entities/note-1');
+ });
+});
diff --git a/frontend/src/lib/post.js b/frontend/src/lib/post.js
index d8a78b8..ab9aa86 100644
--- a/frontend/src/lib/post.js
+++ b/frontend/src/lib/post.js
@@ -9,6 +9,8 @@
* bare coordinates; a token body expresses either without special-casing.
*/
+import { entityReference, mediaReference } from './markdown.js';
+
// The tokens an analyst can drop into a thread body. `sample` feeds the editor
// preview so the layout reads before any real draft exists.
export const TWEET_TOKENS = [
@@ -86,41 +88,98 @@ export function postComposeUrl(target, text) {
}
/**
- * Turn a prepared social thread into a portable, deliberately small Markdown
- * report. This is an export handoff, not the future full Report Builder.
+ * Turn a prepared social thread into a readable case-note report.
+ *
+ * ``proofEntity`` and ``mediaEntities`` use the Notebook's local reference
+ * syntax, so saved reports keep clickable case links and render their evidence
+ * from local media instead of copying files or embedding base64 data.
*/
export function postReportMarkdown({
title,
place,
plusCode,
coordinates,
+ dms,
+ mapLinks = {},
description,
source,
- posts = [],
attachments = [],
+ proofEntity = null,
+ mediaEntities = [],
} = {}) {
const clean = (value) => String(value ?? '').trim();
+ const cell = (value) => clean(value).replace(/\|/g, '\\|').replace(/[\r\n]+/g, ' ');
+ const inlineCode = (value) => `\`${clean(value).replace(/`/g, '\\`')}\``;
const reportTitle = clean(title) || 'Untitled report';
const location = [
- clean(place) && `Place: ${clean(place)}`,
- clean(plusCode) && `Plus code: ${clean(plusCode)}`,
- clean(coordinates) && `Coordinates: ${clean(coordinates)}`,
+ clean(place) && ['Place', cell(place)],
+ clean(coordinates) && ['Coordinates', inlineCode(coordinates)],
+ clean(dms) && ['DMS', inlineCode(dms)],
+ clean(plusCode) && ['Plus code', inlineCode(plusCode)],
].filter(Boolean);
- const cleanPosts = posts.map(clean).filter(Boolean);
+ const mapRows = Object.entries(mapLinks ?? {})
+ .map(([label, href]) => [cell(label), clean(href)])
+ .filter(([, href]) => /^https?:\/\//i.test(href));
+ if (mapRows.length) {
+ location.push([
+ 'Maps',
+ mapRows.map(([label, href]) => `[${label}](${href})`).join(' · '),
+ ]);
+ }
const cleanAttachments = [...new Set(attachments.map(clean).filter(Boolean))];
const sections = [`# ${reportTitle}`];
- if (location.length) sections.push(`## Location\n\n${location.join('\n')}`);
+ if (location.length) {
+ sections.push([
+ '## Location',
+ '',
+ '| Detail | Value |',
+ '| --- | --- |',
+ ...location.map(([label, value]) => `| ${label} | ${value} |`),
+ ].join('\n'));
+ }
if (clean(description)) sections.push(`## Assessment\n\n${clean(description)}`);
- if (clean(source)) sections.push(`## Source\n\n${clean(source)}`);
- if (cleanPosts.length) {
- sections.push(`## Prepared posts\n\n${cleanPosts
- .map((post, index) => `### ${index + 1}\n\n${post}`)
- .join('\n\n')}`);
+ if (clean(source)) {
+ const sourceText = clean(source);
+ const sourceValue = /^https?:\/\//i.test(sourceText)
+ ? `[Open original source](${sourceText})`
+ : sourceText;
+ sections.push(`## Source\n\n${sourceValue}`);
}
- if (cleanAttachments.length) {
- sections.push(`## Attachments\n\n${cleanAttachments.map((path) => `- ${path}`).join('\n')}`);
+ const mediaByPath = new Map(
+ mediaEntities
+ .filter((entity) => entity?.id && entity?.attrs?.path)
+ .map((entity) => [entity.attrs.path, entity]),
+ );
+ const evidence = [];
+ if (proofEntity?.id && proofEntity.attrs?.path) {
+ evidence.push([
+ '### Proof',
+ entityReference(proofEntity),
+ '',
+ '::: center',
+ `${mediaReference(proofEntity)}{width=100% align=center}`,
+ ':::',
+ ].join('\n'));
+ } else if (cleanAttachments[0]?.startsWith('proofs/')) {
+ evidence.push(`### Proof\n\n- ${inlineCode(cleanAttachments[0])}`);
}
+
+ const mediaPaths = cleanAttachments.filter((path) => !path.startsWith('proofs/'));
+ const renderedMedia = mediaPaths.map((path) => {
+ const entity = mediaByPath.get(path);
+ if (!entity) return `- ${inlineCode(path)}`;
+ return [
+ `### ${cell(entity.label || path)}`,
+ entityReference(entity),
+ '',
+ '::: center',
+ `${mediaReference(entity)}{width=100% align=center}`,
+ ':::',
+ ].join('\n');
+ });
+ if (renderedMedia.length) evidence.push(...renderedMedia);
+ if (evidence.length) sections.push(`## Evidence\n\n${evidence.join('\n\n')}`);
return `${sections.join('\n\n')}\n`;
}
diff --git a/frontend/src/lib/post.test.js b/frontend/src/lib/post.test.js
index 4c428af..ac57d09 100644
--- a/frontend/src/lib/post.test.js
+++ b/frontend/src/lib/post.test.js
@@ -381,24 +381,34 @@ describe('post targets', () => {
});
describe('postReportMarkdown', () => {
- it('renders the prepared facts, posts and attachments as portable Markdown', () => {
- expect(postReportMarkdown({
+ it('renders a structured report with links, maps and embedded case media', () => {
+ const report = postReportMarkdown({
title: 'Rooftop match',
place: 'Bakhmut, Ukraine',
plusCode: '8FPGXXXX+XX',
coordinates: '48.850000, 2.350000',
+ dms: '48°51′00.0″N 2°21′00.0″E',
+ mapLinks: {
+ Google: 'https://maps.example.test',
+ OSM: 'https://osm.example.test',
+ },
description: 'Match against reference imagery.',
source: 'https://example.test/source',
- posts: ['First post', 'Second post'],
attachments: ['proofs/match.png', 'media/a.jpg', 'media/a.jpg'],
- })).toBe(
- '# Rooftop match\n\n' +
- '## Location\n\nPlace: Bakhmut, Ukraine\nPlus code: 8FPGXXXX+XX\nCoordinates: 48.850000, 2.350000\n\n' +
- '## Assessment\n\nMatch against reference imagery.\n\n' +
- '## Source\n\nhttps://example.test/source\n\n' +
- '## Prepared posts\n\n### 1\n\nFirst post\n\n### 2\n\nSecond post\n\n' +
- '## Attachments\n\n- proofs/match.png\n- media/a.jpg\n'
- );
+ proofEntity: { id: 'e_proof', label: 'Rooftop proof', attrs: { path: 'proofs/match.png' } },
+ mediaEntities: [{ id: 'e_frame', label: 'Frame', attrs: { path: 'media/a.jpg', kind: 'image' } }],
+ });
+
+ expect(report).toContain('| Coordinates | `48.850000, 2.350000` |');
+ expect(report).toContain('| Maps | [Google](https://maps.example.test) · [OSM](https://osm.example.test) |');
+ expect(report).toContain('[Open original source](https://example.test/source)');
+ expect(report).toContain('## Assessment\n\nMatch against reference imagery.');
+ expect(report).not.toContain('## Prepared thread');
+ expect(report).toContain('[[entity:e_proof|Rooftop proof]]');
+ expect(report).toContain('[[media:e_proof|Rooftop proof]]{width=100% align=center}');
+ expect(report).toContain('[[entity:e_frame|Frame]]');
+ expect(report).toContain('[[media:e_frame|Frame]]{width=100% align=center}');
+ expect(report).not.toContain('- proofs/match.png');
});
it('always gives an otherwise empty export a title', () => {
diff --git a/frontend/src/lib/sentinel.js b/frontend/src/lib/sentinel.js
index b9b956b..58e782a 100644
--- a/frontend/src/lib/sentinel.js
+++ b/frontend/src/lib/sentinel.js
@@ -127,6 +127,27 @@ export function cloudLabel(cloud) {
return `${Math.round(cloud)}% cloud`;
}
+/** Stable place bucket for pass and coverage caches (about 100 m). */
+export function sentinelPlaceKey(lat, lon) {
+ return `${Number(lat).toFixed(3)},${Number(lon).toFixed(3)}`;
+}
+
+/** Local API request that verifies rendered coverage for one candidate day. */
+export function coverageRequestPath({ lat, lon, layer, date }) {
+ const query = new URLSearchParams({
+ lat: String(lat),
+ lon: String(lon),
+ layer,
+ date,
+ });
+ return `/api/satellite/sentinel/coverage?${query}`;
+}
+
+/** Keep the working map unless the candidate day passed its coverage check. */
+export 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 —
diff --git a/frontend/src/lib/sentinel.test.js b/frontend/src/lib/sentinel.test.js
index 16fffab..c59d738 100644
--- a/frontend/src/lib/sentinel.test.js
+++ b/frontend/src/lib/sentinel.test.js
@@ -14,6 +14,9 @@ import {
monthBounds,
monthGrid,
defaultSearchWindow,
+ sentinelPlaceKey,
+ coverageRequestPath,
+ dateAfterCoverage,
DEFAULT_LAYER,
SENTINEL_ID,
} from './sentinel.js';
@@ -167,3 +170,31 @@ describe('defaultSearchWindow', () => {
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');
+ });
+
+ it('builds a request for the selected layer, day and exact crosshair', () => {
+ const path = coverageRequestPath({
+ lat: 48.8584,
+ lon: 2.2945,
+ layer: 'FALSE_COLOR',
+ date: '2026-05-11',
+ });
+ const url = new URL(path, 'http://localhost');
+ expect(url.pathname).toBe('/api/satellite/sentinel/coverage');
+ expect(Object.fromEntries(url.searchParams)).toEqual({
+ lat: '48.8584',
+ lon: '2.2945',
+ layer: 'FALSE_COLOR',
+ date: '2026-05-11',
+ });
+ });
+
+ it('keeps the working date when the candidate has no imagery', () => {
+ expect(dateAfterCoverage('2026-05-06', '2026-05-11', false)).toBe('2026-05-06');
+ expect(dateAfterCoverage('2026-05-06', '2026-05-11', true)).toBe('2026-05-11');
+ });
+});
diff --git a/frontend/src/lib/state.svelte.js b/frontend/src/lib/state.svelte.js
index 7c90a73..154eb9e 100644
--- a/frontend/src/lib/state.svelte.js
+++ b/frontend/src/lib/state.svelte.js
@@ -8,6 +8,7 @@
import { api } from './api.js';
import { formatCoords as renderCoords } from './coords.js';
import { loadWidth, saveWidth, clampWidth } from './sidebar.js';
+import { loadTheme, saveTheme, applyTheme } from './theme.js';
import { shouldShowUpdate } from './appUpdate.js';
/**
@@ -147,6 +148,7 @@ export async function deleteTemplate(kind, id) {
export const uiState = $state({
tool: 'media', // 'media' | 'inspect' | 'satellite' | 'proof' | 'post' | 'settings'
+ theme: loadTheme(), // 'dark' | 'light'; index.html stamps it before first paint
sidebarOpen: true,
sidebarW: loadWidth(), // px, drag-resizable and remembered across reloads
toasts: [],
@@ -156,16 +158,30 @@ export const uiState = $state({
postProof: null, // proof spec handed to the Post Composer
openProof: null, // proof name to load in the Proof Composer
openDraft: null, // draft name to load in the Post Composer
+ openNotebook: null, // { noteId: string|null }; null noteId opens case notes.md
inspectPath: null, // media path to open in the Inspect tool
focusMedia: null, // media path to highlight & scroll to in the Media Library
openInspect: null, // inspect-session name to reopen in the Inspect tool
gotoCoords: null, // { lat, lon } to fly to in the Satellite tool
+ focusCapture: null, // case-relative capture path selected from another workspace
// Satellite reference viewers: floating scratch windows holding a media image
// over the map to eyeball against the imagery. Session-only — never captured
// or saved, and dropped when the open case changes (they point at its media).
refViewers: [],
});
+/** Switch light/dark, mirror it to <html>, and remember it across reloads. */
+export function setTheme(theme) {
+ uiState.theme = theme === 'light' ? 'light' : 'dark';
+ applyTheme(uiState.theme);
+ saveTheme(uiState.theme);
+}
+
+/** Flip to the other theme. Wired to the rail toggle. */
+export function toggleTheme() {
+ setTheme(uiState.theme === 'light' ? 'dark' : 'light');
+}
+
/**
* Resize the case sidebar (px). Clamped against the live window, so a width
* dragged out on a big screen can't wedge the canvas shut on a small one.
@@ -182,9 +198,9 @@ export function persistSidebarWidth() {
let toastSeq = 0;
-export function toast(message, kind = 'info', timeout = 3800) {
+export function toast(message, kind = 'info', timeout = 3800, action = null) {
const id = ++toastSeq;
- uiState.toasts.push({ id, message, kind });
+ uiState.toasts.push({ id, message, kind, action });
setTimeout(() => {
const i = uiState.toasts.findIndex((t) => t.id === id);
if (i !== -1) uiState.toasts.splice(i, 1);
@@ -211,7 +227,11 @@ export async function openCase(id) {
caseState.loading = true;
try {
// reference viewers point at the previous case's media — drop them
- if (caseState.current?.id !== id) uiState.refViewers = [];
+ if (caseState.current?.id !== id) {
+ uiState.refViewers = [];
+ uiState.openNotebook = null;
+ uiState.focusCapture = null;
+ }
caseState.current = await api.get(`/api/cases/${id}`);
rememberCase(id);
} finally {
diff --git a/frontend/src/lib/state.test.js b/frontend/src/lib/state.test.js
index 4a2f452..ad0cccd 100644
--- a/frontend/src/lib/state.test.js
+++ b/frontend/src/lib/state.test.js
@@ -118,6 +118,31 @@ describe('applyPrefs', () => {
});
});
+describe('startup update check', () => {
+ it('checks by default and stays silent when the Settings switch is off', async () => {
+ const { api } = await import('./api.js');
+ api.get.mockReset().mockResolvedValue({
+ current: 'v0.1.0', latest: null, update_available: false,
+ });
+ const { applyPrefs, checkForUpdateOnStart } = await freshState();
+
+ await checkForUpdateOnStart();
+ expect(api.get).toHaveBeenCalledWith('/api/settings/update?check=true');
+
+ api.get.mockClear();
+ applyPrefs({ update_check_on_start: false });
+ await checkForUpdateOnStart();
+ expect(api.get).not.toHaveBeenCalled();
+ });
+
+ it('does not surface an offline failure', async () => {
+ const { api } = await import('./api.js');
+ api.get.mockReset().mockRejectedValue(new Error('offline'));
+ const { checkForUpdateOnStart } = await freshState();
+ await expect(checkForUpdateOnStart()).resolves.toBeUndefined();
+ });
+});
+
describe('templates store', () => {
let api;
beforeEach(async () => {
diff --git a/frontend/src/lib/theme.js b/frontend/src/lib/theme.js
new file mode 100644
index 0000000..7395334
--- /dev/null
+++ b/frontend/src/lib/theme.js
@@ -0,0 +1,40 @@
+/**
+ * Light / dark theme. The whole UI reads design tokens (app.css), so a theme is
+ * just which palette those tokens resolve to: we stamp `data-theme` on the root
+ * element and the CSS does the rest.
+ *
+ * Dark is the default — the app was built for it, and existing users should see
+ * no change until they flip the switch. The choice survives reloads via
+ * localStorage; a missing or garbage value falls back to dark.
+ */
+
+export const THEMES = ['dark', 'light'];
+export const DEFAULT_THEME = 'dark';
+
+const KEY = 'azimut:theme';
+
+/** Snap anything — stored, passed, or garbage — to a known theme. */
+export function normalizeTheme(t) {
+ return THEMES.includes(t) ? t : DEFAULT_THEME;
+}
+
+export function loadTheme() {
+ try {
+ return normalizeTheme(localStorage.getItem(KEY));
+ } catch {
+ return DEFAULT_THEME; // localStorage unavailable (private mode) — non-fatal
+ }
+}
+
+export function saveTheme(t) {
+ try {
+ localStorage.setItem(KEY, normalizeTheme(t));
+ } catch {
+ /* ignore */
+ }
+}
+
+/** Stamp the theme onto <html> so the token overrides in app.css take effect. */
+export function applyTheme(t) {
+ document.documentElement.dataset.theme = normalizeTheme(t);
+}
diff --git a/frontend/src/lib/theme.test.js b/frontend/src/lib/theme.test.js
new file mode 100644
index 0000000..f7f5429
--- /dev/null
+++ b/frontend/src/lib/theme.test.js
@@ -0,0 +1,84 @@
+// @vitest-environment happy-dom
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import {
+ normalizeTheme,
+ loadTheme,
+ saveTheme,
+ applyTheme,
+ DEFAULT_THEME,
+} from './theme.js';
+
+/** A localStorage stand-in that records what it was handed. */
+function fakeStorage(initial = {}) {
+ const data = { ...initial };
+ return {
+ getItem: vi.fn((k) => (k in data ? data[k] : null)),
+ setItem: vi.fn((k, v) => (data[k] = v)),
+ data,
+ };
+}
+
+afterEach(() => vi.unstubAllGlobals());
+
+describe('normalizeTheme', () => {
+ it('keeps a known theme', () => {
+ expect(normalizeTheme('light')).toBe('light');
+ expect(normalizeTheme('dark')).toBe('dark');
+ });
+
+ it('falls back to the default for anything else', () => {
+ expect(normalizeTheme('sepia')).toBe(DEFAULT_THEME);
+ expect(normalizeTheme(null)).toBe(DEFAULT_THEME);
+ expect(normalizeTheme(undefined)).toBe(DEFAULT_THEME);
+ });
+});
+
+describe('loadTheme / saveTheme', () => {
+ it('round-trips a stored theme', () => {
+ vi.stubGlobal('localStorage', fakeStorage());
+ saveTheme('light');
+ expect(loadTheme()).toBe('light');
+ });
+
+ it('defaults to dark when nothing was ever stored', () => {
+ vi.stubGlobal('localStorage', fakeStorage());
+ expect(loadTheme()).toBe('dark');
+ });
+
+ it('re-normalizes a garbage stored value instead of trusting it', () => {
+ vi.stubGlobal('localStorage', fakeStorage({ 'azimut:theme': 'neon' }));
+ expect(loadTheme()).toBe(DEFAULT_THEME);
+ });
+
+ it('never writes a garbage value', () => {
+ const store = fakeStorage();
+ vi.stubGlobal('localStorage', store);
+ saveTheme('neon');
+ expect(store.data['azimut:theme']).toBe(DEFAULT_THEME);
+ });
+
+ it('survives a hostile or absent localStorage (private mode)', () => {
+ vi.stubGlobal('localStorage', {
+ getItem: () => {
+ throw new Error('denied');
+ },
+ setItem: () => {
+ throw new Error('denied');
+ },
+ });
+ expect(loadTheme()).toBe(DEFAULT_THEME);
+ expect(() => saveTheme('light')).not.toThrow();
+ });
+});
+
+describe('applyTheme', () => {
+ it('stamps the theme onto the document root', () => {
+ applyTheme('light');
+ expect(document.documentElement.dataset.theme).toBe('light');
+ });
+
+ it('normalizes before stamping', () => {
+ applyTheme('neon');
+ expect(document.documentElement.dataset.theme).toBe(DEFAULT_THEME);
+ });
+});
diff --git a/frontend/src/lib/toast.test.js b/frontend/src/lib/toast.test.js
new file mode 100644
index 0000000..19e065e
--- /dev/null
+++ b/frontend/src/lib/toast.test.js
@@ -0,0 +1,28 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { toast, uiState } from './state.svelte.js';
+
+afterEach(() => {
+ vi.useRealTimers();
+ uiState.toasts = [];
+});
+
+describe('toast actions', () => {
+ it('keeps an optional action with the toast for the action button to consume', () => {
+ const action = { label: 'OPEN', onClick: vi.fn() };
+
+ toast('Report saved as a note', 'ok', 6000, action);
+
+ expect(uiState.toasts).toHaveLength(1);
+ expect(uiState.toasts[0].action).toBe(action);
+ });
+
+ it('keeps the existing auto-dismiss behavior', () => {
+ vi.useFakeTimers();
+ toast('Report saved as a note', 'ok', 6000);
+
+ vi.advanceTimersByTime(5999);
+ expect(uiState.toasts).toHaveLength(1);
+ vi.advanceTimersByTime(1);
+ expect(uiState.toasts).toHaveLength(0);
+ });
+});
diff --git a/frontend/src/lib/toolLoader.js b/frontend/src/lib/toolLoader.js
new file mode 100644
index 0000000..84a3bd9
--- /dev/null
+++ b/frontend/src/lib/toolLoader.js
@@ -0,0 +1,33 @@
+/** Cache asynchronous component imports while allowing a failed load to retry. */
+export function createToolLoader(loaders) {
+ const loaded = new Map();
+ const pending = new Map();
+
+ return {
+ get(id) {
+ return loaded.get(id) ?? null;
+ },
+
+ load(id) {
+ if (loaded.has(id)) return Promise.resolve(loaded.get(id));
+ if (pending.has(id)) return pending.get(id);
+ const load = loaders[id];
+ if (!load) return Promise.reject(new Error(`Unknown tool: ${id}`));
+
+ const request = Promise.resolve()
+ .then(() => load())
+ .then((module) => {
+ const component = module?.default ?? module;
+ loaded.set(id, component);
+ pending.delete(id);
+ return component;
+ })
+ .catch((error) => {
+ pending.delete(id);
+ throw error;
+ });
+ pending.set(id, request);
+ return request;
+ },
+ };
+}
diff --git a/frontend/src/lib/toolLoader.test.js b/frontend/src/lib/toolLoader.test.js
new file mode 100644
index 0000000..e9d29f4
--- /dev/null
+++ b/frontend/src/lib/toolLoader.test.js
@@ -0,0 +1,30 @@
+import { describe, expect, it, vi } from 'vitest';
+import { createToolLoader } from './toolLoader.js';
+
+describe('createToolLoader', () => {
+ it('deduplicates concurrent imports and caches the component', async () => {
+ const component = () => 'tool';
+ const load = vi.fn(async () => ({ default: component }));
+ const loader = createToolLoader({ media: load });
+
+ const [first, second] = await Promise.all([loader.load('media'), loader.load('media')]);
+ expect(first).toBe(component);
+ expect(second).toBe(component);
+ expect(loader.get('media')).toBe(component);
+ expect(load).toHaveBeenCalledTimes(1);
+ await loader.load('media');
+ expect(load).toHaveBeenCalledTimes(1);
+ });
+
+ it('allows a failed import to be retried', async () => {
+ const component = () => 'tool';
+ const load = vi.fn()
+ .mockRejectedValueOnce(new Error('missing chunk'))
+ .mockResolvedValueOnce({ default: component });
+ const loader = createToolLoader({ media: load });
+
+ await expect(loader.load('media')).rejects.toThrow('missing chunk');
+ await expect(loader.load('media')).resolves.toBe(component);
+ expect(load).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/frontend/src/lib/workspaces.js b/frontend/src/lib/workspaces.js
index 9821865..b82850e 100644
--- a/frontend/src/lib/workspaces.js
+++ b/frontend/src/lib/workspaces.js
@@ -10,16 +10,35 @@
* layer (today the case sidebar covers it).
*/
export const WORKSPACES = [
- { id: 'collect', label: 'Collect', icon: 'download', tools: ['media', 'files', 'reverse'] },
+ { id: 'collect', label: 'Sources', icon: 'download', tools: ['media', 'files', 'reverse'] },
{ id: 'examine', label: 'Examine', icon: 'inspect', tools: ['inspect'] },
{ id: 'map', label: 'Map', icon: 'satellite', tools: ['satellite', 'coordinates'] },
- { id: 'compose', label: 'Compose', icon: 'proof', tools: ['proof', 'post'] },
+ { id: 'compose', label: 'Compose', icon: 'proof', tools: ['proof', 'post', 'notebook'] },
];
+export const TOOL_LABELS = {
+ media: 'Media',
+ files: 'Files',
+ reverse: 'Reverse Search',
+ inspect: 'Inspect',
+ satellite: 'Satellite',
+ coordinates: 'Coordinates',
+ proof: 'Geo Proof',
+ post: 'Geo Report',
+ notebook: 'Notebook',
+ settings: 'Settings',
+};
+
export function workspaceOf(tool) {
return WORKSPACES.find((w) => w.tools.includes(tool)) ?? null;
}
+/** Return the session's sidebar state for a workspace, falling back to defaults. */
+export function sidebarOpenForWorkspace(workspaceId, remembered = {}) {
+ if (remembered[workspaceId] !== undefined) return remembered[workspaceId];
+ return workspaceId !== 'map';
+}
+
/**
* Resolve a location hash to a tool id, or null if it matches nothing.
* Accepted forms, in priority order:
diff --git a/frontend/src/lib/workspaces.test.js b/frontend/src/lib/workspaces.test.js
index f43f89c..1250268 100644
--- a/frontend/src/lib/workspaces.test.js
+++ b/frontend/src/lib/workspaces.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { WORKSPACES, workspaceOf, toolFromHash } from './workspaces.js';
+import { WORKSPACES, TOOL_LABELS, sidebarOpenForWorkspace, workspaceOf, toolFromHash } from './workspaces.js';
const ALL_TOOLS = [
'media', 'files', 'reverse', 'inspect', 'satellite', 'coordinates', 'proof', 'post', 'settings',
@@ -36,6 +36,27 @@ describe('workspaceOf', () => {
});
});
+describe('product-facing labels', () => {
+ it('uses the Sources, Geo Proof and Geo Report names', () => {
+ expect(WORKSPACES.find((w) => w.id === 'collect').label).toBe('Sources');
+ expect(TOOL_LABELS.proof).toBe('Geo Proof');
+ expect(TOOL_LABELS.post).toBe('Geo Report');
+ });
+});
+
+describe('sidebarOpenForWorkspace', () => {
+ it('defaults Map closed and other workspaces open', () => {
+ expect(sidebarOpenForWorkspace('map')).toBe(false);
+ expect(sidebarOpenForWorkspace('collect')).toBe(true);
+ expect(sidebarOpenForWorkspace('examine')).toBe(true);
+ });
+
+ it('uses the remembered state instead of the workspace default', () => {
+ expect(sidebarOpenForWorkspace('map', { map: true })).toBe(true);
+ expect(sidebarOpenForWorkspace('collect', { collect: false })).toBe(false);
+ });
+});
+
describe('toolFromHash', () => {
it('keeps pre-workspace tool links working', () => {
for (const tool of ALL_TOOLS) {
diff --git a/frontend/src/tools/Coordinates.svelte b/frontend/src/tools/Coordinates.svelte
index f29dddc..15875bd 100644
--- a/frontend/src/tools/Coordinates.svelte
+++ b/frontend/src/tools/Coordinates.svelte
@@ -92,7 +92,7 @@
class="input"
placeholder={'Paste any coordinate: 48.8584, 2.2945 · DMS · UTM · MGRS · plus code · geohash'}
bind:value={text}
- title="Decimal, degrees-minutes-seconds, degrees-decimal-minutes, UTM, MGRS, plus code or geohash"
+ title="Decimal, DMS, DDM, UTM, MGRS, plus code or geohash"
/>
<button type="submit" class="btn" disabled={!text.trim() || parsing}>
<Icon name="search" size={15} /> {parsing ? '…' : 'Convert'}
diff --git a/frontend/src/tools/Files.svelte b/frontend/src/tools/Files.svelte
index b030b82..cfe9f00 100644
--- a/frontend/src/tools/Files.svelte
+++ b/frontend/src/tools/Files.svelte
@@ -10,16 +10,18 @@
*/
import { api } from '../lib/api.js';
import { caseState, reloadCase, toast } from '../lib/state.svelte.js';
- import { buildTree, subtreeCount, folderOf, flattenPaths } from '../lib/folderTree.js';
+ import { buildTree, subtreeCount, folderOf, flattenPaths, isInFolderSubtree } from '../lib/folderTree.js';
import { assignFolderBatch } from '../lib/filing.js';
import { createNote } from '../lib/notes.js';
+ import { openNotebook } from '../lib/navigate.js';
import { createBookmark } from '../lib/bookmarks.js';
import { marqueeRect, marqueeHits, toggleSelection } from '../lib/gridSelect.js';
- import { deletePlan } from '../lib/chain.js';
+ import { fetchAllEntities } from '../lib/catalog.js';
import Icon from '../components/Icon.svelte';
import Modal from '../components/Modal.svelte';
import ConfirmDialog from '../components/ConfirmDialog.svelte';
import EntityDetails from '../components/EntityDetails.svelte';
+ import FolderSelect from '../components/FolderSelect.svelte';
const TYPE_ICON = {
media: 'image', capture: 'satellite', note: 'note', proof: 'proof',
@@ -27,13 +29,27 @@
};
const VIDEO_EXTS = new Set(['mp4', 'mov', 'webm', 'mkv', 'avi', 'm4v']);
// Entity types backed by a file on disk — deleting them drops the file too.
- const FILE_BACKED = new Set(['media', 'capture', 'proof', 'post', 'inspect-session']);
+ const FILE_BACKED = new Set(['media', 'capture', 'proof', 'post', 'inspect-session', 'note']);
// ── case data ──────────────────────────────────────────────────────────────
- const confirmed = $derived(
- (caseState.current?.entities ?? []).filter((e) => e.provenance?.status !== 'suggested')
- );
- const links = $derived(caseState.current?.links ?? []);
+ // Every filed artifact, read a page at a time off the bounded catalog rather
+ // than the case-open payload. My work is inherently the whole confirmed
+ // catalog, so it fetches the whole slice — but server-side, never shipped in
+ // the open response, and re-read on case change or a save/delete elsewhere.
+ let confirmed = $state([]);
+ $effect(() => {
+ const id = caseState.current?.id;
+ caseState.rev;
+ if (!id) {
+ confirmed = [];
+ return;
+ }
+ let live = true;
+ fetchAllEntities(id, { status: 'confirmed' })
+ .then((list) => { if (live) confirmed = list; })
+ .catch(() => { if (live) confirmed = []; });
+ return () => { live = false; };
+ });
const tree = $derived(buildTree(caseState.current?.folders ?? [], confirmed));
const allFolders = $derived(flattenPaths(tree));
const unfiled = $derived(confirmed.filter((e) => !folderOf(e)));
@@ -91,7 +107,8 @@
return node;
}
- // free-text search spans the whole of My work, not just the open folder
+ // Search stays inside the open folder and its subfolders. The root is the
+ // one intentional exception: it represents all of My work.
let query = $state('');
const searching = $derived(!!query.trim());
function matches(e) {
@@ -104,8 +121,11 @@
}
const current = $derived(showUnfiled ? { path: '', children: [], entities: unfiled } : nodeAt(cwd));
+ const searchScope = $derived(
+ showUnfiled ? unfiled : cwd ? confirmed.filter((e) => isInFolderSubtree(e, cwd)) : confirmed
+ );
const curFolders = $derived(searching ? [] : current.children);
- const curEntities = $derived(searching ? confirmed.filter(matches) : current.entities);
+ const curEntities = $derived(searching ? searchScope.filter(matches) : current.entities);
const entityOrder = $derived(curEntities.map((e) => e.id));
const crumbs = $derived(cwd ? cwd.split('/') : []);
// the Unfiled bucket shows as a tile at the root, even when empty (drop here
@@ -282,19 +302,31 @@
}
}
- function askDeleteEntities(ids) {
+ async function askDeleteEntities(ids) {
const ents = confirmed.filter((e) => ids.includes(e.id));
if (!ents.length) return;
const multi = ents.length > 1;
+ // The authoritative plan is the backend's; a single delete previews its
+ // dependents endpoint rather than mirroring the whole graph client-side.
+ let consequences = null;
+ if (!multi) {
+ try {
+ consequences = await api.get(
+ `/api/cases/${caseState.current.id}/entities/${ents[0].id}/dependents`
+ );
+ } catch {
+ /* no preview — the delete still enforces the plan server-side */
+ }
+ }
confirmState = {
title: multi ? `Delete ${ents.length} items?` : 'Delete everywhere?',
message: multi
? `${ents.length} items will be removed from the case and their tools.`
: `“${ents[0].label}” will be removed from the case and its tool.`,
detail: ents.some((e) => FILE_BACKED.has(e.type))
- ? 'This permanently deletes the underlying file(s) on disk — it cannot be undone.'
- : 'This permanently removes it from the case — it cannot be undone.',
- consequences: multi ? null : deletePlan(confirmed, links, ents[0].id),
+ ? 'This permanently deletes the underlying file(s) on disk. It cannot be undone.'
+ : 'This permanently removes it from the case. It cannot be undone.',
+ consequences,
confirmLabel: multi ? 'Delete all' : 'Delete everywhere',
tone: 'danger',
icon: 'trash',
@@ -359,6 +391,14 @@
}
ctx = { x: e.clientX, y: e.clientY, kind: 'entity', ids: [...selected] };
}
+
+ function openEntityTile(entity) {
+ if (entity.type === 'note') {
+ openNotebook(entity.id);
+ return;
+ }
+ infoEntityId = entity.id;
+ }
function ctxMoveToUnfiled() {
const ids = ctx?.ids ?? [];
ctx = null;
@@ -373,10 +413,10 @@
}
// ── notes ────────────────────────────────────────────────────────────────
- let noteModal = $state(null); // { folder, title, content }
+ let noteModal = $state(null); // { folder, title }
let noteSaving = $state(false);
function openNewNote(folder) {
- noteModal = { folder: folder ?? '', title: '', content: '' };
+ noteModal = { folder: folder ?? '', title: '' };
}
async function saveNote() {
if (!noteModal || !noteModal.title.trim()) {
@@ -385,10 +425,10 @@
}
noteSaving = true;
try {
- await createNote(caseState.current.id, noteModal);
+ const note = await createNote(caseState.current.id, noteModal);
await reloadCase();
- toast('Note created', 'ok', 1600);
noteModal = null;
+ openNotebook(note.id);
} catch (e) {
toast(e.message, 'danger');
} finally {
@@ -436,7 +476,7 @@
<div class="spacer"></div>
<div class="search-box">
<Icon name="search" size={13} />
- <input class="search-input" placeholder="Search My work…" bind:value={query} />
+ <input class="search-input" placeholder={cwd ? 'Search this folder…' : 'Search My work…'} bind:value={query} />
{#if query}
<button class="search-clear" onclick={() => (query = '')} aria-label="Clear search">
<Icon name="x" size={12} />
@@ -591,8 +631,8 @@
tabindex="0"
title={e.label}
onclick={(ev) => onTileClick(ev, e.id)}
- ondblclick={() => (infoEntityId = e.id)}
- onkeydown={(ev) => ev.key === 'Enter' && (infoEntityId = e.id)}
+ ondblclick={() => openEntityTile(e)}
+ onkeydown={(ev) => ev.key === 'Enter' && openEntityTile(e)}
oncontextmenu={(ev) => openEntityCtx(ev, e)}
ondragstart={(ev) => onTileDragStart(ev, e.id)}
ondragend={() => { draggingIds = []; dropTarget = null; }}
@@ -756,26 +796,8 @@
<label class="modal-label" for="fnote-title">Title</label>
<input id="fnote-title" class="input" placeholder="Note title…" bind:value={noteModal.title} />
- <label class="modal-label" for="fnote-folder" style="margin-top:10px">Folder (in My work)</label>
- <input
- id="fnote-folder"
- class="input"
- placeholder="e.g. research, timeline, sources…"
- bind:value={noteModal.folder}
- list="fnote-folder-suggestions"
- />
- <datalist id="fnote-folder-suggestions">
- {#each allFolders as f (f)}<option value={f}></option>{/each}
- </datalist>
-
- <label class="modal-label" for="fnote-content" style="margin-top:10px">Content</label>
- <textarea
- id="fnote-content"
- class="textarea note-content"
- rows="14"
- placeholder="Write your notes in markdown…"
- bind:value={noteModal.content}
- ></textarea>
+ <span class="modal-label" style="margin-top:10px">Folder (in My work)</span>
+ <FolderSelect bind:value={noteModal.folder} folders={allFolders} emptyLabel="My work (root)" />
<div class="modal-row">
<div style="flex:1"></div>
@@ -796,17 +818,8 @@
<label class="modal-label" for="fbm-title" style="margin-top:10px">Title</label>
<input id="fbm-title" class="input" placeholder="Bookmark title…" bind:value={bookmarkModal.title} />
- <label class="modal-label" for="fbm-folder" style="margin-top:10px">Folder (in My work)</label>
- <input
- id="fbm-folder"
- class="input"
- placeholder="e.g. research, sources…"
- bind:value={bookmarkModal.folder}
- list="fbm-folder-suggestions"
- />
- <datalist id="fbm-folder-suggestions">
- {#each allFolders as f (f)}<option value={f}></option>{/each}
- </datalist>
+ <span class="modal-label" style="margin-top:10px">Folder (in My work)</span>
+ <FolderSelect bind:value={bookmarkModal.folder} folders={allFolders} emptyLabel="My work (root)" />
<label class="modal-label" for="fbm-notes" style="margin-top:10px">Notes</label>
<textarea id="fbm-notes" class="textarea" rows="3" placeholder="Why this page matters…" bind:value={bookmarkModal.notes}></textarea>
@@ -945,12 +958,6 @@
color: var(--text-3);
margin: 8px 0 4px;
}
- .note-content {
- width: 100%;
- resize: vertical;
- font-family: var(--font-mono);
- font-size: var(--fs-xs);
- }
.modal-row {
display: flex;
align-items: center;
diff --git a/frontend/src/tools/Inspector.svelte b/frontend/src/tools/Inspector.svelte
index bf055dc..292334f 100644
--- a/frontend/src/tools/Inspector.svelte
+++ b/frontend/src/tools/Inspector.svelte
@@ -1,9 +1,11 @@
<script>
import { api } from '../lib/api.js';
+ import { lookupEntity } from '../lib/catalog.js';
import { caseState, uiState, reloadCase, toast } from '../lib/state.svelte.js';
import {
- adjustDefaults, buildOps, previewStyle, isNeutral, uid, videoSeed, initialQuad, VIDEO_ADJUST_IDS,
- collageBounds, quadFromCropRect, cropImgStyle, cropAspect, styleText,
+ adjustDefaults, buildFrameOps, previewStyle, uid, videoSeed, initialQuad, VIDEO_ADJUST_IDS,
+ collageBounds, quadFromCropRect, cropImgStyle, cropAspect, styleText, hasVideoEdits,
+ normalizeRightAngleRotation, rotationOps,
} from '../lib/inspect.js';
import { createHistory } from '../lib/history.js';
import { IDENTITY, matrixCss, rotateAbout, isIdentity, matrixAngleDeg, pointerAngleDeg } from '../lib/frameRotate.js';
@@ -17,6 +19,7 @@
import SaveGallery from './inspect/SaveGallery.svelte';
import SaveMenu from './inspect/SaveMenu.svelte';
import PieceCropModal from './inspect/PieceCropModal.svelte';
+ import VideoPlayer from './inspect/VideoPlayer.svelte';
// The Inspect tool is a *scratch workspace*. Opening a photo/video starts a
// session; captured frames, per-frame adjustments, video tuning and a collage
@@ -63,6 +66,7 @@
const session = $state({
source: null,
videoAdjust: {},
+ videoRotation: 0,
frames: [],
activeFrameId: null,
collages: [_firstCollage],
@@ -137,6 +141,12 @@
shared.seekTo = Math.min(Math.max((shared.currentTime ?? 0) + delta, 0), duration);
}
+ function toggleVideoPlayback() {
+ if (!videoEl) return;
+ if (videoEl.paused) videoEl.play().catch(() => {});
+ else videoEl.pause();
+ }
+
function onWindowKeydown(e) {
if (uiState.tool !== 'inspect') return;
const t = e.target;
@@ -159,6 +169,7 @@
else if (e.key === 'ArrowRight') { e.preventDefault(); stepVideo(e.shiftKey ? 1 : frameDur); }
else if (e.key === ',') { e.preventDefault(); stepVideo(-frameDur); }
else if (e.key === '.') { e.preventDefault(); stepVideo(frameDur); }
+ else if (e.key === ' ') { e.preventDefault(); toggleVideoPlayback(); }
}
// keep-alive: tools stay mounted when another tab is shown — silence the video
@@ -187,6 +198,7 @@
// applied (Enter / Apply), a committed *preview* showing the cropped result.
// Re-opening crop (button or double-click) goes back to editing the original.
let cropEditing = $state(false);
+ let frameOrientationBusy = $state(false);
const videoFilters = $derived(filters.filter((f) => VIDEO_ADJUST_IDS.includes(f.id)));
const tabs = $derived(
@@ -195,13 +207,22 @@
const activeFrame = $derived(session.frames.find((f) => f.id === session.activeFrameId) ?? null);
const framePreview = $derived(activeFrame ? previewStyle(filters, activeFrame.adjust) : { filter: '', transform: '' });
const videoPreview = $derived(previewStyle(videoFilters, session.videoAdjust));
+ const videoRotation = $derived(normalizeRightAngleRotation(session.videoRotation));
+ const videoQuarterTurn = $derived(Math.abs(videoRotation) === 90);
+ const videoPreviewTransform = $derived(
+ [videoPreview.transform, videoRotation ? `rotate(${videoRotation}deg)` : ''].filter(Boolean).join(' ')
+ );
const savables = $derived.by(() => {
const out = [];
const cid = caseState.current?.id;
- if (session.source?.kind === 'video' && !isNeutral(videoFilters, session.videoAdjust)) {
+ if (session.source?.kind === 'video' && hasVideoEdits(videoFilters, session.videoAdjust, videoRotation)) {
const t = session.source.thumbnail ? `/files/${cid}/${session.source.thumbnail}` : null;
- out.push({ key: 'video', kind: 'video', label: 'Video 1', thumb: t, saved: !!session.saved.video });
+ out.push({
+ key: 'video', kind: 'video', label: 'Video 1', thumb: t,
+ filter: videoPreview.filter, transform: videoPreviewTransform,
+ saved: !!session.saved.video,
+ });
}
let imgN = 0;
for (const fr of session.frames) {
@@ -288,17 +309,33 @@
// binding instead: Save then files a new one, deliberately.
let sourceGone = $state(false);
$effect(() => {
- caseState.rev;
- const list = caseState.current?.entities ?? [];
- if (
- openedSession &&
- !list.some((e) => e.attrs?.spec === `inspect/${openedSession.name}.json`)
- ) {
- openedSession = null;
- toast('The saved session was deleted — saving now files a new one', 'warn');
- }
+ const id = caseState.current?.id;
+ caseState.rev; // re-check after a delete elsewhere
+ const sessionName = openedSession?.name;
const path = session.source?.path;
- sourceGone = !!path && !list.some((e) => e.attrs?.path === path);
+ if (!id) {
+ sourceGone = false;
+ return;
+ }
+ let live = true;
+ (async () => {
+ if (sessionName) {
+ const bound = await lookupEntity(id, 'spec', `inspect/${sessionName}.json`);
+ if (live && !bound && openedSession?.name === sessionName) {
+ openedSession = null;
+ toast('The saved session was deleted. Saving now creates a new one', 'warn');
+ }
+ }
+ if (path) {
+ const ent = await lookupEntity(id, 'path', path);
+ if (live) sourceGone = !ent;
+ } else if (live) {
+ sourceGone = false;
+ }
+ })();
+ return () => {
+ live = false;
+ };
});
function mediaLabel(m) {
@@ -310,6 +347,7 @@
for (const fr of session.frames) if (fr.url?.startsWith('blob:')) URL.revokeObjectURL(fr.url);
session.source = null;
session.videoAdjust = {};
+ session.videoRotation = 0;
session.frames = [];
session.activeFrameId = null;
const c0 = makeCollage('Collage 1');
@@ -358,7 +396,7 @@
function makeFrame(path, time, url) {
return {
id: uid('fr'), path, time, url,
- adjust: adjustDefaults(filters), crop: null,
+ adjust: adjustDefaults(filters), crop: null, sourceOps: [], rotation: 0,
w: probeInfo?.width, h: probeInfo?.height,
};
}
@@ -433,8 +471,13 @@
// -- frame capture (Selection) -------------------------------------------
async function capture(time) {
try {
- const url = await renderUrl(session.source.path, time, []);
+ const sourceOps = rotationOps(videoRotation);
+ const url = await renderUrl(session.source.path, time, sourceOps);
const frame = makeFrame(session.source.path, time, url);
+ const dim = await imageSize(url);
+ frame.sourceOps = sourceOps;
+ frame.w = dim.w;
+ frame.h = dim.h;
// frames captured from a tuned video inherit those gear adjustments
frame.adjust = videoSeed(filters, session.videoAdjust);
session.frames.push(frame);
@@ -451,7 +494,7 @@
const cl = activeCollage;
if (!cl) return;
try {
- const ops = buildOps(filters, frame.adjust, frame.crop);
+ const ops = buildFrameOps(filters, frame);
const url = await renderUrl(frame.path, frame.time, ops);
const dim = await imageSize(url);
const count = cl.nodes.length;
@@ -533,6 +576,34 @@
if (session.activeFrameId === id) session.activeFrameId = session.frames[0]?.id ?? null;
}
+ async function setFrameRotation(angle) {
+ const frame = activeFrame;
+ if (!frame || frameOrientationBusy) return;
+ const rotation = normalizeRightAngleRotation(angle);
+ frameOrientationBusy = true;
+ try {
+ const url = await renderUrl(frame.path, frame.time, [
+ ...(frame.sourceOps ?? []),
+ ...rotationOps(rotation),
+ ]);
+ const dim = await imageSize(url);
+ if (!session.frames.includes(frame)) {
+ URL.revokeObjectURL(url);
+ return;
+ }
+ const oldUrl = frame.url;
+ frame.url = url;
+ frame.rotation = rotation;
+ frame.w = dim.w;
+ frame.h = dim.h;
+ if (oldUrl?.startsWith('blob:')) URL.revokeObjectURL(oldUrl);
+ } catch (e) {
+ toast(e.message, 'danger');
+ } finally {
+ frameOrientationBusy = false;
+ }
+ }
+
// -- frame viewer: zoom / pan / straighten (Frame tab) -------------------
// Reset the view whenever the active frame changes.
$effect(() => {
@@ -681,7 +752,7 @@
.map((it) => ({
path: it.frame.path,
time: it.frame.time ?? null,
- ops: buildOps(filters, it.frame.adjust, it.frame.crop),
+ ops: buildFrameOps(filters, it.frame),
}));
if (frameItems.length) {
await api.post(`/api/cases/${cid}/inspect/save-frames`, { items: frameItems, folder });
@@ -689,7 +760,7 @@
}
if (chosen.some((it) => it.kind === 'video')) {
await api.post(`/api/cases/${cid}/inspect/enhance-video`, {
- path: session.source.path, params: session.videoAdjust, folder,
+ path: session.source.path, params: session.videoAdjust, rotation: videoRotation, folder,
});
session.saved.video = true;
}
@@ -726,9 +797,12 @@
return {
source: { path: session.source.path, kind: session.source.kind },
videoAdjust: { ...session.videoAdjust },
+ videoRotation,
activeFrameId: session.activeFrameId,
frames: session.frames.map((f) => ({
- id: f.id, path: f.path, time: f.time, adjust: { ...f.adjust }, crop: f.crop, w: f.w, h: f.h,
+ id: f.id, path: f.path, time: f.time, adjust: { ...f.adjust }, crop: f.crop,
+ sourceOps: f.sourceOps ?? [], rotation: normalizeRightAngleRotation(f.rotation),
+ w: f.w, h: f.h,
})),
activeCollageId: session.activeCollageId,
collages: session.collages.map((cl) => ({
@@ -805,10 +879,13 @@
probeInfo = { kind: src.kind };
}
session.videoAdjust = spec.videoAdjust ?? adjustDefaults(videoFilters);
+ session.videoRotation = normalizeRightAngleRotation(spec.videoRotation);
for (const f of spec.frames ?? []) {
try {
- const url = await renderUrl(f.path, f.time, []);
- session.frames.push({ ...f, url });
+ const sourceOps = f.sourceOps ?? [];
+ const rotation = normalizeRightAngleRotation(f.rotation);
+ const url = await renderUrl(f.path, f.time, [...sourceOps, ...rotationOps(rotation)]);
+ session.frames.push({ ...f, sourceOps, rotation, url });
} catch {
/* skip a frame whose source is gone */
}
@@ -958,17 +1035,16 @@
<div class="workspace">
<div class="viewer" class:pad={activeTab !== 'collage' && activeTab !== 'save'}>
{#if activeTab === 'selection'}
- <div class="frame">
- <!-- svelte-ignore a11y_media_has_caption -->
- <video
- bind:this={videoEl}
- src={`/files/${caseState.current?.id}/${session.source.path}`}
- controls
- ontimeupdate={() => (shared.currentTime = videoEl?.currentTime ?? 0)}
- style:filter={videoPreview.filter}
- style:transform={videoPreview.transform}
- ></video>
- </div>
+ <VideoPlayer
+ bind:video={videoEl}
+ src={`/files/${caseState.current?.id}/${session.source.path}`}
+ filter={videoPreview.filter}
+ transform={videoPreviewTransform}
+ quarterTurn={videoQuarterTurn}
+ duration={probeInfo?.duration ?? 0}
+ currentTime={shared.currentTime}
+ ontimeupdate={(time) => (shared.currentTime = time)}
+ />
{:else if activeTab === 'frame'}
{#if activeFrame}
<!-- svelte-ignore a11y_no_static_element_interactions -->
@@ -1064,7 +1140,12 @@
{#if activeTab === 'selection'}
<SelectionMenu {probeInfo} {shared} {videoFilters} {session} {capture} />
{:else if activeTab === 'frame'}
- <FrameMenu {session} {filters} {analyses} {activeFrame} {shared} {removeFrame} bind:cropAspect={frameAspect} bind:cropEditing {beginCrop} {commitCrop} setActive={(id) => (session.activeFrameId = id)} />
+ <FrameMenu
+ {session} {filters} {analyses} {activeFrame} {shared} {removeFrame}
+ bind:cropAspect={frameAspect} bind:cropEditing {beginCrop} {commitCrop}
+ setRotation={setFrameRotation} rotationBusy={frameOrientationBusy}
+ setActive={(id) => (session.activeFrameId = id)}
+ />
{:else if activeTab === 'collage'}
<CollageMenu {session} {filters} bind:selectedIds={collageSelectedIds} {addToCollage} {requestCrop} {renderPiece} />
{:else if activeTab === 'save'}
@@ -1167,10 +1248,6 @@
font-size: var(--fs-lg);
font-weight: 700;
}
- .sub {
- color: var(--text-3);
- font-size: var(--fs-sm);
- }
.spacer {
flex: 1;
}
@@ -1263,18 +1340,6 @@
.viewer.pad {
padding: 18px;
}
- .frame {
- position: relative;
- display: inline-block;
- line-height: 0;
- touch-action: none;
- box-shadow: var(--shadow-2);
- }
- .frame video {
- max-width: 100%;
- max-height: calc(100vh - var(--topbar-h) - 160px);
- display: block;
- }
/* Frame tab: a zoom/pan/rotate surface with the crop overlay on top. */
.frame-viewport {
position: relative;
diff --git a/frontend/src/tools/MediaLibrary.svelte b/frontend/src/tools/MediaLibrary.svelte
index e5426bb..b09694d 100644
--- a/frontend/src/tools/MediaLibrary.svelte
+++ b/frontend/src/tools/MediaLibrary.svelte
@@ -1,5 +1,6 @@
<script>
import { api } from '../lib/api.js';
+ import { lookupEntity } from '../lib/catalog.js';
import { caseState, uiState, ensureCase, reloadCase, toast } from '../lib/state.svelte.js';
import { visibleMedia, SORTS } from '../lib/mediaFilter.js';
import Icon from '../components/Icon.svelte';
@@ -88,6 +89,15 @@
let focusScrolledFor = null;
let focusTimer;
+ // --- thumbnails still generating in the background ---
+ // A broken <img> (a thumbnail evicted by the cache budget between list and
+ // render) falls back to the type icon, reported once by dropping the path in
+ // here — it does not retry on every render.
+ let brokenThumbs = $state(new Set());
+ const thumbsPending = $derived(
+ items.some((i) => i.thumb_state === 'queued' || i.thumb_state === 'running')
+ );
+
$effect(() => {
const id = caseState.current?.id;
caseState.rev; // also refetch when the case is reloaded elsewhere (e.g. sidebar edit)
@@ -131,6 +141,43 @@
if (id) items = await api.get(`/api/cases/${id}/media`);
}
+ // While the single worker is still generating thumbnails (video frames, or a
+ // regenerate), re-list to pick up readiness — only while the tool is visible,
+ // and the poll stops on its own once nothing is pending.
+ $effect(() => {
+ if (!thumbsPending || uiState.tool !== 'media' || !caseState.current) return;
+ const t = setTimeout(() => refresh(), 1500);
+ return () => clearTimeout(t);
+ });
+
+ // Queue (re)generation: a single failed thumbnail (path given) or every
+ // missing/failed one across the case. The worker drains the queue; the poll
+ // above reflects each result as it lands.
+ async function regenerateThumbs(path = null) {
+ const id = caseState.current?.id;
+ if (!id) return;
+ try {
+ const { queued } = await api.post(
+ `/api/cases/${id}/media/thumbnails/regenerate`,
+ path ? { path } : {}
+ );
+ if (path) {
+ const next = new Set(brokenThumbs);
+ next.delete(path);
+ brokenThumbs = next;
+ }
+ await refresh();
+ if (!path) {
+ toast(
+ queued ? `Regenerating ${queued} thumbnail${queued > 1 ? 's' : ''}` : 'Thumbnails are up to date',
+ queued ? 'info' : 'ok'
+ );
+ }
+ } catch (e) {
+ toast(e.message, 'danger');
+ }
+ }
+
async function importFiles(fileList) {
const files = [...fileList];
if (!files.length) return;
@@ -265,8 +312,8 @@
// Open the shared details editor (same body as the case sidebar) for this
// file's case entity — full provenance, derivation chain, title/notes/folder.
- function openInfo(item) {
- const ent = (caseState.current?.entities ?? []).find((e) => e.attrs?.path === item.path);
+ async function openInfo(item) {
+ const ent = await lookupEntity(caseState.current?.id, 'path', item.path);
if (ent) infoEntityId = ent.id;
else toast('This file has no case entity yet', 'warn');
}
@@ -307,6 +354,14 @@
<button class="btn" onclick={() => fileInput.click()}>
<Icon name="upload" size={15} /> Import
</button>
+ <button
+ class="btn"
+ onclick={() => regenerateThumbs()}
+ title="Regenerate missing or failed thumbnails"
+ disabled={!items.length}
+ >
+ <Icon name="reset" size={15} /> Thumbnails
+ </button>
<input
type="file"
multiple
@@ -418,6 +473,8 @@
data-path={item.path}
>
<!-- thumbnail — click to lightbox for images -->
+ <!-- The role and tab stop deliberately exist only for image previews. -->
+ <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
<div
class="thumb"
class:clickable={item.kind === 'image'}
@@ -427,12 +484,31 @@
onkeydown={(e) => e.key === 'Enter' && item.kind === 'image' && (lightboxItem = item)}
aria-label={item.kind === 'image' ? `Preview ${item.filename}` : undefined}
>
- {#if item.thumbnail}
+ {#if item.thumbnail && item.thumb_state === 'ready' && !brokenThumbs.has(item.path)}
<img
src={`/files/${caseState.current.id}/${item.thumbnail}`}
alt={item.filename}
loading="lazy"
+ decoding="async"
+ onerror={() => (brokenThumbs = new Set(brokenThumbs).add(item.path))}
/>
+ {:else if item.thumb_state === 'queued' || item.thumb_state === 'running'}
+ <div class="thumb-status">
+ <Icon name="clock" size={22} />
+ <span>Generating…</span>
+ </div>
+ {:else if item.thumb_state === 'failed'}
+ <button
+ class="thumb-status thumb-retry"
+ title="Retry thumbnail"
+ onclick={(e) => {
+ e.stopPropagation();
+ regenerateThumbs(item.path);
+ }}
+ >
+ <Icon name="reset" size={20} />
+ <span>Retry</span>
+ </button>
{:else}
<Icon name={KIND_ICONS[item.kind] ?? 'file'} size={34} />
{/if}
@@ -485,7 +561,7 @@
{#if item.kind === 'image'}
<button
class="btn btn-ghost btn-sm"
- title="Send to Proof Composer"
+ title="Send to Geo Proof"
onclick={() => sendToComposer(item)}
>
<Icon name="proof" size={14} />
@@ -567,7 +643,8 @@
{#if lightboxItem}
<div
class="lightbox"
- onclick={() => (lightboxItem = null)}
+ onclick={(e) => e.target === e.currentTarget && (lightboxItem = null)}
+ onkeydown={(e) => e.key === 'Escape' && (lightboxItem = null)}
role="dialog"
aria-label="Image preview"
tabindex="-1"
@@ -596,7 +673,6 @@
<img
src={`/files/${caseState.current.id}/${lightboxItem.path}`}
alt={lightboxItem.filename}
- onclick={(e) => e.stopPropagation()}
/>
<span class="lb-caption">
{lightboxItem.title ?? lightboxItem.filename}
@@ -612,7 +688,7 @@
<ConfirmDialog
title="Delete this media?"
message={`“${deleteTarget.title ?? deleteTarget.filename}” and its entity will be removed from the case.`}
- detail="This permanently deletes the file on disk — it cannot be undone."
+ detail="This permanently deletes the file on disk. It cannot be undone."
confirmLabel="Delete"
tone="danger"
busy={deleteBusy}
@@ -785,19 +861,56 @@
}
.thumb {
position: relative;
+ width: 100%;
aspect-ratio: 16 / 10;
+ min-width: 0;
+ min-height: 0;
background: var(--bg-2);
display: flex;
align-items: center;
justify-content: center;
color: var(--text-3);
+ overflow: hidden;
+ flex: 0 0 auto;
}
.thumb.clickable {
cursor: zoom-in;
}
+ .thumb-status {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 4px;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ background: none;
+ border: none;
+ }
+ .thumb-status :global(svg) {
+ opacity: 0.85;
+ animation: thumb-pulse 1.6s ease-in-out infinite;
+ }
+ @keyframes thumb-pulse {
+ 0%, 100% { opacity: 0.4; }
+ 50% { opacity: 0.9; }
+ }
+ .thumb-retry {
+ cursor: pointer;
+ }
+ .thumb-retry:hover {
+ color: var(--text-1);
+ }
+ .thumb-retry :global(svg) {
+ animation: none;
+ }
.thumb img {
+ position: absolute;
+ inset: 0;
+ display: block;
width: 100%;
height: 100%;
+ min-width: 0;
+ min-height: 0;
object-fit: cover;
}
.kind {
diff --git a/frontend/src/tools/MediaLibrary.test.js b/frontend/src/tools/MediaLibrary.test.js
new file mode 100644
index 0000000..70ef7fb
--- /dev/null
+++ b/frontend/src/tools/MediaLibrary.test.js
@@ -0,0 +1,59 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+const source = readFileSync(new URL('./MediaLibrary.svelte', import.meta.url), 'utf8');
+
+function cssBlock(selector) {
+ const start = source.indexOf(`${selector} {`);
+ if (start < 0) return '';
+ const end = source.indexOf('\n }', start);
+ return end < 0 ? '' : source.slice(start, end);
+}
+
+describe('Media Library thumbnail layout', () => {
+ it('keeps every thumbnail in a fixed frame regardless of source dimensions', () => {
+ const thumb = cssBlock('.thumb');
+
+ expect(thumb).toContain('width: 100%;');
+ expect(thumb).toContain('aspect-ratio: 16 / 10;');
+ expect(thumb).toContain('min-height: 0;');
+ expect(thumb).toContain('overflow: hidden;');
+ expect(thumb).toContain('flex: 0 0 auto;');
+ });
+
+ it('prevents the thumbnail image from contributing intrinsic dimensions', () => {
+ const image = cssBlock('.thumb img');
+
+ expect(image).toContain('position: absolute;');
+ expect(image).toContain('inset: 0;');
+ expect(image).toContain('display: block;');
+ expect(image).toContain('min-width: 0;');
+ expect(image).toContain('min-height: 0;');
+ expect(image).toContain('object-fit: cover;');
+ });
+});
+
+describe('Media Library thumbnail states', () => {
+ it('shows the image only when its thumbnail is ready and not broken', () => {
+ // the ready branch is gated on thumb_state and the broken-thumb fallback set
+ expect(source).toContain("item.thumb_state === 'ready' && !brokenThumbs.has(item.path)");
+ // a broken <img> reports once into brokenThumbs rather than retrying
+ expect(source).toContain('onerror={() => (brokenThumbs = new Set(brokenThumbs).add(item.path))}');
+ // lazy + async decode per the doc's UI failure behaviour
+ expect(source).toContain('loading="lazy"');
+ expect(source).toContain('decoding="async"');
+ });
+
+ it('renders a generating placeholder and a retry affordance for failures', () => {
+ expect(source).toContain("item.thumb_state === 'queued' || item.thumb_state === 'running'");
+ expect(source).toContain('Generating…');
+ expect(source).toContain("item.thumb_state === 'failed'");
+ expect(source).toContain('regenerateThumbs(item.path)');
+ });
+
+ it('polls while thumbnails are pending and only while the tool is visible', () => {
+ expect(source).toContain("i.thumb_state === 'queued' || i.thumb_state === 'running'");
+ expect(source).toContain("if (!thumbsPending || uiState.tool !== 'media' || !caseState.current) return;");
+ expect(source).toContain('/media/thumbnails/regenerate');
+ });
+});
diff --git a/frontend/src/tools/Notebook.svelte b/frontend/src/tools/Notebook.svelte
new file mode 100644
index 0000000..66618fd
--- /dev/null
+++ b/frontend/src/tools/Notebook.svelte
@@ -0,0 +1,800 @@
+<script>
+ import { api } from '../lib/api.js';
+ import { fetchAllEntities } from '../lib/catalog.js';
+ import { caseState, uiState, toast, reloadCase } from '../lib/state.svelte.js';
+ import { entityReference, markdownHtml, remoteImageUrls } from '../lib/markdown.js';
+ import { createNote, deleteNote, resetCaseNotes } from '../lib/notes.js';
+ import {
+ clampNotebookHelpPosition, clampNotebookSplit, loadNotebookSplit, loadNotebookText,
+ saveNotebookSplit,
+ } from '../lib/notebook.js';
+ import { downloadNotebookPdf } from '../lib/notebookPdf.js';
+ import { insertNotebookText, notebookImageMarkdown, notebookMediaMarkdown } from '../lib/notebookContent.js';
+ import { caseTab, closeNotebookTab, openNotebookTab } from '../lib/notebookTabs.js';
+ import { openEntity } from '../lib/navigate.js';
+ import Icon from '../components/Icon.svelte';
+ import ConfirmDialog from '../components/ConfirmDialog.svelte';
+ import Modal from '../components/Modal.svelte';
+ import FolderSelect from '../components/FolderSelect.svelte';
+
+ let tabs = $state([]); // [{ id: 'case' | entity id, noteId }]
+ let activeId = $state('case');
+ let tabsCaseId = $state(null);
+ let menuOpen = $state(false);
+ let query = $state('');
+ let previewOnly = $state(false);
+ let split = $state(loadNotebookSplit());
+ let panesEl = $state(null);
+ let resizing = $state(false);
+ let writerEl = $state(null);
+ let referenceOpen = $state(false);
+ let referenceQuery = $state('');
+ let mediaOpen = $state(false);
+ let mediaQuery = $state('');
+ let markdownHelpOpen = $state(false);
+ let markdownHelpCollapsed = $state(false);
+ let notebookEl = $state(null);
+ let markdownHelpEl = $state(null);
+ let markdownHelpPosition = $state(null);
+ let imageUploading = $state(false);
+ let noteModal = $state(null);
+ let noteModalSaving = $state(false);
+ let noteAction = $state(null);
+ let noteActionBusy = $state(false);
+
+ let text = $state('');
+ let loadedKey = $state('');
+ let pendingSaves = $state(0);
+ let saved = $state(true);
+ let editVersion = 0;
+ let saveTimer;
+
+ // The whole entity set — notes to list, references and media to insert, and the
+ // targets `[[mentions]]` resolve to — read off the bounded catalog rather than
+ // the case-open payload. Mention autocomplete inherently spans every entity, so
+ // it fetches the whole slice, but server-side and re-read on any change.
+ let graphEntities = $state([]);
+ $effect(() => {
+ const id = caseState.current?.id;
+ caseState.rev;
+ if (!id) {
+ graphEntities = [];
+ return;
+ }
+ let live = true;
+ fetchAllEntities(id)
+ .then((list) => { if (live) graphEntities = list; })
+ .catch(() => { if (live) graphEntities = []; });
+ return () => { live = false; };
+ });
+
+ const noteEntities = $derived(graphEntities
+ .filter((entity) => entity.type === 'note')
+ .sort((a, b) => a.label.localeCompare(b.label)));
+ const filteredNotes = $derived(noteEntities.filter((entity) => {
+ const haystack = `${entity.label} ${entity.attrs?.folder ?? ''}`.toLowerCase();
+ return haystack.includes(query.trim().toLowerCase());
+ }));
+ const referenceEntities = $derived(graphEntities
+ .filter((entity) => entity.provenance?.status !== 'suggested')
+ .filter((entity) => `${entity.label} ${entity.type}`.toLowerCase().includes(referenceQuery.trim().toLowerCase()))
+ .sort((a, b) => a.label.localeCompare(b.label)));
+ const caseMedia = $derived(graphEntities
+ .filter((entity) => (entity.type === 'media' || entity.type === 'capture') && entity.attrs?.path)
+ .filter((entity) => `${entity.label} ${entity.attrs?.kind ?? ''}`.toLowerCase().includes(mediaQuery.trim().toLowerCase()))
+ .sort((a, b) => a.label.localeCompare(b.label)));
+ const activeTab = $derived(tabs.find((tab) => tab.id === activeId) ?? tabs[0] ?? null);
+ const noteId = $derived(activeTab?.noteId ?? null);
+ const title = $derived(noteId
+ ? noteEntities.find((entity) => entity.id === noteId)?.label ?? 'Note'
+ : 'Case Notes');
+ const endpoint = $derived(noteId
+ ? `/api/cases/${caseState.current?.id}/notes/${noteId}`
+ : `/api/cases/${caseState.current?.id}/notes`);
+ const key = $derived(caseState.current?.id ? `${caseState.current.id}:${noteId ?? 'case'}` : '');
+ const preview = $derived(markdownHtml(text, {
+ entities: graphEntities, caseId: caseState.current?.id ?? '',
+ }));
+ const remoteImages = $derived(remoteImageUrls(text));
+ const saving = $derived(pendingSaves > 0);
+
+ function resetTabs(caseId) {
+ tabsCaseId = caseId;
+ tabs = [caseTab()];
+ activeId = 'case';
+ previewOnly = false;
+ menuOpen = false;
+ query = '';
+ referenceOpen = false;
+ referenceQuery = '';
+ mediaOpen = false;
+ mediaQuery = '';
+ markdownHelpOpen = false;
+ markdownHelpCollapsed = false;
+ markdownHelpPosition = null;
+ noteAction = null;
+ noteActionBusy = false;
+ }
+
+ function openRequestedNote(noteId = null) {
+ ({ tabs, activeId } = openNotebookTab(tabs, noteId));
+ }
+
+ $effect(() => {
+ const caseId = caseState.current?.id ?? null;
+ if (caseId !== tabsCaseId) {
+ if (caseId) resetTabs(caseId);
+ else {
+ tabsCaseId = null;
+ tabs = [];
+ }
+ }
+ if (caseId) openRequestedNote(uiState.openNotebook?.noteId ?? null);
+ });
+
+ $effect(() => {
+ if (!key || key === loadedKey) return;
+ const requestedKey = key;
+ const requestedEndpoint = endpoint;
+ loadedKey = requestedKey;
+ text = '';
+ saved = true;
+ editVersion += 1;
+ loadNotebookText(requestedKey, requestedEndpoint, { get: api.get, currentKey: () => key })
+ .then((result) => {
+ if (result.accepted && loadedKey === requestedKey) text = result.text;
+ })
+ .catch((error) => {
+ if (key === requestedKey) toast(`Could not open note: ${error.message}`, 'danger');
+ });
+ });
+
+ $effect(() => {
+ const clampToPanes = () => {
+ if (panesEl) split = clampNotebookSplit(split, panesEl.clientWidth);
+ const bounds = helpBounds();
+ if (markdownHelpPosition && bounds) {
+ const clamped = clampNotebookHelpPosition(
+ markdownHelpPosition.x,
+ markdownHelpPosition.y,
+ bounds.panelWidth,
+ bounds.panelHeight,
+ bounds.containerWidth,
+ bounds.containerHeight,
+ );
+ if (clamped.x !== markdownHelpPosition.x || clamped.y !== markdownHelpPosition.y) {
+ markdownHelpPosition = clamped;
+ }
+ }
+ };
+ window.addEventListener('resize', clampToPanes);
+ clampToPanes();
+ return () => window.removeEventListener('resize', clampToPanes);
+ });
+
+ function selectTab(tab) {
+ activeId = tab.id;
+ uiState.openNotebook = { noteId: tab.noteId };
+ menuOpen = false;
+ }
+
+ function selectNote(noteId = null) {
+ openRequestedNote(noteId);
+ uiState.openNotebook = { noteId };
+ menuOpen = false;
+ }
+
+ function openNewNote() {
+ noteModal = { title: '', folder: '' };
+ }
+
+ async function saveNote() {
+ if (!noteModal) return;
+ const { title: noteTitle, folder } = noteModal;
+ if (!noteTitle.trim()) {
+ toast('Title required', 'warn');
+ return;
+ }
+ noteModalSaving = true;
+ try {
+ const note = await createNote(caseState.current.id, { title: noteTitle, folder });
+ await reloadCase();
+ noteModal = null;
+ openRequestedNote(note.id);
+ uiState.openNotebook = { noteId: note.id };
+ } catch (error) {
+ toast(error.message, 'danger');
+ } finally {
+ noteModalSaving = false;
+ }
+ }
+
+ function askNoteAction() {
+ if (!caseState.current) return;
+ if (noteId) {
+ const note = noteEntities.find((entity) => entity.id === noteId);
+ if (!note) return;
+ noteAction = { kind: 'delete', noteId, label: note.label };
+ return;
+ }
+ noteAction = { kind: 'reset' };
+ }
+
+ function cancelPendingSave() {
+ clearTimeout(saveTimer);
+ saveTimer = undefined;
+ editVersion += 1;
+ }
+
+ function closeDeletedNote(deletedNoteId) {
+ const next = closeNotebookTab(tabs, activeId, deletedNoteId);
+ tabs = next.tabs;
+ activeId = next.activeId;
+ const active = tabs.find((tab) => tab.id === activeId);
+ uiState.openNotebook = { noteId: active?.noteId ?? null };
+ }
+
+ async function confirmNoteAction() {
+ const action = noteAction;
+ if (!action || !caseState.current) return;
+ noteActionBusy = true;
+ cancelPendingSave();
+ try {
+ if (action.kind === 'delete') {
+ await deleteNote(caseState.current.id, action.noteId);
+ closeDeletedNote(action.noteId);
+ await reloadCase();
+ toast(`Deleted "${action.label}"`, 'info');
+ } else {
+ await resetCaseNotes(caseState.current.id);
+ text = '';
+ saved = true;
+ toast('Note content reset', 'ok', 1800);
+ }
+ } catch (error) {
+ toast(error.message, 'danger');
+ } finally {
+ noteActionBusy = false;
+ noteAction = null;
+ }
+ }
+
+ function closeTab(event, tab) {
+ event.stopPropagation();
+ if (tab.id === 'case') return;
+ const next = closeNotebookTab(tabs, activeId, tab.id);
+ tabs = next.tabs;
+ activeId = next.activeId;
+ if (activeId === tab.id) return;
+ const active = tabs.find((item) => item.id === activeId);
+ if (active) uiState.openNotebook = { noteId: active.noteId };
+ }
+
+ function saveSoon() {
+ saved = false;
+ clearTimeout(saveTimer);
+ const target = endpoint;
+ const targetKey = key;
+ const contents = text;
+ const version = ++editVersion;
+ saveTimer = setTimeout(() => save(target, targetKey, contents, version), 700);
+ }
+
+ async function save(target, targetKey, contents, version) {
+ if (!targetKey) return;
+ pendingSaves += 1;
+ try {
+ await api.put(target, { text: contents });
+ if (key === targetKey && editVersion === version) saved = true;
+ } catch (error) {
+ toast(`Note not saved: ${error.message}`, 'danger');
+ } finally {
+ pendingSaves -= 1;
+ }
+ }
+
+ function setSplitFromClientX(clientX) {
+ const rect = panesEl?.getBoundingClientRect();
+ if (!rect) return;
+ split = clampNotebookSplit(((clientX - rect.left) / rect.width) * 100, rect.width);
+ }
+
+ function startResize(event) {
+ if (event.button !== 0) return;
+ event.preventDefault();
+ resizing = true;
+ setSplitFromClientX(event.clientX);
+ const move = (moveEvent) => setSplitFromClientX(moveEvent.clientX);
+ const stop = () => {
+ resizing = false;
+ saveNotebookSplit(split);
+ window.removeEventListener('pointermove', move);
+ window.removeEventListener('pointerup', stop);
+ };
+ window.addEventListener('pointermove', move);
+ window.addEventListener('pointerup', stop);
+ }
+
+ function onSplitterKey(event) {
+ const direction = { ArrowLeft: -2, ArrowRight: 2 }[event.key];
+ if (direction === undefined) return;
+ event.preventDefault();
+ split = clampNotebookSplit(split + direction, panesEl?.clientWidth);
+ saveNotebookSplit(split);
+ }
+
+ function resetSplit() {
+ split = 50;
+ saveNotebookSplit(split);
+ }
+
+ function downloadPdf() {
+ if (!downloadNotebookPdf({ title, content: preview })) {
+ toast('Allow popups to save the PDF.', 'warn');
+ }
+ }
+
+ function toggleMarkdownHelp() {
+ markdownHelpOpen = !markdownHelpOpen;
+ if (markdownHelpOpen) {
+ markdownHelpCollapsed = false;
+ markdownHelpPosition = null;
+ }
+ }
+
+ function toggleMarkdownHelpCollapsed() {
+ markdownHelpCollapsed = !markdownHelpCollapsed;
+ requestAnimationFrame(() => {
+ const bounds = helpBounds();
+ if (!markdownHelpPosition || !bounds) return;
+ markdownHelpPosition = clampNotebookHelpPosition(
+ markdownHelpPosition.x,
+ markdownHelpPosition.y,
+ bounds.panelWidth,
+ bounds.panelHeight,
+ bounds.containerWidth,
+ bounds.containerHeight,
+ );
+ });
+ }
+
+ function helpBounds() {
+ if (!notebookEl || !markdownHelpEl) return null;
+ return {
+ panelWidth: markdownHelpEl.offsetWidth,
+ panelHeight: markdownHelpEl.offsetHeight,
+ containerWidth: notebookEl.clientWidth,
+ containerHeight: notebookEl.clientHeight,
+ };
+ }
+
+ function startMarkdownHelpDrag(event) {
+ if (event.button !== 0 || event.target.closest('button')) return;
+ const bounds = helpBounds();
+ if (!bounds) return;
+ event.preventDefault();
+ const parentRect = notebookEl.getBoundingClientRect();
+ const panelRect = markdownHelpEl.getBoundingClientRect();
+ const startX = event.clientX;
+ const startY = event.clientY;
+ const originX = panelRect.left - parentRect.left;
+ const originY = panelRect.top - parentRect.top;
+ const move = (moveEvent) => {
+ markdownHelpPosition = clampNotebookHelpPosition(
+ originX + moveEvent.clientX - startX,
+ originY + moveEvent.clientY - startY,
+ bounds.panelWidth,
+ bounds.panelHeight,
+ bounds.containerWidth,
+ bounds.containerHeight,
+ );
+ };
+ const stop = () => {
+ window.removeEventListener('pointermove', move);
+ window.removeEventListener('pointerup', stop);
+ };
+ window.addEventListener('pointermove', move);
+ window.addEventListener('pointerup', stop);
+ }
+
+ function insertAtCursor(value) {
+ const input = writerEl;
+ const start = input?.selectionStart ?? text.length;
+ const end = input?.selectionEnd ?? text.length;
+ const inserted = insertNotebookText(text, value, start, end);
+ text = inserted.text;
+ saveSoon();
+ requestAnimationFrame(() => {
+ input?.focus();
+ input?.setSelectionRange(inserted.cursor, inserted.cursor);
+ });
+ }
+
+ function insertReference(entity) {
+ insertAtCursor(entityReference(entity));
+ referenceOpen = false;
+ referenceQuery = '';
+ }
+
+ function insertCaseMedia(entity) {
+ insertAtCursor(notebookMediaMarkdown(caseState.current.id, entity));
+ mediaOpen = false;
+ mediaQuery = '';
+ }
+
+ async function importImage(file) {
+ if (!file || !file.type.startsWith('image/') || imageUploading) return;
+ imageUploading = true;
+ try {
+ const form = new FormData();
+ form.append('file', file, file.name || 'pasted-image.png');
+ const result = await api.post(`/api/cases/${caseState.current.id}/media/upload`, form);
+ await reloadCase();
+ insertAtCursor(notebookImageMarkdown(caseState.current.id, result.item, result.entity));
+ toast(result.duplicate ? 'Image linked from case media' : 'Image added to case media', 'ok', 1800);
+ } catch (error) {
+ toast(`Image not added: ${error.message}`, 'danger');
+ } finally {
+ imageUploading = false;
+ }
+ }
+
+ function onWriterPaste(event) {
+ const image = [...(event.clipboardData?.items ?? [])].find((item) => item.type.startsWith('image/'));
+ if (!image) return;
+ event.preventDefault();
+ importImage(image.getAsFile());
+ }
+
+ function onWriterDrop(event) {
+ event.preventDefault();
+ const image = [...(event.dataTransfer?.files ?? [])].find((file) => file.type.startsWith('image/'));
+ if (image) importImage(image);
+ }
+
+ function bindEntityLinks(node) {
+ const onClick = (event) => {
+ const link = event.target.closest('[data-entity-id]');
+ if (!link) return;
+ event.preventDefault();
+ const entity = graphEntities.find((item) => item.id === link.dataset.entityId);
+ if (entity) openEntity(entity);
+ };
+ node.addEventListener('click', onClick);
+ return { destroy: () => node.removeEventListener('click', onClick) };
+ }
+</script>
+
+{#if !caseState.current}
+ <div class="empty"><h2>No case open</h2><p>Open a case to write notes.</p></div>
+{:else}
+ <section bind:this={notebookEl} class="notebook">
+ <header class="notebook-bar">
+ <div class="notes-menu-wrap">
+ <button class="menu-toggle" class:active={menuOpen} onclick={() => (menuOpen = !menuOpen)} aria-expanded={menuOpen}>
+ <Icon name="note" size={15} /> Notes <Icon name="chevronDown" size={13} />
+ </button>
+ {#if menuOpen}
+ <div class="notes-menu">
+ <input class="input note-search" bind:value={query} placeholder="Find a note…" />
+ <button class="menu-note" class:selected={activeId === 'case'} onclick={() => selectNote()}>
+ <Icon name="note" size={14} /><span>Case Notes</span>
+ </button>
+ {#each filteredNotes as note (note.id)}
+ <button class="menu-note" class:selected={activeId === note.id} onclick={() => selectNote(note.id)}>
+ <Icon name="note" size={14} />
+ <span>{note.label}</span>
+ {#if note.attrs?.folder}<small>{note.attrs.folder}</small>{/if}
+ </button>
+ {/each}
+ {#if !filteredNotes.length && query.trim()}<p class="menu-empty">No matching notes.</p>{/if}
+ </div>
+ {/if}
+ </div>
+
+ <div class="tabs" aria-label="Open notes">
+ {#each tabs as tab (tab.id)}
+ {@const tabTitle = tab.noteId ? noteEntities.find((entity) => entity.id === tab.noteId)?.label ?? 'Note' : 'Case Notes'}
+ <div class="tab" class:active={tab.id === activeId}>
+ <button class="tab-main" onclick={() => selectTab(tab)} title={tabTitle}>
+ <Icon name="note" size={13} /><span>{tabTitle}</span>
+ </button>
+ {#if tab.id !== 'case'}<button class="tab-close" aria-label={`Close ${tabTitle}`} onclick={(event) => closeTab(event, tab)}><Icon name="x" size={12} /></button>{/if}
+ </div>
+ {/each}
+ </div>
+ <button class="btn btn-ghost btn-sm new-note-button" title="New note" aria-label="New note" onclick={openNewNote}>
+ <Icon name="plus" size={15} />
+ </button>
+
+ <div class="bar-actions">
+ <span class:pending={!saved} class="save-state">{saved ? 'Saved' : saving ? 'Saving…' : 'Unsaved'}</span>
+ <button class="btn btn-ghost btn-sm help-toggle" class:active={markdownHelpOpen} title="Markdown help" aria-label="Markdown help" aria-expanded={markdownHelpOpen} onclick={toggleMarkdownHelp}><Icon name="info" size={15} /></button>
+ {#if markdownHelpOpen}
+ <aside
+ bind:this={markdownHelpEl}
+ class="markdown-help"
+ class:collapsed={markdownHelpCollapsed}
+ aria-label="Markdown help"
+ style:left={markdownHelpPosition ? `${markdownHelpPosition.x}px` : undefined}
+ style:top={markdownHelpPosition ? `${markdownHelpPosition.y}px` : undefined}
+ >
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
+ <div class="help-heading" onpointerdown={startMarkdownHelpDrag} title="Drag to move">
+ <Icon name="grip" size={15} />
+ <div><strong>Markdown reference</strong><span>Drag this header to move the reference.</span></div>
+ <button
+ class="btn btn-ghost btn-sm"
+ title={markdownHelpCollapsed ? 'Expand' : 'Collapse'}
+ aria-label={markdownHelpCollapsed ? 'Expand Markdown help' : 'Collapse Markdown help'}
+ aria-expanded={!markdownHelpCollapsed}
+ onclick={toggleMarkdownHelpCollapsed}
+ ><Icon name={markdownHelpCollapsed ? 'chevronDown' : 'chevronUp'} size={14} /></button>
+ <button class="btn btn-ghost btn-sm" aria-label="Close Markdown help" onclick={() => (markdownHelpOpen = false)}><Icon name="x" size={14} /></button>
+ </div>
+ {#if !markdownHelpCollapsed}
+ <div class="help-body">
+ <div class="help-section">
+ <span class="help-label">Everyday formatting</span>
+ <div class="example-grid">
+ <div class="example-card">
+ <span class="example-name">Headings and text</span>
+ <pre><code># Field notes
+
+**Confirmed** and *unverified*
+
+~~Discarded lead~~</code></pre>
+ <div class="example-result prose-demo"><h3>Field notes</h3><p><strong>Confirmed</strong> and <em>unverified</em></p><p><s>Discarded lead</s></p></div>
+ </div>
+ <div class="example-card">
+ <span class="example-name">Lists and tasks</span>
+ <pre><code>- First observation
+- Second observation
+
+- [x] Archive source
+- [ ] Verify date</code></pre>
+ <div class="example-result list-demo"><ul><li>First observation</li><li>Second observation</li></ul><label><input type="checkbox" checked disabled> Archive source</label><label><input type="checkbox" disabled> Verify date</label></div>
+ </div>
+ <div class="example-card">
+ <span class="example-name">Code block</span>
+ <pre><code>```js
+const status = 'verified';
+console.log(status);
+```</code></pre>
+ <div class="example-result"><pre class="rendered-code"><code>const status = 'verified';
+console.log(status);</code></pre></div>
+ </div>
+ <div class="example-card">
+ <span class="example-name">Table</span>
+ <pre><code>| Source | Status |
+| --- | --- |
+| Photo | Verified |
+| Post | Pending |</code></pre>
+ <div class="example-result table-demo"><table><thead><tr><th>Source</th><th>Status</th></tr></thead><tbody><tr><td>Photo</td><td>Verified</td></tr><tr><td>Post</td><td>Pending</td></tr></tbody></table></div>
+ </div>
+ </div>
+ </div>
+ <div class="help-section">
+ <span class="help-label">Case content</span>
+ <div class="case-help">
+ <div><Icon name="link" size={14} /><span><strong>Link button</strong> inserts a clickable Case item.</span></div>
+ <div><Icon name="media" size={14} /><span><strong>Media button</strong> inserts a Case image or video.</span></div>
+ <div><Icon name="image" size={14} /><span><strong>Paste or drop</strong> adds an image to the Case.</span></div>
+ </div>
+ </div>
+ <div class="help-section layout-help">
+ <span class="help-label">Image and text layout</span>
+ <div class="example-grid">
+ <div class="layout-row"><pre><code>![Map](image.png)&#123;width=50% align=center&#125;</code></pre><div class="image-demo center"><i></i></div></div>
+ <div class="layout-row"><pre><code>::: center
+**Centred finding**
+:::</code></pre><div class="text-demo center"><strong>Centred finding</strong></div></div>
+ </div>
+ <p>Use <code>align=left</code>, <code>align=center</code>, or <code>align=right</code>. Width accepts percentages or pixels.</p>
+ </div>
+ </div>
+ {/if}
+ </aside>
+ {/if}
+ </div>
+ </header>
+
+ <div bind:this={panesEl} class="panes" class:preview-only={previewOnly} class:resizing style={`grid-template-columns: calc(${split}% - 4px) 8px calc(${100 - split}% - 4px);`}>
+ <section class="pane writer">
+ <div class="pane-title">
+ <span>Write</span>
+ <div class="writer-actions">
+ <button class="btn btn-ghost btn-sm" class:active={referenceOpen} title="Insert case reference" onclick={() => (referenceOpen = !referenceOpen)}><Icon name="link" size={14} /></button>
+ <button class="btn btn-ghost btn-sm" class:active={mediaOpen} title="Insert case media" onclick={() => (mediaOpen = !mediaOpen)}><Icon name="media" size={14} /></button>
+ <button
+ class="btn btn-ghost btn-sm"
+ title={noteId ? 'Delete note' : 'Reset note content'}
+ aria-label={noteId ? 'Delete note' : 'Reset note content'}
+ onclick={askNoteAction}
+ ><Icon name={noteId ? 'trash' : 'reset'} size={14} /></button>
+ {#if referenceOpen}
+ <div class="reference-menu">
+ <input class="input" bind:value={referenceQuery} placeholder="Find an entity…" />
+ {#each referenceEntities as entity (entity.id)}
+ <button class="reference-row" onclick={() => insertReference(entity)}><Icon name={entity.type === 'note' ? 'note' : entity.type === 'place' ? 'pin' : 'link'} size={13} /><span>{entity.label}</span><small>{entity.type}</small></button>
+ {/each}
+ {#if !referenceEntities.length}<p>No matching entities.</p>{/if}
+ </div>
+ {/if}
+ {#if mediaOpen}
+ <div class="reference-menu media-menu">
+ <input class="input" bind:value={mediaQuery} placeholder="Find case media…" />
+ {#each caseMedia as entity (entity.id)}
+ <button class="reference-row" onclick={() => insertCaseMedia(entity)}><Icon name={entity.attrs?.kind === 'video' ? 'video' : 'image'} size={13} /><span>{entity.label}</span><small>{entity.attrs?.kind ?? entity.type}</small></button>
+ {/each}
+ {#if !caseMedia.length}<p>No matching media.</p>{/if}
+ </div>
+ {/if}
+ </div>
+ </div>
+ <textarea bind:this={writerEl} bind:value={text} oninput={saveSoon} onpaste={onWriterPaste} ondragover={(event) => event.preventDefault()} ondrop={onWriterDrop} placeholder={imageUploading ? 'Adding image…' : 'Write in Markdown…'}></textarea>
+ {#if remoteImages.length}
+ <p class="remote-image-note">
+ Remote images contact their host every time this note opens. Add them to the case to keep the note local.
+ </p>
+ {/if}
+ </section>
+ <button class="splitter" aria-label="Resize writer and preview" title="Drag to resize · double-click to reset" onpointerdown={startResize} ondblclick={resetSplit} onkeydown={onSplitterKey}></button>
+ <article class="pane reader">
+ <div class="pane-title"><span>Preview</span><div class="preview-actions"><button class="btn btn-ghost btn-sm" title="Download PDF" aria-label="Download PDF" onclick={downloadPdf}><Icon name="download" size={14} /></button><button class="btn btn-ghost btn-sm preview-toggle" title={previewOnly ? 'Show writer' : 'Preview only'} onclick={() => (previewOnly = !previewOnly)}><Icon name={previewOnly ? 'minimize' : 'maximize'} size={14} /></button></div></div>
+ <div class="markdown" aria-label="Markdown preview" use:bindEntityLinks>{@html preview}</div>
+ </article>
+ </div>
+ </section>
+ {#if noteModal}
+ <Modal title="New note" onclose={() => (noteModal = null)} width="580px">
+ <label class="modal-label" for="notebook-note-title">Title</label>
+ <input id="notebook-note-title" class="input" placeholder="Note title…" bind:value={noteModal.title} />
+
+ <span class="modal-label" style="margin-top:10px">Folder (in My work)</span>
+ <FolderSelect bind:value={noteModal.folder} folders={caseState.current?.folders ?? []} emptyLabel="My work (root)" />
+
+ <div class="modal-row">
+ <div style="flex:1"></div>
+ <button class="btn" onclick={() => (noteModal = null)}>Cancel</button>
+ <button class="btn btn-primary" onclick={saveNote} disabled={noteModalSaving}>
+ {noteModalSaving ? 'Creating…' : 'Create'}
+ </button>
+ </div>
+ </Modal>
+ {/if}
+ {#if noteAction}
+ <ConfirmDialog
+ title={noteAction.kind === 'delete' ? 'Delete this note?' : 'Reset note content?'}
+ message={noteAction.kind === 'delete'
+ ? `Are you sure you want to delete “${noteAction.label}”?`
+ : 'Are you sure you want to reset the content of this note?'}
+ detail={noteAction.kind === 'delete'
+ ? 'This permanently removes the note and its content.'
+ : 'The case note will remain, but its content will be cleared.'}
+ confirmLabel={noteAction.kind === 'delete' ? 'Delete' : 'Reset'}
+ tone={noteAction.kind === 'delete' ? 'danger' : 'default'}
+ icon={noteAction.kind === 'delete' ? 'trash' : 'reset'}
+ busy={noteActionBusy}
+ onconfirm={confirmNoteAction}
+ oncancel={() => (noteAction = null)}
+ />
+ {/if}
+{/if}
+
+<style>
+ .notebook { position: relative; height: 100%; display: flex; flex-direction: column; }
+ .notebook-bar { height: 42px; flex: 0 0 42px; display: flex; align-items: stretch; gap: 8px; padding: 0 10px; border-bottom: 1px solid var(--border); background: var(--bg-1); }
+ .notes-menu-wrap { position: relative; display: flex; align-items: center; flex-shrink: 0; }
+ .menu-toggle { display: flex; align-items: center; gap: 5px; padding: 5px 7px; border-radius: var(--r-sm); color: var(--text-2); font-size: var(--fs-sm); }
+ .menu-toggle:hover, .menu-toggle.active { background: var(--bg-2); color: var(--text-1); }
+ .notes-menu { position: absolute; z-index: 8; top: calc(100% + 5px); left: 0; width: 270px; max-height: min(440px, calc(100vh - 115px)); overflow: auto; padding: 6px; border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--bg-1); box-shadow: 0 12px 30px #0004; }
+ .note-search { width: 100%; margin-bottom: 5px; font-size: var(--fs-sm); }
+ .menu-note { display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: center; gap: 7px; width: 100%; padding: 7px; border-radius: var(--r-sm); text-align: left; color: var(--text-2); font-size: var(--fs-sm); }
+ .menu-note:hover, .menu-note.selected { background: var(--bg-2); color: var(--text-1); }
+ .menu-note span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .menu-note small { grid-column: 2; color: var(--text-3); font-size: var(--fs-xs); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .menu-empty { margin: 8px; color: var(--text-3); font-size: var(--fs-sm); }
+ .tabs { flex: 1; min-width: 0; display: flex; align-items: stretch; overflow-x: auto; scrollbar-width: none; }
+ .tabs::-webkit-scrollbar { display: none; }
+ .new-note-button { flex-shrink: 0; align-self: center; color: var(--text-2); }
+ .new-note-button:hover { color: var(--accent); }
+ .tab { display: flex; align-items: center; max-width: 180px; color: var(--text-3); border-bottom: 2px solid transparent; font-size: var(--fs-sm); white-space: nowrap; }
+ .tab:hover { color: var(--text-1); background: var(--bg-2); }
+ .tab.active { color: var(--text-1); border-bottom-color: var(--accent); }
+ .tab-main { min-width: 0; display: flex; align-items: center; gap: 5px; padding: 0 6px 0 8px; color: inherit; }
+ .tab-main > span { overflow: hidden; text-overflow: ellipsis; }
+ .tab-close { display: flex; padding: 2px; color: var(--text-3); border-radius: 3px; }
+ .tab-close:hover { color: var(--text-1); background: var(--bg-3); }
+ .bar-actions { display: flex; align-items: center; gap: 4px; flex-shrink: 0; }
+ .save-state { color: var(--text-3); font-size: var(--fs-xs); }
+ .save-state.pending { color: var(--accent); }
+ .help-toggle.active { color: var(--accent); background: var(--accent-soft); }
+ .markdown-help { position: absolute; z-index: 10; top: 54px; right: 12px; width: min(760px, calc(100% - 24px)); max-height: calc(100% - 66px); overflow: auto; padding: 0 16px 16px; border: 1px solid var(--border); border-radius: var(--r-md); background: color-mix(in srgb, var(--bg-1) 96%, transparent); box-shadow: 0 20px 50px #0007; backdrop-filter: blur(8px); }
+ .markdown-help.collapsed { width: min(380px, calc(100% - 24px)); overflow: hidden; padding-bottom: 0; }
+ .help-heading { position: sticky; z-index: 1; top: 0; display: grid; grid-template-columns: auto minmax(0, 1fr) auto auto; align-items: center; gap: 9px; padding: 13px 0 11px; border-bottom: 1px solid var(--border); background: var(--bg-1); cursor: grab; touch-action: none; }
+ .markdown-help.collapsed .help-heading { padding-bottom: 13px; border-bottom: 0; }
+ .help-heading:active { cursor: grabbing; }
+ .help-heading strong { display: block; color: var(--text-1); font-size: var(--fs-sm); }
+ .help-heading span { display: block; margin-top: 2px; color: var(--text-3); font-size: var(--fs-xs); }
+ .help-section { padding-top: 15px; }
+ .help-label { display: block; margin-bottom: 8px; color: var(--text-3); font-size: var(--fs-xs); font-weight: 600; letter-spacing: .06em; text-transform: uppercase; }
+ .markdown-help code { padding: 2px 4px; border-radius: 3px; background: var(--bg-2); color: var(--text-1); font-family: var(--mono); font-size: 11px; }
+ .example-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; }
+ .example-card { min-width: 0; overflow: hidden; border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--bg-0); }
+ .example-name { display: block; padding: 7px 9px; border-bottom: 1px solid var(--border); color: var(--text-2); font-size: var(--fs-xs); font-weight: 600; }
+ .example-card > pre, .layout-row > pre { min-height: 72px; margin: 0; padding: 9px; overflow: auto; border-bottom: 1px solid var(--border); background: var(--bg-2); line-height: 1.45; white-space: pre-wrap; }
+ .example-card > pre code, .layout-row > pre code, .rendered-code code { padding: 0; background: transparent; }
+ .example-result { min-height: 88px; padding: 10px; color: var(--text-1); font-size: var(--fs-xs); }
+ .prose-demo h3 { margin: 0 0 8px; font-size: 15px; }
+ .prose-demo p { margin: 5px 0; }
+ .list-demo ul { margin: 0 0 7px; padding-left: 18px; }
+ .list-demo label { display: block; margin-top: 4px; }
+ .list-demo input { margin-right: 5px; accent-color: var(--accent); }
+ .rendered-code { margin: 0; padding: 9px; overflow: auto; border: 1px solid var(--border); border-radius: 4px; background: var(--bg-2); line-height: 1.5; }
+ .table-demo table { width: 100%; border-collapse: collapse; }
+ .table-demo th, .table-demo td { padding: 6px 7px; border: 1px solid var(--border); text-align: left; }
+ .table-demo th { background: var(--bg-2); }
+ .case-help { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; }
+ .case-help > div { display: flex; align-items: flex-start; gap: 7px; padding: 9px; border: 1px solid var(--border); border-radius: var(--r-sm); color: var(--text-2); font-size: var(--fs-xs); line-height: 1.45; }
+ .case-help :global(svg) { flex: 0 0 auto; margin-top: 1px; color: var(--accent); }
+ .case-help strong { color: var(--text-1); }
+ .layout-help { padding-bottom: 2px; }
+ .layout-row { min-width: 0; overflow: hidden; border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--bg-0); }
+ .image-demo { height: 68px; margin: 10px; padding: 6px; border: 1px solid var(--border); border-radius: 4px; background: var(--bg-1); }
+ .image-demo i { display: block; width: 50%; height: 100%; border-radius: 2px; background: linear-gradient(135deg, var(--accent-soft), var(--accent)); opacity: .85; }
+ .image-demo.center i { margin: 0 auto; }
+ .text-demo { margin: 10px; padding: 22px 8px; border: 1px solid var(--border); border-radius: 4px; color: var(--text-2); font-size: var(--fs-xs); }
+ .text-demo.center { text-align: center; }
+ .layout-help p { margin: 9px 0 0; color: var(--text-3); font-size: var(--fs-xs); line-height: 1.45; }
+ @media (max-width: 720px) {
+ .example-grid, .case-help { grid-template-columns: 1fr; }
+ .markdown-help { top: 12px; max-height: calc(100% - 24px); }
+ }
+ .panes { flex: 1; min-height: 0; display: grid; }
+ .remote-image-note { margin: 0; padding: 7px 10px; border-top: 1px solid var(--border); color: var(--warn); background: var(--bg-1); font-size: var(--fs-xs); }
+ .pane { min-width: 0; min-height: 0; display: flex; flex-direction: column; padding: 14px 18px; }
+ .pane-title > span { color: var(--text-3); font-size: var(--fs-xs); font-weight: 600; text-transform: uppercase; letter-spacing: .06em; }
+ .writer { background: var(--bg-1); }
+ textarea { flex: 1; min-height: 0; resize: none; margin-top: 10px; padding: 0; border: 0; border-radius: 0; background: transparent; color: var(--text-1); font: 14px/1.65 var(--mono); outline: none; }
+ .splitter { cursor: col-resize; background: var(--border); transition: background .12s; }
+ .splitter:hover, .splitter:focus-visible, .panes.resizing .splitter { background: var(--accent); outline: none; }
+ .reader { overflow: auto; background: var(--bg-0); }
+ .pane-title { position: relative; display: flex; align-items: center; justify-content: space-between; }
+ .writer-actions { position: relative; display: flex; align-items: center; }
+ .writer-actions .active { color: var(--accent); background: var(--accent-soft); }
+ .reference-menu { position: absolute; z-index: 6; top: calc(100% + 6px); right: 0; width: 260px; max-height: min(380px, calc(100vh - 180px)); overflow: auto; padding: 6px; border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--bg-1); box-shadow: 0 12px 30px #0004; }
+ .reference-menu .input { width: 100%; margin-bottom: 5px; font-size: var(--fs-sm); }
+ .reference-menu p { margin: 8px; color: var(--text-3); font-size: var(--fs-sm); }
+ .reference-row { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 7px; width: 100%; padding: 7px; border-radius: var(--r-sm); color: var(--text-2); text-align: left; font-size: var(--fs-sm); }
+ .reference-row:hover { background: var(--bg-2); color: var(--text-1); }
+ .reference-row span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .reference-row small { color: var(--text-3); font-size: var(--fs-xs); }
+ .preview-toggle { margin: -6px -7px -6px 0; }
+ .preview-actions { display: flex; align-items: center; gap: 2px; }
+ .markdown { margin-top: 10px; color: var(--text-1); line-height: 1.65; overflow-wrap: anywhere; }
+ .markdown :global(h1), .markdown :global(h2), .markdown :global(h3) { margin: 0 0 12px; line-height: 1.25; }
+ .markdown :global(p), .markdown :global(ul), .markdown :global(ol), .markdown :global(blockquote) { margin: 0 0 12px; }
+ .markdown :global(blockquote) { padding-left: 12px; border-left: 2px solid var(--border); color: var(--text-2); }
+ .markdown :global(code) { padding: 1px 4px; border-radius: 3px; background: var(--bg-2); font-family: var(--mono); }
+ .markdown :global(pre) { margin: 0 0 12px; padding: 12px; overflow: auto; border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--bg-1); }
+ .markdown :global(pre code) { padding: 0; background: transparent; }
+ .markdown :global(table) { width: 100%; margin: 0 0 12px; border-collapse: collapse; font-size: var(--fs-sm); }
+ .markdown :global(th), .markdown :global(td) { padding: 7px 9px; border: 1px solid var(--border); text-align: left; vertical-align: top; }
+ .markdown :global(th) { background: var(--bg-2); }
+ .markdown :global(input[type='checkbox']) { margin-right: 6px; accent-color: var(--accent); }
+ .markdown :global(.entity-ref) { color: var(--accent); font-weight: 600; }
+ .markdown :global(.broken-ref) { color: var(--text-3); font-style: italic; text-decoration: line-through; }
+ .markdown :global(img), .markdown :global(video) { display: block; max-width: 100%; height: auto; margin: 0 0 12px; border-radius: var(--r-sm); border: 1px solid var(--border); }
+ .markdown :global(video) { background: #000; }
+ .markdown :global(.markdown-image.align-center) { margin-right: auto; margin-left: auto; }
+ .markdown :global(.markdown-image.align-right) { margin-right: 0; margin-left: auto; }
+ .markdown :global(.markdown-align.align-center) { text-align: center; }
+ .markdown :global(.markdown-align.align-right) { text-align: right; }
+ .markdown :global(a) { color: var(--accent); }
+ .preview-only { grid-template-columns: 1fr !important; }
+ .preview-only .writer, .preview-only .splitter { display: none; }
+ .empty { padding: 28px; color: var(--text-2); }
+ .empty h2 { color: var(--text-1); }
+ @media (max-width: 800px) { .panes { grid-template-columns: 1fr !important; } .splitter { display: none; } .writer { min-height: 52%; border-bottom: 1px solid var(--border); } .preview-only .writer { display: none; } }
+</style>
diff --git a/frontend/src/tools/Notebook.test.js b/frontend/src/tools/Notebook.test.js
new file mode 100644
index 0000000..5a49d51
--- /dev/null
+++ b/frontend/src/tools/Notebook.test.js
@@ -0,0 +1,39 @@
+import { describe, expect, it, afterEach } from 'vitest';
+import { render } from 'svelte/server';
+import { caseState, uiState } from '../lib/state.svelte.js';
+import Notebook from './Notebook.svelte';
+
+afterEach(() => {
+ caseState.current = null;
+ uiState.openNotebook = null;
+});
+
+describe('Notebook note creation', () => {
+ it('shows a new-note button beside the open note tabs', () => {
+ caseState.current = { id: 'case-1', entities: [] };
+
+ const { body } = render(Notebook);
+
+ expect(body).toContain('aria-label="New note"');
+ expect(body).toContain('title="New note"');
+ });
+
+ it('shows reset for the case-wide note', () => {
+ caseState.current = { id: 'case-1', entities: [] };
+
+ const { body } = render(Notebook);
+
+ expect(body).toContain('aria-label="Reset note content"');
+ expect(body).not.toContain('aria-label="Delete note"');
+ });
+
+ it('places PDF download beside the preview-only control', () => {
+ caseState.current = { id: 'case-1', entities: [] };
+
+ const { body } = render(Notebook);
+
+ expect(body).toContain('aria-label="Download PDF"');
+ expect(body.indexOf('aria-label="Download PDF"')).toBeLessThan(body.indexOf('title="Preview only"'));
+ });
+
+});
diff --git a/frontend/src/tools/PostComposer.svelte b/frontend/src/tools/PostComposer.svelte
index 772b1cf..a0d7658 100644
--- a/frontend/src/tools/PostComposer.svelte
+++ b/frontend/src/tools/PostComposer.svelte
@@ -1,7 +1,10 @@
<script>
import { api } from '../lib/api.js';
+ import { lookupEntity, fetchDerivation } from '../lib/catalog.js';
import { caseState, uiState, toast, reloadCase, prefs } from '../lib/state.svelte.js';
import { templatesState } from '../lib/state.svelte.js';
+ import { createNote } from '../lib/notes.js';
+ import { openNotebook } from '../lib/navigate.js';
import { proofCoordsText, proofSource, DEFAULT_PROOF_TITLE } from '../lib/composer.js';
import {
buildTweet1 as buildTweet1Lines, DEFAULT_TWEET_BODY,
@@ -15,6 +18,7 @@
import Icon from '../components/Icon.svelte';
import Modal from '../components/Modal.svelte';
import ConfirmDialog from '../components/ConfirmDialog.svelte';
+ import FolderSelect from '../components/FolderSelect.svelte';
let coordsText = $state('');
let geo = $state(null); // {lat, lon, dms, plus_code, links}
@@ -53,18 +57,35 @@
// name. The thread on screen stays — a post outlives its proof (ONTOLOGY §3),
// it only loses the attachment.
$effect(() => {
+ const id = caseState.current?.id;
caseState.rev;
- const entities = caseState.current?.entities ?? [];
- if (draftName && !entities.some((e) => e.attrs?.draft === `exports/${draftName}.json`)) {
- draftName = null;
- toast('The saved draft was deleted — saving now files a new one', 'warn');
- }
- if (proofPng && !entities.some((e) => e.attrs?.path === proofPng)) {
- setProof(null);
- toast('The attached proof was deleted — the thread text is untouched', 'warn');
- }
+ const draft = draftName;
+ const proof = proofPng;
+ if (!id) return;
+ let live = true;
+ (async () => {
+ if (draft) {
+ const bound = await lookupEntity(id, 'draft', `exports/${draft}.json`);
+ if (live && !bound && draftName === draft) {
+ draftName = null;
+ toast('The saved draft was deleted. Saving now creates a new one', 'warn');
+ }
+ }
+ if (proof) {
+ const bound = await lookupEntity(id, 'path', proof);
+ if (live && !bound && proofPng === proof) {
+ setProof(null);
+ toast('The attached proof was deleted. The thread text is unchanged', 'warn');
+ }
+ }
+ })();
+ return () => {
+ live = false;
+ };
});
let saving = $state(false);
+ let reportModal = $state(null); // { title, folder }
+ let reportSaving = $state(false);
let discardConfirm = $state(false);
let openList = $state(null); // list of saved drafts, null = closed
@@ -73,6 +94,26 @@
let mediaLibrary = $state([]);
let mediaPickerTarget = $state(null); // null = tweet 2; an id = a later media tweet
+ // path → media kind, from our own /media shelf, so attach chips can label a
+ // video without scanning the whole entity graph. Refreshed on case change.
+ let kindByPath = $state(new Map());
+ $effect(() => {
+ const id = caseState.current?.id;
+ caseState.rev;
+ if (!id) {
+ kindByPath = new Map();
+ return;
+ }
+ let live = true;
+ api
+ .get(`/api/cases/${id}/media`)
+ .then((items) => {
+ if (live) kindByPath = new Map(items.map((it) => [it.path, it.kind]));
+ })
+ .catch(() => { if (live) kindByPath = new Map(); });
+ return () => { live = false; };
+ });
+
// Proof picker modal
let proofPickerOpen = $state(false);
let proofLibrary = $state([]);
@@ -397,8 +438,14 @@
async function preloadProofMedia(png, proofSourceUrl) {
if (!png || !proofSourceUrl || !caseState.current) return;
try {
- const library = await api.get(`/api/cases/${caseState.current.id}/media`);
- const linkedMedia = proofSourceMediaPaths(caseState.current, png, proofSourceUrl, library);
+ const cid = caseState.current.id;
+ const proof = await lookupEntity(cid, 'path', png);
+ if (!proof) return;
+ const [library, graph] = await Promise.all([
+ api.get(`/api/cases/${cid}/media`),
+ fetchDerivation(cid, proof.id),
+ ]);
+ const linkedMedia = proofSourceMediaPaths(graph, png, proofSourceUrl, library);
if (!linkedMedia.length) return;
const selected = new Set([
@@ -470,7 +517,7 @@
}
function mediaKind(path) {
- return caseState.current?.entities.find((e) => e.attrs?.path === path)?.attrs?.kind ?? 'image';
+ return kindByPath.get(path) ?? 'image';
}
const proofHref = $derived(
@@ -707,26 +754,85 @@
if (!hasContent) target = normalizePostTarget(prefs.postTarget);
});
- async function copyReport() {
- const attachments = [
+ function reportAttachmentPaths() {
+ return [
proofPng,
...mediaPaths,
...extraTweets.flatMap((tweet) => tweet.mediaPaths),
- ];
+ ].filter(Boolean);
+ }
+
+ async function reportEntities() {
+ if (!caseState.current) return { proofEntity: null, mediaEntities: [] };
+ const paths = [...new Set(reportAttachmentPaths())];
+ const resolved = await Promise.all(paths.map(async (path) => {
+ try {
+ return [path, await lookupEntity(caseState.current.id, 'path', path)];
+ } catch {
+ return [path, null];
+ }
+ }));
+ const byPath = new Map(resolved.filter(([, entity]) => entity));
+ return {
+ proofEntity: proofPng ? byPath.get(proofPng) ?? null : null,
+ mediaEntities: paths
+ .filter((path) => path !== proofPng)
+ .map((path) => byPath.get(path))
+ .filter(Boolean),
+ };
+ }
+
+ function reportContent(title = draftTitle(), evidence = {}) {
const coordinates = geo
? `${geo.lat.toFixed(6)}, ${geo.lon.toFixed(6)}`
: coordsText.trim();
- await navigator.clipboard.writeText(postReportMarkdown({
- title: draftTitle(),
+ return postReportMarkdown({
+ title,
place,
plusCode: geo?.plus_code,
coordinates,
+ dms: geo?.dms,
+ mapLinks: geo?.links,
description,
source,
- posts: threadParts(),
- attachments,
- }));
- toast('Markdown report copied', 'ok', 1800);
+ attachments: reportAttachmentPaths(),
+ ...evidence,
+ });
+ }
+
+ function openSaveReport() {
+ if (!caseState.current) {
+ toast('Open a case to save a report', 'warn');
+ return;
+ }
+ reportModal = { title: draftTitle(), folder: '' };
+ }
+
+ async function saveReport() {
+ if (!reportModal || !caseState.current) return;
+ if (!reportModal.title.trim()) {
+ toast('Title required', 'warn');
+ return;
+ }
+ reportSaving = true;
+ try {
+ const evidence = await reportEntities();
+ const note = await createNote(caseState.current.id, {
+ title: reportModal.title,
+ folder: reportModal.folder,
+ content: reportContent(reportModal.title.trim(), evidence),
+ });
+ await reloadCase();
+ reportModal = null;
+ toast('Report saved as a note', 'ok', 6000, {
+ label: 'OPEN',
+ onClick: () => openNotebook(note.id),
+ });
+ } catch (error) {
+ toast(`Report not saved: ${error.message}`, 'danger');
+ } finally {
+ reportSaving = false;
+ }
}
// ---- publish handoff (Azimut never posts on the analyst's behalf) --------
@@ -743,7 +849,7 @@
<div class="tool">
<div class="tool-header">
<div class="head-text">
- <h2>Post Composer</h2>
+ <h2>Geo Report</h2>
</div>
<div class="head-actions">
{#if caseState.current}
@@ -759,6 +865,9 @@
<button class="btn btn-ghost btn-sm" onclick={saveDraft} disabled={saving}>
<Icon name="save" size={14} /> {draftName ? 'Save draft' : 'Save as draft'}
</button>
+ <button class="btn btn-ghost btn-sm" onclick={openSaveReport} disabled={!hasContent || reportSaving}>
+ <Icon name="file" size={14} /> Save report
+ </button>
<button class="btn btn-primary btn-sm" onclick={publish} disabled={!tweet1.trim()} title={`Copy posts and open ${targetInfo.label}`}>
<Icon name="post" size={14} /> Publish on {targetInfo.label}
</button>
@@ -793,7 +902,7 @@
<button
class="tpl-settings-link"
type="button"
- title="Open Settings → Templates to create, edit or delete thread templates"
+ title="Manage thread templates in Settings"
onclick={openTemplateSettings}
>
Settings templates
@@ -822,7 +931,7 @@
<button
class="tpl-inline-link"
type="button"
- title="Open Settings → Templates to create your first thread template"
+ title="Create a thread template in Settings"
onclick={openTemplateSettings}
>
Create one in Settings → Templates.
@@ -1145,9 +1254,6 @@
<button class="btn btn-ghost btn-sm" onclick={copyAll}>
<Icon name="copy" size={13} /> Copy all
</button>
- <button class="btn btn-ghost btn-sm" onclick={copyReport} title="Copy as Markdown">
- <Icon name="file" size={13} /> Copy report
- </button>
</div>
</div>
@@ -1155,6 +1261,24 @@
</div>
</div>
+{#if reportModal}
+ <Modal title="Save report as note" onclose={() => (reportModal = null)} width="580px">
+ <label class="modal-label" for="report-note-title">Title</label>
+ <input id="report-note-title" class="input" placeholder="Report title…" bind:value={reportModal.title} />
+
+ <span class="modal-label" style="margin-top:10px">Folder (in My work)</span>
+ <FolderSelect bind:value={reportModal.folder} folders={caseState.current?.folders ?? []} emptyLabel="My work (root)" />
+
+ <div class="modal-row">
+ <div style="flex:1"></div>
+ <button class="btn" onclick={() => (reportModal = null)}>Cancel</button>
+ <button class="btn btn-primary" onclick={saveReport} disabled={reportSaving}>
+ {reportSaving ? 'Saving…' : 'Save report'}
+ </button>
+ </div>
+ </Modal>
+{/if}
+
{#if openList}
<Modal title="Open a saved draft" onclose={() => (openList = null)} width="560px">
{#if !openList.length}
diff --git a/frontend/src/tools/PostComposer.test.js b/frontend/src/tools/PostComposer.test.js
new file mode 100644
index 0000000..1605982
--- /dev/null
+++ b/frontend/src/tools/PostComposer.test.js
@@ -0,0 +1,21 @@
+import { afterEach, describe, expect, it } from 'vitest';
+import { render } from 'svelte/server';
+import { caseState, uiState } from '../lib/state.svelte.js';
+import PostComposer from './PostComposer.svelte';
+
+afterEach(() => {
+ caseState.current = null;
+ uiState.postProof = null;
+});
+
+describe('Geo Report actions', () => {
+ it('offers Save report and removes the old Copy report action', () => {
+ caseState.current = { id: 'case-1', folders: [], entities: [] };
+
+ const { body } = render(PostComposer);
+
+ expect(body).toContain('Save report');
+ expect(body).toContain('Publish on');
+ expect(body).not.toContain('Copy report');
+ });
+});
diff --git a/frontend/src/tools/ProofComposer.svelte b/frontend/src/tools/ProofComposer.svelte
index 1f500cb..5571b26 100644
--- a/frontend/src/tools/ProofComposer.svelte
+++ b/frontend/src/tools/ProofComposer.svelte
@@ -1,90 +1,18 @@
-<script module>
- /**
- * Keep selection out of pointerdown. Selecting rebuilds the Konva document,
- * so doing it before pointerup destroys the gesture target and can strand
- * Firefox's drag state. A click/tap or dragend is already a settled gesture.
- */
- export function bindPanelPointerLifecycle(group, { onPress, onSelect, onDragEnd }) {
- const isPanelTarget = (event) =>
- event?.target === group || event?.target?.name?.() === 'panel-hit';
- group.on('pointerdown', (event) => {
- if (isPanelTarget(event)) onPress(event);
- });
- group.on('click tap', (event) => {
- if (isPanelTarget(event)) onSelect(event);
- });
- if (onDragEnd) {
- group.on('dragend', (event) => {
- // Konva drag events bubble. A shape dragged inside this panel must keep
- // the shape selected and must never commit the parent panel's position.
- if (event?.target !== group) return;
- onSelect(event);
- onDragEnd(event);
- });
- }
- }
-
- /**
- * Coalesce document rebuilds and keep them out of an active pointer gesture.
- * Replacing Konva nodes between pointerdown and pointerup can leave Firefox
- * dispatching the rest of the gesture to a node that no longer exists.
- */
- export function createCanvasRenderGate(schedule, cancel, { rebuild, refreshUi }) {
- let pointerActive = false;
- let rebuildPending = false;
- let uiPending = false;
- let frame = null;
-
- function arm() {
- if (pointerActive || (!rebuildPending && !uiPending) || frame !== null) return;
- frame = schedule(() => {
- frame = null;
- if (pointerActive || (!rebuildPending && !uiPending)) return;
- const needsRebuild = rebuildPending;
- const needsUi = uiPending;
- rebuildPending = false;
- uiPending = false;
- if (needsRebuild) rebuild();
- else if (needsUi) refreshUi();
- });
- }
-
- return {
- beginPointer() {
- pointerActive = true;
- },
- endPointer() {
- pointerActive = false;
- arm();
- },
- requestRebuild() {
- rebuildPending = true;
- arm();
- },
- requestUi() {
- uiPending = true;
- arm();
- },
- destroy() {
- if (frame !== null) cancel(frame);
- frame = null;
- rebuildPending = false;
- uiPending = false;
- pointerActive = false;
- },
- };
- }
-</script>
-
<script>
import { onMount } from 'svelte';
import Konva from 'konva';
import { api } from '../lib/api.js';
+ import { lookupEntity, fetchAllEntities } from '../lib/catalog.js';
import { caseState, uiState, ensureCase, reloadCase, toast, prefs, fmtCoords } from '../lib/state.svelte.js';
import { templatesState } from '../lib/state.svelte.js';
import Icon from '../components/Icon.svelte';
import Modal from '../components/Modal.svelte';
import ConfirmDialog from '../components/ConfirmDialog.svelte';
+ import ProofToolbar from './proof/ProofToolbar.svelte';
+ import ProofCanvas from './proof/ProofCanvas.svelte';
+ import ProofLayersPanel from './proof/ProofLayersPanel.svelte';
+ import NewProofDialog from './proof/NewProofDialog.svelte';
+ import { bindPanelPointerLifecycle, createCanvasRenderGate } from './proof/canvasLifecycle.js';
import {
ANNO_COLORS, PAD, GAP, ROW_GAP, PANEL_H, TWEET_GUIDES,
CAPTION_SIZE, LEGEND_SIZE, FOOTER_SIZE,
@@ -171,22 +99,51 @@
// next Save writes a deleted proof back into the case under its old name.
// The canvas itself is left alone: the work on screen is still the analyst's.
$effect(() => {
+ const id = caseState.current?.id;
caseState.rev;
- const entities = caseState.current?.entities ?? [];
- if (savedName && !entities.some((e) => e.attrs?.spec === `proofs/${savedName}.json`)) {
- savedName = null;
- dirty = true;
- toast('The saved proof was deleted — saving now files a new one', 'warn');
+ const name = savedName;
+ if (!id || !name) return;
+ let live = true;
+ lookupEntity(id, 'spec', `proofs/${name}.json`).then((bound) => {
+ if (live && !bound && savedName === name) {
+ savedName = null;
+ dirty = true;
+ toast('The saved proof was deleted. Saving now creates a new one', 'warn');
+ }
+ });
+ return () => { live = false; };
+ });
+
+ // Every saved proof (its slugs and titles) and every current media/capture
+ // path, read a page at a time off the bounded catalog and the media shelves
+ // rather than the case-open payload. Refreshed on case change and after any
+ // reload elsewhere.
+ let proofEntities = $state([]);
+ let presentPaths = $state(new Set());
+ $effect(() => {
+ const id = caseState.current?.id;
+ caseState.rev;
+ if (!id) {
+ proofEntities = [];
+ presentPaths = new Set();
+ return;
}
+ let live = true;
+ fetchAllEntities(id, { types: ['proof'] })
+ .then((list) => { if (live) proofEntities = list; })
+ .catch(() => { if (live) proofEntities = []; });
+ Promise.all([api.get(`/api/cases/${id}/media`), api.get(`/api/cases/${id}/satellite`)])
+ .then(([media, sat]) => {
+ if (live) presentPaths = new Set([...media, ...sat].map((it) => it.path));
+ })
+ .catch(() => { if (live) presentPaths = new Set(); });
+ return () => { live = false; };
});
+
// Panels whose media was deleted: the image already drawn stays on the canvas,
// but the panel is flagged so a re-save is not silently building on a ghost.
const gonePanels = $derived(
- caseState.current
- ? proof.panels.filter(
- (p) => !(caseState.current.entities ?? []).some((e) => e.attrs?.path === p.src)
- )
- : []
+ caseState.current ? proof.panels.filter((p) => !presentPaths.has(p.src)) : []
);
let tool = $state('select');
let color = $state(ANNO_COLORS[0]);
@@ -314,7 +271,7 @@
}
// ---- konva ------------------------------------------------------------------
- let containerEl;
+ let containerEl = $state();
let stage, docLayer, uiLayer, transformer, endHandles, guideGroup, panelCtrls;
let canvasRenderGate;
let drawing = null; // {panel, node, start, box, kind}
@@ -1917,12 +1874,12 @@
// Every proof already saved in this case, read off the filed entities: the
// slugs (filename without `proofs/…​.json`) to catch a filename collision, and
// the titles so a fresh proof can take a title that reads apart from them.
- const savedProofNames = () => savedProofSlugs(caseState.current?.entities);
- const savedProofTitles = () => libSavedProofTitles(caseState.current?.entities);
+ const savedProofNames = () => savedProofSlugs(proofEntities);
+ const savedProofTitles = () => libSavedProofTitles(proofEntities);
// Title of a saved proof by its slug, for the overwrite prompt.
function savedProofTitle(name) {
- return libSavedProofTitle(caseState.current?.entities, name);
+ return libSavedProofTitle(proofEntities, name);
}
// Default title for a fresh proof, numbered past any already in the case so
@@ -2083,7 +2040,7 @@
<div class="tool">
<div class="tool-header">
- <h2>Proof Composer</h2>
+ <h2>Geo Proof</h2>
{#if proofStarted}
<input
class="input title-input"
@@ -2119,140 +2076,39 @@
</div>
<div class="body">
- <!-- left: drawing toolbar -->
- <div class="toolbar">
- <button class="tb-btn" title="Undo (Ctrl+Z)" disabled={!canUndo} onclick={undo}>
- <Icon name="undo" size={18} />
- </button>
- <button class="tb-btn" title="Redo (Ctrl+Shift+Z / Ctrl+Y)" disabled={!canRedo} onclick={redo}>
- <Icon name="redo" size={18} />
- </button>
- <div class="tb-sep"></div>
- {#each DRAW_TOOLS as t (t.id)}
- <button
- class="tb-btn"
- class:active={tool === t.id}
- title="{t.label} ({t.shortcut})"
- onclick={() => (tool = t.id)}
- >
- <Icon name={t.icon} size={18} />
- </button>
- {/each}
- <div class="tb-sep"></div>
- {#each proof.palette as c (c)}
- <button
- class="color-btn"
- class:active={activeColor === c}
- style:background={c}
- title="Same color = same feature"
- onclick={() => setColor(c)}
- aria-label={`color ${c}`}
- ></button>
- {/each}
- <label
- class="color-btn color-pick"
- class:active={!proof.palette.includes(activeColor)}
- style:background={activeColor}
- title="Custom color"
- >
- <Icon name="plus" size={12} />
- <input
- type="color"
- value={activeColor}
- oninput={(e) => setColor(e.target.value)}
- aria-label="custom color"
- />
- </label>
- <div class="tb-sep"></div>
- <input
- class="stroke-slider"
- type="range"
- min={selectedShape?.kind === 'text' ? 8 : 1}
- max={selectedShape?.kind === 'text' ? 120 : 24}
- step="1"
- value={selectedShape?.kind === 'text'
- ? (selectedShape.fontSize ?? 28)
- : (selectedShape?.strokeWidth ?? strokeW)}
- oninput={(e) => setStroke(+e.target.value)}
- title={selectedShape?.kind === 'text' ? 'Font size' : selectedShape ? 'Stroke width (selected)' : 'Stroke width'}
- />
- <div class="tb-sep"></div>
- <button class="tb-btn" title="Fit view (f)" onclick={fit}><Icon name="eye" size={18} /></button>
- <div class="tb-sep"></div>
- <button
- class="tb-btn"
- class:active={proof.layout !== 'free'}
- title="Grid layout: panels flow in rows"
- onclick={() => setLayoutMode('grid')}
- >
- <Icon name="grid" size={18} />
- </button>
- <button
- class="tb-btn"
- class:active={proof.layout === 'free'}
- title="Free layout: drag panels anywhere"
- onclick={() => setLayoutMode('free')}
- >
- <Icon name="layers" size={18} />
- </button>
- <div class="tb-sep"></div>
- {#each Object.keys(TWEET_GUIDES) as g (g)}
- <button
- class="tb-btn tb-guide"
- class:active={guide === g}
- title={`Preview the ${g} tweet crop — everything outside is cut off`}
- onclick={() => (guide = guide === g ? null : g)}
- >{g}</button>
- {/each}
- <button
- class="tb-btn tb-magic"
- title={`Auto-fit for a tweet — re-pack panels toward ${guide ?? '16:9'} and reset panel sizes`}
- disabled={!proof.panels.length}
- onclick={applyMagic}
- >
- <Icon name="wand" size={18} />
- </button>
- </div>
-
- <!-- canvas -->
- <div class="canvas-wrap" class:drawing={tool !== 'select'}>
- <div class="konva" bind:this={containerEl}></div>
- {#if textEdit}
- <input
- class="text-edit"
- style:left={`${textEdit.left}px`}
- style:top={`${textEdit.top}px`}
- style:font-size={`${textEdit.size}px`}
- style:color={textEdit.color}
- bind:value={textEdit.value}
- use:focusSelect
- onblur={() => commitTextEdit(true)}
- onkeydown={(e) => {
- e.stopPropagation();
- if (e.key === 'Enter') commitTextEdit(true);
- else if (e.key === 'Escape') commitTextEdit(false);
- }}
- />
- {/if}
- {#if !proofHasContent}
- <div class="empty overlay-empty">
- <div class="empty-icon"><Icon name="proof" size={42} /></div>
- {#if proofStarted}
- <h3>No panels yet</h3>
- <p>Add panels when you are ready.</p>
- <button class="btn" onclick={openPicker}>
- <Icon name="plus" size={15} /> Add panel
- </button>
- {:else}
- <h3>Compose a proof</h3>
- <p>Create a proof to choose its template and starting panels.</p>
- <button class="btn" onclick={openNewProofDialog}>
- <Icon name="plus" size={15} /> New proof
- </button>
- {/if}
- </div>
- {/if}
- </div>
+ <ProofToolbar
+ {canUndo}
+ {canRedo}
+ {undo}
+ {redo}
+ drawTools={DRAW_TOOLS}
+ bind:tool
+ palette={proof.palette}
+ {activeColor}
+ {selectedShape}
+ {strokeW}
+ {setColor}
+ {setStroke}
+ {fit}
+ layout={proof.layout}
+ {setLayoutMode}
+ bind:guide
+ tweetGuides={TWEET_GUIDES}
+ panelCount={proof.panels.length}
+ {applyMagic}
+ />
+
+ <ProofCanvas
+ bind:containerEl
+ {tool}
+ {textEdit}
+ {focusSelect}
+ {commitTextEdit}
+ {proofHasContent}
+ {proofStarted}
+ {openPicker}
+ {openNewProofDialog}
+ />
<!-- right: proof settings, panels & annotations -->
{#if proofStarted}
@@ -2268,7 +2124,7 @@
<button
class="tpl-settings-link"
type="button"
- title="Open Settings → Templates to create, edit or delete house styles"
+ title="Manage proof styles in Settings"
onclick={openTemplateSettings}
>
Settings templates
@@ -2309,7 +2165,7 @@
<Icon name="crosshair" size={13} />
<span>Coordinates</span>
{#if !displayedCoords}
- <span class="meta-warn" title="No satellite panel yet — add one or type the coordinates">
+ <span class="meta-warn" title="Add a satellite panel or type the coordinates">
<Icon name="alert" size={13} />
</span>
{/if}
@@ -2351,191 +2207,33 @@
/>
</div>
- <div class="side-title-row" style="margin-top: 14px">
- <button class="side-title collapsible" onclick={() => (collapsed.panels = !collapsed.panels)}>
- <span><Icon name={collapsed.panels ? 'chevronRight' : 'chevronDown'} size={13} /> Panels <span class="count">{proof.panels.length}</span></span>
- </button>
- <button
- class="btn btn-ghost btn-sm side-add"
- title="Add a panel"
- onclick={openPicker}
- >
- <Icon name="plus" size={13} />
- </button>
- </div>
- {#if !collapsed.panels}
- {#if gonePanels.length}
- <!-- A panel's media was deleted from the case. The proof keeps it: the
- pixels are already composed into the export (ONTOLOGY §3). Only
- reopening this proof later would come up empty. -->
- <div class="gone-note">
- <Icon name="alert" size={12} />
- <span>
- {gonePanels.length} panel{gonePanels.length > 1 ? 's' : ''} whose media was deleted.
- The proof still exports; reopening it later will show them blank.
- </span>
- </div>
- {/if}
- {#each proof.panels as panel, i (panel.id)}
- <div class="panel-row card" class:selected={selectedPanelId === panel.id} class:gone={gonePanels.includes(panel)}>
- <button
- class="panel-thumb"
- title="Select this panel on the canvas"
- onclick={() => (selectedPanelId = selectedPanelId === panel.id ? null : panel.id)}
- >
- <img src={`/files/${caseState.current?.id}/${panel.src}`} alt="" />
- {#if proof.layout === 'free'}
- <span class="row-badge" title="Stacking order — Z1 is the foreground">Z{i + 1}</span>
- {:else}
- <span class="row-badge" title="Row (top→bottom)">R{(panel.row ?? 0) + 1}</span>
- {/if}
- </button>
- <input
- class="input cap-input"
- placeholder="Caption…"
- bind:value={panel.caption}
- onchange={() => (dirty = true)}
- />
- <!-- one compact row: z-order (free only) · size · delete — moving a
- grid panel happens on the canvas (select it, use the arrows) -->
- <div class="panel-actions">
- {#if proof.layout === 'free'}
- <button class="btn btn-ghost btn-sm" disabled={i === 0} title="Bring forward (toward Z1)" onclick={() => movePanelZ(i, -1)}>
- <Icon name="chevronUp" size={13} />
- </button>
- <button class="btn btn-ghost btn-sm" disabled={i === proof.panels.length - 1} title="Send backward" onclick={() => movePanelZ(i, 1)}>
- <Icon name="chevronDown" size={13} />
- </button>
- {/if}
- <div class="panel-scale" title="Panel size — elements scale with it">
- <button
- class="btn btn-ghost btn-sm"
- disabled={(panel.scale ?? 1) <= SCALE_MIN}
- title="Shrink panel"
- onclick={() => scalePanel(i, -SCALE_STEP)}
- >−</button>
- <span class="scale-val">{Math.round((panel.scale ?? 1) * 100)}%</span>
- <button
- class="btn btn-ghost btn-sm"
- disabled={(panel.scale ?? 1) >= SCALE_MAX}
- title="Enlarge panel"
- onclick={() => scalePanel(i, SCALE_STEP)}
- >+</button>
- </div>
- <button class="btn btn-ghost btn-sm" style="margin-left:auto" title="Remove panel" onclick={() => removePanel(i)}>
- <Icon name="trash" size={13} />
- </button>
- </div>
- </div>
- {/each}
- {/if}
-
- <!-- Annotations: one legend note per color (feature), not per element -->
- <button class="side-title collapsible" style="margin-top: 14px" onclick={() => (collapsed.annotations = !collapsed.annotations)}>
- <span><Icon name={collapsed.annotations ? 'chevronRight' : 'chevronDown'} size={13} /> Annotations <span class="count">{featureList.length}</span></span>
- </button>
- {#if !collapsed.annotations}
- {#if !featureList.length}
- <div class="none">Draw on a panel. Same color = same feature.</div>
- {/if}
- {#each featureList as c, i (c)}
- <div class="anno-row" class:active={activeColor === c}>
- <div class="reorder">
- <button class="btn btn-ghost reorder-btn" disabled={i === 0} title="Move up" onclick={() => moveLegendColor(i, -1)}>
- <Icon name="chevronUp" size={11} />
- </button>
- <button class="btn btn-ghost reorder-btn" disabled={i === featureList.length - 1} title="Move down" onclick={() => moveLegendColor(i, 1)}>
- <Icon name="chevronDown" size={11} />
- </button>
- </div>
- <button
- class="chip-num"
- style:background={c}
- title="Select this color"
- onclick={() => setColor(c)}
- >{i + 1}</button>
- <input
- class="input comment-input"
- placeholder={`Feature ${i + 1} legend…`}
- bind:value={proof.notes[c]}
- onchange={() => (dirty = true)}
- />
- </div>
- {/each}
- {/if}
-
- <!-- Elements: every drawn shape, for quick select / delete -->
- <button class="side-title collapsible" style="margin-top: 14px" onclick={() => (collapsed.elements = !collapsed.elements)}>
- <span><Icon name={collapsed.elements ? 'chevronRight' : 'chevronDown'} size={13} /> Elements <span class="count">{proof.shapes.length}</span></span>
- </button>
- {#if !collapsed.elements}
- {#each proof.shapes as s, i (s.id)}
- <div
- class="shape-row"
- class:selected={selectedId === s.id}
- onclick={() => (selectedId = s.id)}
- role="button"
- tabindex="0"
- onkeydown={(e) => e.key === 'Enter' && (selectedId = s.id)}
- >
- <div class="reorder">
- <button class="btn btn-ghost reorder-btn" disabled={!canMoveShapeUp(i)} title="Move up (z-order within its panel)" onclick={(e) => { e.stopPropagation(); moveShape(i, -1); }}>
- <Icon name="chevronUp" size={11} />
- </button>
- <button class="btn btn-ghost reorder-btn" disabled={!canMoveShapeDown(i)} title="Move down (z-order within its panel)" onclick={(e) => { e.stopPropagation(); moveShape(i, 1); }}>
- <Icon name="chevronDown" size={11} />
- </button>
- </div>
- <span class="chip" style:background={s.color}></span>
- <Icon name={KIND_ICON[s.kind]} size={13} />
- {#if s.kind === 'text'}
- <input
- class="input comment-input"
- placeholder="Text…"
- bind:value={s.text}
- onchange={() => (dirty = true)}
- onclick={(e) => e.stopPropagation()}
- />
- <button
- class="btn btn-ghost btn-sm"
- class:active={s.frame}
- title="Frame (border in the text's color)"
- onclick={(e) => { e.stopPropagation(); s.frame = !s.frame; dirty = true; }}
- >
- <Icon name="square" size={13} />
- </button>
- <label
- class="color-btn color-pick bg-pick"
- class:active={!!s.bg}
- style:background={s.bg || 'transparent'}
- title="Background color"
- onclick={(e) => e.stopPropagation()}
- >
- <Icon name="plus" size={11} />
- <input
- type="color"
- value={s.bg || '#000000'}
- oninput={(e) => { s.bg = e.target.value; dirty = true; }}
- aria-label="text background color"
- />
- </label>
- {#if s.bg}
- <button class="btn btn-ghost btn-sm" title="Remove background" onclick={(e) => { e.stopPropagation(); s.bg = null; dirty = true; }}>
- <Icon name="x" size={11} />
- </button>
- {/if}
- {:else}
- <span class="el-label">{KIND_LABEL[s.kind]} <span class="el-id">#{i + 1}</span></span>
- {/if}
- <button class="btn btn-ghost btn-sm" title="Duplicate (Ctrl+D)" onclick={(e) => { e.stopPropagation(); duplicateShape(s.id); }}>
- <Icon name="copy" size={13} />
- </button>
- <button class="btn btn-ghost btn-sm" title="Delete" onclick={(e) => { e.stopPropagation(); deleteShape(s.id); }}>
- <Icon name="trash" size={13} />
- </button>
- </div>
- {/each}
- {/if}
+ <ProofLayersPanel
+ {proof}
+ {collapsed}
+ {gonePanels}
+ bind:selectedPanelId
+ bind:selectedId
+ {activeColor}
+ caseId={caseState.current?.id}
+ scaleMin={SCALE_MIN}
+ scaleMax={SCALE_MAX}
+ scaleStep={SCALE_STEP}
+ {openPicker}
+ {movePanelZ}
+ {scalePanel}
+ {removePanel}
+ {featureList}
+ {moveLegendColor}
+ {setColor}
+ {canMoveShapeUp}
+ {canMoveShapeDown}
+ {moveShape}
+ kindIcon={KIND_ICON}
+ kindLabel={KIND_LABEL}
+ {duplicateShape}
+ {deleteShape}
+ markDirty={() => (dirty = true)}
+ />
<!-- Advanced: text sizes, editable footer, signature (the trickier knobs) -->
<button class="adv-toggle" onclick={() => (advancedOpen = !advancedOpen)} style="margin-top: 14px">
@@ -2694,112 +2392,22 @@
</div>
{#if newProofOpen}
- <Modal
- title="Create proof"
- onclose={() => { if (!creatingProof) newProofOpen = false; }}
- width="780px"
- >
- <form class="new-proof-form" onsubmit={(e) => { e.preventDefault(); requestNewProofCreation(); }}>
- <label class="new-proof-field">
- <span>Name</span>
- <input
- class="input"
- bind:value={newProofName}
- maxlength="200"
- placeholder="Proof name"
- />
- </label>
-
- <label class="new-proof-field">
- <span>Template</span>
- <select class="input" bind:value={newProofTemplateId}>
- <option value="">No template</option>
- {#each templatesState.proof as t (t.id)}
- <option value={t.id}>{t.name}</option>
- {/each}
- </select>
- <small>Sets the look without choosing content.</small>
- </label>
-
- <fieldset class="new-proof-panels">
- <legend>
- <span>Panels</span>
- <span class="selected-count">
- {newProofPanelPaths.length} panel{newProofPanelPaths.length === 1 ? '' : 's'} selected
- </span>
- </legend>
-
- <div class="panel-picker-bar">
- <div class="panel-search">
- <Icon name="search" size={13} />
- <input placeholder="Search panels…" bind:value={newProofQuery} />
- {#if newProofQuery}
- <button type="button" onclick={() => (newProofQuery = '')} aria-label="Clear search">
- <Icon name="x" size={12} />
- </button>
- {/if}
- </div>
- <div class="panel-categories" aria-label="Panel categories">
- <button
- type="button"
- class:active={newProofCategory === 'all'}
- onclick={() => (newProofCategory = 'all')}
- >All <span>{pickerItems.length}</span></button>
- <button
- type="button"
- class:active={newProofCategory === 'satellite'}
- onclick={() => (newProofCategory = 'satellite')}
- >Satellite captures <span>{pickerItems.filter((item) => item.kind === 'satellite').length}</span></button>
- <button
- type="button"
- class:active={newProofCategory === 'media'}
- onclick={() => (newProofCategory = 'media')}
- >Other images <span>{pickerItems.filter((item) => item.kind === 'media').length}</span></button>
- </div>
- </div>
-
- {#if newProofLoading}
- <div class="picker-empty">Loading case images…</div>
- {:else if !pickerItems.length}
- <div class="picker-empty">No case images yet, but you can add panels later.</div>
- {:else if !filteredNewProofItems.length}
- <div class="picker-empty">No panels match this search.</div>
- {:else}
- <div class="pick-grid new-proof-grid">
- {#each filteredNewProofItems as item (item.src)}
- <button
- type="button"
- class="pick card selectable-pick"
- class:selected={newProofPanelPaths.includes(item.src)}
- aria-pressed={newProofPanelPaths.includes(item.src)}
- onclick={() => toggleNewProofPanel(item.src)}
- >
- <span class="pick-image">
- <img src={`/files/${caseState.current?.id}/${item.thumb}`} alt="" loading="lazy" />
- {#if newProofPanelPaths.includes(item.src)}
- <span class="pick-selected"><Icon name="check" size={13} /></span>
- {/if}
- </span>
- <span class="pick-label" title={item.label}>
- <Icon name={item.kind === 'satellite' ? 'satellite' : 'image'} size={12} />
- {item.label}
- </span>
- </button>
- {/each}
- </div>
- {/if}
- </fieldset>
-
- <div class="new-proof-actions">
- <button type="button" class="btn" disabled={creatingProof} onclick={() => (newProofOpen = false)}>
- Cancel
- </button>
- <button type="submit" class="btn btn-primary" disabled={!newProofName.trim() || creatingProof}>
- <Icon name="plus" size={15} /> {creatingProof ? 'Creating…' : 'Create proof'}
- </button>
- </div>
- </form>
- </Modal>
+ <NewProofDialog
+ bind:name={newProofName}
+ bind:templateId={newProofTemplateId}
+ bind:panelPaths={newProofPanelPaths}
+ bind:query={newProofQuery}
+ bind:category={newProofCategory}
+ templates={templatesState.proof}
+ items={pickerItems}
+ filteredItems={filteredNewProofItems}
+ loading={newProofLoading}
+ creating={creatingProof}
+ caseId={caseState.current?.id}
+ togglePanel={toggleNewProofPanel}
+ requestCreation={requestNewProofCreation}
+ close={() => (newProofOpen = false)}
+ />
{/if}
{#if replaceWithNewConfirm}
@@ -2919,125 +2527,6 @@
width: min(320px, 26vw);
font-weight: 600;
}
- .new-proof-form {
- display: flex;
- flex-direction: column;
- gap: 15px;
- }
- .new-proof-field {
- display: grid;
- grid-template-columns: 110px minmax(0, 1fr);
- align-items: center;
- gap: 5px 12px;
- font-size: var(--fs-xs);
- font-weight: 600;
- }
- .new-proof-field small {
- grid-column: 2;
- color: var(--text-3);
- font-weight: 400;
- }
- .new-proof-panels {
- min-width: 0;
- padding: 0;
- border: 0;
- }
- .new-proof-panels legend {
- width: 100%;
- display: flex;
- align-items: center;
- justify-content: space-between;
- margin-bottom: 7px;
- font-size: var(--fs-xs);
- font-weight: 700;
- color: var(--text-2);
- }
- .selected-count { color: var(--text-3); font-weight: 500; }
- .panel-picker-bar {
- display: flex;
- align-items: center;
- flex-wrap: wrap;
- gap: 7px;
- margin-bottom: 10px;
- min-width: 0;
- }
- .panel-search {
- min-width: 170px;
- flex: 1;
- display: flex;
- align-items: center;
- gap: 6px;
- padding: 5px 8px;
- border: 1px solid var(--border);
- border-radius: var(--r-sm);
- background: var(--bg-2);
- color: var(--text-3);
- }
- .panel-search:focus-within { border-color: var(--accent); }
- .panel-search input {
- width: 100%;
- min-width: 0;
- border: 0;
- outline: 0;
- background: transparent;
- color: var(--text-1);
- font: inherit;
- }
- .panel-search button { display: flex; color: var(--text-3); }
- .panel-categories { display: flex; gap: 5px; overflow-x: auto; max-width: 100%; }
- .panel-categories button {
- display: flex;
- align-items: center;
- gap: 5px;
- padding: 5px 8px;
- border: 1px solid var(--border);
- border-radius: var(--r-sm);
- background: var(--bg-2);
- color: var(--text-2);
- font-size: var(--fs-xs);
- white-space: nowrap;
- }
- .panel-categories button:hover { border-color: var(--border-strong); color: var(--text-1); }
- .panel-categories button.active { border-color: var(--accent); color: var(--text-1); }
- .panel-categories span { color: var(--text-3); }
- .new-proof-grid {
- max-height: min(42vh, 390px);
- overflow-y: auto;
- padding: 1px;
- }
- .selectable-pick { position: relative; }
- .selectable-pick.selected { border-color: var(--accent); }
- .pick-image { position: relative; display: block; }
- .pick-selected {
- position: absolute;
- top: 6px;
- right: 6px;
- width: 22px;
- height: 22px;
- display: flex;
- align-items: center;
- justify-content: center;
- border-radius: 50%;
- background: var(--accent);
- color: var(--accent-text);
- }
- .picker-empty {
- min-height: 120px;
- display: flex;
- align-items: center;
- justify-content: center;
- padding: 20px;
- border: 1px dashed var(--border);
- border-radius: var(--r-md);
- color: var(--text-3);
- font-size: var(--fs-sm);
- }
- .new-proof-actions {
- display: flex;
- justify-content: flex-end;
- gap: 8px;
- padding-top: 2px;
- }
.tpl-none {
margin: 0 0 6px;
font-size: var(--fs-xs);
@@ -3049,104 +2538,6 @@
display: flex;
min-height: 0;
}
- .toolbar {
- width: 52px;
- flex-shrink: 0;
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 6px;
- padding: 12px 0;
- border-right: 1px solid var(--border);
- background: var(--bg-1);
- }
- .tb-btn {
- width: 38px;
- height: 38px;
- display: flex;
- align-items: center;
- justify-content: center;
- border-radius: var(--r-sm);
- color: var(--text-3);
- }
- .tb-btn:hover { color: var(--text-1); background: var(--bg-2); }
- .tb-btn.active { color: var(--text-1); background: var(--bg-3); }
- .tb-guide { font-size: 11px; font-weight: 700; }
- .tb-magic:not(:disabled) { color: var(--accent); }
- .tb-magic:not(:disabled):hover { background: var(--accent-soft); }
- .tb-magic:disabled { opacity: 0.4; cursor: default; }
- .tb-sep {
- width: 26px;
- height: 1px;
- background: var(--border);
- margin: 4px 0;
- }
- .color-btn {
- width: 22px;
- height: 22px;
- border-radius: 50%;
- border: 2px solid transparent;
- transition: border-color 0.12s var(--ease);
- flex-shrink: 0;
- }
- .color-btn:hover {
- border-color: var(--text-3);
- }
- .color-btn.active {
- border-color: var(--text-1);
- box-shadow: 0 0 0 2px var(--bg-1), 0 0 0 3.5px var(--text-3);
- }
- .color-pick {
- display: flex;
- align-items: center;
- justify-content: center;
- color: var(--accent-text);
- cursor: pointer;
- position: relative;
- overflow: hidden;
- }
- .color-pick input {
- position: absolute;
- inset: 0;
- opacity: 0;
- cursor: pointer;
- }
- .stroke-slider {
- width: 80px;
- transform: rotate(-90deg);
- margin: 34px 0;
- accent-color: var(--accent);
- }
- .canvas-wrap {
- position: relative;
- flex: 1;
- min-width: 0;
- background:
- radial-gradient(circle at 1px 1px, rgba(148, 163, 196, 0.07) 1px, transparent 0) 0 0 / 22px 22px,
- var(--bg-0);
- }
- .canvas-wrap.drawing { cursor: crosshair; }
- .konva { position: absolute; inset: 0; }
- .tb-btn:disabled { opacity: 0.35; cursor: default; }
- .tb-btn:disabled:hover { color: var(--text-3); background: none; }
- .text-edit {
- position: absolute;
- transform: translateY(-2px);
- min-width: 60px;
- padding: 0 2px;
- font-family: system-ui, sans-serif;
- font-weight: 700;
- background: rgba(14, 14, 14, 0.85);
- border: 1px dashed var(--accent);
- border-radius: 2px;
- outline: none;
- }
- .overlay-empty {
- position: absolute;
- inset: 0;
- pointer-events: none;
- }
- .overlay-empty .btn { pointer-events: auto; }
.side {
width: 300px;
flex-shrink: 0;
@@ -3160,35 +2551,6 @@
overflow-y: auto;
padding: 12px;
}
- .side-title {
- font-size: var(--fs-xs);
- font-weight: 700;
- text-transform: uppercase;
- letter-spacing: 0.07em;
- color: var(--text-2);
- margin-bottom: 8px;
- display: flex;
- justify-content: space-between;
- }
- .side-title.collapsible {
- width: 100%;
- background: none;
- border: none;
- padding: 0;
- cursor: pointer;
- text-align: left;
- font: inherit;
- color: inherit;
- }
- .side-title.collapsible span {
- display: flex;
- align-items: center;
- gap: 4px;
- }
- .side-title-row { display: flex; align-items: center; gap: 4px; }
- .side-title-row .side-title { margin-bottom: 0; }
- .side-add { margin-left: auto; color: var(--text-3); }
- .count { color: var(--text-3); }
.meta-field { margin-bottom: 10px; }
.meta-head {
display: flex;
@@ -3234,58 +2596,6 @@
.tpl-inline-link:hover { color: var(--text-2); }
.meta-input { width: 100%; font-size: var(--fs-xs); padding: 5px 8px; }
.meta-input.warn { border-color: color-mix(in srgb, var(--warn, #e8a33d) 55%, transparent); }
- .gone-note {
- display: flex;
- align-items: flex-start;
- gap: 6px;
- margin-bottom: 8px;
- padding: 7px 9px;
- border-radius: var(--r-sm);
- font-size: var(--fs-xs);
- line-height: 1.4;
- color: color-mix(in srgb, var(--danger, #e5484d) 80%, var(--text-2));
- background: color-mix(in srgb, var(--danger, #e5484d) 10%, transparent);
- }
- .gone-note :global(svg) { flex-shrink: 0; margin-top: 2px; }
- .panel-row.gone {
- border-color: color-mix(in srgb, var(--danger, #e5484d) 40%, transparent);
- }
- .panel-row {
- padding: 8px;
- margin-bottom: 8px;
- display: flex;
- flex-direction: column;
- gap: 6px;
- }
- .panel-thumb {
- position: relative;
- display: block;
- width: 100%;
- padding: 0;
- border: none;
- background: none;
- cursor: pointer;
- }
- .panel-row.selected { border-color: var(--accent); }
- .panel-row img {
- width: 100%;
- max-height: 90px;
- object-fit: cover;
- border-radius: var(--r-sm);
- background: var(--bg-2);
- display: block;
- }
- .row-badge {
- position: absolute;
- top: 5px;
- left: 5px;
- padding: 1px 6px;
- border-radius: var(--r-sm);
- font-size: 10px;
- font-weight: 700;
- color: var(--text-1);
- background: rgba(14, 14, 14, 0.72);
- }
.adv-toggle {
display: flex;
align-items: center;
@@ -3354,110 +2664,6 @@
color: var(--accent);
border-color: var(--accent);
}
- .cap-input { font-size: var(--fs-xs); padding: 5px 8px; }
- .panel-actions { display: flex; align-items: center; gap: 2px; }
- .panel-scale {
- display: flex;
- align-items: center;
- gap: 4px;
- margin: 0 auto; /* centres the size control between z-order and delete */
- }
- .scale-val {
- min-width: 42px;
- text-align: center;
- font-size: var(--fs-xs);
- font-weight: 600;
- color: var(--text-2);
- font-variant-numeric: tabular-nums;
- }
- .none {
- font-size: var(--fs-xs);
- color: var(--text-3);
- padding: 2px 2px 8px;
- }
- .anno-row {
- display: flex;
- align-items: center;
- gap: 8px;
- padding: 3px 4px;
- border-radius: var(--r-sm);
- margin-bottom: 4px;
- border: 1px solid transparent;
- }
- .anno-row.active { border-color: var(--accent); background: var(--accent-soft); }
- .reorder {
- display: flex;
- flex-direction: column;
- gap: 1px;
- flex-shrink: 0;
- }
- .reorder-btn {
- padding: 0 2px;
- line-height: 1;
- color: var(--text-3);
- }
- .reorder-btn:disabled { opacity: 0.25; cursor: default; }
- .bg-pick {
- width: 20px;
- height: 20px;
- flex-shrink: 0;
- border: 1px dashed var(--border);
- }
- .bg-pick.active { border-style: solid; }
- .bg-pick:not(.active) { color: var(--text-3); }
- .chip-num {
- width: 20px;
- height: 20px;
- border-radius: 50%;
- flex-shrink: 0;
- font-size: 11px;
- font-weight: 700;
- color: var(--accent-text);
- display: flex;
- align-items: center;
- justify-content: center;
- border: 2px solid transparent;
- cursor: pointer;
- }
- .chip-num:hover { border-color: var(--text-1); }
- .el-label {
- flex: 1;
- font-size: var(--fs-xs);
- color: var(--text-2);
- min-width: 0;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
- .el-id { color: var(--text-3); }
- .shape-row {
- display: flex;
- align-items: center;
- gap: 7px;
- padding: 5px 6px;
- border-radius: var(--r-sm);
- margin-bottom: 3px;
- border: 1px solid transparent;
- color: var(--text-3);
- cursor: pointer;
- }
- .shape-row:hover { background: var(--bg-2); }
- .shape-row.selected { border-color: var(--accent); background: var(--accent-soft); }
- .chip {
- width: 12px;
- height: 12px;
- border-radius: 50%;
- flex-shrink: 0;
- }
- .comment-input {
- flex: 1;
- font-size: var(--fs-xs);
- padding: 4px 8px;
- background: transparent;
- border-color: transparent;
- min-width: 0;
- }
- .comment-input:hover, .comment-input:focus { background: var(--bg-2); border-color: var(--border); }
.pick-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
diff --git a/frontend/src/tools/ProofComposer.test.js b/frontend/src/tools/ProofComposer.test.js
index f178512..075f283 100644
--- a/frontend/src/tools/ProofComposer.test.js
+++ b/frontend/src/tools/ProofComposer.test.js
@@ -3,10 +3,11 @@ import { render } from 'svelte/server';
vi.mock('konva', () => ({ default: {} }));
-import ProofComposer, {
+import ProofComposer from './ProofComposer.svelte';
+import {
bindPanelPointerLifecycle,
createCanvasRenderGate,
-} from './ProofComposer.svelte';
+} from './proof/canvasLifecycle.js';
describe('Proof Composer empty state', () => {
it('hides proof-specific chrome until a proof is started', () => {
diff --git a/frontend/src/tools/RefViewer.svelte b/frontend/src/tools/RefViewer.svelte
index 75a6299..b3bbdad 100644
--- a/frontend/src/tools/RefViewer.svelte
+++ b/frontend/src/tools/RefViewer.svelte
@@ -19,7 +19,7 @@
let el; // the window root
let headEl;
- let bodyEl;
+ let bodyEl = $state();
// the map-wrap we're positioned in — the box drags/resizes are clamped to
const bounds = () => {
@@ -145,6 +145,9 @@
style:height={viewer.collapsed ? 'auto' : `${viewer.h}px`}
style:z-index={zBase + viewer.z}
onpointerdown={focus}
+ role="dialog"
+ aria-label={viewer.title || 'Reference'}
+ tabindex="0"
>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div bind:this={headEl} class="rv-head" onpointerdown={startWindowDrag} title="Drag to move">
diff --git a/frontend/src/tools/ReverseSearch.svelte b/frontend/src/tools/ReverseSearch.svelte
index d271a98..6552145 100644
--- a/frontend/src/tools/ReverseSearch.svelte
+++ b/frontend/src/tools/ReverseSearch.svelte
@@ -112,7 +112,7 @@
async function copySelection() {
try {
await navigator.clipboard.write([new ClipboardItem({ 'image/png': pngBlob() })]);
- toast(`Copied the ${frameLabel} — paste it (Ctrl+V) in the tab`, 'ok', 4500);
+ toast(`Copied the ${frameLabel}. Paste it in the tab with Ctrl+V`, 'ok', 4500);
} catch (e) {
toast(e.message || 'Could not copy the image', 'warn');
}
@@ -127,7 +127,7 @@
a.download = `reverse-${base}.png`;
a.click();
URL.revokeObjectURL(a.href);
- toast(`Saved the ${frameLabel} — drag it into the tab`, 'ok', 4500);
+ toast(`Saved the ${frameLabel}. Drag it into the tab`, 'ok', 4500);
} catch (e) {
toast(e.message || 'Could not save the image', 'warn');
}
diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelte
index 568f229..e74d5a9 100644
--- a/frontend/src/tools/Satellite.svelte
+++ b/frontend/src/tools/Satellite.svelte
@@ -3,6 +3,7 @@
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import { api } from '../lib/api.js';
+ import { fetchAllEntities } from '../lib/catalog.js';
import {
caseState, uiState, ensureCase, reloadCase, toast, prefs, fmtCoords, prefsReady,
} from '../lib/state.svelte.js';
@@ -10,7 +11,7 @@
import * as measure from '../lib/measure.js';
import * as gridSearch from '../lib/gridSearch.js';
import { dragBearing, pivotPanOffset } from '../lib/satRotate.js';
- import { SIZE_MIN, SIZE_MAX, clampSize, scaledCapture } from '../lib/captureSize.js';
+ import { clampSize, scaledCapture } from '../lib/captureSize.js';
import { isRegistered, sourceRect, frameFitsView } from '../lib/screenCrop.js';
import { extensionVersion, captureTab, onActivated } from '../lib/extBridge.js';
import {
@@ -33,6 +34,9 @@
monthBounds,
monthGrid,
addMonths,
+ sentinelPlaceKey,
+ coverageRequestPath,
+ dateAfterCoverage,
} from '../lib/sentinel.js';
import { createViewer, nextZ, restack } from '../lib/refViewers.js';
import { loadGoogleMaps, createSatelliteMutant } from '../lib/gmaps.js';
@@ -40,6 +44,10 @@
import Modal from '../components/Modal.svelte';
import ConfirmDialog from '../components/ConfirmDialog.svelte';
import RefViewer from './RefViewer.svelte';
+ import MapToolCluster from './satellite/MapToolCluster.svelte';
+ import GridSearchPanel from './satellite/GridSearchPanel.svelte';
+ import SentinelPicker from './satellite/SentinelPicker.svelte';
+ import CaptureOptions from './satellite/CaptureOptions.svelte';
let mapEl;
let toolEl; // tool root — target of the real (browser) fullscreen (item 5)
@@ -68,6 +76,8 @@
let captures = $state([]);
let capturesFor = $state(null);
let capturesCollapsed = $state(false);
+ let capturesSubCollapsed = $state(false);
+ let focusedCapturePath = $state(null);
let mapReady = $state(false);
// OSM labels overlay: a transparent labels-only layer laid over the imagery so
@@ -98,7 +108,7 @@
// of several passes, which is not a thing you can point at and date.)
let s2Date = $state(''); // '' = the layer's default, i.e. the most recent pass
let s2MenuOpen = $state(false);
- let s2MenuEl; // bound to the popover wrapper — outside-click detection
+ let s2MenuEl = $state(); // bound to the popover wrapper — outside-click detection
let s2Layers = $state([]); // [{id,label,hint}] — catalogue until the instance is asked
let s2LayersSource = $state('');
let s2LayersAsked = false; // the instance is asked once per session, on first open
@@ -110,6 +120,8 @@
let s2PassesFor = $state(''); // the month+place s2Passes describes
let s2PassesBusy = $state(false);
let s2PassesNote = $state('');
+ let s2VerifyingDate = $state('');
+ let s2CoverageRev = $state(0);
// The newest pass over this point — what "most recent" is actually showing.
// The layer's default window renders the latest acquisition, so naming it is
// the difference between a dated image and an undated one.
@@ -361,7 +373,7 @@
document.addEventListener('fullscreenchange', onFullscreenChange);
// the user clicked the extension after a refused capture — close the loop
const offActivated = onActivated(() =>
- toast('Extension ready — press Capture again', 'ok', 5000)
+ toast('Extension ready. Press Capture again', 'ok', 5000)
);
mapReady = true;
return () => {
@@ -471,29 +483,47 @@
// month already seen is free; the key is the map centre rounded to ~100 m,
// because a nudge of the map is not a new question.
const s2PassCache = new Map();
- const s2PlaceKey = () => `${center.lat.toFixed(3)},${center.lon.toFixed(3)}`;
+ const s2PassPending = new Map();
+ const s2CoverageCache = new Map();
+ const s2PlaceKey = () => sentinelPlaceKey(center.lat, center.lon);
+ const s2CoverageKey = (day, place = s2PlaceKey(), layer = s2Layer) =>
+ `${layer}@${day}@${place}`;
+ let s2PassRequestId = 0;
+ let s2PickRequestId = 0;
/**
* One month's passes over one place: `{ 'YYYY-MM-DD': {cloud, granules} }`,
* or null when the lookup failed. Cached — paging back to a month already
* seen must not spend a second request.
*/
- async function fetchS2Month(month, place, force = false) {
+ async function fetchS2Month(
+ month, place, force = false, lat = center.lat, lon = center.lon
+ ) {
const key = `${month}@${place}`;
if (!force && s2PassCache.has(key)) return s2PassCache.get(key);
+ if (!force && s2PassPending.has(key)) return s2PassPending.get(key);
+ if (force) s2PassCache.delete(key);
const { from, to } = monthBounds(month);
- try {
- const r = await api.get(
- `/api/satellite/sentinel/dates?lat=${center.lat}&lon=${center.lon}` +
+ const request = (async () => {
+ try {
+ const r = await api.get(
+ `/api/satellite/sentinel/dates?lat=${lat}&lon=${lon}` +
`&start=${from}&end=${to}`
- );
- const byDay = {};
- for (const d of r.dates) byDay[d.date] = { cloud: d.cloud, granules: d.granules };
- s2PassCache.set(key, byDay);
- refreshUsage(); // the lookup is billed: keep the pill honest
- return byDay;
- } catch {
- return null;
+ );
+ const byDay = {};
+ for (const d of r.dates) byDay[d.date] = { cloud: d.cloud, granules: d.granules };
+ s2PassCache.set(key, byDay);
+ refreshUsage(); // the lookup is billed: keep the pill honest
+ return byDay;
+ } catch {
+ return null;
+ }
+ })();
+ s2PassPending.set(key, request);
+ try {
+ return await request;
+ } finally {
+ if (s2PassPending.get(key) === request) s2PassPending.delete(key);
}
}
@@ -505,12 +535,15 @@
* processing units), only while the picker is open.
*/
async function loadS2Passes(force = false) {
- if (s2PassesBusy) return;
+ const requestId = ++s2PassRequestId;
+ const lat = center.lat;
+ const lon = center.lon;
const place = s2PlaceKey();
const key = `${s2Month}@${place}`;
s2PassesBusy = true;
s2PassesNote = '';
- const days = await fetchS2Month(s2Month, place, force);
+ const days = await fetchS2Month(s2Month, place, force, lat, lon);
+ if (requestId !== s2PassRequestId) return;
if (days) {
s2Passes = days;
s2PassesFor = key;
@@ -521,7 +554,7 @@
// what exists.
s2Passes = {};
s2PassesFor = '';
- s2PassesNote = 'Could not read this month’s passes — the days below are not a coverage answer.';
+ s2PassesNote = 'Could not read this month’s passes. The days below do not confirm coverage.';
}
s2PassesBusy = false;
}
@@ -558,9 +591,60 @@
s2LatestFor = place;
}
- function pickS2Date(day) {
- if (!s2Passes[day]) return; // no pass, nothing to render — the cell is dead
- s2Date = day === s2Date ? '' : day; // clicking the pinned day unpins it
+ function clearS2Date() {
+ s2PickRequestId += 1;
+ s2VerifyingDate = '';
+ s2Date = '';
+ }
+
+ function s2DateStatus(day) {
+ s2CoverageRev;
+ return s2CoverageCache.get(s2CoverageKey(day));
+ }
+
+ async function pickS2Date(day) {
+ if (day === s2Date) {
+ clearS2Date();
+ return;
+ }
+ if (!s2Passes[day] || s2PassesStale || s2PassesBusy || s2VerifyingDate) return;
+
+ const lat = center.lat;
+ const lon = center.lon;
+ const place = s2PlaceKey();
+ const layer = s2Layer;
+ const key = s2CoverageKey(day, place, layer);
+ const known = s2CoverageCache.get(key);
+ if (known === true) {
+ s2Date = day;
+ return;
+ }
+ if (known === false) {
+ toast(`No imagery at the crosshair on ${day}.`, 'warn');
+ return;
+ }
+
+ const requestId = ++s2PickRequestId;
+ s2VerifyingDate = day;
+ try {
+ const result = await api.get(coverageRequestPath({ lat, lon, layer, date: day }));
+ s2CoverageCache.set(key, result.available === true);
+ s2CoverageRev += 1;
+ refreshUsage();
+ if (requestId !== s2PickRequestId) return;
+ if (place !== s2PlaceKey() || layer !== s2Layer) {
+ toast('The map moved. Pick the date again.', 'warn');
+ return;
+ }
+ s2Date = dateAfterCoverage(s2Date, day, result.available);
+ if (!result.available) toast(`No imagery at the crosshair on ${day}.`, 'warn');
+ } catch (e) {
+ if (requestId === s2PickRequestId) {
+ toast(`Could not check imagery for ${day}: ${e.message}`, 'danger');
+ }
+ } finally {
+ if (requestId === s2PickRequestId) s2VerifyingDate = '';
+ }
}
// The passes on screen describe the place they were fetched for; once the map
@@ -569,6 +653,18 @@
!!s2PassesFor && s2PassesFor !== `${s2Month}@${s2PlaceKey()}`
);
+ // While the picker is open, a settled pan refreshes its dates. The stale
+ // cells are disabled immediately; the debounce avoids a request per frame.
+ $effect(() => {
+ if (!s2MenuOpen || !isSentinel) return;
+ s2Month;
+ s2PlaceKey();
+ clearTimeout(s2PassTimer);
+ s2PassTimer = setTimeout(() => loadS2Passes(), 600);
+ return () => clearTimeout(s2PassTimer);
+ });
+ let s2PassTimer;
+
// Naming the date of what's on screen is why you'd pick this basemap, so the
// latest pass is resolved as soon as Sentinel-2 is actually being displayed —
// one metadata request, on the user's own action (choosing the basemap), and
@@ -685,7 +781,7 @@
// toolbar stay visible — so degrading into it silently reads as a
// broken fullscreen button rather than a refusal. Name the reason.
toast(
- `Real fullscreen refused (${e.name}: ${e.message}) — filling the window instead`,
+ `Real fullscreen refused (${e.name}: ${e.message}). Filling the window instead`,
'warn',
8000
);
@@ -850,7 +946,7 @@
detail: 'Google rejected the Maps JavaScript key (gm_authFailure)',
});
} catch { /* the toast still tells the user */ }
- toast('Google rejected the Maps JavaScript key — basemap disabled (see Settings)', 'danger', 8000);
+ toast('Google rejected the Maps JavaScript key. Basemap disabled; see Settings', 'danger', 8000);
providers = await api.get('/api/satellite/providers');
},
});
@@ -967,6 +1063,16 @@
api.get(`/api/cases/${id}/satellite`).then((r) => (captures = r));
});
+ $effect(() => {
+ const path = uiState.focusCapture;
+ if (!path || !captures.some((capture) => capture.path === path)) return;
+ uiState.focusCapture = null;
+ capturesCollapsed = false;
+ capturesSubCollapsed = false;
+ focusedCapturePath = path;
+ requestAnimationFrame(() => document.querySelector(`[data-capture-path="${CSS.escape(path)}"]`)?.scrollIntoView({ behavior: 'smooth', block: 'nearest' }));
+ });
+
// the map container resizes when the sidebar toggles or is dragged wider, and
// reappears from display:none when the tool tab is re-selected (tools stay
// mounted) — all need Leaflet to re-measure and redraw tiles for the exposed area
@@ -982,7 +1088,11 @@
$effect(() => {
const target = uiState.gotoCoords;
if (mapReady && target && Number.isFinite(target.lat) && Number.isFinite(target.lon)) {
+ if (target.provider && !providers.length) return;
uiState.gotoCoords = null;
+ if (target.provider && providers.some((provider) => provider.id === target.provider)) {
+ providerId = target.provider;
+ }
const zoom = Number.isFinite(target.zoom) ? target.zoom : Math.max(map.getZoom(), 16);
map.setView([target.lat, target.lon], zoom);
setBearing(Number.isFinite(target.bearing) ? target.bearing : 0);
@@ -1068,7 +1178,7 @@
// resolution settings.
let captureMode = $state('center'); // 'center' | 'select'
let sizeMenuOpen = $state(false); // the mode/size/ratio/resolution popover
- let sizeMenuEl; // bound to the popover's wrapper — used to detect outside clicks
+ let sizeMenuEl = $state(); // bound to the popover's wrapper — used to detect outside clicks
let selectArmed = $state(false); // marquee mode: drag a box on the map to capture
let selRect = $state(null); // live marquee { x0, y0, x1, y1 } in map-container px
@@ -1191,9 +1301,9 @@
await reloadCase();
toast(
result.tiles_missing
- ? `Captured with ${result.tiles_missing} missing tile(s) — no imagery there`
+ ? `Captured with ${result.tiles_missing} missing tile(s). No imagery was available there`
: result.tiles_upscaled
- ? `Captured — ${result.tiles_upscaled} tile(s) upscaled from a lower zoom (recorded in provenance)`
+ ? `Captured. ${result.tiles_upscaled} tile(s) were upscaled from a lower zoom and recorded in provenance`
: 'Satellite crop captured & filed',
result.tiles_missing || result.tiles_upscaled ? 'warn' : 'ok'
);
@@ -1256,7 +1366,7 @@
img.src = dataUrl;
});
if (!isRegistered(img.naturalWidth, img.naturalHeight, window.innerWidth, window.innerHeight)) {
- throw new Error('the captured frame does not match this view — try again');
+ throw new Error('the captured frame does not match this view. Try again');
}
return img;
}
@@ -1273,7 +1383,7 @@
videoHeight: img.naturalHeight,
});
if (!src) {
- throw new Error('the frame runs past the captured area — resize the window or pick a smaller size');
+ throw new Error('the frame runs past the captured area. Resize the window or pick a smaller size');
}
const { sx, sy, sw, sh } = src;
const canvas = document.createElement('canvas');
@@ -1294,7 +1404,7 @@
const mapRect = mapEl.getBoundingClientRect();
if (!frameFitsView(rect, mapRect)) {
toast(
- `The ${Math.round(rect.w)}×${Math.round(rect.h)} frame is bigger than the map view — screen pixels are the ceiling here. Pick a smaller size or enlarge the window`,
+ `The ${Math.round(rect.w)}×${Math.round(rect.h)} frame is bigger than the map view. Pick a smaller size or enlarge the window`,
'warn', 7000
);
return;
@@ -1412,7 +1522,7 @@
if (blob) shotTake(new File([blob], 'screenshot.png', { type: 'image/png' }));
} catch (e) {
// extension missing or refused — the paste path still works
- toast(`Screen capture unavailable (${e.message}) — paste a screenshot instead`, 'warn', 6000);
+ toast(`Screen capture unavailable (${e.message}). Paste a screenshot instead`, 'warn', 6000);
} finally {
shotGrabbing = false;
}
@@ -1715,7 +1825,7 @@
dragBounds = null;
const resized = gridSearch.resizeRect(grid, b);
if (gridSearch.estimateCells(resized) > GRID_MAX_CELLS) {
- toast(`That area is too fine for ${grid.cell_m} m cells — keeping the previous size`, 'warn', 5000);
+ toast(`That area is too fine for ${grid.cell_m} m cells. Keeping the previous size`, 'warn', 5000);
renderAoi(); // snap the handles back
return;
}
@@ -1752,7 +1862,7 @@
liveVerts = null;
const resized = gridSearch.resizePolygon(grid, verts);
if (gridSearch.estimateCells(resized) > GRID_MAX_CELLS) {
- toast(`That shape is too fine for ${grid.cell_m} m cells — keeping the previous one`, 'warn', 5000);
+ toast(`That shape is too fine for ${grid.cell_m} m cells. Keeping the previous one`, 'warn', 5000);
renderAoi();
return;
}
@@ -1883,7 +1993,7 @@
const cellM = Math.max(10, Number(gridCellM) || 500); // never a NaN lattice
const g = gridSearch.createGrid(aoi, cellM);
if (gridSearch.estimateCells(g) > GRID_MAX_CELLS) {
- toast(`That area is too fine — over the ${GRID_MAX_CELLS}-cell limit. Use a larger cell size.`, 'warn', 6000);
+ toast(`That area exceeds the ${GRID_MAX_CELLS}-cell limit. Use a larger cell size.`, 'warn', 6000);
renderGrid(); // restore the previous grid we hid to draw
return;
}
@@ -1923,7 +2033,7 @@
editArea = false;
const cell = gridSearch.nextUnchecked(grid, null);
if (!cell) {
- toast('Every cell is marked — sweep complete', 'ok');
+ toast('Every cell is marked. Sweep complete', 'ok');
return;
}
flyToCell(cell);
@@ -2188,10 +2298,22 @@
map?.invalidateSize();
}
- // saved places (navigable points) live on the case as `place` entities
- const places = $derived(
- (caseState.current?.entities ?? []).filter((e) => e.type === 'place')
- );
+ // saved places (navigable points) live on the case as `place` entities, read
+ // a page at a time off the bounded catalog rather than the case-open payload.
+ let places = $state([]);
+ $effect(() => {
+ const id = caseState.current?.id;
+ caseState.rev; // re-read after a place is added/removed here or elsewhere
+ if (!id) {
+ places = [];
+ return;
+ }
+ let live = true;
+ fetchAllEntities(id, { types: ['place'] })
+ .then((list) => { if (live) places = list; })
+ .catch(() => { if (live) places = []; });
+ return () => { live = false; };
+ });
function flyToPlace(p) {
const lat = Number(p.attrs?.lat);
@@ -2208,7 +2330,6 @@
// collapse state for the two saved-work sections
let placesCollapsed = $state(false);
- let capturesSubCollapsed = $state(false);
// --- place edit modal (title + notes), used for both save & later edits ---
// { id: string|null, title, notes, lat, lon, zoom, bearing }; id null = new
@@ -2302,7 +2423,7 @@
<div class="body">
<div
- class="map-wrap"
+ class="map-wrap dark-surface"
class:measuring={measureMode}
class:selecting={selectArmed}
class:grid-drawing={!!gridDraw}
@@ -2312,255 +2433,54 @@
<!-- top-left control cluster: fullscreen, OSM labels overlay, measure tools -->
<div class="map-tools">
- <div class="tool-cluster card">
- <button
- class="mtbtn"
- class:on={fullscreen}
- onclick={toggleFullscreen}
- title={fullscreen ? 'Exit fullscreen (Esc)' : 'Fullscreen map'}
- aria-label="Toggle fullscreen"
- >
- <Icon name={fullscreen ? 'minimize' : 'maximize'} size={16} />
- </button>
- <button
- class="mtbtn"
- class:on={osmOverlay}
- onclick={() => (osmOverlay = !osmOverlay)}
- disabled={!baseIsImagery}
- title={baseIsImagery
- ? 'Overlay OSM labels (roads, place names) on the imagery'
- : 'Labels overlay is only useful over satellite imagery'}
- aria-label="Toggle OSM labels overlay"
- >
- <Icon name="layers" size={16} />
- </button>
- <button
- class="mtbtn"
- class:on={toolsOpen || measureMode}
- onclick={toggleTools}
- title="Measure tools"
- aria-label="Measure tools"
- >
- <Icon name="ruler" size={16} />
- </button>
- <button
- class="mtbtn"
- class:on={gridMode}
- onclick={toggleGridMode}
- title="Grid Search — sweep an area cell by cell"
- aria-label="Grid Search"
- >
- <Icon name="grid" size={16} />
- </button>
- <button
- class="mtbtn"
- class:on={uiState.refViewers.length}
- onclick={openRefPicker}
- title="Add a reference image or video over the map"
- aria-label="Add reference"
- >
- <Icon name="image" size={16} />
- </button>
- </div>
-
- {#if toolsOpen}
- <div class="measure-panel card">
- <div class="measure-btns">
- <button
- class="btn btn-sm"
- class:on={measureMode === 'distance'}
- onclick={() => setMeasureMode('distance')}
- >
- <Icon name="ruler" size={14} /> Distance
- </button>
- <button
- class="btn btn-sm"
- class:on={measureMode === 'area'}
- onclick={() => setMeasureMode('area')}
- >
- <Icon name="polygon" size={14} /> Area
- </button>
- <button
- class="btn btn-sm"
- class:on={measureMode === 'angle'}
- onclick={() => setMeasureMode('angle')}
- >
- <Icon name="angle" size={14} /> Angle
- </button>
- </div>
- {#if measureMode}
- <div class="measure-readout">
- {#if measureReadout}
- <span class="measure-value mono">{measureReadout}</span>
- {:else}
- <span class="measure-hint">{MEASURE_HINT[measureMode]}</span>
- {/if}
- <button class="btn btn-ghost btn-sm" onclick={clearMeasure} title="Clear points">
- <Icon name="reset" size={13} />
- </button>
- </div>
- {/if}
- </div>
- {/if}
+ <MapToolCluster
+ {fullscreen}
+ {toggleFullscreen}
+ bind:osmOverlay
+ {baseIsImagery}
+ {toolsOpen}
+ {measureMode}
+ {toggleTools}
+ {gridMode}
+ {toggleGridMode}
+ referenceCount={uiState.refViewers.length}
+ {openRefPicker}
+ {setMeasureMode}
+ {measureReadout}
+ measureHint={MEASURE_HINT}
+ {clearMeasure}
+ />
{#if gridMode}
- <div class="grid-panel card" class:collapsed={gridCollapsed}>
- <div class="grid-head">
- <button
- class="grid-collapse"
- onclick={() => (gridCollapsed = !gridCollapsed)}
- title={gridCollapsed ? 'Expand' : 'Collapse'}
- aria-label={gridCollapsed ? 'Expand panel' : 'Collapse panel'}
- >
- <Icon name={gridCollapsed ? 'chevronDown' : 'chevronUp'} size={14} />
- </button>
- {#if renamingGrid}
- <!-- svelte-ignore a11y_autofocus -->
- <input
- class="input grid-rename"
- bind:value={renameText}
- autofocus
- onblur={commitRename}
- onkeydown={(e) => {
- if (e.key === 'Enter') commitRename();
- else if (e.key === 'Escape') {
- renameText = grid.title || '';
- renamingGrid = false;
- }
- }}
- />
- {:else}
- <!-- svelte-ignore a11y_no_static_element_interactions -->
- <span
- class="grid-head-title"
- class:renamable={grid}
- ondblclick={startRename}
- title={grid ? 'Double-click to rename' : ''}
- >
- {grid ? grid.title || 'Grid' : 'Grid Search'}
- </span>
- {/if}
- {#if grid}
- <button
- class="grid-eye"
- onclick={toggleGridHidden}
- title={gridHidden ? 'Show grid' : 'Hide grid'}
- aria-label={gridHidden ? 'Show grid' : 'Hide grid'}
- >
- <Icon name={gridHidden ? 'eyeOff' : 'eye'} size={14} />
- </button>
- {#if gridCov}
- <span class="grid-head-pct mono">{gridCov.percent}%</span>
- {/if}
- {/if}
- </div>
-
- {#if !gridCollapsed}
- <div class="grid-body">
- {#if grid}
- <div class="grid-cov">
- <div class="grid-bar">
- <span class="grid-bar-fill" style="width:{gridCov.percent}%"></span>
- </div>
- <span class="grid-cov-text mono">
- {gridCov.cleared + gridCov.flagged}/{gridCov.total} · {gridCov.percent}%{#if gridCov.flagged} · {gridCov.flagged} flagged{/if}
- </span>
- </div>
-
- {#if reviewKey}
- <div class="grid-hint">
- <b>C</b> clear · <b>F</b> flag · <b>S</b> skip · <b>P</b> place · <b>Esc</b> stop
- </div>
- <div class="grid-btns">
- <button class="btn btn-sm" onclick={() => markReview('cleared')}>
- <Icon name="check" size={13} /> Clear
- </button>
- <button class="btn btn-sm" onclick={() => markReview('flagged')}>
- <Icon name="pin" size={13} /> Flag
- </button>
- <button class="btn btn-sm" onclick={reviewToPlace} title="Flag and save as a place">
- <Icon name="plus" size={13} /> Place
- </button>
- <button class="btn btn-ghost btn-sm" onclick={stopReview}>Stop</button>
- </div>
- {:else}
- <div class="grid-btns">
- <button class="btn btn-sm" onclick={startReview} title="Fly through the unchecked cells">
- <Icon name="eye" size={13} /> Review
- </button>
- <button class="btn btn-sm" class:on={editArea} onclick={toggleEditArea} title="Show the area box to resize or reshape it">
- <Icon name="edit" size={13} /> Edit area
- </button>
- <button class="btn btn-sm grid-discard" onclick={discardOpenGrid} title="Close this grid (it stays saved) to draw or open another">
- Discard
- </button>
- <button class="btn btn-ghost btn-sm" onclick={() => deleteGrid(gridName)} title="Delete this grid for good">
- <Icon name="trash" size={13} />
- </button>
- </div>
- {#if editArea}
- <div class="grid-hint">Drag the {grid.aoi.type === 'rect' ? 'corners' : 'points'} to reshape.</div>
- {/if}
- {/if}
- {/if}
-
- {#if !grid}
- <div class="grid-new">
- <div class="grid-size">
- <span>Cell</span>
- <input
- class="input"
- type="number"
- min="10"
- step="10"
- bind:value={gridCellM}
- title="Cell size in metres for the next grid"
- />
- <span>m</span>
- </div>
- <div class="grid-btns">
- <button class="btn btn-sm" class:on={gridDraw === 'rect'} onclick={() => startDraw('rect')}>
- <Icon name="square" size={13} /> Box
- </button>
- <button class="btn btn-sm" class:on={gridDraw === 'polygon'} onclick={() => startDraw('polygon')}>
- <Icon name="polygon" size={13} /> Polygon
- </button>
- </div>
- {#if gridDraw === 'polygon'}
- <div class="grid-hint">Click to add points{#if polyDraft.length} · {polyDraft.length}{/if}. Drag to adjust.</div>
- <div class="grid-btns">
- <button class="btn btn-sm" disabled={polyDraft.length < 3} onclick={confirmPolygon}>Confirm</button>
- <button class="btn btn-ghost btn-sm" onclick={cancelGridDraw}>Cancel</button>
- </div>
- {:else if gridDraw === 'rect'}
- <div class="grid-hint">Drag a box on the map. Esc to cancel.</div>
- {/if}
- </div>
- {/if}
-
- {#if !grid && savedOthers.length}
- <div class="grid-saved">
- <div class="grid-saved-label">Saved grids ({savedOthers.length})</div>
- <div class="grid-saved-list">
- {#each savedOthers as g (g.name)}
- <div class="grid-saved-row">
- <button class="grid-load" onclick={() => loadGrid(g.name)} title="Open this grid">
- {g.title || g.name}
- </button>
- <span class="grid-saved-cov mono" title="cleared · flagged">
- {g.cleared}{#if g.flagged}<span class="flagged"> ⚑{g.flagged}</span>{/if}
- </span>
- <button class="btn btn-ghost btn-sm" onclick={() => deleteGrid(g.name)} title="Delete">
- <Icon name="trash" size={12} />
- </button>
- </div>
- {/each}
- </div>
- </div>
- {/if}
- </div>
- {/if}
- </div>
+ <GridSearchPanel
+ bind:collapsed={gridCollapsed}
+ bind:renaming={renamingGrid}
+ bind:renameText
+ {commitRename}
+ {startRename}
+ {grid}
+ toggleHidden={toggleGridHidden}
+ hidden={gridHidden}
+ coverage={gridCov}
+ {reviewKey}
+ {markReview}
+ {reviewToPlace}
+ {stopReview}
+ {startReview}
+ {editArea}
+ {toggleEditArea}
+ discard={discardOpenGrid}
+ {deleteGrid}
+ {gridName}
+ bind:cellMetres={gridCellM}
+ drawMode={gridDraw}
+ {startDraw}
+ polygonDraft={polyDraft}
+ {confirmPolygon}
+ cancelDraw={cancelGridDraw}
+ savedGrids={savedOthers}
+ {loadGrid}
+ />
{/if}
</div>
@@ -2648,8 +2568,8 @@
title={s2PinnedDate
? `Sentinel-2 ${s2LayerLabel} from this exact date`
: s2Latest
- ? `Sentinel-2 ${s2LayerLabel} — most recent pass over this point`
- : `Sentinel-2 ${s2LayerLabel} — most recent pass (open the picker to date it)`}
+ ? `Sentinel-2 ${s2LayerLabel}: most recent pass over this point`
+ : `Sentinel-2 ${s2LayerLabel}: most recent pass (open the picker to date it)`}
>
<Icon name="clock" size={11} />
{s2PinnedDate ?? s2Latest ?? ''}
@@ -2719,105 +2639,32 @@
{/each}
</select>
{#if isSentinel}
- <div class="s2-wrap" bind:this={s2MenuEl}>
- <!-- icon-only: the bar is shared with the capture controls and has a
- finite width — the chosen layer and date read from the pill in
- the map's corner, where they don't cost the bar a row -->
- <button
- class="btn btn-icon"
- class:on={s2MenuOpen}
- onclick={toggleS2Menu}
- title="Sentinel-2 — layer & date"
- aria-label="Sentinel-2 layer and date"
- >
- <Icon name="layers" size={14} />
- </button>
- {#if s2MenuOpen}
- <div class="s2-menu card">
- <div class="menu-row">
- <span class="menu-label">Layer</span>
- <select class="select" bind:value={s2Layer}>
- {#each s2Layers as l (l.id)}
- <option value={l.id}>{l.label}</option>
- {/each}
- </select>
- </div>
- {#if s2LayerHint}
- <div class="menu-hint">{s2LayerHint}</div>
- {/if}
- <div class="menu-hint dim">
- {s2LayersSource === 'instance'
- ? 'Read from your configuration — these are the layers it serves.'
- : 'Could not read your configuration; showing the standard layers.'}
- <button class="linkish" onclick={() => loadS2Layers(true)}>Refresh</button>
- </div>
-
- <div class="menu-sep" aria-hidden="true"></div>
-
- <div class="menu-row">
- <span class="menu-label">Date</span>
- <div class="chips">
- <button class="chip" class:on={!s2Date} onclick={() => (s2Date = '')}>
- Most recent
- </button>
- </div>
- </div>
-
- <div class="cal">
- <div class="cal-head">
- <button class="cal-nav" onclick={() => stepS2Month(-1)} aria-label="Previous month">
- <Icon name="chevronLeft" size={13} />
- </button>
- <span class="cal-month">{monthLabel(s2Month)}</span>
- <button class="cal-nav" onclick={() => stepS2Month(1)} aria-label="Next month">
- <Icon name="chevronRight" size={13} />
- </button>
- </div>
- <div class="cal-grid" class:busy={s2PassesBusy}>
- {#each ['M', 'T', 'W', 'T', 'F', 'S', 'S'] as d, i (i)}
- <span class="cal-dow" aria-hidden="true">{d}</span>
- {/each}
- {#each monthGrid(s2Month) as day, i (day ?? `pad${i}`)}
- {#if !day}
- <span class="cal-pad" aria-hidden="true"></span>
- {:else}
- {@const pass = s2Passes[day]}
- <button
- class="cal-day {pass ? cloudClass(pass.cloud) : ''}"
- class:has={!!pass}
- class:on={s2Date === day}
- disabled={!pass}
- onclick={() => pickS2Date(day)}
- title={pass
- ? `${day} — ${cloudLabel(pass.cloud) || 'cloud cover unknown'}`
- : `${day} — no Sentinel-2 pass`}
- >
- {Number(day.slice(8))}
- </button>
- {/if}
- {/each}
- </div>
- </div>
-
- {#if s2PassesBusy}
- <div class="menu-hint dim">Reading this month's passes…</div>
- {:else if s2PassesNote}
- <div class="menu-hint warn">{s2PassesNote}</div>
- {:else if s2PassesStale}
- <div class="menu-hint">
- <span class="warn">The map moved — these passes are for where you were.</span>
- <button class="linkish" onclick={() => loadS2Passes(true)}>Refresh</button>
- </div>
- {:else}
- <div class="menu-hint dim">
- Only days Sentinel-2 passed over this point are selectable; the colour is
- cloud cover. A pinned day shows that pass alone — near a swath edge it can
- still be black (no data), so try the neighbouring date.
- </div>
- {/if}
- </div>
- {/if}
- </div>
+ <SentinelPicker
+ bind:menuEl={s2MenuEl}
+ menuOpen={s2MenuOpen}
+ toggleMenu={toggleS2Menu}
+ bind:layer={s2Layer}
+ layers={s2Layers}
+ layerHint={s2LayerHint}
+ layersSource={s2LayersSource}
+ loadLayers={loadS2Layers}
+ bind:date={s2Date}
+ month={s2Month}
+ {monthLabel}
+ stepMonth={stepS2Month}
+ {monthGrid}
+ passes={s2Passes}
+ {cloudClass}
+ {cloudLabel}
+ passesBusy={s2PassesBusy}
+ passesNote={s2PassesNote}
+ passesStale={s2PassesStale}
+ verifyingDate={s2VerifyingDate}
+ dateStatus={s2DateStatus}
+ pickDate={pickS2Date}
+ clearDate={clearS2Date}
+ loadPasses={loadS2Passes}
+ />
{/if}
{#if usagePill}
<span
@@ -2830,11 +2677,11 @@
class="fallback-pill"
class:paused={meterBlocked}
title={meterBlocked
- ? `${currentProvider.label} passed 90% of its monthly free tier — showing free imagery instead. Override in Settings to keep using it (billed).`
- : `Eco mode: free imagery at low zoom — zoom in to get ${currentProvider.label} detail. Toggle in Settings.`}
+ ? `${currentProvider.label} passed 90% of its monthly free tier. Free imagery is shown instead. Override in Settings to keep using it (billed).`
+ : `Eco mode shows free imagery at low zoom. Zoom in for ${currentProvider.label} detail. Toggle in Settings.`}
>
<Icon name={meterBlocked ? 'alert' : 'leaf'} size={11} />
- {meterBlocked ? `${currentProvider.label} paused — free imagery` : 'eco — free imagery'}
+ {meterBlocked ? `${currentProvider.label} paused · free imagery` : 'eco · free imagery'}
</span>
{/if}
<select class="select" bind:value={markerStyle} title="Marker style">
@@ -2876,165 +2723,26 @@
mode + size/ratio/resolution settings. Hovering/focusing the main
button previews the centred crop frame, only while that's the
active mode. -->
- <div class="capture-split" role="group">
- <button
- class="btn btn-primary capture-main"
- class:on={captureMode === 'select' && selectArmed}
- onmouseenter={() => (captureHover = captureMode === 'center')}
- onmouseleave={() => (captureHover = false)}
- onfocusin={() => (captureHover = captureMode === 'center')}
- onfocusout={() => (captureHover = false)}
- onclick={runCapture}
- disabled={capturing || captureBlocked}
- title={captureBlocked
- ? 'View-only basemap — this provider cannot be captured'
- : captureMode === 'select'
- ? `Draw a rectangle on the map to capture exactly that area${isWidgetBase ? ' (grabbed from the screen)' : ''}`
- : `Capture the centred preset size${isWidgetBase ? ' (grabbed from the screen)' : ''}`}
- >
- {#if capturing}
- <span class="spinner"></span> Capturing…
- {:else if captureMode === 'select'}
- <Icon name="crop" size={14} /> {selectArmed ? 'Draw box…' : 'Select area'}
- {:else}
- <Icon name="satellite" size={15} /> Capture
- {/if}
- </button>
-
- <div class="size-menu-wrap" bind:this={sizeMenuEl}>
- <button
- class="btn btn-icon capture-arrow"
- class:on={sizeMenuOpen}
- onclick={() => (sizeMenuOpen = !sizeMenuOpen)}
- title={isWidgetBase
- ? 'Capture mode, size & ratio'
- : 'Capture mode, size, ratio & resolution'}
- aria-label="Capture options"
- >
- <Icon name="chevronDown" size={13} />
- </button>
- {#if sizeMenuOpen}
- <div class="size-menu card">
- <div class="menu-row">
- <span class="menu-label">Mode</span>
- <div class="chips">
- <button class="chip" class:on={captureMode === 'center'} onclick={() => (captureMode = 'center')}>
- Capture
- </button>
- <button class="chip" class:on={captureMode === 'select'} onclick={() => (captureMode = 'select')}>
- Select area
- </button>
- </div>
- </div>
- <div class="menu-hint">
- {captureMode === 'center'
- ? 'Captures the centred size below.'
- : 'Drag a box on the map to capture exactly it.'}
- </div>
-
- {#if captureMode === 'select'}
- <div class="menu-row">
- <span class="menu-label">Ratio</span>
- <div class="chips">
- {#each RATIOS as r (r.id)}
- <button class="chip" class:on={ratio === r.id} onclick={() => (ratio = r.id)}>
- {r.label}
- </button>
- {/each}
- </div>
- </div>
- <div class="menu-hint">Locks the dragged box's shape.</div>
- {:else}
- <div class="menu-row">
- <span class="menu-label">Size</span>
- <div class="chips">
- {#each PRESETS as p (p.id)}
- <button class="chip" class:on={preset === p.id} onclick={() => (preset = p.id)}>
- {p.label}
- </button>
- {/each}
- </div>
- </div>
- {#if preset === 'custom'}
- <div class="custom-size" title="Custom crop size ({SIZE_MIN}–{SIZE_MAX} px)">
- <input
- class="input size-input"
- type="number"
- min={SIZE_MIN}
- max={SIZE_MAX}
- bind:value={customW}
- onblur={() => (customW = clampSize(customW))}
- aria-label="Crop width"
- />
- <span>×</span>
- <input
- class="input size-input"
- type="number"
- min={SIZE_MIN}
- max={SIZE_MAX}
- bind:value={customH}
- onblur={() => (customH = clampSize(customH))}
- aria-label="Crop height"
- />
- </div>
- {/if}
- {/if}
-
- <!-- the widget's one real difference: its pixels come off the
- screen, so there is no deeper zoom to capture and no
- resolution to choose -->
- {#if isWidgetBase}
- <div class="menu-row">
- <span class="menu-label">Source</span>
- <div class="chips">
- {#if extensionVersion()}
- <button
- class="chip"
- onclick={() => {
- sizeMenuOpen = false;
- shotOpen = true;
- }}
- >
- Paste a screenshot…
- </button>
- {:else}
- <button
- class="chip"
- onclick={() => {
- sizeMenuOpen = false;
- extGateOpen = true;
- }}
- >
- Get the capture extension
- </button>
- {/if}
- </div>
- </div>
- <div class="menu-hint">
- {#if extensionVersion()}
- This basemap is captured from the screen (Google's terms allow nothing
- programmatic out of it), so the frame can't go past the map view and screen
- pixels are the ceiling.
- {:else}
- This basemap is captured from the screen, so filing it needs the capture
- extension (Google's terms allow nothing programmatic out).
- {/if}
- </div>
- {:else}
- <div class="menu-row">
- <span class="menu-label">Resolution</span>
- <div class="chips">
- <button class="chip" class:on={resolution === 1} onclick={() => (resolution = 1)}>1×</button>
- <button class="chip" class:on={resolution === 2} onclick={() => (resolution = 2)}>2×</button>
- <button class="chip" class:on={resolution === 'max'} onclick={() => (resolution = 'max')}>Max</button>
- </div>
- </div>
- <div class="menu-hint">Captures a deeper zoom for a sharper file.</div>
- {/if}
- </div>
- {/if}
- </div>
- </div>
+ <CaptureOptions
+ bind:menuEl={sizeMenuEl}
+ bind:menuOpen={sizeMenuOpen}
+ bind:mode={captureMode}
+ bind:hover={captureHover}
+ {selectArmed}
+ {capturing}
+ blocked={captureBlocked}
+ widgetBase={isWidgetBase}
+ {runCapture}
+ ratios={RATIOS}
+ bind:ratio
+ presets={PRESETS}
+ bind:preset
+ bind:customWidth={customW}
+ bind:customHeight={customH}
+ bind:resolution
+ openScreenshot={() => (shotOpen = true)}
+ openExtensionGate={() => (extGateOpen = true)}
+ />
</div>
<!-- floating reference-image windows (scratch aids over the map) -->
{#each uiState.refViewers as v (v.id)}
@@ -3178,7 +2886,7 @@
{:else}
<div class="cap-list">
{#each (caseState.current ? captures : []) as item (item.path)}
- <div class="cap card">
+ <div class="cap card" class:focused={focusedCapturePath === item.path} data-capture-path={item.path}>
<a
class="cap-goto"
class:disabled={fullscreen}
@@ -3240,7 +2948,7 @@
<button
class="btn btn-ghost btn-sm"
disabled={fullscreen}
- title={leavesFullscreen ?? 'Send to Proof Composer'}
+ title={leavesFullscreen ?? 'Send to Geo Proof'}
onclick={() => sendToComposer(item)}
>
<Icon name="proof" size={14} />
@@ -3286,8 +2994,8 @@
? `“${deleteTarget.item.title ?? coordsLabel(deleteTarget.item)}” will be removed from the case.`
: `“${deleteTarget.item.label}” will be removed from the case.`}
detail={deleteTarget.kind === 'capture'
- ? 'This permanently deletes the image file on disk — it cannot be undone.'
- : 'This permanently removes the saved point — it cannot be undone.'}
+ ? 'This permanently deletes the image file on disk. It cannot be undone.'
+ : 'This permanently removes the saved point. It cannot be undone.'}
confirmLabel="Delete"
tone="danger"
busy={deleteBusy}
@@ -3299,8 +3007,9 @@
<!-- satellite notes modal -->
{#if notesItem}
<Modal title="Capture details" onclose={() => (notesItem = null)} width="420px">
- <label style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin-bottom:5px">Title</label>
+ <label for="capture-title" style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin-bottom:5px">Title</label>
<input
+ id="capture-title"
class="input"
placeholder={coordsLabel(notesItem)}
bind:value={notesTitle}
@@ -3329,8 +3038,9 @@
</div>
</div>
<hr style="border:none;border-top:1px solid var(--border);margin:12px 0" />
- <label style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin-bottom:5px">Notes</label>
+ <label for="capture-notes" style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin-bottom:5px">Notes</label>
<textarea
+ id="capture-notes"
class="textarea"
rows="5"
placeholder="Add observations, links, context…"
@@ -3355,7 +3065,7 @@
grab the whole map view below, or paste
(<span class="mono">Ctrl+V</span>) / drop your own OS screenshot.
Unlike a framed capture, this is filed at the current <em>view</em>
- (<span class="mono">{fmtCoords(center.lat, center.lon)}</span>, z{center.zoom}) —
+ (<span class="mono">{fmtCoords(center.lat, center.lon)}</span>, z{center.zoom}).
the coordinates describe the map, not a registered crop. The Google attribution
is burned into a footer either way; keep Google's on-screen credits inside the
frame too.
@@ -3430,8 +3140,9 @@
onclose={() => (placeModal = null)}
width="420px"
>
- <label style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin-bottom:5px">Title</label>
+ <label for="place-title" style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin-bottom:5px">Title</label>
<input
+ id="place-title"
class="input"
placeholder={placeCoordsLabel(placeModal)}
bind:value={placeModal.title}
@@ -3448,8 +3159,9 @@
</div>
</div>
<hr style="border:none;border-top:1px solid var(--border);margin:12px 0" />
- <label style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin-bottom:5px">Notes</label>
+ <label for="place-notes" style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin-bottom:5px">Notes</label>
<textarea
+ id="place-notes"
class="textarea"
rows="5"
placeholder="Add observations, links, context…"
@@ -3476,7 +3188,7 @@
<div class="ref-empty">Loading…</div>
{:else if !refMedia.length}
<div class="ref-empty">
- No images or videos in this case yet — import one in the Media Library first.
+ No images or videos in this case yet. Import one in the Media Library first.
</div>
{:else}
<div class="ref-grid">
@@ -3666,79 +3378,6 @@
gap: 8px;
align-items: flex-start;
}
- .tool-cluster {
- display: flex;
- gap: 2px;
- padding: 4px;
- background: rgba(24, 24, 24, 0.88);
- backdrop-filter: blur(6px);
- }
- .mtbtn {
- display: grid;
- place-items: center;
- width: 30px;
- height: 30px;
- border-radius: var(--radius-1);
- color: var(--text-2);
- cursor: pointer;
- }
- .mtbtn:hover {
- color: var(--text-1);
- background: var(--bg-3);
- }
- .mtbtn.on {
- color: var(--accent-text);
- background: var(--accent);
- }
- .mtbtn:disabled {
- opacity: 0.35;
- cursor: not-allowed;
- }
- .mtbtn:disabled:hover {
- color: var(--text-2);
- background: none;
- }
- /* float to the right of the tool cluster instead of below it, where the
- Leaflet zoom control sits — otherwise the two overlap (item 7) */
- .measure-panel {
- position: absolute;
- top: 0;
- left: calc(100% + 8px);
- width: max-content;
- display: flex;
- flex-direction: column;
- gap: 8px;
- padding: 10px;
- background: rgba(24, 24, 24, 0.92);
- backdrop-filter: blur(6px);
- box-shadow: var(--shadow-2);
- }
- .measure-btns {
- display: flex;
- gap: 4px;
- }
- .measure-btns .btn.on {
- background: var(--accent);
- color: var(--accent-text);
- border-color: var(--accent);
- }
- .measure-readout {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 8px;
- padding-top: 6px;
- border-top: 1px solid var(--border);
- }
- .measure-value {
- font-size: var(--fs-md);
- font-weight: 700;
- color: var(--accent);
- }
- .measure-hint {
- font-size: var(--fs-xs);
- color: var(--text-3);
- }
.map-wrap.measuring :global(.leaflet-container),
.map-wrap.selecting :global(.leaflet-container) {
cursor: crosshair;
@@ -3747,198 +3386,6 @@
cursor: crosshair;
}
- /* Grid Search panel — same shelf as the measure panel, to the cluster's right */
- .grid-panel {
- position: absolute;
- top: 0;
- left: calc(100% + 8px);
- width: 218px;
- display: flex;
- flex-direction: column;
- background: rgba(24, 24, 24, 0.92);
- backdrop-filter: blur(6px);
- box-shadow: var(--shadow-2);
- }
- .grid-head {
- display: flex;
- align-items: center;
- gap: 6px;
- padding: 6px 8px;
- }
- .grid-collapse {
- display: grid;
- place-items: center;
- width: 22px;
- height: 22px;
- border-radius: var(--radius-1);
- color: var(--text-2);
- cursor: pointer;
- flex-shrink: 0;
- }
- .grid-collapse:hover {
- color: var(--text-1);
- background: var(--bg-3);
- }
- .grid-head-title {
- flex: 1;
- min-width: 0;
- font-size: var(--fs-sm);
- font-weight: 600;
- color: var(--text-1);
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- }
- .grid-head-title.renamable {
- cursor: text;
- }
- .grid-rename {
- flex: 1;
- min-width: 0;
- height: 24px;
- padding: 2px 6px;
- font-size: var(--fs-sm);
- }
- .grid-eye {
- display: grid;
- place-items: center;
- width: 22px;
- height: 22px;
- border-radius: var(--radius-1);
- color: var(--text-2);
- cursor: pointer;
- flex-shrink: 0;
- }
- .grid-eye:hover {
- color: var(--text-1);
- background: var(--bg-3);
- }
- .grid-head-pct {
- font-size: var(--fs-xs);
- color: var(--accent);
- flex-shrink: 0;
- }
- .grid-body {
- display: flex;
- flex-direction: column;
- gap: 8px;
- padding: 0 10px 10px;
- }
- .grid-size {
- display: flex;
- align-items: center;
- gap: 6px;
- font-size: var(--fs-xs);
- color: var(--text-2);
- }
- .grid-size .input {
- width: 64px;
- }
- .grid-btns {
- display: flex;
- flex-wrap: wrap;
- gap: 4px;
- }
- .grid-btns .btn.on {
- background: var(--accent);
- color: var(--accent-text);
- border-color: var(--accent);
- }
- .grid-discard {
- background: rgba(255, 255, 255, 0.1);
- border-color: rgba(255, 255, 255, 0.18);
- color: var(--text-1);
- }
- .grid-discard:hover {
- background: rgba(255, 255, 255, 0.16);
- color: var(--text-1);
- }
- .grid-hint {
- font-size: var(--fs-xs);
- color: var(--text-3);
- }
- .grid-hint b {
- color: var(--text-2);
- }
- .grid-cov {
- display: flex;
- flex-direction: column;
- gap: 4px;
- }
- .grid-bar {
- height: 6px;
- border-radius: 3px;
- background: rgba(124, 138, 165, 0.25);
- overflow: hidden;
- }
- .grid-bar-fill {
- display: block;
- height: 100%;
- background: var(--accent);
- transition: width 0.15s ease;
- }
- .grid-cov-text {
- font-size: var(--fs-xs);
- color: var(--text-2);
- }
- .grid-new {
- display: flex;
- flex-direction: column;
- gap: 6px;
- padding-top: 8px;
- border-top: 1px solid var(--border);
- }
- .grid-saved {
- display: flex;
- flex-direction: column;
- gap: 3px;
- padding-top: 8px;
- border-top: 1px solid var(--border);
- }
- .grid-saved-label {
- font-size: var(--fs-xs);
- color: var(--text-3);
- margin-bottom: 2px;
- }
- .grid-saved-list {
- display: flex;
- flex-direction: column;
- gap: 3px;
- /* hundreds of grids scroll inside the panel instead of stretching it down
- the whole page */
- max-height: 240px;
- overflow-y: auto;
- }
- .grid-saved-row {
- display: flex;
- align-items: center;
- gap: 4px;
- }
- .grid-load {
- flex: 1;
- min-width: 0;
- text-align: left;
- padding: 3px 6px;
- border-radius: var(--radius-1);
- font-size: var(--fs-xs);
- color: var(--text-2);
- cursor: pointer;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- }
- .grid-load:hover {
- color: var(--text-1);
- background: var(--bg-3);
- }
- .grid-saved-cov {
- font-size: var(--fs-xs);
- color: var(--text-3);
- flex-shrink: 0;
- }
- .grid-saved-cov .flagged {
- color: #ffcf33;
- }
/* draggable square handle for the area corners / polygon vertices */
:global(.grid-handle) {
background: var(--accent, #f5a623);
@@ -4100,255 +3547,6 @@
.fallback-pill.paused {
color: var(--danger);
}
- /* the capture split-button: main action + arrow fused into one pill,
- mirroring .place-save's main/edit split */
- .capture-split {
- display: flex;
- align-items: stretch;
- }
- .capture-main {
- border-top-right-radius: 0;
- border-bottom-right-radius: 0;
- }
- .capture-arrow {
- border-top-left-radius: 0;
- border-bottom-left-radius: 0;
- background: var(--accent);
- border-color: transparent;
- border-left: 1px solid rgba(0, 0, 0, 0.2);
- color: var(--accent-text);
- }
- .capture-arrow:hover:not(:disabled) {
- background: var(--accent-hover);
- }
- .size-menu-wrap .capture-arrow.on {
- background: var(--accent-hover);
- }
- .capture-main.on {
- box-shadow: inset 0 0 0 2px rgba(255, 255, 255, 0.5);
- }
- .custom-size {
- display: flex;
- align-items: center;
- gap: 4px;
- font-size: var(--fs-xs);
- color: var(--text-3);
- }
- .size-input {
- width: 64px;
- padding: 5px 6px;
- font-size: var(--fs-xs);
- text-align: center;
- }
-
- /* square icon button (the size/ratio/resolution popover trigger) */
- .btn-icon {
- padding: 6px 8px;
- }
- .btn-icon.on {
- background: var(--accent);
- color: var(--accent-text);
- border-color: var(--accent);
- }
- .size-menu-wrap {
- position: relative;
- display: flex;
- }
- .size-menu {
- position: absolute;
- bottom: calc(100% + 8px);
- right: 0;
- width: max-content;
- max-width: 280px;
- display: flex;
- flex-direction: column;
- gap: 4px;
- padding: 12px;
- background: rgba(24, 24, 24, 0.96);
- backdrop-filter: blur(6px);
- box-shadow: var(--shadow-2);
- z-index: 700;
- }
- .menu-row {
- display: flex;
- align-items: center;
- gap: 10px;
- justify-content: space-between;
- }
- .menu-label {
- font-size: var(--fs-xs);
- color: var(--text-3);
- font-weight: 600;
- }
- .chips {
- display: flex;
- gap: 4px;
- flex-wrap: wrap;
- justify-content: flex-end;
- }
- .chip {
- padding: 4px 9px;
- border-radius: var(--r-sm);
- border: 1px solid var(--border);
- background: var(--bg-2);
- color: var(--text-2);
- font-size: var(--fs-xs);
- white-space: nowrap;
- cursor: pointer;
- transition: border-color 0.12s, color 0.12s, background 0.12s;
- }
- .chip:hover {
- border-color: var(--border-strong);
- color: var(--text-1);
- }
- .chip.on {
- border-color: var(--accent);
- background: var(--accent-soft);
- color: var(--accent);
- }
- .menu-hint {
- font-size: 10px;
- color: var(--text-3);
- margin: -1px 0 5px;
- }
- .menu-hint.dim {
- opacity: 0.75;
- }
- .menu-hint .warn,
- .menu-hint.warn {
- color: var(--warn, #e2a03f);
- }
- .menu-sep {
- height: 1px;
- background: var(--border);
- margin: 4px 0 6px;
- }
-
- /* --- Sentinel-2 layer + date popover --- */
- .s2-wrap {
- position: relative;
- display: flex;
- }
- .s2-menu {
- position: absolute;
- bottom: calc(100% + 8px);
- left: 0;
- width: max-content;
- max-width: 320px;
- display: flex;
- flex-direction: column;
- gap: 4px;
- padding: 12px;
- background: rgba(24, 24, 24, 0.96);
- backdrop-filter: blur(6px);
- box-shadow: var(--shadow-2);
- z-index: 700;
- }
- .s2-menu .select {
- max-width: 190px;
- }
- .linkish {
- background: none;
- border: 0;
- padding: 0;
- color: var(--accent);
- font-size: 10px;
- cursor: pointer;
- text-decoration: underline;
- }
- /* --- the pass calendar --- */
- .cal {
- display: flex;
- flex-direction: column;
- gap: 6px;
- margin: 2px 0 6px;
- }
- .cal-head {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 8px;
- }
- .cal-month {
- font-size: var(--fs-xs);
- font-weight: 600;
- color: var(--text-1);
- }
- .cal-nav {
- display: flex;
- padding: 3px 5px;
- border: 1px solid var(--border);
- border-radius: var(--r-sm);
- background: var(--bg-2);
- color: var(--text-2);
- cursor: pointer;
- }
- .cal-nav:hover {
- color: var(--text-1);
- border-color: var(--text-3);
- }
- .cal-grid {
- display: grid;
- grid-template-columns: repeat(7, 1fr);
- gap: 2px;
- }
- .cal-grid.busy {
- opacity: 0.5;
- pointer-events: none;
- }
- .cal-dow {
- text-align: center;
- font-size: 9px;
- color: var(--text-3);
- padding-bottom: 2px;
- }
- .cal-day {
- aspect-ratio: 1;
- display: flex;
- align-items: center;
- justify-content: center;
- border: 1px solid transparent;
- border-radius: var(--r-sm);
- background: transparent;
- color: var(--text-3);
- font-size: 10px;
- font-family: var(--font-mono);
- cursor: pointer;
- }
- /* a day with no pass isn't dimmed decoration — there is nothing to render, so
- it cannot be chosen (the same rule the Copernicus browser follows) */
- .cal-day:disabled {
- opacity: 0.28;
- cursor: default;
- }
- .cal-day.has {
- color: var(--text-1);
- background: var(--bg-2);
- border-color: var(--border);
- }
- /* cloud cover, at a glance: most passes are white and cost a tile to find out */
- .cal-day.clear {
- border-color: color-mix(in srgb, var(--ok, #46a758) 65%, transparent);
- color: var(--ok, #46a758);
- }
- .cal-day.part {
- border-color: color-mix(in srgb, var(--warn, #e2a03f) 55%, transparent);
- color: var(--warn, #e2a03f);
- }
- .cal-day.cloudy,
- .cal-day.unknown {
- border-color: var(--border);
- color: var(--text-2);
- }
- .cal-day.has:hover {
- border-color: var(--text-1);
- }
- .cal-day.on {
- background: var(--accent);
- border-color: var(--accent);
- color: var(--accent-text);
- font-weight: 700;
- }
/* a pinned date is a fact about the pixels; "latest" is an inference from the
pass list — they must not look identical */
.date-pill.exact {
@@ -4368,10 +3566,6 @@
color: var(--accent);
border-color: color-mix(in srgb, var(--accent) 45%, transparent);
}
- .menu-row + .custom-size {
- justify-content: flex-end;
- padding: 2px 0;
- }
.prov.dates {
display: flex;
align-items: center;
@@ -4621,6 +3815,7 @@
overflow: hidden;
flex-shrink: 0;
}
+ .cap.focused { outline: 1px solid var(--accent); box-shadow: 0 0 0 2px var(--accent-soft); }
.cap-goto {
display: block;
width: 100%;
diff --git a/frontend/src/tools/Settings.svelte b/frontend/src/tools/Settings.svelte
index c936c40..0be1b12 100644
--- a/frontend/src/tools/Settings.svelte
+++ b/frontend/src/tools/Settings.svelte
@@ -120,7 +120,7 @@
steps: [
'Register (free) on dataspace.copernicus.eu, then open the Sentinel Hub Dashboard.',
'Configuration Utility → New configuration, based on "Simple Sentinel-2 L2A template".',
- 'Open it and turn Show logo and Show warnings OFF — both are burned into every tile.',
+ 'Open it and turn off Show logo and Show warnings. Both are burned into every tile.',
'Copy the ID under "Service endpoints" and paste it here.',
],
overage:
@@ -194,7 +194,7 @@
toast('Pairing token copied', 'ok');
} catch {
tokenShown = true; // clipboard blocked — show it for manual copy
- toast('Could not copy — the token is shown for manual copy', 'warn');
+ toast('Could not copy. The token is shown for manual copy', 'warn');
}
}
@@ -211,7 +211,7 @@
async function rotateToken() {
const r = await api.post('/api/settings/ingest-token/rotate');
ingestToken = r.ingest_token;
- toast('New token minted — every paired extension must re-pair', 'ok', 6000);
+ toast('New token minted. Every extension must pair again', 'ok', 6000);
}
// the home-view fields are edited as text, so a half-typed "-" or "48." isn't
// fought by the number parser mid-keystroke; committed on change
@@ -321,7 +321,7 @@
try {
const r = await api.del(`/api/settings/scrapers/${dist}`);
await loadScrapers();
- if (r.restart_required) toast(`${dist} reverted — restart Azimut to use it`, 'warn');
+ if (r.restart_required) toast(`${dist} reverted. Restart Azimut to use it`, 'warn');
else toast(`${dist} reverted to the bundled version`, 'ok');
} catch (e) {
toast(`${dist}: ${e.message}`, 'danger');
@@ -581,7 +581,7 @@
if (bound && bound !== keys[id].trim()) {
testResult[id] = {
ok: false,
- detail: 'Google Maps is already loaded with the previous key — reload the app (F5), then test',
+ detail: 'Google Maps still has the previous key. Reload the app (F5), then test.',
};
} else {
const url = `https://maps.googleapis.com/maps/api/js?key=${encodeURIComponent(keys[id].trim())}&v=weekly`;
@@ -647,7 +647,7 @@
</div>
<p class="sample mono">{coordSample}</p>
<p class="note">
- Display only — captures, proofs and <span class="mono">case.json</span> always
+ Display only. Captures, proofs and <span class="mono">case.json</span> always
keep decimal degrees, so a case reads the same for everyone.
</p>
</section>
@@ -678,7 +678,7 @@
<h3>Satellite home view</h3>
<p class="intro">
Where the Satellite tab opens. A case artifact or a “go to coordinates”
- handoff still wins — this is only the starting point.
+ handoff still wins. This is only the starting point.
</p>
<div class="grid-3">
<label class="field">
@@ -697,7 +697,7 @@
</section>
<section class="group">
- <h3>Post composer</h3>
+ <h3>Geo Report</h3>
<div class="row">
<div class="row-label">
<span>Default mention</span>
@@ -714,7 +714,7 @@
<div class="row">
<div class="row-label">
<span>Preferred platform</span>
- <span class="row-hint">Used for new post drafts.</span>
+ <span class="row-hint">Used for new Geo Report drafts.</span>
</div>
<div class="seg" role="group" aria-label="Preferred platform">
{#each Object.values(POST_TARGETS) as option (option.id)}
@@ -751,7 +751,7 @@
<div class="row-label">
<span>Your logo</span>
<span class="row-hint">
- A transparent PNG, under 2 MB. Stays on this machine — the proof
+ A transparent PNG under 2 MB. It stays on this machine. The proof
composer stamps it onto proofs you tick “Signature” on, and
nothing else ever carries it.
</span>
@@ -784,7 +784,7 @@
<section class="group">
<h3>Providers</h3>
<p class="intro">
- Optional. The built-in basemaps (Esri, OSM, OpenTopoMap) never need a key — your own
+ Optional. The built-in basemaps (Esri, OSM, OpenTopoMap) never need a key. Your own
Mapbox / Google / Copernicus accounts just unlock extra ones in the Satellite tab.
Keys stay in <span class="mono">settings.json</span> on this machine, never in a case
or an export, and Azimut counts every request it sends so a free tier is never a
@@ -902,13 +902,13 @@
</p>
{/if}
- <p class="overage">{k.cost} — {k.overage}</p>
+ <p class="overage">{k.cost}. {k.overage}</p>
{#if keys[k.id] || count}
{#if usageBlocked(count, k.id, overrides, tiers)}
<p class="blocked">
<Icon name="alert" size={12} />
- Paused at {Math.round(BLOCK_SHARE * 100)}% of the free tier — the map and
+ Paused at {Math.round(BLOCK_SHARE * 100)}% of the free tier. The map and
captures fall back to free imagery until next month, or:
</p>
{/if}
@@ -930,7 +930,7 @@
<label
class="ctrl"
title={k.tierNote ??
- "What this account's monthly free allowance really is — check the provider's dashboard"}
+ "This account's monthly free allowance. Check the provider dashboard"}
>
<span>Free allowance</span>
<input
@@ -956,7 +956,7 @@
{:else}
<label
class="ctrl"
- title="Threshold for this basemap (blank inherits the global one, 0 turns eco off)"
+ title="Blank uses global; 0 disables eco mode"
>
<span>Eco below z ≤</span>
<input
@@ -990,7 +990,7 @@
</div>
<div class="cards-foot">
- <span class="row-hint">Counters for {month} — local bookkeeping, never sent anywhere.</span>
+ <span class="row-hint">Counters for {month}. Stored locally.</span>
<button class="btn btn-ghost btn-sm" onclick={() => load()} title="Refresh counters">
<Icon name="reset" size={13} /> Refresh
</button>
@@ -1031,7 +1031,7 @@
>
<Icon name={termsOpen ? 'chevronDown' : 'chevronRight'} size={13} />
<span class="card-name">Provider terms</span>
- <span class="card-gives">Encoded — nothing to do</span>
+ <span class="card-gives">Encoded; nothing to do</span>
</button>
</div>
{#if termsOpen}
@@ -1063,7 +1063,7 @@
· update bundled (<span class="mono">v{about.extension_version}</span>)
{/if}
{:else}
- not detected — after installing, reload this tab
+ not detected. After installing, reload this tab
{/if}
</span>
</div>
@@ -1108,7 +1108,7 @@
</div>
<p class="note">
The token only authorizes filing captures into this Azimut on
- <span class="mono">127.0.0.1</span> — nothing leaves your machine. The
+ <span class="mono">127.0.0.1</span>. Nothing leaves your machine. The
extension takes one screenshot per explicit click, reads only the page
URL, and refuses non-map sites.
</p>
@@ -1157,7 +1157,7 @@
<span>Check for a newer release</span>
<span class="row-hint">
{#if appUpdate?.update_available}
- <span class="mono">{appUpdate.latest}</span> is out — you have
+ <span class="mono">{appUpdate.latest}</span> is out. You have
<span class="mono">{about.version}</span>
{:else if appUpdate && !appUpdate.error}
you're on the latest (<span class="mono">{about.version}</span>)
@@ -1194,7 +1194,7 @@
<p class="note">
A <span class="mono">pip</span> or <span class="mono">pipx</span> install updates with
<span class="mono">pipx upgrade azimut</span>. For the standalone binary, download the new
- release and replace the file — your cases under the workspace are untouched.
+ release and replace the file. Your cases under the workspace are untouched.
</p>
</section>
@@ -1225,7 +1225,7 @@
<h3>Downloaders</h3>
<p class="note">
Media download leans on two projects that track sites as they change. They
- age faster than Azimut does — if a link stops resolving, update these first.
+ age faster than Azimut does. Update these first if a link stops resolving.
</p>
{#each scrapers as s (s.dist)}
<div class="row">
@@ -1277,9 +1277,9 @@
{#if tab === 'templates'}
<section class="group">
- <h3>Proof templates</h3>
+ <h3>Geo Proof templates</h3>
<p class="note">
- A proof's house style — background, margins, text sizes, footer,
+ A proof's house style: background, margins, text sizes, footer,
signature placement and preferred colours. New proofs can start
from one. Shared across every case.
</p>
@@ -1308,9 +1308,9 @@
</section>
<section class="group">
- <h3>Post templates</h3>
+ <h3>Geo Report templates</h3>
<p class="note">
- A thread skeleton — the mention, which lines the first tweet keeps,
+ A thread skeleton: the mention, which lines the first tweet keeps,
whether a media tweet rides along, and boilerplate extra tweets.
</p>
<div class="tpl-list">
diff --git a/frontend/src/tools/inspect/CollageCanvas.svelte b/frontend/src/tools/inspect/CollageCanvas.svelte
index dd65cfa..6913165 100644
--- a/frontend/src/tools/inspect/CollageCanvas.svelte
+++ b/frontend/src/tools/inspect/CollageCanvas.svelte
@@ -380,7 +380,7 @@
onpointerdown={(e) => e.stopPropagation()}
onclick={() => (node.ghost = !node.ghost)}
aria-label="Toggle piece transparency"
- title="See through this piece to align features (view only, never exported)"
+ title="Fade this piece while aligning; not exported"
>
<Icon name="ghost" size={15 / scale} />
</button>
diff --git a/frontend/src/tools/inspect/CollageMenu.svelte b/frontend/src/tools/inspect/CollageMenu.svelte
index 4854d96..acee999 100644
--- a/frontend/src/tools/inspect/CollageMenu.svelte
+++ b/frontend/src/tools/inspect/CollageMenu.svelte
@@ -116,7 +116,7 @@
// into each piece's recipe — bounded and undistorted however far you panned, at
// the cost of the corner handles.
const MODES = [
- { id: 'planar', label: 'Planar', hint: 'One flat surface — a facade, the ground, a map. Pieces stay warpable.' },
+ { id: 'planar', label: 'Planar', hint: 'One flat surface such as a facade, the ground or a map. Pieces stay warpable.' },
{ id: 'cylindrical', label: 'Cylindrical', hint: 'A camera panning sideways. Bounded and even end to end.' },
{ id: 'spherical', label: 'Spherical', hint: 'A camera that pans *and* tilts. Same, over both axes.' },
];
@@ -157,7 +157,7 @@
selectedIds = [];
const placed = res.nodes.length;
if (res.dropped.length) {
- toast(`Stitched ${placed} — ${res.dropped.length} left in place (no overlap found)`, 'warn');
+ toast(`Stitched ${placed}. ${res.dropped.length} left in place because no overlap was found`, 'warn');
} else {
toast(`Stitched ${placed} pieces`, 'ok');
}
@@ -218,7 +218,7 @@
{#if session.frames.length === 0}<p class="empty">No frames captured yet.</p>{/if}
</div>
- <p class="hint">Exported as a <strong>transparent PNG</strong> — only the pieces, trimmed to their bounds on save.</p>
+ <p class="hint">Exports only the pieces as a <strong>transparent PNG</strong>, trimmed to their bounds.</p>
{#if selected}
<div class="section">
@@ -276,7 +276,7 @@
<div class="section-head"><span>Auto panorama</span></div>
<p class="hint">
Solves the layout from the overlapping imagery itself, then drops the pieces back on the
- canvas — still draggable, so you can hand-tune the machine's guess.
+ canvas. You can still drag pieces to correct the result.
</p>
<div class="modes">
{#each MODES as m (m.id)}
@@ -413,7 +413,7 @@
bottom: 3px;
right: 3px;
background: var(--accent);
- color: #10141c;
+ color: var(--accent-text);
border-radius: 4px;
display: flex;
padding: 1px;
diff --git a/frontend/src/tools/inspect/FrameMenu.svelte b/frontend/src/tools/inspect/FrameMenu.svelte
index 84af6e2..e2654bf 100644
--- a/frontend/src/tools/inspect/FrameMenu.svelte
+++ b/frontend/src/tools/inspect/FrameMenu.svelte
@@ -1,10 +1,11 @@
<script>
import { api } from '../../lib/api.js';
import { caseState, toast } from '../../lib/state.svelte.js';
- import { adjustDefaults, buildOps, previewStyle, cropImgStyle, styleText } from '../../lib/inspect.js';
+ import { adjustDefaults, buildFrameOps, previewStyle, cropImgStyle, styleText } from '../../lib/inspect.js';
import Icon from '../../components/Icon.svelte';
import AdjustSliders from './AdjustSliders.svelte';
import CropControls from './CropControls.svelte';
+ import OrientationControls from './OrientationControls.svelte';
// Right-panel menu for the Frame tab. Works on the *active* tray frame:
// pick it, adjust it (live-previewed), crop it, or analyse it — all without
@@ -12,6 +13,7 @@
let {
session, filters, analyses, activeFrame, shared, removeFrame, setActive,
cropAspect = $bindable(null), cropEditing = $bindable(false), beginCrop, commitCrop,
+ setRotation, rotationBusy = false,
} = $props();
let showAnalyze = $state(false);
@@ -19,13 +21,14 @@
let analysis = $state(null);
let canvasEl = $state();
- function reset() {
+ async function reset() {
if (!activeFrame) return;
activeFrame.adjust = adjustDefaults(filters);
activeFrame.crop = null;
shared.cropMode = false;
cropAspect = null;
cropEditing = false;
+ await setRotation(0);
}
function clearCrop() {
@@ -44,7 +47,7 @@
path: activeFrame.path,
name,
time: activeFrame.time ?? null,
- ops: buildOps(filters, activeFrame.adjust, activeFrame.crop),
+ ops: buildFrameOps(filters, activeFrame),
});
if (analysis.kind === 'histogram') requestAnimationFrame(drawHistogram);
} catch (e) {
@@ -104,6 +107,13 @@
{#if activeFrame}
<div class="section">
+ <div class="section-head"><span>Orientation</span></div>
+ <OrientationControls
+ value={activeFrame.rotation ?? 0}
+ disabled={rotationBusy}
+ onchange={setRotation}
+ hint="The saved image uses this orientation."
+ />
<AdjustSliders {filters} values={activeFrame.adjust} />
<div class="crop-block">
<div class="crop-row">
@@ -230,7 +240,7 @@
bottom: 2px;
left: 2px;
background: var(--accent);
- color: #10141c;
+ color: var(--accent-text);
border-radius: 4px;
display: flex;
padding: 1px;
diff --git a/frontend/src/tools/inspect/OrientationControls.svelte b/frontend/src/tools/inspect/OrientationControls.svelte
new file mode 100644
index 0000000..18eec0d
--- /dev/null
+++ b/frontend/src/tools/inspect/OrientationControls.svelte
@@ -0,0 +1,33 @@
+<script>
+ import { RIGHT_ANGLE_ROTATIONS } from '../../lib/inspect.js';
+
+ let { value = 0, disabled = false, onchange, hint } = $props();
+</script>
+
+<div class="rotation-options">
+ {#each RIGHT_ANGLE_ROTATIONS as angle (angle)}
+ <button
+ class="btn btn-sm"
+ class:active={value === angle}
+ aria-pressed={value === angle}
+ {disabled}
+ onclick={() => onchange(angle)}
+ >
+ {angle > 0 ? '+' : ''}{angle}°
+ </button>
+ {/each}
+</div>
+{#if hint}<p class="hint">{hint}</p>{/if}
+
+<style>
+ .rotation-options {
+ display: grid;
+ grid-template-columns: repeat(5, 1fr);
+ gap: 6px;
+ }
+ .hint {
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ margin: 0;
+ }
+</style>
diff --git a/frontend/src/tools/inspect/PieceCropModal.svelte b/frontend/src/tools/inspect/PieceCropModal.svelte
index 4832325..29905bd 100644
--- a/frontend/src/tools/inspect/PieceCropModal.svelte
+++ b/frontend/src/tools/inspect/PieceCropModal.svelte
@@ -12,11 +12,21 @@
let { node, onapply, onclose } = $props();
let imgEl = $state();
- let natW = $state(node.w ?? null);
- let natH = $state(node.h ?? null);
- let crop = $state(node.crop ? { ...node.crop } : null);
+ let sourceNode = $state();
+ let natW = $state(null);
+ let natH = $state(null);
+ let crop = $state(null);
let aspect = $state(null);
- let draw = $state(!node.crop);
+ let draw = $state(false);
+
+ $effect(() => {
+ if (sourceNode === node) return;
+ sourceNode = node;
+ natW = node.w ?? null;
+ natH = node.h ?? null;
+ crop = node.crop ? { ...node.crop } : null;
+ draw = !node.crop;
+ });
function onImgLoad(e) {
natW = e.currentTarget.naturalWidth;
diff --git a/frontend/src/tools/inspect/SaveGallery.svelte b/frontend/src/tools/inspect/SaveGallery.svelte
index 2ad93fd..6718a08 100644
--- a/frontend/src/tools/inspect/SaveGallery.svelte
+++ b/frontend/src/tools/inspect/SaveGallery.svelte
@@ -30,7 +30,7 @@
<CollagePreview collage={it.collage} />
{/if}
{:else if it.thumb}
- <img src={it.thumb} alt={it.label} style:filter={it.filter} />
+ <img src={it.thumb} alt={it.label} style:filter={it.filter} style:transform={it.transform} />
{:else}
<Icon name={it.kind === 'collage' ? 'layers' : it.kind === 'video' ? 'video' : 'image'} size={30} />
{/if}
@@ -147,7 +147,7 @@
.card.sel .tick {
background: var(--accent);
border-color: var(--accent);
- color: #10141c;
+ color: var(--accent-text);
}
.label {
font-size: var(--fs-sm);
diff --git a/frontend/src/tools/inspect/SaveMenu.svelte b/frontend/src/tools/inspect/SaveMenu.svelte
index ea2e7c1..1c0afff 100644
--- a/frontend/src/tools/inspect/SaveMenu.svelte
+++ b/frontend/src/tools/inspect/SaveMenu.svelte
@@ -1,6 +1,7 @@
<script>
import { caseState, uiState } from '../../lib/state.svelte.js';
import Icon from '../../components/Icon.svelte';
+ import FolderSelect from '../../components/FolderSelect.svelte';
// Right-panel menu for the Save tab: choose a destination folder and commit the
// ticked items. This is the *only* place the Inspect session files case
@@ -26,13 +27,10 @@
<button class="btn btn-sm" onclick={selectNone} disabled={!count}>Clear</button>
</div>
- <label class="folder">
+ <div class="folder">
<span><Icon name="folder" size={14} /> Folder (optional)</span>
- <input list="inspect-folders" placeholder="Unfiled" bind:value={saveUi.folder} />
- <datalist id="inspect-folders">
- {#each folders as f (f)}<option value={f}></option>{/each}
- </datalist>
- </label>
+ <FolderSelect bind:value={saveUi.folder} {folders} emptyLabel="Unfiled" />
+ </div>
<button class="btn btn-primary w-full" disabled={saving || !count} onclick={save}>
<Icon name="save" size={15} /> {saving ? 'Saving…' : `Save ${count || ''} to case`.trim()}
@@ -70,14 +68,6 @@
align-items: center;
gap: 6px;
}
- .folder input {
- background: var(--bg-2);
- border: 1px solid var(--border);
- border-radius: var(--r-sm);
- padding: 6px 8px;
- color: var(--text-1);
- font-size: var(--fs-sm);
- }
.w-full {
width: 100%;
justify-content: center;
diff --git a/frontend/src/tools/inspect/SelectionMenu.svelte b/frontend/src/tools/inspect/SelectionMenu.svelte
index c681585..0911cba 100644
--- a/frontend/src/tools/inspect/SelectionMenu.svelte
+++ b/frontend/src/tools/inspect/SelectionMenu.svelte
@@ -4,6 +4,7 @@
import { adjustDefaults, isNeutral } from '../../lib/inspect.js';
import Icon from '../../components/Icon.svelte';
import AdjustSliders from './AdjustSliders.svelte';
+ import OrientationControls from './OrientationControls.svelte';
// Right-panel menu for the Selection tab: scrub the video, capture frames into
// the transient tray (nothing is filed here), and tune video-level adjustments
@@ -93,9 +94,18 @@
</button>
<p class="hint tray-note">
<Icon name="layers" size={12} /> {session.frames.length} frame{session.frames.length === 1 ? '' : 's'}
- in tray — nothing is saved until the Save tab.
+ in the tray. Nothing is saved until you use the Save tab.
</p>
+ <div class="section">
+ <div class="section-head"><span>Orientation</span></div>
+ <OrientationControls
+ value={session.videoRotation}
+ onchange={(angle) => (session.videoRotation = angle)}
+ hint="The saved video and any new frames use this orientation."
+ />
+ </div>
+
<div class="section">
<button class="section-head as-btn" onclick={() => (showGear = !showGear)}>
<span><Icon name="settings" size={14} /> Video adjustments {#if gearActive}<span class="dot"></span>{/if}</span>
@@ -118,7 +128,7 @@
{scanning ? 'Scanning…' : 'Scan'}
</button>
</div>
- <p class="hint">Samples the clip and ranks frames by focus — sharper is higher.</p>
+ <p class="hint">Samples the clip and ranks frames by focus. Higher scores are sharper.</p>
{#each suggestions as s (s.time)}
<div class="sugg" class:top={s.rank === 0}>
<span class="mono">{fmt(s.time)}</span>
diff --git a/frontend/src/tools/inspect/VideoPlayer.svelte b/frontend/src/tools/inspect/VideoPlayer.svelte
new file mode 100644
index 0000000..8379af7
--- /dev/null
+++ b/frontend/src/tools/inspect/VideoPlayer.svelte
@@ -0,0 +1,171 @@
+<script>
+ import Icon from '../../components/Icon.svelte';
+
+ let {
+ src,
+ filter = '',
+ transform = '',
+ quarterTurn = false,
+ duration = 0,
+ currentTime = 0,
+ video = $bindable(),
+ ontimeupdate,
+ } = $props();
+
+ let shell = $state();
+ let canvas = $state();
+ let canvasSize = $state({ width: 0, height: 0 });
+ let paused = $state(true);
+ let muted = $state(false);
+ let mediaDuration = $state(0);
+
+ const totalDuration = $derived(duration || mediaDuration || 0);
+ const maxWidth = $derived(
+ canvasSize.width ? `${quarterTurn ? canvasSize.height : canvasSize.width}px` : undefined
+ );
+ const maxHeight = $derived(
+ canvasSize.height ? `${quarterTurn ? canvasSize.width : canvasSize.height}px` : undefined
+ );
+
+ $effect(() => {
+ if (!canvas) return;
+ const update = () => {
+ const rect = canvas.getBoundingClientRect();
+ canvasSize = { width: rect.width, height: rect.height };
+ };
+ update();
+ const observer = new ResizeObserver(update);
+ observer.observe(canvas);
+ return () => observer.disconnect();
+ });
+
+ function togglePlayback() {
+ if (!video) return;
+ if (video.paused) video.play().catch(() => {});
+ else video.pause();
+ }
+
+ function seek(e) {
+ if (!video) return;
+ video.currentTime = Number(e.currentTarget.value);
+ ontimeupdate(video.currentTime);
+ }
+
+ function toggleMute() {
+ if (!video) return;
+ video.muted = !video.muted;
+ muted = video.muted;
+ }
+
+ function toggleFullscreen() {
+ if (document.fullscreenElement === shell) document.exitFullscreen?.();
+ else shell?.requestFullscreen?.();
+ }
+
+ function fmt(value) {
+ const seconds = Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
+ return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;
+ }
+</script>
+
+<div class="video-shell" bind:this={shell}>
+ <div class="video-canvas" bind:this={canvas}>
+ <!-- svelte-ignore a11y_media_has_caption -->
+ <video
+ bind:this={video}
+ {src}
+ playsinline
+ onloadedmetadata={() => (mediaDuration = video?.duration ?? 0)}
+ ontimeupdate={() => ontimeupdate(video?.currentTime ?? 0)}
+ onplay={() => (paused = false)}
+ onpause={() => (paused = true)}
+ onvolumechange={() => (muted = video?.muted ?? false)}
+ style:filter
+ style:max-width={maxWidth}
+ style:max-height={maxHeight}
+ style:transform
+ ></video>
+ </div>
+ <div class="player-bar">
+ <button class="player-btn" onclick={togglePlayback} aria-label={paused ? 'Play' : 'Pause'}>
+ <Icon name={paused ? 'play' : 'pause'} size={16} />
+ </button>
+ <input
+ class="player-seek"
+ type="range"
+ min="0"
+ max={totalDuration}
+ step="any"
+ value={currentTime}
+ oninput={seek}
+ aria-label="Video position"
+ />
+ <span class="player-time mono">{fmt(currentTime)} / {fmt(totalDuration)}</span>
+ <button class="player-btn" onclick={toggleMute} aria-label={muted ? 'Unmute' : 'Mute'}>
+ <Icon name={muted ? 'volumeOff' : 'volume'} size={16} />
+ </button>
+ <button class="player-btn" onclick={toggleFullscreen} aria-label="Full screen">
+ <Icon name="maximize" size={16} />
+ </button>
+ </div>
+</div>
+
+<style>
+ .video-shell {
+ width: 100%;
+ height: 100%;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+ background: var(--bg-0);
+ }
+ .video-canvas {
+ position: relative;
+ flex: 1;
+ min-height: 0;
+ overflow: hidden;
+ }
+ .video-canvas video {
+ position: absolute;
+ inset: 0;
+ margin: auto;
+ display: block;
+ transform-origin: center;
+ box-shadow: var(--shadow-2);
+ }
+ .player-bar {
+ flex-shrink: 0;
+ min-height: 40px;
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 7px 9px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-1);
+ }
+ .player-btn {
+ width: 28px;
+ height: 28px;
+ flex: 0 0 28px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ border-radius: var(--r-sm);
+ color: var(--text-2);
+ }
+ .player-btn:hover {
+ color: var(--text-1);
+ background: var(--bg-2);
+ }
+ .player-seek {
+ flex: 1;
+ min-width: 60px;
+ accent-color: var(--accent);
+ }
+ .player-time {
+ flex-shrink: 0;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+</style>
diff --git a/frontend/src/tools/inspect/VideoPlayer.test.js b/frontend/src/tools/inspect/VideoPlayer.test.js
new file mode 100644
index 0000000..442de14
--- /dev/null
+++ b/frontend/src/tools/inspect/VideoPlayer.test.js
@@ -0,0 +1,26 @@
+import { describe, expect, it } from 'vitest';
+import { render } from 'svelte/server';
+import VideoPlayer from './VideoPlayer.svelte';
+
+describe('Inspect video player', () => {
+ it('keeps an unrotated control bar outside the transformed video canvas', () => {
+ const { body } = render(VideoPlayer, {
+ props: {
+ src: '/files/case/media/clip.mp4',
+ transform: 'rotate(90deg)',
+ quarterTurn: true,
+ duration: 125,
+ currentTime: 5,
+ ontimeupdate: () => {},
+ },
+ });
+
+ expect(body).toContain('class="video-canvas ');
+ expect(body).toContain('style="transform: rotate(90deg);"');
+ expect(body).toContain('class="player-bar ');
+ expect(body.indexOf('class="player-bar ')).toBeGreaterThan(body.indexOf('</video>'));
+ expect(body).toContain('aria-label="Video position"');
+ expect(body).toContain('0:05 / 2:05');
+ expect(body).not.toContain(' controls');
+ });
+});
diff --git a/frontend/src/tools/proof/NewProofDialog.svelte b/frontend/src/tools/proof/NewProofDialog.svelte
new file mode 100644
index 0000000..7661e44
--- /dev/null
+++ b/frontend/src/tools/proof/NewProofDialog.svelte
@@ -0,0 +1,239 @@
+<script>
+ import Icon from '../../components/Icon.svelte';
+ import Modal from '../../components/Modal.svelte';
+
+ let {
+ name = $bindable(),
+ templateId = $bindable(),
+ panelPaths = $bindable(),
+ query = $bindable(),
+ category = $bindable(),
+ templates,
+ items,
+ filteredItems,
+ loading,
+ creating,
+ caseId,
+ togglePanel,
+ requestCreation,
+ close,
+ } = $props();
+</script>
+
+<Modal title="Create proof" onclose={() => { if (!creating) close(); }} width="780px">
+ <form class="new-proof-form" onsubmit={(event) => { event.preventDefault(); requestCreation(); }}>
+ <label class="new-proof-field">
+ <span>Name</span>
+ <input class="input" bind:value={name} maxlength="200" placeholder="Proof name" />
+ </label>
+
+ <label class="new-proof-field">
+ <span>Template</span>
+ <select class="input" bind:value={templateId}>
+ <option value="">No template</option>
+ {#each templates as template (template.id)}
+ <option value={template.id}>{template.name}</option>
+ {/each}
+ </select>
+ <small>Sets the look without choosing content.</small>
+ </label>
+
+ <fieldset class="new-proof-panels">
+ <legend>
+ <span>Panels</span>
+ <span class="selected-count">
+ {panelPaths.length} panel{panelPaths.length === 1 ? '' : 's'} selected
+ </span>
+ </legend>
+
+ <div class="panel-picker-bar">
+ <div class="panel-search">
+ <Icon name="search" size={13} />
+ <input placeholder="Search panels…" bind:value={query} />
+ {#if query}
+ <button type="button" onclick={() => (query = '')} aria-label="Clear search">
+ <Icon name="x" size={12} />
+ </button>
+ {/if}
+ </div>
+ <div class="panel-categories" aria-label="Panel categories">
+ <button type="button" class:active={category === 'all'} onclick={() => (category = 'all')}>
+ All <span>{items.length}</span>
+ </button>
+ <button type="button" class:active={category === 'satellite'} onclick={() => (category = 'satellite')}>
+ Satellite captures <span>{items.filter((item) => item.kind === 'satellite').length}</span>
+ </button>
+ <button type="button" class:active={category === 'media'} onclick={() => (category = 'media')}>
+ Other images <span>{items.filter((item) => item.kind === 'media').length}</span>
+ </button>
+ </div>
+ </div>
+
+ {#if loading}
+ <div class="picker-empty">Loading case images…</div>
+ {:else if !items.length}
+ <div class="picker-empty">No case images yet, but you can add panels later.</div>
+ {:else if !filteredItems.length}
+ <div class="picker-empty">No panels match this search.</div>
+ {:else}
+ <div class="pick-grid new-proof-grid">
+ {#each filteredItems as item (item.src)}
+ <button
+ type="button"
+ class="pick card selectable-pick"
+ class:selected={panelPaths.includes(item.src)}
+ aria-pressed={panelPaths.includes(item.src)}
+ onclick={() => togglePanel(item.src)}
+ >
+ <span class="pick-image">
+ <img src={`/files/${caseId}/${item.thumb}`} alt="" loading="lazy" />
+ {#if panelPaths.includes(item.src)}
+ <span class="pick-selected"><Icon name="check" size={13} /></span>
+ {/if}
+ </span>
+ <span class="pick-label" title={item.label}>
+ <Icon name={item.kind === 'satellite' ? 'satellite' : 'image'} size={12} />
+ {item.label}
+ </span>
+ </button>
+ {/each}
+ </div>
+ {/if}
+ </fieldset>
+
+ <div class="new-proof-actions">
+ <button type="button" class="btn" disabled={creating} onclick={close}>Cancel</button>
+ <button type="submit" class="btn btn-primary" disabled={!name.trim() || creating}>
+ <Icon name="plus" size={15} /> {creating ? 'Creating…' : 'Create proof'}
+ </button>
+ </div>
+ </form>
+</Modal>
+
+<style>
+ .new-proof-form { display: flex; flex-direction: column; gap: 15px; }
+ .new-proof-field {
+ display: grid;
+ grid-template-columns: 110px minmax(0, 1fr);
+ align-items: center;
+ gap: 5px 12px;
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ }
+ .new-proof-field small { grid-column: 2; color: var(--text-3); font-weight: 400; }
+ .new-proof-panels { min-width: 0; padding: 0; border: 0; }
+ .new-proof-panels legend {
+ width: 100%;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 7px;
+ font-size: var(--fs-xs);
+ font-weight: 700;
+ color: var(--text-2);
+ }
+ .selected-count { color: var(--text-3); font-weight: 500; }
+ .panel-picker-bar {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 7px;
+ margin-bottom: 10px;
+ min-width: 0;
+ }
+ .panel-search {
+ min-width: 170px;
+ flex: 1;
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 5px 8px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ color: var(--text-3);
+ }
+ .panel-search:focus-within { border-color: var(--accent); }
+ .panel-search input {
+ width: 100%;
+ min-width: 0;
+ border: 0;
+ outline: 0;
+ background: transparent;
+ color: var(--text-1);
+ font: inherit;
+ }
+ .panel-search button { display: flex; color: var(--text-3); }
+ .panel-categories { display: flex; gap: 5px; overflow-x: auto; max-width: 100%; }
+ .panel-categories button {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ padding: 5px 8px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ white-space: nowrap;
+ }
+ .panel-categories button:hover { border-color: var(--border-strong); color: var(--text-1); }
+ .panel-categories button.active { border-color: var(--accent); color: var(--text-1); }
+ .panel-categories span { color: var(--text-3); }
+ .pick-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
+ gap: 10px;
+ }
+ .new-proof-grid { max-height: min(42vh, 390px); overflow-y: auto; padding: 1px; }
+ .pick {
+ overflow: hidden;
+ text-align: left;
+ transition: border-color 0.15s var(--ease);
+ }
+ .pick:hover, .selectable-pick.selected { border-color: var(--accent); }
+ .selectable-pick { position: relative; }
+ .pick img {
+ width: 100%;
+ aspect-ratio: 16 / 11;
+ object-fit: cover;
+ background: var(--bg-2);
+ }
+ .pick-image { position: relative; display: block; }
+ .pick-selected {
+ position: absolute;
+ top: 6px;
+ right: 6px;
+ width: 22px;
+ height: 22px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ border-radius: 50%;
+ background: var(--accent);
+ color: var(--accent-text);
+ }
+ .pick-label {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ padding: 6px 8px;
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .picker-empty {
+ min-height: 120px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 20px;
+ border: 1px dashed var(--border);
+ border-radius: var(--r-md);
+ color: var(--text-3);
+ font-size: var(--fs-sm);
+ }
+ .new-proof-actions { display: flex; justify-content: flex-end; gap: 8px; padding-top: 2px; }
+</style>
diff --git a/frontend/src/tools/proof/ProofCanvas.svelte b/frontend/src/tools/proof/ProofCanvas.svelte
new file mode 100644
index 0000000..53e2f7e
--- /dev/null
+++ b/frontend/src/tools/proof/ProofCanvas.svelte
@@ -0,0 +1,85 @@
+<script>
+ import Icon from '../../components/Icon.svelte';
+
+ let {
+ containerEl = $bindable(),
+ tool,
+ textEdit,
+ focusSelect,
+ commitTextEdit,
+ proofHasContent,
+ proofStarted,
+ openPicker,
+ openNewProofDialog,
+ } = $props();
+</script>
+
+<div class="canvas-wrap" class:drawing={tool !== 'select'}>
+ <div class="konva" bind:this={containerEl}></div>
+ {#if textEdit}
+ <input
+ class="text-edit"
+ style:left={`${textEdit.left}px`}
+ style:top={`${textEdit.top}px`}
+ style:font-size={`${textEdit.size}px`}
+ style:color={textEdit.color}
+ bind:value={textEdit.value}
+ use:focusSelect
+ onblur={() => commitTextEdit(true)}
+ onkeydown={(event) => {
+ event.stopPropagation();
+ if (event.key === 'Enter') commitTextEdit(true);
+ else if (event.key === 'Escape') commitTextEdit(false);
+ }}
+ />
+ {/if}
+ {#if !proofHasContent}
+ <div class="empty overlay-empty">
+ <div class="empty-icon"><Icon name="proof" size={42} /></div>
+ {#if proofStarted}
+ <h3>No panels yet</h3>
+ <p>Add panels when you are ready.</p>
+ <button class="btn" onclick={openPicker}>
+ <Icon name="plus" size={15} /> Add panel
+ </button>
+ {:else}
+ <h3>Compose a proof</h3>
+ <p>Create a proof to choose its template and starting panels.</p>
+ <button class="btn" onclick={openNewProofDialog}>
+ <Icon name="plus" size={15} /> New proof
+ </button>
+ {/if}
+ </div>
+ {/if}
+</div>
+
+<style>
+ .canvas-wrap {
+ position: relative;
+ flex: 1;
+ min-width: 0;
+ background:
+ radial-gradient(circle at 1px 1px, rgba(148, 163, 196, 0.07) 1px, transparent 0) 0 0 / 22px 22px,
+ var(--bg-0);
+ }
+ .canvas-wrap.drawing { cursor: crosshair; }
+ .konva { position: absolute; inset: 0; }
+ .text-edit {
+ position: absolute;
+ transform: translateY(-2px);
+ min-width: 60px;
+ padding: 0 2px;
+ font-family: system-ui, sans-serif;
+ font-weight: 700;
+ background: rgba(14, 14, 14, 0.85);
+ border: 1px dashed var(--accent);
+ border-radius: 2px;
+ outline: none;
+ }
+ .overlay-empty {
+ position: absolute;
+ inset: 0;
+ pointer-events: none;
+ }
+ .overlay-empty .btn { pointer-events: auto; }
+</style>
diff --git a/frontend/src/tools/proof/ProofLayersPanel.svelte b/frontend/src/tools/proof/ProofLayersPanel.svelte
new file mode 100644
index 0000000..af4aabb
--- /dev/null
+++ b/frontend/src/tools/proof/ProofLayersPanel.svelte
@@ -0,0 +1,418 @@
+<script>
+ import Icon from '../../components/Icon.svelte';
+
+ let {
+ proof,
+ collapsed,
+ gonePanels,
+ selectedPanelId = $bindable(),
+ selectedId = $bindable(),
+ activeColor,
+ caseId,
+ scaleMin,
+ scaleMax,
+ scaleStep,
+ openPicker,
+ movePanelZ,
+ scalePanel,
+ removePanel,
+ featureList,
+ moveLegendColor,
+ setColor,
+ canMoveShapeUp,
+ canMoveShapeDown,
+ moveShape,
+ kindIcon,
+ kindLabel,
+ duplicateShape,
+ deleteShape,
+ markDirty,
+ } = $props();
+</script>
+
+<div class="side-title-row" style="margin-top: 14px">
+ <button class="side-title collapsible" onclick={() => (collapsed.panels = !collapsed.panels)}>
+ <span>
+ <Icon name={collapsed.panels ? 'chevronRight' : 'chevronDown'} size={13} />
+ Panels <span class="count">{proof.panels.length}</span>
+ </span>
+ </button>
+ <button class="btn btn-ghost btn-sm side-add" title="Add a panel" onclick={openPicker}>
+ <Icon name="plus" size={13} />
+ </button>
+</div>
+{#if !collapsed.panels}
+ {#if gonePanels.length}
+ <div class="gone-note">
+ <Icon name="alert" size={12} />
+ <span>
+ {gonePanels.length} panel{gonePanels.length > 1 ? 's' : ''} whose media was deleted.
+ The proof still exports; reopening it later will show them blank.
+ </span>
+ </div>
+ {/if}
+ {#each proof.panels as panel, index (panel.id)}
+ <div
+ class="panel-row card"
+ class:selected={selectedPanelId === panel.id}
+ class:gone={gonePanels.includes(panel)}
+ >
+ <button
+ class="panel-thumb"
+ title="Select this panel on the canvas"
+ onclick={() => (selectedPanelId = selectedPanelId === panel.id ? null : panel.id)}
+ >
+ <img src={`/files/${caseId}/${panel.src}`} alt="" />
+ {#if proof.layout === 'free'}
+ <span class="row-badge" title="Z1 is the foreground">Z{index + 1}</span>
+ {:else}
+ <span class="row-badge" title="Row (top→bottom)">R{(panel.row ?? 0) + 1}</span>
+ {/if}
+ </button>
+ <input
+ class="input cap-input"
+ placeholder="Caption…"
+ bind:value={panel.caption}
+ onchange={markDirty}
+ />
+ <div class="panel-actions">
+ {#if proof.layout === 'free'}
+ <button
+ class="btn btn-ghost btn-sm"
+ disabled={index === 0}
+ title="Bring forward (toward Z1)"
+ onclick={() => movePanelZ(index, -1)}
+ ><Icon name="chevronUp" size={13} /></button>
+ <button
+ class="btn btn-ghost btn-sm"
+ disabled={index === proof.panels.length - 1}
+ title="Send backward"
+ onclick={() => movePanelZ(index, 1)}
+ ><Icon name="chevronDown" size={13} /></button>
+ {/if}
+ <div class="panel-scale" title="Panel size; elements scale with it">
+ <button
+ class="btn btn-ghost btn-sm"
+ disabled={(panel.scale ?? 1) <= scaleMin}
+ title="Shrink panel"
+ onclick={() => scalePanel(index, -scaleStep)}
+ >−</button>
+ <span class="scale-val">{Math.round((panel.scale ?? 1) * 100)}%</span>
+ <button
+ class="btn btn-ghost btn-sm"
+ disabled={(panel.scale ?? 1) >= scaleMax}
+ title="Enlarge panel"
+ onclick={() => scalePanel(index, scaleStep)}
+ >+</button>
+ </div>
+ <button
+ class="btn btn-ghost btn-sm remove-panel"
+ title="Remove panel"
+ onclick={() => removePanel(index)}
+ ><Icon name="trash" size={13} /></button>
+ </div>
+ </div>
+ {/each}
+{/if}
+
+<button
+ class="side-title collapsible spaced"
+ onclick={() => (collapsed.annotations = !collapsed.annotations)}
+>
+ <span>
+ <Icon name={collapsed.annotations ? 'chevronRight' : 'chevronDown'} size={13} />
+ Annotations <span class="count">{featureList.length}</span>
+ </span>
+</button>
+{#if !collapsed.annotations}
+ {#if !featureList.length}
+ <div class="none">Draw on a panel. Same color = same feature.</div>
+ {/if}
+ {#each featureList as entry, index (entry)}
+ <div class="anno-row" class:active={activeColor === entry}>
+ <div class="reorder">
+ <button class="btn btn-ghost reorder-btn" disabled={index === 0} title="Move up" onclick={() => moveLegendColor(index, -1)}>
+ <Icon name="chevronUp" size={11} />
+ </button>
+ <button class="btn btn-ghost reorder-btn" disabled={index === featureList.length - 1} title="Move down" onclick={() => moveLegendColor(index, 1)}>
+ <Icon name="chevronDown" size={11} />
+ </button>
+ </div>
+ <button class="chip-num" style:background={entry} title="Select this color" onclick={() => setColor(entry)}>
+ {index + 1}
+ </button>
+ <input
+ class="input comment-input"
+ placeholder={`Feature ${index + 1} legend…`}
+ bind:value={proof.notes[entry]}
+ onchange={markDirty}
+ />
+ </div>
+ {/each}
+{/if}
+
+<button
+ class="side-title collapsible spaced"
+ onclick={() => (collapsed.elements = !collapsed.elements)}
+>
+ <span>
+ <Icon name={collapsed.elements ? 'chevronRight' : 'chevronDown'} size={13} />
+ Elements <span class="count">{proof.shapes.length}</span>
+ </span>
+</button>
+{#if !collapsed.elements}
+ {#each proof.shapes as shape, index (shape.id)}
+ <div
+ class="shape-row"
+ class:selected={selectedId === shape.id}
+ onclick={() => (selectedId = shape.id)}
+ role="button"
+ tabindex="0"
+ onkeydown={(event) => event.key === 'Enter' && (selectedId = shape.id)}
+ >
+ <div class="reorder">
+ <button
+ class="btn btn-ghost reorder-btn"
+ disabled={!canMoveShapeUp(index)}
+ title="Move up (z-order within its panel)"
+ onclick={(event) => { event.stopPropagation(); moveShape(index, -1); }}
+ ><Icon name="chevronUp" size={11} /></button>
+ <button
+ class="btn btn-ghost reorder-btn"
+ disabled={!canMoveShapeDown(index)}
+ title="Move down (z-order within its panel)"
+ onclick={(event) => { event.stopPropagation(); moveShape(index, 1); }}
+ ><Icon name="chevronDown" size={11} /></button>
+ </div>
+ <span class="chip" style:background={shape.color}></span>
+ <Icon name={kindIcon[shape.kind]} size={13} />
+ {#if shape.kind === 'text'}
+ <input
+ class="input comment-input"
+ placeholder="Text…"
+ bind:value={shape.text}
+ onchange={markDirty}
+ onclick={(event) => event.stopPropagation()}
+ />
+ <button
+ class="btn btn-ghost btn-sm"
+ class:active={shape.frame}
+ title="Frame (border in the text's color)"
+ onclick={(event) => {
+ event.stopPropagation();
+ shape.frame = !shape.frame;
+ markDirty();
+ }}
+ ><Icon name="square" size={13} /></button>
+ <label
+ class="color-btn color-pick bg-pick"
+ class:active={!!shape.bg}
+ style:background={shape.bg || 'transparent'}
+ title="Background color"
+ >
+ <Icon name="plus" size={11} />
+ <input
+ type="color"
+ value={shape.bg || '#000000'}
+ oninput={(event) => { shape.bg = event.target.value; markDirty(); }}
+ onclick={(event) => event.stopPropagation()}
+ aria-label="text background color"
+ />
+ </label>
+ {#if shape.bg}
+ <button
+ class="btn btn-ghost btn-sm"
+ title="Remove background"
+ onclick={(event) => { event.stopPropagation(); shape.bg = null; markDirty(); }}
+ ><Icon name="x" size={11} /></button>
+ {/if}
+ {:else}
+ <span class="el-label">{kindLabel[shape.kind]} <span class="el-id">#{index + 1}</span></span>
+ {/if}
+ <button
+ class="btn btn-ghost btn-sm"
+ title="Duplicate (Ctrl+D)"
+ onclick={(event) => { event.stopPropagation(); duplicateShape(shape.id); }}
+ ><Icon name="copy" size={13} /></button>
+ <button
+ class="btn btn-ghost btn-sm"
+ title="Delete"
+ onclick={(event) => { event.stopPropagation(); deleteShape(shape.id); }}
+ ><Icon name="trash" size={13} /></button>
+ </div>
+ {/each}
+{/if}
+
+<style>
+ .side-title {
+ font-size: var(--fs-xs);
+ font-weight: 700;
+ text-transform: uppercase;
+ letter-spacing: 0.07em;
+ color: var(--text-2);
+ margin-bottom: 8px;
+ display: flex;
+ justify-content: space-between;
+ }
+ .side-title.collapsible {
+ width: 100%;
+ background: none;
+ border: none;
+ padding: 0;
+ cursor: pointer;
+ text-align: left;
+ font: inherit;
+ color: inherit;
+ }
+ .side-title.collapsible span { display: flex; align-items: center; gap: 4px; }
+ .side-title.spaced { margin-top: 14px; }
+ .side-title-row { display: flex; align-items: center; gap: 4px; }
+ .side-title-row .side-title { margin-bottom: 0; }
+ .side-add { margin-left: auto; color: var(--text-3); }
+ .count { color: var(--text-3); }
+ .gone-note {
+ display: flex;
+ align-items: flex-start;
+ gap: 6px;
+ margin-bottom: 8px;
+ padding: 7px 9px;
+ border-radius: var(--r-sm);
+ font-size: var(--fs-xs);
+ line-height: 1.4;
+ color: color-mix(in srgb, var(--danger, #e5484d) 80%, var(--text-2));
+ background: color-mix(in srgb, var(--danger, #e5484d) 10%, transparent);
+ }
+ .gone-note :global(svg) { flex-shrink: 0; margin-top: 2px; }
+ .panel-row.gone { border-color: color-mix(in srgb, var(--danger, #e5484d) 40%, transparent); }
+ .panel-row {
+ padding: 8px;
+ margin-bottom: 8px;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ }
+ .panel-thumb {
+ position: relative;
+ display: block;
+ width: 100%;
+ padding: 0;
+ border: none;
+ background: none;
+ cursor: pointer;
+ }
+ .panel-row.selected { border-color: var(--accent); }
+ .panel-row img {
+ width: 100%;
+ max-height: 90px;
+ object-fit: cover;
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ display: block;
+ }
+ .row-badge {
+ position: absolute;
+ top: 5px;
+ left: 5px;
+ padding: 1px 6px;
+ border-radius: var(--r-sm);
+ font-size: 10px;
+ font-weight: 700;
+ color: var(--text-1);
+ background: rgba(14, 14, 14, 0.72);
+ }
+ .cap-input { font-size: var(--fs-xs); padding: 5px 8px; }
+ .panel-actions { display: flex; align-items: center; gap: 2px; }
+ .remove-panel { margin-left: auto; }
+ .panel-scale { display: flex; align-items: center; gap: 4px; margin: 0 auto; }
+ .scale-val {
+ min-width: 42px;
+ text-align: center;
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ color: var(--text-2);
+ font-variant-numeric: tabular-nums;
+ }
+ .none { font-size: var(--fs-xs); color: var(--text-3); padding: 2px 2px 8px; }
+ .anno-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 3px 4px;
+ border-radius: var(--r-sm);
+ margin-bottom: 4px;
+ border: 1px solid transparent;
+ }
+ .anno-row.active { border-color: var(--accent); background: var(--accent-soft); }
+ .reorder { display: flex; flex-direction: column; gap: 1px; flex-shrink: 0; }
+ .reorder-btn { padding: 0 2px; line-height: 1; color: var(--text-3); }
+ .reorder-btn:disabled { opacity: 0.25; cursor: default; }
+ .color-btn {
+ width: 22px;
+ height: 22px;
+ border-radius: 50%;
+ border: 2px solid transparent;
+ flex-shrink: 0;
+ }
+ .color-btn.active { border-color: var(--text-1); box-shadow: 0 0 0 2px var(--bg-1), 0 0 0 3.5px var(--text-3); }
+ .color-pick {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: var(--accent-text);
+ cursor: pointer;
+ position: relative;
+ overflow: hidden;
+ }
+ .color-pick input { position: absolute; inset: 0; opacity: 0; cursor: pointer; }
+ .bg-pick { width: 20px; height: 20px; flex-shrink: 0; border: 1px dashed var(--border); }
+ .bg-pick.active { border-style: solid; }
+ .bg-pick:not(.active) { color: var(--text-3); }
+ .chip-num {
+ width: 20px;
+ height: 20px;
+ border-radius: 50%;
+ flex-shrink: 0;
+ font-size: 11px;
+ font-weight: 700;
+ color: var(--accent-text);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ border: 2px solid transparent;
+ cursor: pointer;
+ }
+ .chip-num:hover { border-color: var(--text-1); }
+ .el-label {
+ flex: 1;
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .el-id { color: var(--text-3); }
+ .shape-row {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ padding: 5px 6px;
+ border-radius: var(--r-sm);
+ margin-bottom: 3px;
+ border: 1px solid transparent;
+ color: var(--text-3);
+ cursor: pointer;
+ }
+ .shape-row:hover { background: var(--bg-2); }
+ .shape-row.selected { border-color: var(--accent); background: var(--accent-soft); }
+ .chip { width: 12px; height: 12px; border-radius: 50%; flex-shrink: 0; }
+ .comment-input {
+ flex: 1;
+ font-size: var(--fs-xs);
+ padding: 4px 8px;
+ background: transparent;
+ border-color: transparent;
+ min-width: 0;
+ }
+ .comment-input:hover, .comment-input:focus { background: var(--bg-2); border-color: var(--border); }
+</style>
diff --git a/frontend/src/tools/proof/ProofToolbar.svelte b/frontend/src/tools/proof/ProofToolbar.svelte
new file mode 100644
index 0000000..8e0b210
--- /dev/null
+++ b/frontend/src/tools/proof/ProofToolbar.svelte
@@ -0,0 +1,196 @@
+<script>
+ import Icon from '../../components/Icon.svelte';
+
+ let {
+ canUndo,
+ canRedo,
+ undo,
+ redo,
+ drawTools,
+ tool = $bindable(),
+ palette,
+ activeColor,
+ selectedShape,
+ strokeW,
+ setColor,
+ setStroke,
+ fit,
+ layout,
+ setLayoutMode,
+ guide = $bindable(),
+ tweetGuides,
+ panelCount,
+ applyMagic,
+ } = $props();
+</script>
+
+<div class="toolbar">
+ <button class="tb-btn" title="Undo (Ctrl+Z)" disabled={!canUndo} onclick={undo}>
+ <Icon name="undo" size={18} />
+ </button>
+ <button class="tb-btn" title="Redo (Ctrl+Shift+Z / Ctrl+Y)" disabled={!canRedo} onclick={redo}>
+ <Icon name="redo" size={18} />
+ </button>
+ <div class="tb-sep"></div>
+ {#each drawTools as entry (entry.id)}
+ <button
+ class="tb-btn"
+ class:active={tool === entry.id}
+ title="{entry.label} ({entry.shortcut})"
+ onclick={() => (tool = entry.id)}
+ >
+ <Icon name={entry.icon} size={18} />
+ </button>
+ {/each}
+ <div class="tb-sep"></div>
+ {#each palette as entry (entry)}
+ <button
+ class="color-btn"
+ class:active={activeColor === entry}
+ style:background={entry}
+ title="Same color = same feature"
+ onclick={() => setColor(entry)}
+ aria-label={`color ${entry}`}
+ ></button>
+ {/each}
+ <label
+ class="color-btn color-pick"
+ class:active={!palette.includes(activeColor)}
+ style:background={activeColor}
+ title="Custom color"
+ >
+ <Icon name="plus" size={12} />
+ <input
+ type="color"
+ value={activeColor}
+ oninput={(event) => setColor(event.target.value)}
+ aria-label="custom color"
+ />
+ </label>
+ <div class="tb-sep"></div>
+ <input
+ class="stroke-slider"
+ type="range"
+ min={selectedShape?.kind === 'text' ? 8 : 1}
+ max={selectedShape?.kind === 'text' ? 120 : 24}
+ step="1"
+ value={selectedShape?.kind === 'text'
+ ? (selectedShape.fontSize ?? 28)
+ : (selectedShape?.strokeWidth ?? strokeW)}
+ oninput={(event) => setStroke(+event.target.value)}
+ title={selectedShape?.kind === 'text'
+ ? 'Font size'
+ : selectedShape
+ ? 'Stroke width (selected)'
+ : 'Stroke width'}
+ />
+ <div class="tb-sep"></div>
+ <button class="tb-btn" title="Fit view (f)" onclick={fit}>
+ <Icon name="eye" size={18} />
+ </button>
+ <div class="tb-sep"></div>
+ <button
+ class="tb-btn"
+ class:active={layout !== 'free'}
+ title="Grid layout: panels flow in rows"
+ onclick={() => setLayoutMode('grid')}
+ >
+ <Icon name="grid" size={18} />
+ </button>
+ <button
+ class="tb-btn"
+ class:active={layout === 'free'}
+ title="Free layout: drag panels anywhere"
+ onclick={() => setLayoutMode('free')}
+ >
+ <Icon name="layers" size={18} />
+ </button>
+ <div class="tb-sep"></div>
+ {#each Object.keys(tweetGuides) as entry (entry)}
+ <button
+ class="tb-btn tb-guide"
+ class:active={guide === entry}
+ title={`Preview the ${entry} tweet crop. Everything outside is cut off`}
+ onclick={() => (guide = guide === entry ? null : entry)}
+ >{entry}</button>
+ {/each}
+ <button
+ class="tb-btn tb-magic"
+ title={`Repack panels toward ${guide ?? '16:9'} and reset panel sizes`}
+ disabled={!panelCount}
+ onclick={applyMagic}
+ >
+ <Icon name="wand" size={18} />
+ </button>
+</div>
+
+<style>
+ .toolbar {
+ width: 52px;
+ flex-shrink: 0;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 6px;
+ padding: 12px 0;
+ border-right: 1px solid var(--border);
+ background: var(--bg-1);
+ }
+ .tb-btn {
+ width: 38px;
+ height: 38px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ border-radius: var(--r-sm);
+ color: var(--text-3);
+ }
+ .tb-btn:hover { color: var(--text-1); background: var(--bg-2); }
+ .tb-btn.active { color: var(--text-1); background: var(--bg-3); }
+ .tb-guide { font-size: 11px; font-weight: 700; }
+ .tb-magic:not(:disabled) { color: var(--accent); }
+ .tb-magic:not(:disabled):hover { background: var(--accent-soft); }
+ .tb-magic:disabled { opacity: 0.4; cursor: default; }
+ .tb-sep {
+ width: 26px;
+ height: 1px;
+ background: var(--border);
+ margin: 4px 0;
+ }
+ .color-btn {
+ width: 22px;
+ height: 22px;
+ border-radius: 50%;
+ border: 2px solid transparent;
+ transition: border-color 0.12s var(--ease);
+ flex-shrink: 0;
+ }
+ .color-btn:hover { border-color: var(--text-3); }
+ .color-btn.active {
+ border-color: var(--text-1);
+ box-shadow: 0 0 0 2px var(--bg-1), 0 0 0 3.5px var(--text-3);
+ }
+ .color-pick {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: var(--accent-text);
+ cursor: pointer;
+ position: relative;
+ overflow: hidden;
+ }
+ .color-pick input {
+ position: absolute;
+ inset: 0;
+ opacity: 0;
+ cursor: pointer;
+ }
+ .stroke-slider {
+ width: 80px;
+ transform: rotate(-90deg);
+ margin: 34px 0;
+ accent-color: var(--accent);
+ }
+ .tb-btn:disabled { opacity: 0.35; cursor: default; }
+ .tb-btn:disabled:hover { color: var(--text-3); background: none; }
+</style>
diff --git a/frontend/src/tools/proof/canvasLifecycle.js b/frontend/src/tools/proof/canvasLifecycle.js
new file mode 100644
index 0000000..54cb2f4
--- /dev/null
+++ b/frontend/src/tools/proof/canvasLifecycle.js
@@ -0,0 +1,75 @@
+/**
+ * Keep selection out of pointerdown. Selecting rebuilds the Konva document,
+ * so doing it before pointerup destroys the gesture target and can strand
+ * Firefox's drag state. A click/tap or dragend is already a settled gesture.
+ */
+export function bindPanelPointerLifecycle(group, { onPress, onSelect, onDragEnd }) {
+ const isPanelTarget = (event) =>
+ event?.target === group || event?.target?.name?.() === 'panel-hit';
+ group.on('pointerdown', (event) => {
+ if (isPanelTarget(event)) onPress(event);
+ });
+ group.on('click tap', (event) => {
+ if (isPanelTarget(event)) onSelect(event);
+ });
+ if (onDragEnd) {
+ group.on('dragend', (event) => {
+ // Konva drag events bubble. A shape dragged inside this panel must keep
+ // the shape selected and must never commit the parent panel's position.
+ if (event?.target !== group) return;
+ onSelect(event);
+ onDragEnd(event);
+ });
+ }
+}
+
+/**
+ * Coalesce document rebuilds and keep them out of an active pointer gesture.
+ * Replacing Konva nodes between pointerdown and pointerup can leave Firefox
+ * dispatching the rest of the gesture to a node that no longer exists.
+ */
+export function createCanvasRenderGate(schedule, cancel, { rebuild, refreshUi }) {
+ let pointerActive = false;
+ let rebuildPending = false;
+ let uiPending = false;
+ let frame = null;
+
+ function arm() {
+ if (pointerActive || (!rebuildPending && !uiPending) || frame !== null) return;
+ frame = schedule(() => {
+ frame = null;
+ if (pointerActive || (!rebuildPending && !uiPending)) return;
+ const needsRebuild = rebuildPending;
+ const needsUi = uiPending;
+ rebuildPending = false;
+ uiPending = false;
+ if (needsRebuild) rebuild();
+ else if (needsUi) refreshUi();
+ });
+ }
+
+ return {
+ beginPointer() {
+ pointerActive = true;
+ },
+ endPointer() {
+ pointerActive = false;
+ arm();
+ },
+ requestRebuild() {
+ rebuildPending = true;
+ arm();
+ },
+ requestUi() {
+ uiPending = true;
+ arm();
+ },
+ destroy() {
+ if (frame !== null) cancel(frame);
+ frame = null;
+ rebuildPending = false;
+ uiPending = false;
+ pointerActive = false;
+ },
+ };
+}
diff --git a/frontend/src/tools/satellite/CaptureOptions.svelte b/frontend/src/tools/satellite/CaptureOptions.svelte
new file mode 100644
index 0000000..940fc41
--- /dev/null
+++ b/frontend/src/tools/satellite/CaptureOptions.svelte
@@ -0,0 +1,233 @@
+<script>
+ import Icon from '../../components/Icon.svelte';
+ import { SIZE_MIN, SIZE_MAX, clampSize } from '../../lib/captureSize.js';
+ import { extensionVersion } from '../../lib/extBridge.js';
+
+ let {
+ menuEl = $bindable(),
+ menuOpen = $bindable(),
+ mode = $bindable(),
+ hover = $bindable(),
+ selectArmed,
+ capturing,
+ blocked,
+ widgetBase,
+ runCapture,
+ ratios,
+ ratio = $bindable(),
+ presets,
+ preset = $bindable(),
+ customWidth = $bindable(),
+ customHeight = $bindable(),
+ resolution = $bindable(),
+ openScreenshot,
+ openExtensionGate,
+ } = $props();
+</script>
+
+<div class="capture-split" role="group">
+ <button
+ class="btn btn-primary capture-main"
+ class:on={mode === 'select' && selectArmed}
+ onmouseenter={() => (hover = mode === 'center')}
+ onmouseleave={() => (hover = false)}
+ onfocusin={() => (hover = mode === 'center')}
+ onfocusout={() => (hover = false)}
+ onclick={runCapture}
+ disabled={capturing || blocked}
+ title={blocked
+ ? 'This basemap is view-only'
+ : mode === 'select'
+ ? `Draw a rectangle on the map to capture exactly that area${widgetBase ? ' (grabbed from the screen)' : ''}`
+ : `Capture the centred preset size${widgetBase ? ' (grabbed from the screen)' : ''}`}
+ >
+ {#if capturing}
+ <span class="spinner"></span> Capturing…
+ {:else if mode === 'select'}
+ <Icon name="crop" size={14} /> {selectArmed ? 'Draw box…' : 'Select area'}
+ {:else}
+ <Icon name="satellite" size={15} /> Capture
+ {/if}
+ </button>
+
+ <div class="size-menu-wrap" bind:this={menuEl}>
+ <button
+ class="btn btn-icon capture-arrow"
+ class:on={menuOpen}
+ onclick={() => (menuOpen = !menuOpen)}
+ title={widgetBase ? 'Capture mode, size & ratio' : 'Capture mode, size, ratio & resolution'}
+ aria-label="Capture options"
+ >
+ <Icon name="chevronDown" size={13} />
+ </button>
+ {#if menuOpen}
+ <div class="size-menu card">
+ <div class="menu-row">
+ <span class="menu-label">Mode</span>
+ <div class="chips">
+ <button class="chip" class:on={mode === 'center'} onclick={() => (mode = 'center')}>Capture</button>
+ <button class="chip" class:on={mode === 'select'} onclick={() => (mode = 'select')}>Select area</button>
+ </div>
+ </div>
+ <div class="menu-hint">
+ {mode === 'center' ? 'Captures the centred size below.' : 'Drag a box on the map to capture exactly it.'}
+ </div>
+
+ {#if mode === 'select'}
+ <div class="menu-row">
+ <span class="menu-label">Ratio</span>
+ <div class="chips">
+ {#each ratios as entry (entry.id)}
+ <button class="chip" class:on={ratio === entry.id} onclick={() => (ratio = entry.id)}>
+ {entry.label}
+ </button>
+ {/each}
+ </div>
+ </div>
+ <div class="menu-hint">Locks the dragged box's shape.</div>
+ {:else}
+ <div class="menu-row">
+ <span class="menu-label">Size</span>
+ <div class="chips">
+ {#each presets as entry (entry.id)}
+ <button class="chip" class:on={preset === entry.id} onclick={() => (preset = entry.id)}>
+ {entry.label}
+ </button>
+ {/each}
+ </div>
+ </div>
+ {#if preset === 'custom'}
+ <div class="custom-size" title="Custom crop size ({SIZE_MIN}–{SIZE_MAX} px)">
+ <input
+ class="input size-input"
+ type="number"
+ min={SIZE_MIN}
+ max={SIZE_MAX}
+ bind:value={customWidth}
+ onblur={() => (customWidth = clampSize(customWidth))}
+ aria-label="Crop width"
+ />
+ <span>×</span>
+ <input
+ class="input size-input"
+ type="number"
+ min={SIZE_MIN}
+ max={SIZE_MAX}
+ bind:value={customHeight}
+ onblur={() => (customHeight = clampSize(customHeight))}
+ aria-label="Crop height"
+ />
+ </div>
+ {/if}
+ {/if}
+
+ {#if widgetBase}
+ <div class="menu-row">
+ <span class="menu-label">Source</span>
+ <div class="chips">
+ {#if extensionVersion()}
+ <button class="chip" onclick={() => { menuOpen = false; openScreenshot(); }}>
+ Paste a screenshot…
+ </button>
+ {:else}
+ <button class="chip" onclick={() => { menuOpen = false; openExtensionGate(); }}>
+ Get the capture extension
+ </button>
+ {/if}
+ </div>
+ </div>
+ <div class="menu-hint">
+ {#if extensionVersion()}
+ This basemap is captured from the screen (Google's terms allow nothing
+ programmatic out of it), so the frame can't go past the map view and screen
+ pixels are the ceiling.
+ {:else}
+ This basemap is captured from the screen, so filing it needs the capture
+ extension (Google's terms allow nothing programmatic out).
+ {/if}
+ </div>
+ {:else}
+ <div class="menu-row">
+ <span class="menu-label">Resolution</span>
+ <div class="chips">
+ <button class="chip" class:on={resolution === 1} onclick={() => (resolution = 1)}>1×</button>
+ <button class="chip" class:on={resolution === 2} onclick={() => (resolution = 2)}>2×</button>
+ <button class="chip" class:on={resolution === 'max'} onclick={() => (resolution = 'max')}>Max</button>
+ </div>
+ </div>
+ <div class="menu-hint">Captures a deeper zoom for a sharper file.</div>
+ {/if}
+ </div>
+ {/if}
+ </div>
+</div>
+
+<style>
+ .capture-split { display: flex; align-items: stretch; }
+ .capture-main { border-top-right-radius: 0; border-bottom-right-radius: 0; }
+ .capture-arrow {
+ border-top-left-radius: 0;
+ border-bottom-left-radius: 0;
+ background: var(--accent);
+ border-color: transparent;
+ border-left: 1px solid rgba(0, 0, 0, 0.2);
+ color: var(--accent-text);
+ }
+ .capture-arrow:hover:not(:disabled), .size-menu-wrap .capture-arrow.on { background: var(--accent-hover); }
+ .capture-main.on { box-shadow: inset 0 0 0 2px rgba(255, 255, 255, 0.5); }
+ .spinner {
+ width: 13px;
+ height: 13px;
+ border: 2px solid var(--accent-text);
+ border-top-color: transparent;
+ border-radius: 50%;
+ animation: spin 0.7s linear infinite;
+ }
+ @keyframes spin {
+ to { transform: rotate(360deg); }
+ }
+ .custom-size {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ }
+ .size-input { width: 64px; padding: 5px 6px; font-size: var(--fs-xs); text-align: center; }
+ .btn-icon { padding: 6px 8px; }
+ .btn-icon.on { background: var(--accent); color: var(--accent-text); border-color: var(--accent); }
+ .size-menu-wrap { position: relative; display: flex; }
+ .size-menu {
+ position: absolute;
+ bottom: calc(100% + 8px);
+ right: 0;
+ width: max-content;
+ max-width: 280px;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ padding: 12px;
+ background: rgba(24, 24, 24, 0.96);
+ backdrop-filter: blur(6px);
+ box-shadow: var(--shadow-2);
+ z-index: 700;
+ }
+ .menu-row { display: flex; align-items: center; gap: 10px; justify-content: space-between; }
+ .menu-label { font-size: var(--fs-xs); color: var(--text-3); font-weight: 600; }
+ .chips { display: flex; gap: 4px; flex-wrap: wrap; justify-content: flex-end; }
+ .chip {
+ padding: 4px 9px;
+ border-radius: var(--r-sm);
+ border: 1px solid var(--border);
+ background: var(--bg-2);
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ white-space: nowrap;
+ cursor: pointer;
+ transition: border-color 0.12s, color 0.12s, background 0.12s;
+ }
+ .chip:hover { border-color: var(--border-strong); color: var(--text-1); }
+ .chip.on { border-color: var(--accent); background: var(--accent-soft); color: var(--accent); }
+ .menu-hint { font-size: 10px; color: var(--text-3); margin: -1px 0 5px; }
+ .menu-row + .custom-size { justify-content: flex-end; padding: 2px 0; }
+</style>
diff --git a/frontend/src/tools/satellite/GridSearchPanel.svelte b/frontend/src/tools/satellite/GridSearchPanel.svelte
new file mode 100644
index 0000000..86b1f28
--- /dev/null
+++ b/frontend/src/tools/satellite/GridSearchPanel.svelte
@@ -0,0 +1,327 @@
+<script>
+ import Icon from '../../components/Icon.svelte';
+
+ let {
+ collapsed = $bindable(),
+ renaming = $bindable(),
+ renameText = $bindable(),
+ commitRename,
+ startRename,
+ grid,
+ toggleHidden,
+ hidden,
+ coverage,
+ reviewKey,
+ markReview,
+ reviewToPlace,
+ stopReview,
+ startReview,
+ editArea,
+ toggleEditArea,
+ discard,
+ deleteGrid,
+ gridName,
+ cellMetres = $bindable(),
+ drawMode,
+ startDraw,
+ polygonDraft,
+ confirmPolygon,
+ cancelDraw,
+ savedGrids,
+ loadGrid,
+ } = $props();
+</script>
+
+<div class="grid-panel card" class:collapsed>
+ <div class="grid-head">
+ <button
+ class="grid-collapse"
+ onclick={() => (collapsed = !collapsed)}
+ title={collapsed ? 'Expand' : 'Collapse'}
+ aria-label={collapsed ? 'Expand panel' : 'Collapse panel'}
+ >
+ <Icon name={collapsed ? 'chevronDown' : 'chevronUp'} size={14} />
+ </button>
+ {#if renaming}
+ <!-- svelte-ignore a11y_autofocus -->
+ <input
+ class="input grid-rename"
+ bind:value={renameText}
+ autofocus
+ onblur={commitRename}
+ onkeydown={(event) => {
+ if (event.key === 'Enter') commitRename();
+ else if (event.key === 'Escape') {
+ renameText = grid.title || '';
+ renaming = false;
+ }
+ }}
+ />
+ {:else}
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
+ <span
+ class="grid-head-title"
+ class:renamable={grid}
+ ondblclick={startRename}
+ title={grid ? 'Double-click to rename' : ''}
+ >
+ {grid ? grid.title || 'Grid' : 'Grid Search'}
+ </span>
+ {/if}
+ {#if grid}
+ <button
+ class="grid-eye"
+ onclick={toggleHidden}
+ title={hidden ? 'Show grid' : 'Hide grid'}
+ aria-label={hidden ? 'Show grid' : 'Hide grid'}
+ >
+ <Icon name={hidden ? 'eyeOff' : 'eye'} size={14} />
+ </button>
+ {#if coverage}
+ <span class="grid-head-pct mono">{coverage.percent}%</span>
+ {/if}
+ {/if}
+ </div>
+
+ {#if !collapsed}
+ <div class="grid-body">
+ {#if grid}
+ <div class="grid-cov">
+ <div class="grid-bar">
+ <span class="grid-bar-fill" style="width:{coverage.percent}%"></span>
+ </div>
+ <span class="grid-cov-text mono">
+ {coverage.cleared + coverage.flagged}/{coverage.total} · {coverage.percent}%{#if coverage.flagged} · {coverage.flagged} flagged{/if}
+ </span>
+ </div>
+
+ {#if reviewKey}
+ <div class="grid-hint">
+ <b>C</b> clear · <b>F</b> flag · <b>S</b> skip · <b>P</b> place · <b>Esc</b> stop
+ </div>
+ <div class="grid-btns">
+ <button class="btn btn-sm" onclick={() => markReview('cleared')}>
+ <Icon name="check" size={13} /> Clear
+ </button>
+ <button class="btn btn-sm" onclick={() => markReview('flagged')}>
+ <Icon name="pin" size={13} /> Flag
+ </button>
+ <button class="btn btn-sm" onclick={reviewToPlace} title="Flag and save as a place">
+ <Icon name="plus" size={13} /> Place
+ </button>
+ <button class="btn btn-ghost btn-sm" onclick={stopReview}>Stop</button>
+ </div>
+ {:else}
+ <div class="grid-btns">
+ <button class="btn btn-sm" onclick={startReview} title="Fly through the unchecked cells">
+ <Icon name="eye" size={13} /> Review
+ </button>
+ <button class="btn btn-sm" class:on={editArea} onclick={toggleEditArea} title="Show the area box to resize or reshape it">
+ <Icon name="edit" size={13} /> Edit area
+ </button>
+ <button class="btn btn-sm grid-discard" onclick={discard} title="Close this grid (it stays saved) to draw or open another">
+ Discard
+ </button>
+ <button class="btn btn-ghost btn-sm" onclick={() => deleteGrid(gridName)} title="Delete this grid for good">
+ <Icon name="trash" size={13} />
+ </button>
+ </div>
+ {#if editArea}
+ <div class="grid-hint">Drag the {grid.aoi.type === 'rect' ? 'corners' : 'points'} to reshape.</div>
+ {/if}
+ {/if}
+ {/if}
+
+ {#if !grid}
+ <div class="grid-new">
+ <div class="grid-size">
+ <span>Cell</span>
+ <input
+ class="input"
+ type="number"
+ min="10"
+ step="10"
+ bind:value={cellMetres}
+ title="Cell size in metres for the next grid"
+ />
+ <span>m</span>
+ </div>
+ <div class="grid-btns">
+ <button class="btn btn-sm" class:on={drawMode === 'rect'} onclick={() => startDraw('rect')}>
+ <Icon name="square" size={13} /> Box
+ </button>
+ <button class="btn btn-sm" class:on={drawMode === 'polygon'} onclick={() => startDraw('polygon')}>
+ <Icon name="polygon" size={13} /> Polygon
+ </button>
+ </div>
+ {#if drawMode === 'polygon'}
+ <div class="grid-hint">Click to add points{#if polygonDraft.length} · {polygonDraft.length}{/if}. Drag to adjust.</div>
+ <div class="grid-btns">
+ <button class="btn btn-sm" disabled={polygonDraft.length < 3} onclick={confirmPolygon}>Confirm</button>
+ <button class="btn btn-ghost btn-sm" onclick={cancelDraw}>Cancel</button>
+ </div>
+ {:else if drawMode === 'rect'}
+ <div class="grid-hint">Drag a box on the map. Esc to cancel.</div>
+ {/if}
+ </div>
+ {/if}
+
+ {#if !grid && savedGrids.length}
+ <div class="grid-saved">
+ <div class="grid-saved-label">Saved grids ({savedGrids.length})</div>
+ <div class="grid-saved-list">
+ {#each savedGrids as saved (saved.name)}
+ <div class="grid-saved-row">
+ <button class="grid-load" onclick={() => loadGrid(saved.name)} title="Open this grid">
+ {saved.title || saved.name}
+ </button>
+ <span class="grid-saved-cov mono" title="cleared · flagged">
+ {saved.cleared}{#if saved.flagged}<span class="flagged"> ⚑{saved.flagged}</span>{/if}
+ </span>
+ <button class="btn btn-ghost btn-sm" onclick={() => deleteGrid(saved.name)} title="Delete">
+ <Icon name="trash" size={12} />
+ </button>
+ </div>
+ {/each}
+ </div>
+ </div>
+ {/if}
+ </div>
+ {/if}
+</div>
+
+<style>
+ .grid-panel {
+ position: absolute;
+ top: 0;
+ left: calc(100% + 8px);
+ width: 218px;
+ display: flex;
+ flex-direction: column;
+ background: rgba(24, 24, 24, 0.92);
+ backdrop-filter: blur(6px);
+ box-shadow: var(--shadow-2);
+ }
+ .grid-head {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 6px 8px;
+ }
+ .grid-collapse, .grid-eye {
+ display: grid;
+ place-items: center;
+ width: 22px;
+ height: 22px;
+ border-radius: var(--radius-1);
+ color: var(--text-2);
+ cursor: pointer;
+ flex-shrink: 0;
+ }
+ .grid-collapse:hover, .grid-eye:hover {
+ color: var(--text-1);
+ background: var(--bg-3);
+ }
+ .grid-head-title {
+ flex: 1;
+ min-width: 0;
+ font-size: var(--fs-sm);
+ font-weight: 600;
+ color: var(--text-1);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+ .grid-head-title.renamable { cursor: text; }
+ .grid-rename {
+ flex: 1;
+ min-width: 0;
+ height: 24px;
+ padding: 2px 6px;
+ font-size: var(--fs-sm);
+ }
+ .grid-head-pct {
+ font-size: var(--fs-xs);
+ color: var(--accent);
+ flex-shrink: 0;
+ }
+ .grid-body {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ padding: 0 10px 10px;
+ }
+ .grid-size {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ }
+ .grid-size .input { width: 64px; }
+ .grid-btns { display: flex; flex-wrap: wrap; gap: 4px; }
+ .grid-btns .btn.on {
+ background: var(--accent);
+ color: var(--accent-text);
+ border-color: var(--accent);
+ }
+ .grid-discard {
+ background: rgba(255, 255, 255, 0.1);
+ border-color: rgba(255, 255, 255, 0.18);
+ color: var(--text-1);
+ }
+ .grid-discard:hover { background: rgba(255, 255, 255, 0.16); color: var(--text-1); }
+ .grid-hint { font-size: var(--fs-xs); color: var(--text-3); }
+ .grid-hint b { color: var(--text-2); }
+ .grid-cov { display: flex; flex-direction: column; gap: 4px; }
+ .grid-bar {
+ height: 6px;
+ border-radius: 3px;
+ background: rgba(124, 138, 165, 0.25);
+ overflow: hidden;
+ }
+ .grid-bar-fill {
+ display: block;
+ height: 100%;
+ background: var(--accent);
+ transition: width 0.15s ease;
+ }
+ .grid-cov-text { font-size: var(--fs-xs); color: var(--text-2); }
+ .grid-new, .grid-saved {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ padding-top: 8px;
+ border-top: 1px solid var(--border);
+ }
+ .grid-saved { gap: 3px; }
+ .grid-saved-label {
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ margin-bottom: 2px;
+ }
+ .grid-saved-list {
+ display: flex;
+ flex-direction: column;
+ gap: 3px;
+ max-height: 240px;
+ overflow-y: auto;
+ }
+ .grid-saved-row { display: flex; align-items: center; gap: 4px; }
+ .grid-load {
+ flex: 1;
+ min-width: 0;
+ text-align: left;
+ padding: 3px 6px;
+ border-radius: var(--radius-1);
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ cursor: pointer;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+ .grid-load:hover { color: var(--text-1); background: var(--bg-3); }
+ .grid-saved-cov { font-size: var(--fs-xs); color: var(--text-3); flex-shrink: 0; }
+ .grid-saved-cov .flagged { color: var(--warn); }
+</style>
diff --git a/frontend/src/tools/satellite/MapToolCluster.svelte b/frontend/src/tools/satellite/MapToolCluster.svelte
new file mode 100644
index 0000000..8a83c96
--- /dev/null
+++ b/frontend/src/tools/satellite/MapToolCluster.svelte
@@ -0,0 +1,138 @@
+<script>
+ import Icon from '../../components/Icon.svelte';
+
+ let {
+ fullscreen,
+ toggleFullscreen,
+ osmOverlay = $bindable(),
+ baseIsImagery,
+ toolsOpen,
+ measureMode,
+ toggleTools,
+ gridMode,
+ toggleGridMode,
+ referenceCount,
+ openRefPicker,
+ setMeasureMode,
+ measureReadout,
+ measureHint,
+ clearMeasure,
+ } = $props();
+</script>
+
+<div class="tool-cluster card">
+ <button
+ class="mtbtn"
+ class:on={fullscreen}
+ onclick={toggleFullscreen}
+ title={fullscreen ? 'Exit fullscreen (Esc)' : 'Fullscreen map'}
+ aria-label="Toggle fullscreen"
+ ><Icon name={fullscreen ? 'minimize' : 'maximize'} size={16} /></button>
+ <button
+ class="mtbtn"
+ class:on={osmOverlay}
+ onclick={() => (osmOverlay = !osmOverlay)}
+ disabled={!baseIsImagery}
+ title={baseIsImagery
+ ? 'Overlay OSM labels (roads, place names) on the imagery'
+ : 'Labels overlay is only useful over satellite imagery'}
+ aria-label="Toggle OSM labels overlay"
+ ><Icon name="layers" size={16} /></button>
+ <button
+ class="mtbtn"
+ class:on={toolsOpen || measureMode}
+ onclick={toggleTools}
+ title="Measure tools"
+ aria-label="Measure tools"
+ ><Icon name="ruler" size={16} /></button>
+ <button
+ class="mtbtn"
+ class:on={gridMode}
+ onclick={toggleGridMode}
+ title="Sweep an area cell by cell"
+ aria-label="Grid Search"
+ ><Icon name="grid" size={16} /></button>
+ <button
+ class="mtbtn"
+ class:on={referenceCount}
+ onclick={openRefPicker}
+ title="Add a reference image or video over the map"
+ aria-label="Add reference"
+ ><Icon name="image" size={16} /></button>
+</div>
+
+{#if toolsOpen}
+ <div class="measure-panel card">
+ <div class="measure-btns">
+ <button class="btn btn-sm" class:on={measureMode === 'distance'} onclick={() => setMeasureMode('distance')}>
+ <Icon name="ruler" size={14} /> Distance
+ </button>
+ <button class="btn btn-sm" class:on={measureMode === 'area'} onclick={() => setMeasureMode('area')}>
+ <Icon name="polygon" size={14} /> Area
+ </button>
+ <button class="btn btn-sm" class:on={measureMode === 'angle'} onclick={() => setMeasureMode('angle')}>
+ <Icon name="angle" size={14} /> Angle
+ </button>
+ </div>
+ {#if measureMode}
+ <div class="measure-readout">
+ {#if measureReadout}
+ <span class="measure-value mono">{measureReadout}</span>
+ {:else}
+ <span class="measure-hint">{measureHint[measureMode]}</span>
+ {/if}
+ <button class="btn btn-ghost btn-sm" onclick={clearMeasure} title="Clear points">
+ <Icon name="reset" size={13} />
+ </button>
+ </div>
+ {/if}
+ </div>
+{/if}
+
+<style>
+ .tool-cluster {
+ display: flex;
+ gap: 2px;
+ padding: 4px;
+ background: rgba(24, 24, 24, 0.88);
+ backdrop-filter: blur(6px);
+ }
+ .mtbtn {
+ display: grid;
+ place-items: center;
+ width: 30px;
+ height: 30px;
+ border-radius: var(--radius-1);
+ color: var(--text-2);
+ cursor: pointer;
+ }
+ .mtbtn:hover { color: var(--text-1); background: var(--bg-3); }
+ .mtbtn.on { color: var(--accent-text); background: var(--accent); }
+ .mtbtn:disabled { opacity: 0.35; cursor: not-allowed; }
+ .mtbtn:disabled:hover { color: var(--text-2); background: none; }
+ .measure-panel {
+ position: absolute;
+ top: 0;
+ left: calc(100% + 8px);
+ width: max-content;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ padding: 10px;
+ background: rgba(24, 24, 24, 0.92);
+ backdrop-filter: blur(6px);
+ box-shadow: var(--shadow-2);
+ }
+ .measure-btns { display: flex; gap: 4px; }
+ .measure-btns .btn.on { background: var(--accent); color: var(--accent-text); border-color: var(--accent); }
+ .measure-readout {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ padding-top: 6px;
+ border-top: 1px solid var(--border);
+ }
+ .measure-value { font-size: var(--fs-md); font-weight: 700; color: var(--accent); }
+ .measure-hint { font-size: var(--fs-xs); color: var(--text-3); }
+</style>
diff --git a/frontend/src/tools/satellite/SentinelPicker.svelte b/frontend/src/tools/satellite/SentinelPicker.svelte
new file mode 100644
index 0000000..05461d0
--- /dev/null
+++ b/frontend/src/tools/satellite/SentinelPicker.svelte
@@ -0,0 +1,216 @@
+<script>
+ import Icon from '../../components/Icon.svelte';
+
+ let {
+ menuEl = $bindable(),
+ menuOpen,
+ toggleMenu,
+ layer = $bindable(),
+ layers,
+ layerHint,
+ layersSource,
+ loadLayers,
+ date = $bindable(),
+ month,
+ monthLabel,
+ stepMonth,
+ monthGrid,
+ passes,
+ cloudClass,
+ cloudLabel,
+ passesBusy,
+ passesNote,
+ passesStale,
+ verifyingDate,
+ dateStatus,
+ pickDate,
+ clearDate,
+ loadPasses,
+ } = $props();
+</script>
+
+<div class="s2-wrap" bind:this={menuEl}>
+ <button
+ class="btn btn-icon"
+ class:on={menuOpen}
+ onclick={toggleMenu}
+ title="Sentinel-2 layer and date"
+ aria-label="Sentinel-2 layer and date"
+ ><Icon name="layers" size={14} /></button>
+ {#if menuOpen}
+ <div class="s2-menu card">
+ <div class="menu-row">
+ <span class="menu-label">Layer</span>
+ <select class="select" bind:value={layer}>
+ {#each layers as entry (entry.id)}
+ <option value={entry.id}>{entry.label}</option>
+ {/each}
+ </select>
+ </div>
+ {#if layerHint}<div class="menu-hint">{layerHint}</div>{/if}
+ <div class="menu-hint dim">
+ {layersSource === 'instance'
+ ? 'These layers come from your configuration.'
+ : 'Could not read your configuration; showing the standard layers.'}
+ <button class="linkish" onclick={() => loadLayers(true)}>Refresh</button>
+ </div>
+
+ <div class="menu-sep" aria-hidden="true"></div>
+
+ <div class="menu-row">
+ <span class="menu-label">Date</span>
+ <div class="chips">
+ <button class="chip" class:on={!date} onclick={clearDate}>Most recent</button>
+ </div>
+ </div>
+
+ <div class="cal">
+ <div class="cal-head">
+ <button class="cal-nav" onclick={() => stepMonth(-1)} aria-label="Previous month">
+ <Icon name="chevronLeft" size={13} />
+ </button>
+ <span class="cal-month">{monthLabel(month)}</span>
+ <button class="cal-nav" onclick={() => stepMonth(1)} aria-label="Next month">
+ <Icon name="chevronRight" size={13} />
+ </button>
+ </div>
+ <div class="cal-grid" class:busy={passesBusy}>
+ {#each ['M', 'T', 'W', 'T', 'F', 'S', 'S'] as entry, index (index)}
+ <span class="cal-dow" aria-hidden="true">{entry}</span>
+ {/each}
+ {#each monthGrid(month) as day, index (day ?? `pad${index}`)}
+ {#if !day}
+ <span class="cal-pad" aria-hidden="true"></span>
+ {:else}
+ {@const pass = passes[day]}
+ {@const status = dateStatus(day)}
+ {@const unavailable = status === false}
+ {@const verifying = verifyingDate === day}
+ <button
+ class="cal-day {pass ? cloudClass(pass.cloud) : ''}"
+ class:has={!!pass}
+ class:on={date === day}
+ class:unavailable
+ class:verifying
+ disabled={date !== day && (!pass || passesStale || passesBusy || unavailable || !!verifyingDate)}
+ onclick={() => pickDate(day)}
+ title={unavailable
+ ? `No imagery at the crosshair on ${day}`
+ : verifying
+ ? `Checking imagery for ${day}`
+ : passesStale
+ ? `Refreshing dates for this location`
+ : pass
+ ? `${day}: ${cloudLabel(pass.cloud) || 'cloud cover unknown'}`
+ : `${day}: no Sentinel-2 pass`}
+ >{Number(day.slice(8))}</button>
+ {/if}
+ {/each}
+ </div>
+ </div>
+
+ {#if passesBusy}
+ <div class="menu-hint dim">Reading this month's passes…</div>
+ {:else if passesNote}
+ <div class="menu-hint warn">{passesNote}</div>
+ {:else if passesStale}
+ <div class="menu-hint">
+ <span class="warn">Refreshing dates for this location.</span>
+ <button class="linkish" onclick={() => loadPasses(true)}>Refresh</button>
+ </div>
+ {:else}
+ <div class="menu-hint dim">
+ Dates with a pass are checked at the crosshair before the map changes.
+ </div>
+ {/if}
+ </div>
+ {/if}
+</div>
+
+<style>
+ .s2-wrap { position: relative; display: flex; }
+ .s2-menu {
+ position: absolute;
+ bottom: calc(100% + 8px);
+ left: 0;
+ width: max-content;
+ max-width: 320px;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ padding: 12px;
+ background: rgba(24, 24, 24, 0.96);
+ backdrop-filter: blur(6px);
+ box-shadow: var(--shadow-2);
+ z-index: 700;
+ }
+ .s2-menu .select { max-width: 190px; }
+ .menu-row { display: flex; align-items: center; gap: 10px; justify-content: space-between; }
+ .menu-label { font-size: var(--fs-xs); color: var(--text-3); font-weight: 600; }
+ .chips { display: flex; gap: 4px; flex-wrap: wrap; justify-content: flex-end; }
+ .chip {
+ padding: 4px 9px;
+ border-radius: var(--r-sm);
+ border: 1px solid var(--border);
+ background: var(--bg-2);
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ white-space: nowrap;
+ cursor: pointer;
+ transition: border-color 0.12s, color 0.12s, background 0.12s;
+ }
+ .chip:hover { color: var(--text-1); border-color: var(--border-strong); }
+ .chip.on { border-color: var(--accent); background: var(--accent-soft); color: var(--accent); }
+ .menu-hint { font-size: 10px; color: var(--text-3); margin: -1px 0 5px; }
+ .menu-hint.dim { opacity: 0.75; }
+ .menu-hint .warn, .menu-hint.warn { color: var(--warn, #e2a03f); }
+ .menu-sep { height: 1px; background: var(--border); margin: 4px 0 6px; }
+ .linkish {
+ background: none;
+ border: 0;
+ padding: 0;
+ color: var(--accent);
+ font-size: 10px;
+ cursor: pointer;
+ text-decoration: underline;
+ }
+ .cal { display: flex; flex-direction: column; gap: 6px; margin: 2px 0 6px; }
+ .cal-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
+ .cal-month { font-size: var(--fs-xs); font-weight: 600; color: var(--text-1); }
+ .cal-nav {
+ display: flex;
+ padding: 3px 5px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ color: var(--text-2);
+ cursor: pointer;
+ }
+ .cal-nav:hover { color: var(--text-1); border-color: var(--text-3); }
+ .cal-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 2px; }
+ .cal-grid.busy { opacity: 0.5; pointer-events: none; }
+ .cal-dow { text-align: center; font-size: 9px; color: var(--text-3); padding-bottom: 2px; }
+ .cal-day {
+ aspect-ratio: 1;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ border: 1px solid transparent;
+ border-radius: var(--r-sm);
+ background: transparent;
+ color: var(--text-3);
+ font-size: 10px;
+ font-family: var(--font-mono);
+ cursor: pointer;
+ }
+ .cal-day:disabled { opacity: 0.28; cursor: default; }
+ .cal-day.has { color: var(--text-1); background: var(--bg-2); border-color: var(--border); }
+ .cal-day.clear { border-color: color-mix(in srgb, var(--ok, #46a758) 65%, transparent); color: var(--ok, #46a758); }
+ .cal-day.part { border-color: color-mix(in srgb, var(--warn, #e2a03f) 55%, transparent); color: var(--warn, #e2a03f); }
+ .cal-day.cloudy, .cal-day.unknown { border-color: var(--border); color: var(--text-2); }
+ .cal-day.unavailable { text-decoration: line-through; }
+ .cal-day.verifying { opacity: 0.55; animation: pulse 0.8s ease-in-out infinite alternate; }
+ .cal-day.has:hover { border-color: var(--text-1); }
+ .cal-day.on { background: var(--accent); border-color: var(--accent); color: var(--accent-text); font-weight: 700; }
+ @keyframes pulse { to { opacity: 1; } }
+</style>
diff --git a/frontend/src/tools/satellite/SentinelPicker.test.js b/frontend/src/tools/satellite/SentinelPicker.test.js
new file mode 100644
index 0000000..f76a29a
--- /dev/null
+++ b/frontend/src/tools/satellite/SentinelPicker.test.js
@@ -0,0 +1,57 @@
+import { describe, expect, it, vi } from 'vitest';
+import { render } from 'svelte/server';
+import SentinelPicker from './SentinelPicker.svelte';
+
+function props(overrides = {}) {
+ return {
+ menuOpen: true,
+ toggleMenu: vi.fn(),
+ layer: 'TRUE_COLOR',
+ layers: [{ id: 'TRUE_COLOR', label: 'True colour' }],
+ layerHint: '',
+ layersSource: 'instance',
+ loadLayers: vi.fn(),
+ date: '',
+ month: '2026-05',
+ monthLabel: () => 'May 2026',
+ stepMonth: vi.fn(),
+ monthGrid: () => ['2026-05-11'],
+ passes: { '2026-05-11': { cloud: 4, granules: 1 } },
+ cloudClass: () => 'clear',
+ cloudLabel: () => '4% cloud',
+ passesBusy: false,
+ passesNote: '',
+ passesStale: false,
+ verifyingDate: '',
+ dateStatus: () => undefined,
+ pickDate: vi.fn(),
+ clearDate: vi.fn(),
+ loadPasses: vi.fn(),
+ ...overrides,
+ };
+}
+
+describe('SentinelPicker date safety', () => {
+ it('disables dates from the previous map location', () => {
+ const { body } = render(SentinelPicker, { props: props({ passesStale: true }) });
+ expect(body).toContain('Refreshing dates for this location.');
+ expect(body).toMatch(/<button[^>]*class="cal-day[^>]*disabled[^>]*>/);
+ });
+
+ it('marks a checked date that has no imagery as unavailable', () => {
+ const { body } = render(SentinelPicker, {
+ props: props({ dateStatus: () => false }),
+ });
+ expect(body).toMatch(/class="cal-day clear [^"]*has unavailable"/);
+ expect(body).toContain('No imagery at the crosshair on 2026-05-11');
+ expect(body).toMatch(/<button[^>]*class="cal-day clear [^"]*has unavailable"[^>]*disabled/);
+ });
+
+ it('shows which date is being checked', () => {
+ const { body } = render(SentinelPicker, {
+ props: props({ verifyingDate: '2026-05-11' }),
+ });
+ expect(body).toMatch(/class="cal-day clear [^"]*has verifying"/);
+ expect(body).toContain('Checking imagery for 2026-05-11');
+ });
+});
diff --git a/frontend/vite.config.js b/frontend/vite.config.js
index 2bebd6e..ef7d66a 100644
--- a/frontend/vite.config.js
+++ b/frontend/vite.config.js
@@ -4,6 +4,9 @@ import { svelte } from '@sveltejs/vite-plugin-svelte';
// Builds straight into the Python package so `pip install .` ships the UI.
export default defineConfig({
plugins: [svelte()],
+ test: {
+ include: ['src/**/*.test.js'],
+ },
build: {
outDir: '../src/azimut/static',
emptyOutDir: true,
diff --git a/pyproject.toml b/pyproject.toml
index 1bb89d2..b226cd8 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,11 +1,11 @@
[build-system]
-requires = ["hatchling"]
+requires = ["hatchling>=1.27,<2"]
build-backend = "hatchling.build"
[project]
name = "azimut"
version = "0.2.0"
-description = "The OSINT investigator's workbench — local-first media, geolocation proofs and case management."
+description = "A local OSINT workspace for media, geolocation proofs and case management."
readme = "README.md"
requires-python = ">=3.11"
license = { text = "AGPL-3.0-only" }
@@ -59,6 +59,15 @@ dev = [
"mypy>=2.3,<3",
]
+[dependency-groups]
+# Release-only tools are locked with the application dependencies. Build the
+# distributions without isolation so hatchling also comes from uv.lock.
+release = [
+ "build>=1.2,<2",
+ "hatchling>=1.27,<2",
+ "pyinstaller>=6,<7",
+]
+
[project.scripts]
azimut = "azimut.cli:main"
diff --git a/scripts/relaunch.py b/scripts/relaunch.py
new file mode 100755
index 0000000..4d1f74a
--- /dev/null
+++ b/scripts/relaunch.py
@@ -0,0 +1,242 @@
+#!/usr/bin/env python3
+"""Rebuild and relaunch the local Azimut checkout on any supported OS.
+
+The tool supervises the process it starts and exposes a token-protected local
+control socket. A later invocation can therefore stop that exact process
+without scanning process names or killing unrelated Vite/Azimut instances.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import secrets
+import shutil
+import signal
+import socket
+import subprocess
+import sys
+import threading
+import time
+from pathlib import Path
+from typing import Any
+
+
+ROOT = Path(__file__).resolve().parent.parent
+STATE_PATH = ROOT / ".azimut-relaunch.json"
+
+
+def _read_state(path: Path) -> dict[str, Any] | None:
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return None
+ if not isinstance(data, dict):
+ return None
+ port = data.get("port")
+ token = data.get("token")
+ if not isinstance(port, int) or not 1 <= port <= 65535:
+ return None
+ if not isinstance(token, str) or len(token) != 64:
+ return None
+ return {"port": port, "token": token}
+
+
+def _remove_owned_state(path: Path, token: str) -> None:
+ state = _read_state(path)
+ if state and state["token"] == token:
+ path.unlink(missing_ok=True)
+
+
+class _ControlServer:
+ """Accept a stop request from the next relaunch invocation."""
+
+ def __init__(self, state_path: Path) -> None:
+ self.state_path = state_path
+ self.token = secrets.token_hex(32)
+ self.stop_requested = threading.Event()
+ self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ self._socket.bind(("127.0.0.1", 0))
+ self._socket.listen(1)
+ self._socket.settimeout(0.25)
+ self.port = int(self._socket.getsockname()[1])
+ self._thread = threading.Thread(target=self._serve, daemon=True)
+
+ def start(self) -> None:
+ temp = self.state_path.with_name(f"{self.state_path.name}.{self.token}.tmp")
+ temp.write_text(
+ json.dumps({"port": self.port, "token": self.token}),
+ encoding="utf-8",
+ )
+ try:
+ temp.chmod(0o600)
+ except OSError:
+ pass
+ os.replace(temp, self.state_path)
+ self._thread.start()
+
+ def _serve(self) -> None:
+ while not self.stop_requested.is_set():
+ try:
+ connection, _ = self._socket.accept()
+ except TimeoutError:
+ continue
+ except OSError:
+ return
+ with connection:
+ connection.settimeout(1)
+ try:
+ supplied = connection.recv(128).decode("ascii").strip()
+ except (OSError, UnicodeError):
+ continue
+ if secrets.compare_digest(supplied, self.token):
+ connection.sendall(b"OK\n")
+ self.stop_requested.set()
+
+ def close(self) -> None:
+ self.stop_requested.set()
+ self._socket.close()
+ if self._thread.is_alive() and self._thread is not threading.current_thread():
+ self._thread.join(timeout=1)
+ _remove_owned_state(self.state_path, self.token)
+
+
+def _stop_previous(path: Path, timeout: float = 10) -> bool:
+ state = _read_state(path)
+ if state is None:
+ path.unlink(missing_ok=True)
+ return False
+ try:
+ with socket.create_connection(("127.0.0.1", state["port"]), timeout=1) as connection:
+ connection.sendall(f"{state['token']}\n".encode("ascii"))
+ if connection.recv(16).strip() != b"OK":
+ raise RuntimeError("the previous launcher rejected the stop request")
+ except OSError:
+ _remove_owned_state(path, state["token"])
+ return False
+
+ deadline = time.monotonic() + timeout
+ while path.exists() and time.monotonic() < deadline:
+ time.sleep(0.05)
+ if path.exists():
+ raise RuntimeError("the previous launcher did not stop within 10 seconds")
+ return True
+
+
+def _venv_python(root: Path, platform: str = os.name) -> Path:
+ relative = Path("Scripts/python.exe") if platform == "nt" else Path("bin/python")
+ python = root / ".venv" / relative
+ if not python.is_file():
+ raise RuntimeError(f"virtual environment not found at {python}; create .venv first")
+ return python
+
+
+def _npm_build_command(platform: str = os.name) -> list[str]:
+ npm = shutil.which("npm")
+ if not npm:
+ raise RuntimeError("npm was not found on PATH; install Node.js 20 or newer")
+ if platform == "nt" and Path(npm).suffix.lower() in {".cmd", ".bat"}:
+ command = os.environ.get("COMSPEC", "cmd.exe")
+ return [command, "/d", "/s", "/c", npm, "run", "build"]
+ return [npm, "run", "build"]
+
+
+def _spawn(command: list[str], cwd: Path) -> subprocess.Popen[bytes]:
+ if os.name == "nt":
+ return subprocess.Popen(
+ command,
+ cwd=cwd,
+ creationflags=subprocess.CREATE_NEW_PROCESS_GROUP,
+ )
+ return subprocess.Popen(command, cwd=cwd, start_new_session=True)
+
+
+def _terminate(process: subprocess.Popen[bytes]) -> None:
+ if process.poll() is not None:
+ return
+ if os.name == "nt":
+ subprocess.run(
+ ["taskkill", "/PID", str(process.pid), "/T", "/F"],
+ check=False,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ )
+ else:
+ try:
+ os.killpg(process.pid, signal.SIGTERM)
+ except ProcessLookupError:
+ return
+ try:
+ process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ if os.name == "nt":
+ process.kill()
+ else:
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ process.wait(timeout=5)
+
+
+def _run_process(
+ command: list[str], cwd: Path, stop_requested: threading.Event
+) -> int | None:
+ process = _spawn(command, cwd)
+ try:
+ while process.poll() is None:
+ if stop_requested.wait(0.2):
+ _terminate(process)
+ return None
+ return process.returncode
+ except BaseException:
+ _terminate(process)
+ raise
+
+
+def run(*, port: int, no_browser: bool) -> int:
+ if _stop_previous(STATE_PATH):
+ print("Stopped the previous managed Azimut instance.")
+
+ control = _ControlServer(STATE_PATH)
+ control.start()
+ try:
+ print("Rebuilding the frontend...")
+ result = _run_process(_npm_build_command(), ROOT / "frontend", control.stop_requested)
+ if result is None:
+ return 0
+ if result != 0:
+ return result
+
+ command = [str(_venv_python(ROOT)), "-m", "azimut.cli", "--port", str(port)]
+ if no_browser:
+ command.append("--no-browser")
+ print(f"Starting Azimut on http://127.0.0.1:{port}")
+ result = _run_process(command, ROOT, control.stop_requested)
+ return 0 if result is None else result
+ finally:
+ control.close()
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(
+ description="Rebuild the frontend and relaunch the local Azimut checkout"
+ )
+ parser.add_argument("--port", type=int, default=8477)
+ parser.add_argument("--no-browser", action="store_true")
+ args = parser.parse_args()
+ if not 1 <= args.port <= 65535:
+ parser.error("--port must be between 1 and 65535")
+ try:
+ return run(port=args.port, no_browser=args.no_browser)
+ except RuntimeError as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 1
+ except KeyboardInterrupt:
+ return 130
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/relaunch.sh b/scripts/relaunch.sh
deleted file mode 100755
index c4f035e..0000000
--- a/scripts/relaunch.sh
+++ /dev/null
@@ -1,23 +0,0 @@
-#!/usr/bin/env bash
-# One-shot dev relaunch: kill anything running on the azimut ports, rebuild
-# the frontend, and start a single backend process that serves the fresh
-# build directly (no vite dev server, no proxy — just one process).
-set -euo pipefail
-cd "$(dirname "$0")/.."
-
-echo "==> Killing any existing azimut / vite processes"
-pkill -f ".venv/bin/azimut" 2>/dev/null || true
-pkill -f "vite" 2>/dev/null || true
-for port in 8477 5173; do
- pid=$(lsof -ti:"$port" 2>/dev/null || true)
- if [ -n "$pid" ]; then
- kill $pid 2>/dev/null || true
- fi
-done
-sleep 1
-
-echo "==> Rebuilding frontend"
-(cd frontend && npm run build)
-
-echo "==> Starting azimut on http://127.0.0.1:8477"
-exec .venv/bin/azimut
diff --git a/scripts/smoke_binary.py b/scripts/smoke_binary.py
new file mode 100644
index 0000000..ec51067
--- /dev/null
+++ b/scripts/smoke_binary.py
@@ -0,0 +1,106 @@
+"""Exercise a release binary as a running local application.
+
+The release workflow uses this after PyInstaller finishes. It verifies the
+server, bundled frontend and bundled ffmpeg from the artifact itself.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import socket
+import subprocess
+import tempfile
+import time
+import urllib.error
+import urllib.request
+from pathlib import Path
+from typing import Any
+
+
+def _free_port() -> int:
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
+ sock.bind(("127.0.0.1", 0))
+ return int(sock.getsockname()[1])
+
+
+def _request(url: str) -> tuple[int, str, str]:
+ with urllib.request.urlopen(url, timeout=2) as response:
+ return (
+ response.status,
+ response.headers.get_content_type(),
+ response.read().decode("utf-8", "replace"),
+ )
+
+
+def check_application(base_url: str) -> None:
+ status, content_type, body = _request(f"{base_url}/api/health")
+ health: dict[str, Any] = json.loads(body)
+ if status != 200 or health.get("status") != "ok":
+ raise RuntimeError(f"health check failed: {status} {health!r}")
+
+ status, content_type, body = _request(f"{base_url}/")
+ if status != 200 or content_type != "text/html" or '<div id="app"></div>' not in body:
+ raise RuntimeError("the binary did not serve the built frontend")
+
+ status, content_type, body = _request(f"{base_url}/api/settings/ffmpeg")
+ ffmpeg: dict[str, Any] = json.loads(body)
+ if status != 200 or not ffmpeg.get("available") or ffmpeg.get("source") != "bundled":
+ raise RuntimeError(f"bundled ffmpeg was not detected: {ffmpeg!r}")
+
+
+def wait_until_ready(base_url: str, process: subprocess.Popen[bytes], timeout: float = 60) -> None:
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ code = process.poll()
+ if code is not None:
+ raise RuntimeError(f"binary exited before it became ready (exit {code})")
+ try:
+ check_application(base_url)
+ return
+ except (OSError, urllib.error.URLError):
+ time.sleep(0.25)
+ raise RuntimeError(f"binary did not become ready within {timeout:g} seconds")
+
+
+def stop(process: subprocess.Popen[bytes]) -> None:
+ if process.poll() is not None:
+ return
+ process.terminate()
+ try:
+ process.wait(timeout=10)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait(timeout=10)
+
+
+def smoke(binary: Path) -> None:
+ binary = binary.resolve()
+ if not binary.is_file():
+ raise FileNotFoundError(binary)
+
+ port = _free_port()
+ base_url = f"http://127.0.0.1:{port}"
+ with tempfile.TemporaryDirectory(prefix="azimut-binary-smoke-") as workspace:
+ env = os.environ.copy()
+ env["AZIMUT_HOME"] = workspace
+ process = subprocess.Popen(
+ [str(binary), "--no-browser", "--port", str(port)],
+ env=env,
+ )
+ try:
+ wait_until_ready(base_url, process)
+ finally:
+ stop(process)
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("binary", type=Path)
+ args = parser.parse_args()
+ smoke(args.binary)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/azimut/__init__.py b/src/azimut/__init__.py
index 7847f67..025ade7 100644
--- a/src/azimut/__init__.py
+++ b/src/azimut/__init__.py
@@ -1,4 +1,4 @@
-"""Azimut — the OSINT investigator's workbench."""
+"""Azimut, a local OSINT workspace."""
from PIL import Image as _Image
diff --git a/src/azimut/api/cases.py b/src/azimut/api/cases.py
index f809a06..5e5140b 100644
--- a/src/azimut/api/cases.py
+++ b/src/azimut/api/cases.py
@@ -2,13 +2,14 @@
from __future__ import annotations
-from typing import Any
+from typing import Any, cast
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field
from ..engine import links as link_engine
from ..engine import media as media_engine
+from ..repository import EntityStatus
from ..workspace import Case, CaseError
router = APIRouter(prefix="/api/cases", tags=["cases"])
@@ -57,6 +58,8 @@ def _delete_artifact_files(case: Case, entity: dict[str, Any]) -> None:
_unlink_inside(case, attrs["draft"])
elif etype == "inspect-session" and attrs.get("spec"):
_unlink_inside(case, attrs["spec"])
+ elif etype == "note" and attrs.get("path"):
+ _unlink_inside(case, attrs["path"])
def delete_entity_deep(case: Case, entity_id: str) -> dict[str, Any]:
@@ -71,7 +74,9 @@ def delete_entity_deep(case: Case, entity_id: str) -> dict[str, Any]:
tombstone first, while the target can still describe itself.
"""
plan = link_engine.plan_delete(case, entity_id)
- target = next(e for e in case.read()["entities"] if e["id"] == entity_id)
+ target = case.get_entity(entity_id)
+ if target is None:
+ raise CaseError(f"entity '{entity_id}' not found")
going = [target, *plan["cascade"]]
# Scar the survivors first, while the doomed can still describe themselves.
@@ -135,25 +140,24 @@ class Notes(BaseModel):
text: str
+class NoteIn(BaseModel):
+ title: str = Field(min_length=1, max_length=300)
+ folder: str = Field(default="", max_length=120)
+ content: str = ""
+
+
class EntityIn(BaseModel):
type: str = Field(min_length=1, max_length=40)
label: str = Field(min_length=1, max_length=300)
attrs: dict[str, Any] = Field(default_factory=dict)
- status: str = "confirmed"
+ status: EntityStatus = "confirmed"
class EntityPatch(BaseModel):
type: str | None = None
label: str | None = None
attrs: dict[str, Any] | None = None
- status: str | None = None
-
-
-class LinkIn(BaseModel):
- from_id: str
- to_id: str
- type: str = Field(min_length=1, max_length=60)
- status: str = "confirmed"
+ status: EntityStatus | None = None
class FolderIn(BaseModel):
@@ -172,19 +176,19 @@ def create_case(body: CreateCase) -> dict[str, Any]:
case = Case.create(body.name)
except CaseError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
- return {"id": case.id, **case.read()}
+ return {"id": case.id, **case.overview()}
@router.post("/scratch")
def create_scratch() -> dict[str, Any]:
case = Case.create("Scratch session", scratch=True)
- return {"id": case.id, **case.read()}
+ return {"id": case.id, **case.overview()}
@router.get("/{case_id}")
def read_case(case_id: str) -> dict[str, Any]:
case = get_case(case_id)
- return {"id": case.id, "scratch": case.is_scratch, **case.read()}
+ return {"id": case.id, "scratch": case.is_scratch, **case.overview()}
@router.post("/{case_id}/promote")
@@ -195,7 +199,7 @@ def promote_case(case_id: str, body: PromoteCase) -> dict[str, Any]:
promoted = case.promote(body.name)
except CaseError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
- return {"id": promoted.id, **promoted.read()}
+ return {"id": promoted.id, **promoted.overview()}
@router.patch("/{case_id}")
@@ -203,7 +207,7 @@ def rename_case(case_id: str, body: CreateCase) -> dict[str, Any]:
case = get_case(case_id)
_ensure_name_free(body.name, exclude_id=case.id)
case.rename(body.name)
- return {"id": case.id, **case.read()}
+ return {"id": case.id, **case.overview()}
@router.delete("/{case_id}")
@@ -223,12 +227,91 @@ def write_notes(case_id: str, body: Notes) -> dict[str, str]:
return {"status": "saved"}
[email protected]("/{case_id}/notes")
+def create_note(case_id: str, body: NoteIn) -> dict[str, Any]:
+ return get_case(case_id).create_note(body.title.strip(), body.folder.strip(), body.content)
+
+
[email protected]("/{case_id}/notes/{note_id}")
+def read_note(case_id: str, note_id: str) -> dict[str, str]:
+ try:
+ return {"text": get_case(case_id).read_note(note_id)}
+ except CaseError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+
+
[email protected]("/{case_id}/notes/{note_id}")
+def write_note(case_id: str, note_id: str, body: Notes) -> dict[str, str]:
+ try:
+ get_case(case_id).write_note(note_id, body.text)
+ except CaseError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+ return {"status": "saved"}
+
+
[email protected]("/{case_id}/catalog/entities")
+def catalog_entities(
+ case_id: str,
+ cursor: str | None = None,
+ limit: int = 100,
+ type: str | None = None,
+ status: str | None = None,
+ q: str | None = None,
+ folder: str | None = None,
+ unfiled: bool = False,
+) -> dict[str, Any]:
+ """A bounded page of the entity catalog (Step 5, "Bounded loading").
+
+ Stable cursor order, server-side filters (a comma-separated ``type`` set,
+ ``status``, a label substring ``q``, and folder — ``unfiled=true`` or an
+ exact ``folder`` path) and a ``next_cursor`` that is null on the last page.
+ ``limit`` is clamped so no request can ask for the whole graph at once.
+ """
+ case = get_case(case_id)
+ limit = max(1, min(limit, 500))
+ types = [t.strip() for t in type.split(",") if t.strip()] if type else None
+ valid_status = (
+ cast(EntityStatus, status) if status in ("confirmed", "suggested") else None
+ )
+ try:
+ return case.page_entities(
+ limit=limit, cursor=cursor, types=types, status=valid_status,
+ query=q, folder=folder, unfiled=unfiled,
+ )
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+
[email protected]("/{case_id}/catalog/summary")
+def catalog_summary(case_id: str) -> dict[str, Any]:
+ """Total plus per-type and per-status counts, so the catalog can show badges
+ without loading the graph."""
+ return get_case(case_id).catalog_summary()
+
+
[email protected]("/{case_id}/entities/lookup")
+def lookup_entity(case_id: str, attr: str, value: str) -> dict[str, Any]:
+ """One entity by an ``attrs`` value (``path``, ``spec``, ``draft``), or null.
+
+ The bounded replacement for a tool scanning the whole graph to answer "is the
+ file/spec I am bound to still in the case?" after a delete elsewhere, or to
+ resolve a file path back to its entity (Step 5).
+ """
+ entity = get_case(case_id).find_entity(attr=attr, value=value)
+ return {"entity": entity}
+
+
@router.post("/{case_id}/entities")
def add_entity(case_id: str, body: EntityIn) -> dict[str, Any]:
case = get_case(case_id)
- return case.add_entity(
- body.type, body.label, body.attrs, by="user", status=body.status # type: ignore[arg-type]
- )
+ if body.type == "note":
+ attrs = body.attrs
+ return case.create_note(
+ body.label.strip(),
+ str(attrs.get("folder", "")).strip(),
+ str(attrs.get("content", "")),
+ )
+ return case.add_entity(body.type, body.label, body.attrs, by="user", status=body.status)
@router.patch("/{case_id}/entities/{entity_id}")
@@ -259,35 +342,39 @@ def entity_dependents(case_id: str, entity_id: str) -> dict[str, Any]:
}
[email protected]("/{case_id}/entities/{entity_id}")
-def remove_entity(case_id: str, entity_id: str) -> dict[str, Any]:
- """Delete an entity and the on-disk artifact it stands for, so removing a
- row in the sidebar deletes it everywhere it appears (spec §3.5)."""
[email protected]("/{case_id}/entities/{entity_id}/chain")
+def entity_chain(case_id: str, entity_id: str) -> dict[str, Any]:
+ """One entity plus its derivation chain (sources, dependents, lost sources),
+ read from its incident links only — the Details panel's relations without
+ shipping the whole graph (Step 5)."""
case = get_case(case_id)
- try:
- return delete_entity_deep(case, entity_id)
- except CaseError as exc:
- raise HTTPException(status_code=404, detail=str(exc)) from exc
+ chain = link_engine.chain_of(case, entity_id)
+ if chain is None:
+ raise HTTPException(status_code=404, detail=f"entity '{entity_id}' not found")
+ return chain
[email protected]("/{case_id}/links")
-def add_link(case_id: str, body: LinkIn) -> dict[str, Any]:
[email protected]("/{case_id}/entities/{entity_id}/derivation")
+def entity_derivation(case_id: str, entity_id: str) -> dict[str, Any]:
+ """The transitive ``derived-from`` closure rooted at this entity as
+ ``{entities, links}`` — the Post composer traces a proof back to its original
+ downloaded media over this slice, not the whole graph (Step 5)."""
case = get_case(case_id)
- try:
- return case.add_link(
- body.from_id, body.to_id, body.type, by="user", status=body.status # type: ignore[arg-type]
- )
- except CaseError as exc:
- raise HTTPException(status_code=404, detail=str(exc)) from exc
+ subgraph = link_engine.derivation_subgraph(case, entity_id)
+ if subgraph is None:
+ raise HTTPException(status_code=404, detail=f"entity '{entity_id}' not found")
+ return subgraph
[email protected]("/{case_id}/links/{link_id}")
-def remove_link(case_id: str, link_id: str) -> dict[str, str]:
[email protected]("/{case_id}/entities/{entity_id}")
+def remove_entity(case_id: str, entity_id: str) -> dict[str, Any]:
+ """Delete an entity and the on-disk artifact it stands for, so removing a
+ row in the sidebar deletes it everywhere it appears (spec §3.5)."""
+ case = get_case(case_id)
try:
- get_case(case_id).remove_link(link_id)
+ return delete_entity_deep(case, entity_id)
except CaseError as exc:
raise HTTPException(status_code=404, detail=str(exc)) from exc
- return {"status": "deleted"}
@router.get("/{case_id}/folders")
@@ -307,4 +394,3 @@ def add_folder(case_id: str, body: FolderIn) -> list[str]:
@router.delete("/{case_id}/folders")
def remove_folder(case_id: str, name: str) -> list[str]:
return get_case(case_id).remove_folder(name)
-
diff --git a/src/azimut/api/ingest.py b/src/azimut/api/ingest.py
index 9625e21..2e724d1 100644
--- a/src/azimut/api/ingest.py
+++ b/src/azimut/api/ingest.py
@@ -38,12 +38,10 @@ from ..engine import geo, mapsites, media as media_engine, satellite as satellit
from ..workspace import Case
from . import events
from .cases import get_case
+from .limits import MAX_IMAGE_BYTES
router = APIRouter(prefix="/api/ingest", tags=["ingest"])
-# Screenshots are viewport-sized PNGs — a 4K display lands well under this.
-MAX_IMAGE_BYTES = 25 * 1024 * 1024
-
# Browser extensions are the only cross-origin callers these routes accept.
EXTENSION_ORIGIN_SCHEMES = ("chrome-extension://", "moz-extension://", "safari-web-extension://")
@@ -160,7 +158,7 @@ async def ingest_screenshot(
parsed = mapsites.parse_map_url(url)
if parsed is None:
raise HTTPException(
- status_code=422, detail="not a recognized map site — captures are for maps only"
+ status_code=422, detail="not a recognized map site; captures are for maps only"
)
# popup corrections win; the URL fills whatever the client didn't send
diff --git a/src/azimut/api/inspect.py b/src/azimut/api/inspect.py
index b544e6a..12ff7c9 100644
--- a/src/azimut/api/inspect.py
+++ b/src/azimut/api/inspect.py
@@ -87,6 +87,7 @@ class StitchIn(BaseModel):
class EnhanceVideoIn(BaseModel):
path: str
params: dict[str, Any] = {}
+ rotation: Literal[-180, -90, 0, 90, 180] = 0
label: str | None = None
folder: str | None = None
@@ -238,11 +239,12 @@ def compose_preview(case_id: str, body: ComposeIn) -> Response:
@router.post("/cases/{case_id}/inspect/enhance-video")
def enhance_video(case_id: str, body: EnhanceVideoIn) -> dict[str, Any]:
- """Re-encode a video with the gear's adjustments and file it as new media."""
+ """Re-encode a video with its adjustments and orientation, then file it."""
case = get_case(case_id)
try:
return inspect_engine.enhance_video(
- case, body.path, body.params, label=body.label, folder=body.folder
+ case, body.path, body.params, rotation=body.rotation,
+ label=body.label, folder=body.folder,
)
except CaseError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
diff --git a/src/azimut/api/limits.py b/src/azimut/api/limits.py
new file mode 100644
index 0000000..641018a
--- /dev/null
+++ b/src/azimut/api/limits.py
@@ -0,0 +1,4 @@
+"""Shared request-body limits for API surfaces that ingest the same data."""
+
+# A viewport screenshot, including a 4K display, stays comfortably below this.
+MAX_IMAGE_BYTES = 25 * 1024 * 1024
diff --git a/src/azimut/api/media.py b/src/azimut/api/media.py
index cb62b90..040182b 100644
--- a/src/azimut/api/media.py
+++ b/src/azimut/api/media.py
@@ -9,7 +9,8 @@ from pydantic import BaseModel, HttpUrl
from .. import jobs
from ..engine import media as media_engine
-from ..workspace import CaseError
+from ..engine import thumbnails as thumbnail_engine
+from ..workspace import Case, CaseError
from .cases import delete_by_path, get_case
router = APIRouter(prefix="/api", tags=["media"])
@@ -32,9 +33,61 @@ class UpdateIn(BaseModel):
title: str | None = None
+class ThumbRegenIn(BaseModel):
+ path: str | None = None
+
+
+def _with_thumb_state(case: Case, items: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Tag each media item with a ``thumb_state`` the grid renders: ``ready`` when
+ the cached file is present, ``queued``/``running``/``failed`` from its
+ thumbnail job while the worker is on it, else ``none`` (no thumbnail, e.g. an
+ audio file, or one pruned from the cache). A referenced-but-missing thumbnail
+ (evicted by the budget) is reported as absent so the grid falls back cleanly.
+ """
+ jobs_by_path = {j["key"]: j for j in case.list_jobs(kind=thumbnail_engine.THUMB_KIND)}
+ for item in items:
+ thumb = item.get("thumbnail")
+ if thumb and case.resolve_inside(thumb).exists():
+ item["thumb_state"] = "ready"
+ continue
+ item["thumbnail"] = None
+ if item.get("kind") not in thumbnail_engine.THUMBNAILED_KINDS:
+ item["thumb_state"] = "none"
+ else:
+ job = jobs_by_path.get(item["path"])
+ item["thumb_state"] = (
+ job["state"] if job and job["state"] in ("queued", "running", "failed") else "none"
+ )
+ return items
+
+
@router.get("/cases/{case_id}/media")
def list_media(case_id: str) -> list[dict[str, Any]]:
- return media_engine.list_media(get_case(case_id))
+ case = get_case(case_id)
+ return _with_thumb_state(case, media_engine.list_media(case))
+
+
[email protected]("/cases/{case_id}/media/thumbnails/regenerate")
+def regenerate_thumbnails(case_id: str, body: ThumbRegenIn) -> dict[str, int]:
+ """Queue (re)generation of thumbnails. With a ``path`` it re-queues that one
+ item — the per-card retry for a failed thumbnail. Without one it queues every
+ thumbnailable item whose cached thumbnail is missing or failed, skipping the
+ ones already ready. The single worker drains the queue one at a time.
+ """
+ case = get_case(case_id)
+ items = media_engine.list_media(case)
+ if body.path is not None:
+ targets = [i["path"] for i in items if i["path"] == body.path]
+ else:
+ targets = [
+ i["path"]
+ for i in items
+ if i.get("kind") in thumbnail_engine.THUMBNAILED_KINDS
+ and not (i.get("thumbnail") and case.resolve_inside(i["thumbnail"]).exists())
+ ]
+ for path in targets:
+ thumbnail_engine.enqueue(case, path)
+ return {"queued": len(targets)}
@router.post("/cases/{case_id}/media/upload")
diff --git a/src/azimut/api/satellite.py b/src/azimut/api/satellite.py
index eea5a79..6d3c626 100644
--- a/src/azimut/api/satellite.py
+++ b/src/azimut/api/satellite.py
@@ -3,12 +3,16 @@
from __future__ import annotations
import json
+import math
+import os
import re
+import tempfile
from datetime import datetime, timezone
+from pathlib import Path
from typing import Any
import httpx
-from fastapi import APIRouter, Form, HTTPException, UploadFile
+from fastapi import APIRouter, Form, HTTPException, Query, UploadFile
from fastapi.responses import Response
from PIL import Image
from pydantic import BaseModel, Field
@@ -25,6 +29,7 @@ from ..engine import (
)
from ..workspace import CaseError
from .cases import delete_by_path, get_case
+from .limits import MAX_IMAGE_BYTES
router = APIRouter(prefix="/api", tags=["satellite"])
@@ -200,7 +205,7 @@ def sentinel_dates(lat: float, lon: float, start: str, end: str) -> dict[str, An
raise HTTPException(
status_code=429,
detail=f"Sentinel Hub is paused: {int(config.BLOCK_SHARE * 100)}% of the monthly "
- "free tier is used — enable the override in Settings to keep going",
+ "free tier is used; enable the override in Settings to keep going",
)
try:
found = sentinel.dates(instance, lat, lon, start, end)
@@ -210,6 +215,28 @@ def sentinel_dates(lat: float, lon: float, start: str, end: str) -> dict[str, An
return {"dates": found, "start": start, "end": end}
[email protected]("/satellite/sentinel/coverage")
+def sentinel_coverage(
+ lat: float, lon: float, layer: str, date: str
+) -> dict[str, Any]:
+ """Verify a candidate date against the configured layer at the crosshair."""
+ instance = _sentinel_instance()
+ if config.usage_blocked("sentinelhub"):
+ raise HTTPException(
+ status_code=429,
+ detail=f"Sentinel Hub is paused: {int(config.BLOCK_SHARE * 100)}% of the monthly "
+ "free tier is used; enable the override in Settings to keep going",
+ )
+ try:
+ result = sentinel.coverage(instance, lat, lon, layer, date)
+ except ValueError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ except Exception as exc:
+ raise HTTPException(status_code=502, detail=f"coverage check failed: {exc}") from exc
+ config.record_usage("sentinelhub", 1)
+ return result
+
+
@router.post("/satellite/usage/{meter}")
def record_widget_usage(meter: str) -> dict[str, Any]:
"""Count one billed *map load* for a widget basemap.
@@ -317,17 +344,20 @@ def tile_proxy(provider_id: str, z: int, x: int, y: int) -> Response:
(404s / "not yet available" placeholders) are overzoomed — the parent
tile's quadrant upscaled — instead of breaking the map.
"""
- if z < 0 or not (0 <= x < (1 << z)) or not (0 <= y < (1 << z)):
- raise HTTPException(status_code=422, detail="tile coordinates out of range")
try:
provider = tiles.get_provider(provider_id)
except KeyError as exc:
raise HTTPException(status_code=404, detail=str(exc)) from exc
+ if z < 0 or z > provider.max_zoom:
+ raise HTTPException(status_code=422, detail="tile zoom out of range")
+ grid_size = 1 << z
+ if not (0 <= x < grid_size) or not (0 <= y < grid_size):
+ raise HTTPException(status_code=422, detail="tile coordinates out of range")
if provider.meter and config.usage_blocked(provider.meter):
raise HTTPException(
status_code=429,
detail=f"{provider.label} is paused: {int(config.BLOCK_SHARE * 100)}% of the "
- "monthly free tier is used — enable the override in Settings to keep going",
+ "monthly free tier is used; enable the override in Settings to keep going",
)
# Past the provider's native ceiling there is nothing new upstream: Sentinel
@@ -375,7 +405,12 @@ def tile_proxy(provider_id: str, z: int, x: int, y: int) -> Response:
@router.get("/satellite/imagery-date")
-def imagery_date(lat: float, lon: float, zoom: int, provider: str = "esri-world-imagery") -> dict[str, Any]:
+def imagery_date(
+ lat: float = Query(ge=-90, le=90),
+ lon: float = Query(ge=-180, le=180),
+ zoom: int = Query(ge=1, le=22),
+ provider: str = "esri-world-imagery",
+) -> dict[str, Any]:
"""Best-effort acquisition date of the imagery under a point.
Only Esri World Imagery exposes per-scene capture dates; for any other
@@ -474,6 +509,7 @@ def capture(case_id: str, body: CaptureIn) -> dict[str, Any]:
extra_attrs={
"coords": coords_dd, "lat": marker_lat, "lon": marker_lon,
"plus_code": plus_code, "zoom": provenance["zoom"], "bearing": body.bearing,
+ "provider": provenance["provider"],
},
title=label,
dedupe=False, # a capture is 1:1 with its entity — never collapse re-captures
@@ -520,7 +556,12 @@ async def capture_screenshot(
import io
- raw = await image.read()
+ raw = await image.read(MAX_IMAGE_BYTES + 1)
+ if len(raw) > MAX_IMAGE_BYTES:
+ raise HTTPException(
+ status_code=413,
+ detail=f"screenshot must be under {MAX_IMAGE_BYTES // 1024 // 1024} MB",
+ )
try:
img = Image.open(io.BytesIO(raw)).convert("RGB")
except Exception as exc:
@@ -565,6 +606,7 @@ async def capture_screenshot(
extra_attrs={
"coords": coords_dd, "lat": lat, "lon": lon,
"plus_code": plus_code, "zoom": zoom, "bearing": bearing,
+ "provider": prov.id,
},
title=label,
dedupe=False,
@@ -634,6 +676,99 @@ def update_capture(case_id: str, body: SatelliteUpdateIn) -> dict[str, Any]:
return {**(updated.get("source") or {}), **updated}
+def _grid_number(value: Any, name: str, *, low: float, high: float) -> float:
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ raise ValueError(f"grid {name} must be a finite number")
+ try:
+ number = float(value)
+ except (OverflowError, ValueError) as exc:
+ raise ValueError(f"grid {name} must be a finite number") from exc
+ if not math.isfinite(number):
+ raise ValueError(f"grid {name} must be a finite number")
+ if not low <= number <= high:
+ raise ValueError(f"grid {name} is out of range")
+ return number
+
+
+def _validate_grid_spec(value: Any) -> dict[str, Any]:
+ """Return a usable saved grid or raise a concise corruption error."""
+ if not isinstance(value, dict):
+ raise ValueError("grid root must be an object")
+ if value.get("azimut_grid") != 1:
+ raise ValueError("grid schema is not supported")
+ cell_m = _grid_number(value.get("cell_m"), "cell size", low=1, high=1_000_000)
+ anchor = value.get("anchor")
+ if not isinstance(anchor, dict):
+ raise ValueError("grid anchor must be an object")
+ _grid_number(anchor.get("lat"), "anchor latitude", low=-90, high=90)
+ _grid_number(anchor.get("lon"), "anchor longitude", low=-180, high=180)
+ lat_step = _grid_number(value.get("lat_step"), "latitude step", low=0, high=180)
+ lon_step = _grid_number(value.get("lon_step"), "longitude step", low=0, high=360)
+ if cell_m <= 0 or lat_step <= 0 or lon_step <= 0:
+ raise ValueError("grid size and steps must be positive")
+
+ aoi = value.get("aoi")
+ if not isinstance(aoi, dict):
+ raise ValueError("grid area must be an object")
+ if aoi.get("type") == "rect":
+ bounds = aoi.get("bounds")
+ if not isinstance(bounds, dict):
+ raise ValueError("grid rectangle bounds must be an object")
+ south = _grid_number(bounds.get("south"), "south bound", low=-90, high=90)
+ north = _grid_number(bounds.get("north"), "north bound", low=-90, high=90)
+ west = _grid_number(bounds.get("west"), "west bound", low=-180, high=180)
+ east = _grid_number(bounds.get("east"), "east bound", low=-180, high=180)
+ if south >= north or west >= east:
+ raise ValueError("grid rectangle bounds are empty or reversed")
+ elif aoi.get("type") == "polygon":
+ vertices = aoi.get("vertices")
+ if not isinstance(vertices, list) or len(vertices) < 3:
+ raise ValueError("grid polygon needs at least three vertices")
+ for index, vertex in enumerate(vertices):
+ if not isinstance(vertex, (list, tuple)) or len(vertex) != 2:
+ raise ValueError(f"grid polygon vertex {index} is invalid")
+ _grid_number(vertex[0], f"polygon latitude {index}", low=-90, high=90)
+ _grid_number(vertex[1], f"polygon longitude {index}", low=-180, high=180)
+ else:
+ raise ValueError("grid needs a rect or polygon area")
+
+ statuses = value.get("statuses")
+ if not isinstance(statuses, dict):
+ raise ValueError("grid statuses must be an object")
+ if len(statuses) > GRID_MAX_STATUSES:
+ raise ValueError("grid has too many cells")
+ for key, status in statuses.items():
+ if not isinstance(key, str) or re.fullmatch(r"-?\d+:-?\d+", key) is None:
+ raise ValueError("grid contains an invalid cell key")
+ if status not in GRID_STATUSES:
+ raise ValueError("grid contains an invalid cell status")
+ if "title" in value and not isinstance(value["title"], str):
+ raise ValueError("grid title must be text")
+ return value
+
+
+def _read_grid(path: Path) -> dict[str, Any]:
+ try:
+ value = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError) as exc:
+ raise ValueError("grid file is not readable JSON") from exc
+ return _validate_grid_spec(value)
+
+
+def _write_grid_atomic(path: Path, spec: dict[str, Any]) -> None:
+ payload = json.dumps(spec, indent=2, ensure_ascii=False, allow_nan=False) + "\n"
+ fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)
+ tmp_path = path.with_name(os.path.basename(tmp_name))
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ handle.write(payload)
+ handle.flush()
+ os.fsync(handle.fileno())
+ os.replace(tmp_path, path)
+ finally:
+ tmp_path.unlink(missing_ok=True)
+
+
@router.get("/cases/{case_id}/search-grids")
def list_search_grids(case_id: str) -> list[dict[str, Any]]:
"""Summaries of every saved grid, newest first, for the picker."""
@@ -641,10 +776,8 @@ def list_search_grids(case_id: str) -> list[dict[str, Any]]:
out = []
for spec_path in case.subdir("search").glob("*.json"):
try:
- spec = json.loads(spec_path.read_text(encoding="utf-8"))
- except (OSError, json.JSONDecodeError):
- continue
- if spec.get("azimut_grid") != 1:
+ spec = _read_grid(spec_path)
+ except ValueError:
continue
statuses = spec.get("statuses") or {}
out.append({
@@ -669,7 +802,10 @@ def get_search_grid(case_id: str, name: str) -> dict[str, Any]:
raise HTTPException(status_code=403, detail=str(exc)) from exc
if not spec_path.exists():
raise HTTPException(status_code=404, detail="grid not found")
- return json.loads(spec_path.read_text(encoding="utf-8"))
+ try:
+ return _read_grid(spec_path)
+ except ValueError as exc:
+ raise HTTPException(status_code=422, detail=f"corrupt grid: {exc}") from exc
@router.put("/cases/{case_id}/search-grids/{name}")
@@ -695,8 +831,12 @@ def save_search_grid(case_id: str, name: str, body: GridSaveIn) -> dict[str, Any
spec.setdefault("title", slug)
spec.setdefault("created_at", _now())
spec["updated_at"] = _now()
+ try:
+ _validate_grid_spec(spec)
+ except ValueError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
spec_path = case.subdir("search") / f"{slug}.json"
- spec_path.write_text(json.dumps(spec, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+ _write_grid_atomic(spec_path, spec)
return {"name": slug, "title": spec["title"], "updated_at": spec["updated_at"]}
diff --git a/src/azimut/api/settings.py b/src/azimut/api/settings.py
index 7f60ecd..0e1faf9 100644
--- a/src/azimut/api/settings.py
+++ b/src/azimut/api/settings.py
@@ -11,12 +11,12 @@ from __future__ import annotations
import json
import re
-from typing import Any
+from typing import Annotated, Any, Literal
import httpx
from fastapi import APIRouter, HTTPException, Response, UploadFile
from fastapi.responses import FileResponse
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, ConfigDict, Field, field_validator
from .. import __version__, config
from ..engine import ffmpeg, google_tiles, scrapers, sentinel, tiles, updates
@@ -277,22 +277,128 @@ def export_settings() -> Response:
)
+ShortId = Annotated[str, Field(min_length=1, max_length=64, pattern=r"^[A-Za-z0-9_-]+$")]
+SecretValue = Annotated[str, Field(max_length=4096)]
+UsageMonth = Annotated[str, Field(pattern=r"^\d{4}-(0[1-9]|1[0-2])$")]
+UsageCount = Annotated[int, Field(ge=0, le=1_000_000_000_000)]
+FreeTier = Annotated[int, Field(ge=1, le=10_000_000)]
+EcoZoom = Annotated[int, Field(ge=0, le=21)]
+
+
+class ImportedTileProvider(BaseModel):
+ """Canonical shape of a custom XYZ provider in a settings backup."""
+
+ model_config = ConfigDict(extra="ignore", strict=True)
+
+ id: ShortId
+ url: str = Field(min_length=1, max_length=2048)
+ label: str | None = Field(default=None, max_length=120)
+ attribution: str | None = Field(default=None, max_length=500)
+ max_zoom: int = Field(default=19, ge=1, le=24)
+ imagery: bool = True
+ tile_size: Literal[256, 512] = 256
+
+
+class ImportedProviderStatus(BaseModel):
+ model_config = ConfigDict(extra="ignore", strict=True)
+
+ ok: bool
+ detail: str = Field(default="", max_length=300)
+ at: str = Field(default="", max_length=64)
+
+
+class ImportedHomeView(BaseModel):
+ model_config = ConfigDict(extra="forbid", strict=True)
+
+ lat: float = Field(ge=-90, le=90)
+ lon: float = Field(ge=-180, le=180)
+ zoom: int = Field(ge=1, le=21)
+
+
+class ImportedSettings(BaseModel):
+ """Validated, canonical subset of a settings backup.
+
+ Unknown top-level and provider keys are ignored for forward compatibility.
+ Every key this build recognises is strictly typed and bounded before the
+ live file is touched.
+ """
+
+ model_config = ConfigDict(extra="ignore", strict=True, populate_by_name=True)
+
+ schema_version: int = Field(
+ default=config.SETTINGS_SCHEMA,
+ alias="schema",
+ ge=config.SETTINGS_SCHEMA,
+ le=config.SETTINGS_SCHEMA,
+ )
+ tile_providers: list[ImportedTileProvider] = Field(default_factory=list, max_length=100)
+ api_keys: dict[ShortId, SecretValue] = Field(default_factory=dict, max_length=128)
+ usage: dict[ShortId, dict[UsageMonth, UsageCount]] = Field(
+ default_factory=dict, max_length=128
+ )
+ providers_enabled: dict[ShortId, bool] = Field(default_factory=dict, max_length=128)
+ usage_overrides: dict[ShortId, bool] = Field(default_factory=dict, max_length=128)
+ free_tiers: dict[ShortId, FreeTier] = Field(default_factory=dict, max_length=128)
+ provider_status: dict[ShortId, ImportedProviderStatus] = Field(
+ default_factory=dict, max_length=128
+ )
+ eco_zoom_fallback: bool = True
+ eco_max_zoom: int = Field(default=config.ECO_MAX_ZOOM, ge=1, le=21)
+ eco_max_zooms: dict[ShortId, EcoZoom] = Field(default_factory=dict, max_length=128)
+ coord_format: Literal["dd", "dms", "mgrs"] = "dd"
+ units: Literal["metric", "imperial"] = "metric"
+ home_view: ImportedHomeView = Field(
+ default_factory=lambda: ImportedHomeView.model_validate(DEFAULT_HOME_VIEW)
+ )
+ post_mention: str = Field(default=DEFAULT_POST_MENTION, max_length=64)
+ post_target: Literal["x", "bluesky", "mastodon"] = DEFAULT_POST_TARGET
+ signature_handle: str = Field(default=DEFAULT_SIGNATURE_HANDLE, max_length=64)
+ ingest_token: str = Field(default="", max_length=128, pattern=r"^[A-Za-z0-9_-]*$")
+ update_check_on_start: bool = True
+ update_dismissed_version: str = Field(default="", max_length=64)
+
+ @field_validator("api_keys")
+ @classmethod
+ def canonical_keys(cls, value: dict[str, str]) -> dict[str, str]:
+ return {key: secret for key, raw in value.items() if (secret := raw.strip())}
+
+ @field_validator("providers_enabled", "usage_overrides")
+ @classmethod
+ def canonical_keyed_flags(cls, value: dict[str, bool]) -> dict[str, bool]:
+ return {key: enabled for key, enabled in value.items() if key in KEYED_PROVIDERS}
+
+ @field_validator("free_tiers", "provider_status")
+ @classmethod
+ def canonical_meter_maps(cls, value: dict[str, Any]) -> dict[str, Any]:
+ return {key: item for key, item in value.items() if key in config.FREE_TIER}
+
+ @field_validator("eco_max_zooms")
+ @classmethod
+ def canonical_eco_zooms(cls, value: dict[str, int]) -> dict[str, int]:
+ return {key: zoom for key, zoom in value.items() if key in ECO_TUNABLE}
+
+ @field_validator("post_mention", "signature_handle", "update_dismissed_version")
+ @classmethod
+ def strip_short_text(cls, value: str) -> str:
+ return value.strip()
+
+
class ImportIn(BaseModel):
"""A previously exported settings blob. Only keys Azimut recognises are
applied — anything else in the file is ignored, so a hand-edited or foreign
JSON can't inject arbitrary state."""
- settings: dict[str, Any]
+ settings: ImportedSettings
@router.post("/settings/import")
def import_settings(body: ImportIn) -> dict[str, Any]:
- known = set(config.DEFAULT_SETTINGS)
- applied = sorted(k for k in body.settings if k in known)
+ canonical = body.settings.model_dump(exclude_unset=True, by_alias=True)
+ applied = sorted(canonical)
def apply(settings: dict[str, Any]) -> None:
for key in applied:
- settings[key] = body.settings[key]
+ settings[key] = canonical[key]
config.update_settings(apply)
return {"imported": applied}
diff --git a/src/azimut/cli.py b/src/azimut/cli.py
index 1384986..338ae4a 100644
--- a/src/azimut/cli.py
+++ b/src/azimut/cli.py
@@ -11,13 +11,13 @@ DEFAULT_PORT = 8477 # uncommon high port, clear of common dev ranges
def main() -> None:
- parser = argparse.ArgumentParser(prog="azimut", description="Azimut — the OSINT investigator's workbench")
+ parser = argparse.ArgumentParser(prog="azimut", description="Azimut, a local OSINT workspace")
parser.add_argument("--port", type=int, default=DEFAULT_PORT)
parser.add_argument("--no-browser", action="store_true", help="don't open the browser tab")
parser.add_argument("--version", action="version", version=f"azimut {__version__}")
args = parser.parse_args()
- print(f"Azimut {__version__} — http://127.0.0.1:{args.port} (local only, nothing leaves this machine)")
+ print(f"Azimut {__version__} · http://127.0.0.1:{args.port} (local only)")
print("Runs in your browser tab. Close this window to stop Azimut.")
serve(args.port, open_browser=not args.no_browser)
diff --git a/src/azimut/config.py b/src/azimut/config.py
index 5447fe2..8b00f7d 100644
--- a/src/azimut/config.py
+++ b/src/azimut/config.py
@@ -266,12 +266,23 @@ def load_settings() -> dict[str, Any]:
def save_settings(settings: dict[str, Any]) -> None:
- settings_path().parent.mkdir(parents=True, exist_ok=True)
- settings_path().write_text(
- json.dumps(settings, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
- )
- # Holds the user's API keys and pairing token — owner-read/write only.
- _restrict(settings_path(), 0o600)
+ path = settings_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ _restrict(path.parent, 0o700)
+ payload = json.dumps(settings, indent=2, ensure_ascii=False, allow_nan=False) + "\n"
+ fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)
+ tmp_path = Path(tmp_name)
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ handle.write(payload)
+ handle.flush()
+ os.fsync(handle.fileno())
+ _restrict(tmp_path, 0o600)
+ os.replace(tmp_path, path)
+ # Holds the user's API keys and pairing token — owner-read/write only.
+ _restrict(path, 0o600)
+ finally:
+ tmp_path.unlink(missing_ok=True)
def month_key(when: datetime | None = None) -> str:
diff --git a/src/azimut/engine/inspect.py b/src/azimut/engine/inspect.py
index 0051c13..219e55c 100644
--- a/src/azimut/engine/inspect.py
+++ b/src/azimut/engine/inspect.py
@@ -22,6 +22,8 @@ import base64
import io
import json
import subprocess
+import tempfile
+import threading
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
@@ -44,6 +46,23 @@ SUGGEST_CAP = 60 # hard cap on how many "sharpest frame" suggestions we return
SCAN_DIM = 480
+def _scan_timeout(duration: float) -> float:
+ """Allow slow software decoding without letting a broken scan run forever."""
+ return max(30.0, min(1800.0, duration * 4 + 15))
+
+
+def _stop_process(proc: subprocess.Popen[Any]) -> None:
+ """Stop a child promptly, escalating when graceful termination stalls."""
+ if proc.poll() is not None:
+ return
+ proc.terminate()
+ try:
+ proc.wait(timeout=2)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ proc.wait(timeout=2)
+
+
def _now() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
@@ -270,7 +289,7 @@ def _ela(img: Image.Image, params: dict[str, Any]) -> dict[str, Any]:
"kind": "image",
"data_url": f"data:image/png;base64,{data}",
"note": "Error Level Analysis is a tampering *hint*, not proof. "
- "Bright, uneven regions can indicate edits — or just texture and edges.",
+ "Bright, uneven regions can indicate edits, texture or hard edges.",
}
@@ -469,31 +488,54 @@ def scan_focus(
expected = max(1, int(duration * fps))
frame_bytes = w * h
- proc = subprocess.Popen(
- [ffmpeg_engine.ffmpeg_exe(), "-v", "error", "-i", str(video_path),
- "-vf", f"scale={w}:{h}", "-f", "rawvideo", "-pix_fmt", "gray", "pipe:1"],
- stdout=subprocess.PIPE, stderr=subprocess.PIPE,
- )
out: list[dict[str, Any]] = []
- try:
- assert proc.stdout is not None
- index = 0
- while True:
- buf = proc.stdout.read(frame_bytes)
- if not buf or len(buf) < frame_bytes:
- break
- gray = np.frombuffer(buf, dtype=np.uint8).reshape(h, w)
- out.append({"time": round(index / fps, 3), "score": round(_focus_score(gray), 4)})
- index += 1
- if set_progress and index % 25 == 0:
- set_progress({"percent": round(min(99.0, index * 100 / expected), 1)})
- finally:
- if proc.stdout:
- proc.stdout.close()
- err = proc.stderr.read() if proc.stderr else b""
- if proc.stderr:
- proc.stderr.close()
- proc.wait()
+ timed_out = threading.Event()
+ with tempfile.TemporaryFile() as stderr_file:
+ proc = subprocess.Popen(
+ [ffmpeg_engine.ffmpeg_exe(), "-v", "error", "-i", str(video_path),
+ "-vf", f"scale={w}:{h}", "-f", "rawvideo", "-pix_fmt", "gray", "pipe:1"],
+ stdout=subprocess.PIPE, stderr=stderr_file,
+ )
+
+ def expire() -> None:
+ timed_out.set()
+ _stop_process(proc)
+
+ timer = threading.Timer(_scan_timeout(duration), expire)
+ timer.daemon = True
+ timer.start()
+ try:
+ assert proc.stdout is not None
+ index = 0
+ while True:
+ buf = proc.stdout.read(frame_bytes)
+ if not buf or len(buf) < frame_bytes:
+ break
+ gray = np.frombuffer(buf, dtype=np.uint8).reshape(h, w)
+ out.append({"time": round(index / fps, 3), "score": round(_focus_score(gray), 4)})
+ index += 1
+ if set_progress and index % 25 == 0:
+ set_progress({"percent": round(min(99.0, index * 100 / expected), 1)})
+ except BaseException:
+ _stop_process(proc)
+ raise
+ finally:
+ timer.cancel()
+ if proc.stdout:
+ proc.stdout.close()
+ if proc.poll() is None:
+ try:
+ proc.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ _stop_process(proc)
+ stderr_file.seek(0)
+ err = stderr_file.read()
+ if timed_out.is_set():
+ raise RuntimeError("frame scan timed out")
+ if proc.returncode not in (0, None):
+ raise RuntimeError(
+ (err or b"").decode("utf-8", "replace").strip() or "frame scan failed"
+ )
if not out:
raise RuntimeError(
(err or b"").decode("utf-8", "replace").strip() or "frame scan decoded nothing"
@@ -821,20 +863,40 @@ def _eq_filterchain(params: dict[str, Any]) -> str | None:
return ",".join(parts) or None
+def _rotation_filterchain(rotation: int) -> str | None:
+ """Map the UI's clockwise degrees to ffmpeg right-angle filters."""
+ chains = {
+ -180: "hflip,vflip",
+ -90: "transpose=cclock",
+ 0: None,
+ 90: "transpose=clock",
+ 180: "hflip,vflip",
+ }
+ if rotation not in chains:
+ raise ValueError("video rotation must be -180, -90, 0, 90 or 180 degrees")
+ return chains[rotation]
+
+
+def _video_filterchain(params: dict[str, Any], rotation: int) -> str | None:
+ parts = (_rotation_filterchain(rotation), _eq_filterchain(params))
+ return ",".join(part for part in parts if part) or None
+
+
def enhance_video(
case: Case,
video_rel: str,
params: dict[str, Any],
*,
+ rotation: int = 0,
label: str | None = None,
folder: str | None = None,
) -> dict[str, Any]:
- """Re-encode a video with the gear's adjustments and file it as new media."""
+ """Re-encode a video with its adjustments and orientation, then file it."""
if not media_engine.ffmpeg_available():
raise RuntimeError("ffmpeg is required to enhance video")
- vf = _eq_filterchain(params)
+ vf = _video_filterchain(params, rotation)
if not vf:
- raise ValueError("no adjustments to apply — tune the gear first")
+ raise ValueError("no adjustments or rotation to apply")
src = case.resolve_inside(video_rel)
stem = Path(src.name).stem[:40]
@@ -842,7 +904,7 @@ def enhance_video(
try:
proc = subprocess.run(
[ffmpeg_engine.ffmpeg_exe(), "-y", "-loglevel", "error", "-i", str(src),
- "-vf", vf, "-c:a", "copy", str(tmp)],
+ "-vf", vf, "-c:a", "copy", "-metadata:s:v:0", "rotate=0", str(tmp)],
capture_output=True, timeout=600,
)
if proc.returncode != 0 or not tmp.exists():
@@ -850,7 +912,10 @@ def enhance_video(
(proc.stderr or b"").decode("utf-8", "replace").strip() or "video enhance failed"
)
name = f"{stem}_enhanced_{_stamp()}.mp4"
- source = _derivation(video_rel, _source_sha(case, video_rel), op="enhance-video", params=params)
+ source = _derivation(
+ video_rel, _source_sha(case, video_rel), op="enhance-video",
+ params=params, rotation=rotation,
+ )
result = media_engine.import_produced_file(case, tmp, name, source, by="inspect")
finally:
tmp.unlink(missing_ok=True)
diff --git a/src/azimut/engine/links.py b/src/azimut/engine/links.py
index e3564a8..af519f1 100644
--- a/src/azimut/engine/links.py
+++ b/src/azimut/engine/links.py
@@ -31,11 +31,14 @@ from __future__ import annotations
from datetime import datetime, timezone
from typing import Any
-from ..workspace import Case, CaseError
+from ..repository import CaseRepository
+from ..workspace import CaseError
DERIVED_FROM = "derived-from"
DEPENDS_ON = "depends-on"
+#: The two link types the derivation chain reads, in either direction.
+CHAIN_TYPES = (DERIVED_FROM, DEPENDS_ON)
#: Incoming links of these types take their holder down with the target.
CASCADE_TYPES = (DEPENDS_ON,)
#: Incoming links of these types leave their holder in place, with a tombstone.
@@ -49,11 +52,11 @@ def _now() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
-def _entity(case: Case, entity_id: str) -> dict[str, Any]:
- for entity in case.read()["entities"]:
- if entity["id"] == entity_id:
- return entity
- raise CaseError(f"entity '{entity_id}' not found")
+def _entity(case: CaseRepository, entity_id: str) -> dict[str, Any]:
+ entity = case.get_entity(entity_id)
+ if entity is None:
+ raise CaseError(f"entity '{entity_id}' not found")
+ return entity
def artifact_path(entity: dict[str, Any]) -> str | None:
@@ -65,14 +68,14 @@ def artifact_path(entity: dict[str, Any]) -> str | None:
return None
-def resolve(case: Case, rel_paths: list[str]) -> tuple[list[str], list[str]]:
+def resolve(case: CaseRepository, rel_paths: list[str]) -> tuple[list[str], list[str]]:
"""Map case-relative artifact paths to entity ids, in one read.
Returns ``(entity_ids, unresolved_paths)``. A path resolves to nothing when
its artifact was deleted while the tool that references it was open.
"""
by_path: dict[str, str] = {}
- for entity in case.read()["entities"]:
+ for entity in case.list_entities():
path = artifact_path(entity)
if path:
by_path.setdefault(path, entity["id"])
@@ -86,7 +89,7 @@ def resolve(case: Case, rel_paths: list[str]) -> tuple[list[str], list[str]]:
def sync(
- case: Case, entity_id: str, type_: str, rel_paths: list[str], *, by: str
+ case: CaseRepository, entity_id: str, type_: str, rel_paths: list[str], *, by: str
) -> None:
"""Restate an artifact's sources: reconcile its links, tombstone the rest.
@@ -101,7 +104,7 @@ def sync(
def link_all(
- case: Case, entity_id: str, type_: str, rel_paths: list[str], *, by: str
+ case: CaseRepository, entity_id: str, type_: str, rel_paths: list[str], *, by: str
) -> None:
"""Add an artifact's source links without removing any (see ``sync``).
@@ -135,7 +138,7 @@ def tombstone_of(entity: dict[str, Any]) -> dict[str, Any]:
return {k: v for k, v in fields.items() if v}
-def add_tombstone(case: Case, entity_id: str, info: dict[str, Any]) -> None:
+def add_tombstone(case: CaseRepository, entity_id: str, info: dict[str, Any]) -> None:
"""Record on an artifact that one of its sources is gone.
Keyed by path, so re-saving or a second delete never stacks duplicates.
@@ -143,7 +146,7 @@ def add_tombstone(case: Case, entity_id: str, info: dict[str, Any]) -> None:
add_tombstones(case, entity_id, [info])
-def add_tombstones(case: Case, entity_id: str, infos: list[dict[str, Any]]) -> None:
+def add_tombstones(case: CaseRepository, entity_id: str, infos: list[dict[str, Any]]) -> None:
"""Record several lost sources with one case read and at most one write."""
if not infos:
return
@@ -162,13 +165,13 @@ def add_tombstones(case: Case, entity_id: str, infos: list[dict[str, Any]]) -> N
case.update_entity(entity_id, {"attrs": {LOST: lost}})
-def losses(case: Case, doomed_ids: set[str]) -> dict[str, list[dict[str, Any]]]:
+def losses(case: CaseRepository, doomed_ids: set[str]) -> dict[str, list[dict[str, Any]]]:
"""Per surviving artifact, the doomed sources it *actually* derives from.
Scars belong only where the derivation was: a proof loses the media it was
composed from, not whatever else happened to be deleted in the same breath.
"""
- data = case.read()
+ data = case.snapshot()
by_id = {e["id"]: e for e in data["entities"]}
out: dict[str, list[dict[str, Any]]] = {}
for link in data["links"]:
@@ -182,7 +185,76 @@ def losses(case: Case, doomed_ids: set[str]) -> dict[str, list[dict[str, Any]]]:
return out
-def plan_delete(case: Case, entity_id: str) -> dict[str, list[dict[str, Any]]]:
+def chain_of(case: CaseRepository, entity_id: str) -> dict[str, Any] | None:
+ """One entity's derivation chain (ONTOLOGY §3), for the Details panel.
+
+ Mirrors the frontend ``chainOf``: its direct ``sources`` (outgoing
+ ``derived-from`` / ``depends-on`` edges), its direct ``dependents`` (the
+ incoming ones), and the tombstoned ``lost_sources`` it still carries. Reads
+ only the edges incident to this entity (``links_of``) plus each neighbour, so
+ it never materialises the whole graph. Returns ``None`` if the entity is
+ gone.
+ """
+ entity = case.get_entity(entity_id)
+ if entity is None:
+ return None
+ sources: list[dict[str, Any]] = []
+ dependents: list[dict[str, Any]] = []
+ for link in case.links_of(entity_id):
+ if link["type"] not in CHAIN_TYPES:
+ continue
+ if link["from"] == entity_id:
+ neighbour = case.get_entity(link["to"])
+ if neighbour is not None:
+ sources.append({"entity": neighbour, "type": link["type"]})
+ elif link["to"] == entity_id:
+ neighbour = case.get_entity(link["from"])
+ if neighbour is not None:
+ dependents.append({"entity": neighbour, "type": link["type"]})
+ lost = list(entity.get("attrs", {}).get(LOST, []))
+ return {
+ "entity": entity,
+ "sources": sources,
+ "lost": lost,
+ "dependents": dependents,
+ "empty": not sources and not lost and not dependents,
+ }
+
+
+def derivation_subgraph(case: CaseRepository, entity_id: str) -> dict[str, Any] | None:
+ """The transitive ``derived-from`` closure rooted at an entity.
+
+ Walks only the outgoing ``derived-from`` edges (artifact → source) through
+ bounded ``links_of`` reads and returns ``{entities, links}`` — the slice the
+ Post composer needs to trace a proof back to the original downloaded media it
+ was built from, without shipping the whole graph. Returns ``None`` if the
+ root entity is gone.
+ """
+ root = case.get_entity(entity_id)
+ if root is None:
+ return None
+ entities: dict[str, dict[str, Any]] = {entity_id: root}
+ links: list[dict[str, Any]] = []
+ seen_links: set[str] = set()
+ frontier = [entity_id]
+ while frontier:
+ current = frontier.pop()
+ for link in case.links_of(current):
+ if link["type"] != DERIVED_FROM or link["from"] != current:
+ continue
+ if link["id"] not in seen_links:
+ seen_links.add(link["id"])
+ links.append(link)
+ to_id = link["to"]
+ if to_id not in entities:
+ neighbour = case.get_entity(to_id)
+ if neighbour is not None:
+ entities[to_id] = neighbour
+ frontier.append(to_id)
+ return {"entities": list(entities.values()), "links": links}
+
+
+def plan_delete(case: CaseRepository, entity_id: str) -> dict[str, list[dict[str, Any]]]:
"""What deleting ``entity_id`` takes with it, and what it leaves standing.
``cascade`` follows ``depends-on`` transitively (a session dies with its
@@ -191,7 +263,7 @@ def plan_delete(case: Case, entity_id: str) -> dict[str, list[dict[str, Any]]]:
``tombstone`` lists the artifacts that survive with a scar, computed over
everything about to go, not just the entity that was asked for.
"""
- data = case.read()
+ data = case.snapshot()
by_id = {e["id"]: e for e in data["entities"]}
if entity_id not in by_id:
raise CaseError(f"entity '{entity_id}' not found")
diff --git a/src/azimut/engine/media.py b/src/azimut/engine/media.py
index e60a554..08e2677 100644
--- a/src/azimut/engine/media.py
+++ b/src/azimut/engine/media.py
@@ -12,7 +12,6 @@ import json
import mimetypes
import re
import shutil
-import subprocess
import uuid
from datetime import datetime, timezone
from pathlib import Path
@@ -23,9 +22,12 @@ from PIL import Image
from ..workspace import Case, ensure_dir
from . import ffmpeg as ffmpeg_engine
from . import links as link_engine
+from . import thumbnails as thumbnail_engine
-THUMB_DIR = ".thumbs"
-THUMB_MAX = 512
+# The thumbnail cache lives here; content-addressed generation, the durable job
+# model and cache budgeting are owned by `thumbnails.py`. Re-exported for the
+# test fixtures that build a case's `.thumbs/` directly.
+THUMB_DIR = thumbnail_engine.THUMB_DIR
SIDECAR_SUFFIX = ".azimut.json"
# a post's attachments (photos on a tweet, an album, …) fit comfortably under
# this; above it, treat the link as a real playlist and just grab its first
@@ -74,35 +76,6 @@ def ffmpeg_available() -> bool:
return ffmpeg_engine.ffmpeg_available()
-def make_thumbnail(media_path: Path, thumb_path: Path) -> bool:
- """Best-effort thumbnail. Images via Pillow, videos via ffmpeg if present."""
- ensure_dir(thumb_path.parent)
- kind = media_kind(media_path.name)
- try:
- if kind == "image":
- with Image.open(media_path) as img:
- rgb = img.convert("RGB")
- rgb.thumbnail((THUMB_MAX, THUMB_MAX))
- rgb.save(thumb_path, "JPEG", quality=82)
- return True
- if kind == "video" and ffmpeg_available():
- subprocess.run(
- [
- ffmpeg_engine.ffmpeg_exe(), "-y", "-loglevel", "error",
- "-ss", "1", "-i", str(media_path),
- "-frames:v", "1", "-vf", f"scale={THUMB_MAX}:-2",
- str(thumb_path),
- ],
- check=True,
- timeout=30,
- capture_output=True,
- )
- return thumb_path.exists()
- except Exception:
- thumb_path.unlink(missing_ok=True)
- return False
-
-
def _sidecar_path(media_path: Path) -> Path:
return media_path.with_name(media_path.name + SIDECAR_SUFFIX)
@@ -163,17 +136,20 @@ def _register(
return {"duplicate": True, "entity": existing, "item": read_item(case, existing["attrs"]["path"])}
rel_path = f"media/{media_path.name}"
- thumb = case.subdir("media") / THUMB_DIR / (media_path.name + ".jpg")
- has_thumb = make_thumbnail(media_path, thumb)
+ kind = media_kind(media_path.name)
+ # Cheap image thumbnails render inline for instant feedback; a failed image
+ # render and every (CPU-heavy) video are queued to the single worker, which
+ # fills the sidecar in later via `set_thumbnail`.
+ thumb_rel = thumbnail_engine.on_register(case, rel_path, digest, kind)
sidecar = {
"filename": media_path.name,
- "kind": media_kind(media_path.name),
+ "kind": kind,
"sha256": digest,
"size": media_path.stat().st_size,
"added_at": _now(),
"source": source,
- "thumbnail": f"media/{THUMB_DIR}/{media_path.name}.jpg" if has_thumb else None,
+ "thumbnail": thumb_rel,
}
if title:
sidecar["title"] = title
@@ -583,6 +559,19 @@ def download_url(
return result
+def set_thumbnail(case: Case, rel_path: str, thumb_rel: str | None) -> None:
+ """Record (or clear) a media item's thumbnail path in its sidecar. The
+ thumbnail worker calls this once it finishes a queued (e.g. video) render, so
+ the next media listing reports the thumbnail as ready."""
+ media_path = case.resolve_inside(rel_path)
+ sidecar = _sidecar_path(media_path)
+ if not sidecar.exists():
+ return
+ data = json.loads(sidecar.read_text(encoding="utf-8"))
+ data["thumbnail"] = thumb_rel
+ _write_sidecar(media_path, data)
+
+
def read_item(case: Case, rel_path: str) -> dict[str, Any] | None:
media_path = case.resolve_inside(rel_path)
sidecar = _sidecar_path(media_path)
@@ -661,4 +650,9 @@ def delete_media_files(case: Case, rel_path: str) -> None:
media_path.unlink(missing_ok=True)
sidecar.unlink(missing_ok=True)
if data and data.get("thumbnail"):
- case.resolve_inside(data["thumbnail"]).unlink(missing_ok=True)
+ # Thumbnails are content-addressed, so identical-bytes captures can share
+ # one file (satellite re-captures dedupe to the same sha). Drop the cached
+ # thumbnail only when no surviving sidecar still points at it.
+ thumb = data["thumbnail"]
+ if not any(it.get("thumbnail") == thumb for it in list_media(case)):
+ case.resolve_inside(thumb).unlink(missing_ok=True)
diff --git a/src/azimut/engine/scrapers.py b/src/azimut/engine/scrapers.py
index 9dc7338..f4e4d50 100644
--- a/src/azimut/engine/scrapers.py
+++ b/src/azimut/engine/scrapers.py
@@ -276,7 +276,7 @@ def _download_wheel(url: str, expected_sha256: str) -> bytes:
for chunk in response.iter_bytes():
buffer.write(chunk)
if buffer.tell() > WHEEL_MAX_BYTES:
- raise RuntimeError("scraper wheel is implausibly large — refusing")
+ raise RuntimeError("scraper wheel is implausibly large; refusing")
data = buffer.getvalue()
digest = hashlib.sha256(data).hexdigest()
if digest != expected_sha256:
@@ -333,7 +333,7 @@ def update(dist: str) -> dict[str, Any]:
"previous": before,
"restart_required": restart,
"detail": (
- f"updated to {version} — restart Azimut to use it"
+ f"updated to {version}; restart Azimut to use it"
if restart
else f"updated to {version}"
),
diff --git a/src/azimut/engine/sentinel.py b/src/azimut/engine/sentinel.py
index 3190440..aee5d06 100644
--- a/src/azimut/engine/sentinel.py
+++ b/src/azimut/engine/sentinel.py
@@ -18,6 +18,9 @@ instance itself, which is the only authority (user-triggered — local-first).
from __future__ import annotations
+import base64
+import io
+import math
import re
import xml.etree.ElementTree as ET
from dataclasses import dataclass
@@ -25,6 +28,7 @@ from datetime import date
from typing import Any, Callable
import httpx
+from PIL import Image, UnidentifiedImageError
BASE = "https://sh.dataspace.copernicus.eu/ogc"
USER_AGENT = "Azimut/0.1 (+local OSINT workbench; single-user)"
@@ -53,7 +57,7 @@ class Layer:
# `hint` is the reason to pick one — this is a workbench, and "SWIR" tells a
# user nothing about why they'd want it.
LAYERS: tuple[Layer, ...] = (
- Layer("TRUE_COLOR", "True colour", "Natural colour (B04/B03/B02) — what the eye would see."),
+ Layer("TRUE_COLOR", "True colour", "Natural colour (B04/B03/B02), close to what the eye would see."),
Layer(
"FALSE_COLOR",
"False colour (infrared)",
@@ -63,24 +67,24 @@ LAYERS: tuple[Layer, ...] = (
Layer(
"SWIR",
"SWIR (short-wave infrared)",
- "B12/B8A/B04: water is darkest of all — the strongest contrast for vessels at "
+ "B12/B8A/B04: water is darkest of all, giving the strongest contrast for vessels at "
"sea, and the band that sees through thin haze and smoke to fires and flares.",
),
- Layer("NDVI", "NDVI (vegetation index)", "Vegetation vigour — crops, clearing, seasonal change."),
+ Layer("NDVI", "NDVI (vegetation index)", "Vegetation vigour for crops, clearing and seasonal change."),
)
# Hints for layers we know but don't offer by default — a configuration that
# ships them gets the explanation, not a bare identifier.
KNOWN_HINTS: dict[str, str] = {
- "HIGHLIGHT_OPTIMIZED": "Natural colour with the highlights pulled back — bright objects on "
+ "HIGHLIGHT_OPTIMIZED": "Natural colour with highlights pulled back. Bright objects on "
"dark water keep their shape instead of blowing out.",
- "NDWI": "Water/land boundary as an index — the shoreline, flooding, and what is water at "
+ "NDWI": "Water/land boundary as an index. Shows shorelines, flooding and what is water at "
"all on a given date.",
"SCENE_CLASSIFICATION": "The scene's own per-pixel classes (cloud, shadow, water, "
- "vegetation) — whether a date is worth looking at before you look.",
- "MOISTURE_INDEX": "Surface/vegetation water content — irrigation, drought, burn scars.",
+ "vegetation). Use it to decide whether a date is worth opening.",
+ "MOISTURE_INDEX": "Surface and vegetation water content for irrigation, drought and burn scars.",
"FALSE_COLOR_URBAN": "B12/B11/B04: built-up surfaces separate from bare ground and vegetation.",
- "NDSI": "Snow index — snow and ice against cloud, which they otherwise resemble.",
+ "NDSI": "Snow index that separates snow and ice from similar-looking cloud.",
}
DEFAULT_LAYER = LAYERS[0].id
@@ -182,6 +186,32 @@ _BBOX_PAD = 0.005
# dates that collapsed to.
_MAX_FEATURES = 100
+# A metadata hit says a scene intersects the search area. It does not prove the
+# configured layer has source pixels at the crosshair. This tiny WMS override
+# asks the layer's own data source for dataMask only, over an 80 m square. The
+# 8x8 response is enough to answer coverage without paying to render a map tile.
+_COVERAGE_HALF_METRES = 40.0
+_COVERAGE_SIZE = 8
+_COVERAGE_MAX_BYTES = 1_000_000
+_COVERAGE_MAX_PIXELS = 4096
+_COVERAGE_EVALSCRIPT = base64.b64encode(
+ b"""//VERSION=3
+function setup() {
+ return {
+ input: ["dataMask"],
+ output: { bands: 1, sampleType: "UINT8" }
+ };
+}
+function evaluatePixel(sample) {
+ return [sample.dataMask * 255];
+}
+"""
+).decode("ascii")
+
+
+class CoverageError(RuntimeError):
+ """Sentinel Hub did not return a usable dataMask image."""
+
def _cloud(props: dict[str, Any]) -> float | None:
for name in ("cloudCoverPercentage", "tileCloudCoverPercentage"):
@@ -304,6 +334,73 @@ def dates(
return sorted(by_date.values(), key=lambda entry: entry["date"], reverse=True)
+def coverage(
+ instance: str,
+ lat: float,
+ lon: float,
+ layer: str,
+ day: str,
+ *,
+ get: Callable[..., Any] | None = None,
+) -> dict[str, Any]:
+ """Check whether ``layer`` has source pixels near a point on ``day``.
+
+ WFS supplies candidate acquisition dates. This WMS dataMask probe is the
+ final authority before the UI replaces a working map with a dated layer.
+ It uses the configured layer, so a custom layer is checked against its own
+ collection rather than the date catalogue's L2A assumption.
+ """
+ if not (-90 <= lat <= 90 and -180 <= lon <= 180):
+ raise ValueError("coordinates are outside WGS84 bounds")
+ # Reuse the variant parser as the validation boundary for both URL values.
+ checked_layer, checked_day, _ = parse_variant(
+ f"{layer}{VARIANT_SEP}{day}{VARIANT_SEP}{day}"
+ )
+
+ earth_radius = 6_378_137.0
+ clamped_lat = min(max(lat, -85.05112878), 85.05112878)
+ x = earth_radius * math.radians(lon)
+ y = earth_radius * math.log(math.tan(math.pi / 4 + math.radians(clamped_lat) / 2))
+ half = _COVERAGE_HALF_METRES
+ params = {
+ "SERVICE": "WMS",
+ "REQUEST": "GetMap",
+ "VERSION": "1.3.0",
+ "LAYERS": checked_layer,
+ "CRS": "EPSG:3857",
+ "BBOX": f"{x - half},{y - half},{x + half},{y + half}",
+ "WIDTH": str(_COVERAGE_SIZE),
+ "HEIGHT": str(_COVERAGE_SIZE),
+ "FORMAT": "image/png",
+ "TIME": f"{checked_day}/{checked_day}",
+ "EVALSCRIPT": _COVERAGE_EVALSCRIPT,
+ }
+ fetch = get or httpx.get
+ response = fetch(
+ f"{BASE}/wms/{instance}", params=params,
+ headers={"User-Agent": USER_AGENT}, timeout=15,
+ )
+ response.raise_for_status()
+ if len(response.content) > _COVERAGE_MAX_BYTES:
+ raise CoverageError("coverage probe returned an oversized image")
+ try:
+ with Image.open(io.BytesIO(response.content)) as source:
+ if source.width * source.height > _COVERAGE_MAX_PIXELS:
+ raise CoverageError("coverage probe returned an oversized image")
+ values = source.convert("L").tobytes()
+ except (OSError, UnidentifiedImageError) as exc:
+ raise CoverageError("coverage probe returned no readable image") from exc
+ if not values:
+ raise CoverageError("coverage probe returned an empty image")
+ valid = sum(value > 0 for value in values)
+ return {
+ "available": valid > 0,
+ "coverage": round(valid / len(values), 3),
+ "date": checked_day,
+ "layer": checked_layer,
+ }
+
+
# -- layer discovery (GetCapabilities) -----------------------------------------
_WMTS_NS = {"ows": "http://www.opengis.net/ows/1.1", "wmts": "http://www.opengis.net/wmts/1.0"}
diff --git a/src/azimut/engine/stitch.py b/src/azimut/engine/stitch.py
index 98525f1..b91369b 100644
--- a/src/azimut/engine/stitch.py
+++ b/src/azimut/engine/stitch.py
@@ -292,7 +292,7 @@ def solve_layout(images: list[Image.Image], *, width: int, height: int) -> dict[
if not edges:
raise RuntimeError(
- "auto-stitch found no overlap between these pieces — do they show the same scene?"
+ "auto-stitch found no overlap between these pieces. Do they show the same scene?"
)
anchor, chained = _anchor_and_chain(edges, weights, len(images))
@@ -560,7 +560,7 @@ def solve_rotation_layout(
pairwise, keep = _match_component(cv2, feats)
if len(keep) < 2:
raise RuntimeError(
- "auto-stitch found no overlap between these pieces — do they show the same scene?"
+ "auto-stitch found no overlap between these pieces. Do they show the same scene?"
)
if len(keep) < len(images):
# Re-match on the subset alone: the estimator indexes cameras by position
diff --git a/src/azimut/engine/thumbnails.py b/src/azimut/engine/thumbnails.py
new file mode 100644
index 0000000..1d10b0e
--- /dev/null
+++ b/src/azimut/engine/thumbnails.py
@@ -0,0 +1,320 @@
+"""Thumbnail cache and its durable job model (doc "Thumbnail and background-job
+model").
+
+Thumbnails are disposable pixels: a broken or missing one must never block access
+to the original file. This module owns their whole lifecycle.
+
+- **Cache identity** is content-addressed: the file name folds in the original's
+ SHA-256 and the generator version (`THUMB_GEN`). A changed original or a bumped
+ generator therefore lands a *new* file rather than serving stale pixels, and
+ old ones fall out as orphans that `repair` sweeps.
+- **Generation is atomic**: pixels are rendered to a unique temp file, validated,
+ then renamed into `.thumbs/` — a reader never sees a half-written thumbnail, and
+ the Windows rename rules are respected.
+- **Cheap image thumbnails run inline** for instant feedback; the **CPU-heavy
+ path (ffmpeg video frames) goes through the durable per-case `jobs` queue** and
+ is drained by a single worker, so several imports never spawn several ffmpegs at
+ once. A failed inline render is enqueued for the worker 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.
+- **Budget**: `prune_cache` evicts least-recently-used thumbnails past a size
+ budget; it only ever touches the cache, never originals or database rows.
+"""
+
+from __future__ import annotations
+
+import subprocess
+import threading
+import time
+import uuid
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+from PIL import Image
+
+from ..workspace import ensure_dir
+from . import ffmpeg as ffmpeg_engine
+
+if TYPE_CHECKING:
+ from ..workspace import Case as CaseType
+
+THUMB_DIR = ".thumbs"
+THUMB_MAX = 512
+# Bump when the render changes (size, format, quality) so every case's cached
+# thumbnails are superseded by a differently-named file on next generation, and
+# the stale ones become orphans `repair` removes.
+THUMB_GEN = 1
+# Job kind for the durable queue. One worker drains these one at a time, so
+# ffmpeg (the CPU-heavy path) never runs several instances at once.
+THUMB_KIND = "thumbnail"
+# Only these media kinds get a raster thumbnail; audio and generic files show a
+# type icon instead.
+THUMBNAILED_KINDS = frozenset({"image", "video"})
+# Default cache budget (bytes). Eviction is LRU by mtime and never touches
+# originals. Generous for a local single-user app; a preference can lower it.
+DEFAULT_BUDGET_BYTES = 512 * 1024 * 1024
+
+
+class ThumbnailError(Exception):
+ """A thumbnail could not be produced (unreadable image, ffmpeg failure or
+ absence). The original file is untouched; the caller queues a retry."""
+
+
+def thumb_relpath(sha256: str, kind: str) -> str | None:
+ """The case-relative path a ``kind`` thumbnail with this ``sha256`` lives at,
+ or None for a kind we don't thumbnail. Content- and generator-addressed, so a
+ new original or a bumped generator maps to a new file."""
+ if kind not in THUMBNAILED_KINDS or not sha256:
+ return None
+ return f"media/{THUMB_DIR}/{sha256[:24]}-g{THUMB_GEN}.jpg"
+
+
+def _render(media_path: Path, out_path: Path, kind: str) -> bool:
+ """Render a thumbnail for ``media_path`` into ``out_path``. Images go through
+ Pillow (under the process-wide decode-pixel clamp); video frames through
+ ffmpeg with a bounded run time. Returns whether a file was produced."""
+ if kind == "image":
+ with Image.open(media_path) as img:
+ rgb = img.convert("RGB")
+ rgb.thumbnail((THUMB_MAX, THUMB_MAX))
+ rgb.save(out_path, "JPEG", quality=82)
+ return True
+ if kind == "video":
+ if not ffmpeg_engine.ffmpeg_available():
+ return False
+ subprocess.run(
+ [
+ ffmpeg_engine.ffmpeg_exe(), "-y", "-loglevel", "error",
+ "-ss", "1", "-i", str(media_path),
+ "-frames:v", "1", "-vf", f"scale={THUMB_MAX}:-2",
+ str(out_path),
+ ],
+ check=True,
+ timeout=30,
+ capture_output=True,
+ )
+ return out_path.exists()
+ return False
+
+
+def generate(case: "CaseType", rel_media: str, sha256: str, kind: str) -> str | None:
+ """Produce the thumbnail for one media file, atomically, and return its
+ case-relative path (or None for a non-thumbnailed kind).
+
+ A cache hit (the content-addressed file already exists) returns immediately.
+ Otherwise pixels are rendered to a unique temp file and renamed into
+ ``.thumbs/`` so a reader never sees a partial file. A render that yields
+ nothing (e.g. video with no ffmpeg) raises `ThumbnailError`; a partial temp is
+ always cleaned up.
+ """
+ thumb_rel = thumb_relpath(sha256, kind)
+ if thumb_rel is None:
+ return None
+ thumb_path = case.resolve_inside(thumb_rel)
+ if thumb_path.exists():
+ return thumb_rel
+ media_path = case.resolve_inside(rel_media)
+ if not media_path.exists():
+ raise ThumbnailError(f"media file missing: {rel_media}")
+ ensure_dir(thumb_path.parent)
+ tmp = thumb_path.with_name(f".{uuid.uuid4().hex}.tmp.jpg")
+ try:
+ produced = _render(media_path, tmp, kind)
+ except Exception as exc: # unreadable image, ffmpeg error, decode-bomb clamp
+ tmp.unlink(missing_ok=True)
+ raise ThumbnailError(str(exc)) from exc
+ if not produced or not tmp.exists():
+ tmp.unlink(missing_ok=True)
+ raise ThumbnailError(f"no thumbnail produced for {rel_media}")
+ from ..workspace import _replace_with_retry
+
+ _replace_with_retry(tmp, thumb_path)
+ return thumb_rel
+
+
+def enqueue(case: "CaseType", rel_media: str) -> dict[str, Any]:
+ """Queue a thumbnail job for one media file and wake the worker. Keyed on the
+ media path, so re-enqueue (a retry or a regenerate) never stacks duplicates."""
+ job = case.enqueue_job(THUMB_KIND, key=rel_media, payload={"path": rel_media})
+ wake(case)
+ return job
+
+
+def on_register(case: "CaseType", rel_media: str, sha256: str, kind: str) -> str | None:
+ """Decide a freshly-registered media file's thumbnail. Cheap image thumbnails
+ render inline (instant feedback); a failed image render and every video are
+ handed to the durable queue. Returns the thumbnail path if produced inline,
+ else None (the worker fills it in and updates the sidecar)."""
+ if kind == "image":
+ try:
+ return generate(case, rel_media, sha256, kind)
+ except ThumbnailError:
+ enqueue(case, rel_media)
+ return None
+ if kind == "video":
+ enqueue(case, rel_media)
+ return None
+ return None
+
+
+# -- durable worker --------------------------------------------------------
+#
+# One background worker across all cases: a single daemon thread drains queued
+# thumbnail jobs one at a time, so ffmpeg (CPU-heavy) never runs several at once
+# — the doc's "default to one CPU-heavy worker". Work only ever starts from a
+# user action (an import, a regenerate) or crash recovery, never from merely
+# opening a case or tab.
+
+_worker_lock = threading.Lock()
+_pending: dict[str, "CaseType"] = {}
+_worker_running = False
+
+# When False, `wake` does not start the background thread — the queue is drained
+# explicitly instead (tests, and any caller that wants deterministic draining).
+start_workers = True
+
+
+def _process_one(case: "CaseType", job: dict[str, Any]) -> None:
+ """Run one claimed thumbnail job: render the file, update its sidecar, and
+ settle the job. A missing media file cancels the job (nothing to render); any
+ other failure is recorded and retried until the attempt budget is spent."""
+ from . import media as media_engine
+
+ rel = job["payload"].get("path")
+ item = media_engine.read_item(case, rel) if rel else None
+ if item is None: # the media (or its sidecar) is gone — nothing to do
+ case.cancel_job(job["id"])
+ return
+ try:
+ thumb_rel = generate(case, rel, item.get("sha256", ""), item.get("kind", ""))
+ except ThumbnailError as exc:
+ case.fail_job(job["id"], str(exc))
+ return
+ media_engine.set_thumbnail(case, rel, thumb_rel)
+ case.complete_job(job["id"])
+
+
+def drain(case: "CaseType") -> int:
+ """Process every queued thumbnail job for one case, one at a time, in the
+ calling thread. Returns how many jobs were handled. Synchronous and
+ deterministic — the worker loop and the tests both call it."""
+ handled = 0
+ while True:
+ job = case.claim_job(kinds=[THUMB_KIND])
+ if job is None:
+ return handled
+ _process_one(case, job)
+ handled += 1
+
+
+def _run_loop() -> None:
+ global _worker_running
+ while True:
+ with _worker_lock:
+ if not _pending:
+ _worker_running = False
+ return
+ case_id, case = next(iter(_pending.items()))
+ try:
+ drain(case)
+ except Exception: # a worker must never die on one case's failure
+ pass
+ with _worker_lock:
+ _pending.pop(case_id, None)
+
+
+def wake(case: "CaseType") -> None:
+ """Ensure the single background worker is draining ``case``'s queue. Registers
+ the case and starts the worker thread if it isn't already running; a no-op if
+ the case is already pending."""
+ global _worker_running
+ if not start_workers:
+ return
+ with _worker_lock:
+ _pending[case.id] = case
+ if _worker_running:
+ return
+ _worker_running = True
+ threading.Thread(target=_run_loop, name="thumbnail-worker", daemon=True).start()
+
+
+def wait_until_idle(timeout: float = 5.0) -> bool:
+ """Wait for the shared worker to finish its current queue, if any.
+
+ This is mainly useful for orderly shutdown and deterministic callers that
+ need to remove a case directory after queuing work. It never interrupts an
+ active render; ``False`` means the caller's timeout elapsed first.
+ """
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ with _worker_lock:
+ if not _worker_running:
+ return True
+ time.sleep(0.01)
+ with _worker_lock:
+ return not _worker_running
+
+
+# -- cache maintenance -----------------------------------------------------
+
+
+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 repair(case: "CaseType") -> int:
+ """Sweep the cache: delete abandoned temp files and thumbnails no live media
+ sidecar references any more (orphans left by a generator bump or a delete).
+ Returns how many files were removed. Never touches originals."""
+ from . import media as media_engine
+
+ thumbs = _thumb_dir(case)
+ if not thumbs.is_dir():
+ return 0
+ referenced = {
+ item["thumbnail"].rsplit("/", 1)[-1]
+ for item in media_engine.list_media(case)
+ if item.get("thumbnail")
+ }
+ removed = 0
+ for path in thumbs.iterdir():
+ if not path.is_file():
+ continue
+ if path.name.endswith(".tmp.jpg") or path.name not in referenced:
+ path.unlink(missing_ok=True)
+ removed += 1
+ return removed
+
+
+def prune_cache(case: "CaseType", budget_bytes: int = DEFAULT_BUDGET_BYTES) -> int:
+ """Evict least-recently-used thumbnails until the cache fits ``budget_bytes``.
+
+ LRU by file mtime (the cache carries no other access record, and thumbnails
+ are safe to lose — they regenerate on demand). Returns how many were evicted.
+ Originals and database rows are never touched.
+ """
+ thumbs = _thumb_dir(case)
+ if not thumbs.is_dir():
+ return 0
+ files = sorted(
+ (p for p in thumbs.iterdir() if p.is_file() and not p.name.endswith(".tmp.jpg")),
+ key=lambda p: p.stat().st_mtime,
+ )
+ total = sum(p.stat().st_size for p in files)
+ evicted = 0
+ for path in files:
+ if total <= budget_bytes:
+ break
+ size = path.stat().st_size
+ path.unlink(missing_ok=True)
+ total -= size
+ evicted += 1
+ return evicted
diff --git a/src/azimut/engine/tiles.py b/src/azimut/engine/tiles.py
index 07231ba..bd8f716 100644
--- a/src/azimut/engine/tiles.py
+++ b/src/azimut/engine/tiles.py
@@ -464,7 +464,7 @@ def fetch_crop(
if provider.meter and config.usage_blocked(provider.meter):
raise TileFetchError(
f"{provider.label} is paused: {int(config.BLOCK_SHARE * 100)}% of the monthly "
- "free tier is used — enable the override in Settings to keep going (billed)"
+ "free tier is used; enable the override in Settings to keep going (billed)"
)
# Bigger tiles keep the caller's visual zoom (same m/px) but request a
# lower URL z: one 512px tile at z-1 covers four 256px tiles at z.
@@ -505,7 +505,7 @@ def fetch_crop(
n_tiles = (tile_x1 - tile_x0 + 1) * (tile_y1 - tile_y0 + 1)
if n_tiles > MAX_TILES_PER_CROP:
raise TileFetchError(
- f"crop needs {n_tiles} tiles (max {MAX_TILES_PER_CROP}) — reduce size or zoom"
+ f"crop needs {n_tiles} tiles (max {MAX_TILES_PER_CROP}); reduce size or zoom"
)
max_index = (1 << tile_z) - 1
diff --git a/src/azimut/engine/updates.py b/src/azimut/engine/updates.py
index 61d1b3f..5a545eb 100644
--- a/src/azimut/engine/updates.py
+++ b/src/azimut/engine/updates.py
@@ -1,9 +1,10 @@
"""Is a newer Azimut out? — a self-check for the binary, which has no package
manager behind it (a ``pip``/``pipx`` user runs ``pipx upgrade`` instead).
-Local-first: this reaches the network only when the user presses "Check for
-updates" (api/settings.py gates it behind ``?check=true``, the same opt-in the
-scraper check uses). Nothing here runs on launch or on opening Settings.
+The frontend calls this once on startup by default so binary users hear about
+new releases. Settings can disable that call; the manual button uses the same
+``?check=true`` route, and failures are always returned inline rather than
+breaking the app.
"""
from __future__ import annotations
diff --git a/src/azimut/repository.py b/src/azimut/repository.py
new file mode 100644
index 0000000..5380900
--- /dev/null
+++ b/src/azimut/repository.py
@@ -0,0 +1,202 @@
+"""The case graph storage boundary.
+
+`CaseRepository` is the interface every tool and route uses to read and mutate
+a case's entities, links, folders and durable jobs. The active implementation
+stores that graph in per-case SQLite; callers do not reach into database tables
+or the legacy ``case.json`` graph shape.
+
+`workspace.Case` owns the case folder and delegates graph operations to the
+SQLite implementation. Legacy JSON cases migrate on open before using this
+contract. Keep the Protocol limited to operations with real consumers.
+
+File-backed content (media bytes, note bodies) is deliberately **not** here: it
+stays on the case shell (`Case`), which owns the filesystem layout, lifecycle
+and path resolution. This Protocol is the graph, not the folder.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Literal, Protocol, runtime_checkable
+
+#: Confidence on an entity or link: an analyst's `confirmed` vs a tool's
+#: `suggested` (SPEC §4). Defined here so it is owned by the storage contract;
+#: `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_checkable
+class CaseRepository(Protocol):
+ """Graph read/write contract for one case. `Case` is the JSON backend."""
+
+ # -- reads -------------------------------------------------------------
+
+ def snapshot(self) -> dict[str, Any]:
+ """The full case view — manifest plus graph — in one consistent read.
+
+ The format-agnostic whole-case read behind the current case-open
+ response and the graph algorithms that need entities and links
+ together. The bounded catalog API (Step 5) shrinks the callers of this
+ until only export and migration need the whole graph at once.
+ """
+ ...
+
+ def list_entities(self) -> list[dict[str, Any]]:
+ ...
+
+ def page_entities(
+ self,
+ *,
+ limit: int = 100,
+ cursor: str | None = None,
+ types: list[str] | None = None,
+ status: EntityStatus | None = None,
+ query: str | None = None,
+ folder: str | None = None,
+ unfiled: bool = False,
+ ) -> dict[str, Any]:
+ """A bounded, filtered slice of the catalog (Step 5, "Bounded loading").
+
+ Returns ``{"items": [...], "next_cursor": str | None}`` in a stable
+ insertion order. ``cursor`` is an opaque token from a previous page;
+ ``next_cursor`` is None on the last page. Filters (``types`` set,
+ ``status``, a label ``query``, and folder — ``unfiled`` or an exact
+ ``folder`` path) run in the backend so the caller never materialises the
+ whole graph. The cursor keys on insertion order so a concurrent append
+ never shifts a page already returned.
+ """
+ ...
+
+ def catalog_summary(self) -> dict[str, Any]:
+ """Total plus per-type, per-status and per-folder counts, in the backend.
+
+ Feeds the catalog's badges without shipping entities to the caller —
+ ``{"total": int, "by_type": {type: n}, "by_status": {status: n},
+ "by_folder": {path: n}}``.
+ """
+ ...
+
+ def list_links(self) -> list[dict[str, Any]]:
+ ...
+
+ def links_of(self, entity_id: str) -> list[dict[str, Any]]:
+ """Every link incident to ``entity_id`` (either endpoint), in stable
+ order. The bounded neighbour read behind the derivation chain — reads only
+ the edges touching one entity, not the whole graph.
+ """
+ ...
+
+ def get_entity(self, entity_id: str) -> dict[str, Any] | None:
+ ...
+
+ def find_entity(self, *, attr: str, value: Any) -> dict[str, Any] | None:
+ ...
+
+ def list_folders(self) -> list[str]:
+ ...
+
+ # -- entity mutations --------------------------------------------------
+
+ def add_entity(
+ self,
+ type_: str,
+ label: str,
+ attrs: dict[str, Any] | None = None,
+ *,
+ by: str,
+ status: EntityStatus = "confirmed",
+ source: str | None = None,
+ ) -> dict[str, Any]:
+ ...
+
+ def update_entity(self, entity_id: str, patch: dict[str, Any]) -> dict[str, Any]:
+ ...
+
+ def remove_entity(self, entity_id: str) -> None:
+ ...
+
+ # -- link mutations ----------------------------------------------------
+
+ def add_link(
+ self,
+ from_id: str,
+ to_id: str,
+ type_: str,
+ *,
+ by: str,
+ status: EntityStatus = "confirmed",
+ unique: bool = False,
+ ) -> dict[str, Any]:
+ ...
+
+ def sync_links(
+ self,
+ from_id: str,
+ type_: str,
+ to_ids: list[str],
+ *,
+ by: str,
+ status: EntityStatus = "confirmed",
+ ) -> list[dict[str, Any]]:
+ ...
+
+ def remove_link(self, link_id: str) -> None:
+ ...
+
+ # -- folders -----------------------------------------------------------
+
+ def add_folder(self, name: str) -> list[str]:
+ ...
+
+ def remove_folder(self, name: str) -> list[str]:
+ ...
+
+ # -- durable jobs ------------------------------------------------------
+ #
+ # Local background work (thumbnails today; EXIF, OCR, transcripts later) that
+ # must survive a restart. Keyed jobs are idempotent — a re-enqueue for the
+ # same ``(kind, key)`` never stacks a duplicate — so the same call both
+ # schedules and regenerates. The single worker claims one at a time.
+
+ def enqueue_job(
+ self,
+ kind: str,
+ *,
+ key: str | None = None,
+ payload: dict[str, Any] | None = None,
+ max_attempts: int = 3,
+ ) -> dict[str, Any]:
+ ...
+
+ def claim_job(self, *, kinds: list[str] | None = None) -> dict[str, Any] | None:
+ ...
+
+ def complete_job(self, job_id: str) -> None:
+ ...
+
+ def fail_job(self, job_id: str, error: str) -> dict[str, Any]:
+ ...
+
+ def cancel_job(self, job_id: str) -> None:
+ ...
+
+ def get_job(self, job_id: str) -> dict[str, Any] | None:
+ ...
+
+ def list_jobs(
+ self, *, kind: str | None = None, state: str | None = None
+ ) -> list[dict[str, Any]]:
+ ...
+
+ def count_jobs(self) -> dict[str, int]:
+ ...
+
+ def recover_jobs(self) -> int:
+ ...
+
+ def prune_jobs(self, *, kind: str | None = None) -> int:
+ ...
diff --git a/src/azimut/server.py b/src/azimut/server.py
index b7f632f..10f98d1 100644
--- a/src/azimut/server.py
+++ b/src/azimut/server.py
@@ -61,6 +61,23 @@ def install_local_guard(app: FastAPI) -> None:
return await call_next(request)
+def _recover_jobs() -> None:
+ """On startup, return jobs a crashed process left ``running`` to the queue and
+ wake the worker for any case with pending thumbnail work. A `running` row
+ nothing owns would otherwise stall forever; recovery resumes it."""
+ from .engine import thumbnails
+ from .workspace import Case
+
+ for row in Case.list_all():
+ try:
+ case = Case.open(row["id"])
+ case.recover_jobs()
+ except Exception:
+ continue
+ if any(j["state"] == "queued" for j in case.list_jobs(kind=thumbnails.THUMB_KIND)):
+ thumbnails.wake(case)
+
+
def create_app() -> FastAPI:
config.ensure_workspace()
# Before any router can import a scraper: point yt-dlp/gallery-dl at the
@@ -77,6 +94,14 @@ def create_app() -> FastAPI:
except OSError:
pass
+ # Reclaim background jobs a previous run left mid-flight and resume any
+ # pending thumbnail work through the single worker. Best-effort: housekeeping
+ # must never block or crash startup.
+ try:
+ _recover_jobs()
+ except Exception:
+ pass
+
app = FastAPI(title="Azimut", version=__version__, docs_url="/api/docs")
from .api import cases, drafts, events, files, ingest, inspect, media, proofs, satellite, settings, templates
@@ -119,7 +144,7 @@ def create_app() -> FastAPI:
return JSONResponse(
{
"azimut": __version__,
- "hint": "frontend not built — run `npm run build` in frontend/ "
+ "hint": "frontend not built; run `npm run build` in frontend/ "
"or use the Vite dev server (npm run dev)",
}
)
diff --git a/src/azimut/sqlite_backend.py b/src/azimut/sqlite_backend.py
new file mode 100644
index 0000000..9f8e5ab
--- /dev/null
+++ b/src/azimut/sqlite_backend.py
@@ -0,0 +1,1042 @@
+"""SQLite-backed `CaseRepository` (Step 3 of docs/STORAGE_AND_PERFORMANCE.md).
+
+`SqliteCase` is the second implementation of the graph contract in
+`repository.py`; `workspace.Case` is the first (JSON). It answers the same
+methods from a per-case `case.db`, so a single mutation touches one row and one
+short transaction instead of rewriting the whole file — the O(n)-per-write
+ceiling the migration removes.
+
+Scope of this step: the store and the JSON->SQLite converter, exercised by the
+shared contract tests in `tests/test_repository.py` and by
+`tests/test_sqlite_backend.py`. Wiring it into `Case.open` behind the manifest's
+storage format is deliberately a *later* step (Delivery 4, "Safe activation"),
+so nothing here changes production behavior yet.
+
+Frozen-binary constraints (see the doc): SQLite is the stdlib `sqlite3` module,
+already bundled by PyInstaller, so this adds no runtime dependency. Anything
+beyond core SQL (FTS5, JSON1, RTree) is per-binary and must be probed at runtime
+with a fallback before it enters the contract — this module stays on core SQL:
+`find_entity` scans and matches attrs in Python rather than relying on JSON1.
+"""
+
+from __future__ import annotations
+
+import json
+import sqlite3
+from contextlib import contextmanager
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Callable, Iterator, TypeVar
+
+from .repository import EntityStatus
+from .workspace import Case, CaseError, _new_id, _now, _parse_cursor, _replace_with_retry
+
+if TYPE_CHECKING:
+ from .repository import CaseRepository
+
+# SQLite storage schema. Independent of the JSON `CASE_SCHEMA`: the manifest's
+# storage-format field selects the backend, and each format counts its own shape
+# upgrades. Bump this in the same change that adds a migration to
+# `_SQLITE_MIGRATIONS` (and update `_SCHEMA` so a fresh db is born current).
+#
+# Schema 2 denormalises `attrs.folder` into an indexed `folder` column so the
+# catalog can page and count a folder's entities without a JSON scan.
+# Schema 3 adds the durable `jobs` table: local background work (thumbnails
+# today, EXIF/OCR/transcript later) that must survive a restart and be
+# recoverable — the doc's "thumbnail and background-job model".
+SQLITE_SCHEMA = 3
+
+_SCHEMA = """
+CREATE TABLE meta (
+ key TEXT PRIMARY KEY,
+ value TEXT NOT NULL
+);
+CREATE TABLE schema_migrations (
+ version INTEGER PRIMARY KEY,
+ applied_at TEXT NOT NULL
+);
+CREATE TABLE entities (
+ id TEXT PRIMARY KEY,
+ type TEXT NOT NULL,
+ label TEXT NOT NULL,
+ attrs_json TEXT NOT NULL DEFAULT '{}',
+ folder TEXT,
+ prov_by TEXT NOT NULL,
+ prov_at TEXT NOT NULL,
+ prov_status TEXT NOT NULL DEFAULT 'confirmed',
+ prov_source TEXT
+);
+CREATE TABLE links (
+ id TEXT PRIMARY KEY,
+ from_id TEXT NOT NULL REFERENCES entities(id),
+ to_id TEXT NOT NULL REFERENCES entities(id),
+ type TEXT NOT NULL,
+ prov_by TEXT NOT NULL,
+ prov_at TEXT NOT NULL,
+ prov_status TEXT NOT NULL DEFAULT 'confirmed',
+ prov_source TEXT
+);
+CREATE TABLE folders (
+ path TEXT PRIMARY KEY
+);
+CREATE TABLE jobs (
+ id TEXT PRIMARY KEY,
+ kind TEXT NOT NULL,
+ job_key TEXT,
+ state TEXT NOT NULL DEFAULT 'queued',
+ attempts INTEGER NOT NULL DEFAULT 0,
+ max_attempts INTEGER NOT NULL DEFAULT 3,
+ payload_json TEXT NOT NULL DEFAULT '{}',
+ error TEXT,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL
+);
+CREATE INDEX idx_entities_type ON entities(type);
+CREATE INDEX idx_entities_status ON entities(prov_status);
+CREATE INDEX idx_entities_folder ON entities(folder);
+CREATE INDEX idx_links_from ON links(from_id);
+CREATE INDEX idx_links_to ON links(to_id);
+CREATE INDEX idx_links_type ON links(type);
+CREATE INDEX idx_jobs_state ON jobs(state);
+CREATE UNIQUE INDEX idx_jobs_key ON jobs(kind, job_key) WHERE job_key IS NOT NULL;
+"""
+
+# Job lifecycle (doc "Job states"): a fresh job is `queued`; the worker claims it
+# `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")
+
+
+def _like_contains(term: str) -> str:
+ """Wrap a search term for a case-insensitive ``LIKE ? ESCAPE '\\'`` substring
+ match, escaping the LIKE wildcards so a literal ``%`` or ``_`` matches
+ itself."""
+ escaped = term.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
+ return f"%{escaped}%"
+
+
+def _folder_of(attrs: dict[str, Any] | None) -> str | None:
+ """The indexed folder value for an entity: its ``attrs.folder`` path, or None
+ when unfiled — an absent or empty folder both read as unfiled."""
+ folder = (attrs or {}).get("folder")
+ return folder or None
+
+
+def _migrate_1_to_2(conn: sqlite3.Connection) -> None:
+ """Add the ``folder`` column, backfill it from each entity's ``attrs.folder``
+ (in Python, no JSON1 dependency), and index it."""
+ conn.execute("ALTER TABLE entities ADD COLUMN folder TEXT")
+ for row in conn.execute("SELECT id, attrs_json FROM entities").fetchall():
+ folder = _folder_of(json.loads(row["attrs_json"]))
+ if folder is not None:
+ conn.execute("UPDATE entities SET folder = ? WHERE id = ?", (folder, row["id"]))
+ conn.execute("CREATE INDEX idx_entities_folder ON entities(folder)")
+
+
+def _migrate_2_to_3(conn: sqlite3.Connection) -> None:
+ """Add the durable ``jobs`` table and its indexes (background-job model)."""
+ conn.execute(
+ "CREATE TABLE jobs ("
+ " id TEXT PRIMARY KEY, kind TEXT NOT NULL, job_key TEXT,"
+ " state TEXT NOT NULL DEFAULT 'queued', attempts INTEGER NOT NULL DEFAULT 0,"
+ " max_attempts INTEGER NOT NULL DEFAULT 3, payload_json TEXT NOT NULL DEFAULT '{}',"
+ " error TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL)"
+ )
+ conn.execute("CREATE INDEX idx_jobs_state ON jobs(state)")
+ conn.execute("CREATE UNIQUE INDEX idx_jobs_key ON jobs(kind, job_key) WHERE job_key IS NOT NULL")
+
+
+# from_version -> function(conn) applying the in-place upgrade to from_version + 1.
+# Runs inside one transaction per step in `SqliteCase._upgrade`, which stamps the
+# new schema_version and records the migration; the step only reshapes the db.
+_SQLITE_MIGRATIONS: dict[int, Callable[[sqlite3.Connection], None]] = {
+ 1: _migrate_1_to_2,
+ 2: _migrate_2_to_3,
+}
+
+
+class SqliteCase:
+ """SQLite implementation of `CaseRepository` over one `case.db` file."""
+
+ def __init__(self, db_path: Path):
+ self.db_path = Path(db_path)
+
+ # -- lifecycle ---------------------------------------------------------
+
+ @classmethod
+ def create(
+ cls,
+ db_path: Path,
+ *,
+ name: str,
+ created_at: str | None = None,
+ updated_at: str | None = None,
+ ) -> "SqliteCase":
+ db_path = Path(db_path)
+ if db_path.exists():
+ raise CaseError(f"case db '{db_path.name}' already exists")
+ store = cls(db_path)
+ now = _now()
+ with store._connect() as conn:
+ conn.executescript(_SCHEMA)
+ conn.execute("BEGIN IMMEDIATE")
+ try:
+ for key, value in (
+ ("schema_version", str(SQLITE_SCHEMA)),
+ ("name", name),
+ ("created_at", created_at or now),
+ ("updated_at", updated_at or now),
+ ):
+ conn.execute("INSERT INTO meta(key, value) VALUES(?, ?)", (key, value))
+ conn.execute(
+ "INSERT INTO schema_migrations(version, applied_at) VALUES(?, ?)",
+ (SQLITE_SCHEMA, now),
+ )
+ conn.execute("COMMIT")
+ except BaseException:
+ conn.execute("ROLLBACK")
+ raise
+ return store
+
+ @classmethod
+ def open(cls, db_path: Path) -> "SqliteCase":
+ """Open an existing `case.db`, upgrading an older schema and refusing a
+ newer one.
+
+ Mirrors `Case.migrate`'s forward-compat guarantee for the JSON format: a
+ database written by a newer Azimut is refused rather than mangled, and an
+ older one is brought up to `SQLITE_SCHEMA` in order before use.
+ """
+ db_path = Path(db_path)
+ if not db_path.exists():
+ raise CaseError(f"case db '{db_path.name}' not found")
+ store = cls(db_path)
+ with store._connect() as conn:
+ row = conn.execute("SELECT value FROM meta WHERE key = 'schema_version'").fetchone()
+ version = int(row["value"]) if row else 1
+ if version > SQLITE_SCHEMA:
+ raise CaseError(
+ f"case db '{db_path.name}' was made with a newer Azimut "
+ f"(schema {version} > {SQLITE_SCHEMA}); update Azimut to open it"
+ )
+ if version < SQLITE_SCHEMA:
+ store._upgrade()
+ return store
+
+ def _upgrade(self) -> None:
+ """Bring an older `case.db` up to `SQLITE_SCHEMA`, each step in its own
+ immediate transaction and rolled back on failure. Re-reads the version
+ inside the transaction so a second opener that raced the first finds
+ nothing left to apply rather than replaying a migration."""
+ with self._connect() as conn:
+ conn.execute("BEGIN IMMEDIATE")
+ try:
+ row = conn.execute(
+ "SELECT value FROM meta WHERE key = 'schema_version'"
+ ).fetchone()
+ current = int(row["value"]) if row else 1
+ for step in range(current, SQLITE_SCHEMA):
+ migrate = _SQLITE_MIGRATIONS.get(step)
+ if migrate is None:
+ raise CaseError(f"no migration for case db schema {step}")
+ migrate(conn)
+ conn.execute(
+ "UPDATE meta SET value = ? WHERE key = 'schema_version'", (str(step + 1),)
+ )
+ conn.execute(
+ "INSERT INTO schema_migrations(version, applied_at) VALUES(?, ?)",
+ (step + 1, _now()),
+ )
+ conn.execute("COMMIT")
+ except BaseException:
+ conn.execute("ROLLBACK")
+ raise
+
+ # -- connection / transaction plumbing ---------------------------------
+
+ @contextmanager
+ def _connect(self) -> Iterator[sqlite3.Connection]:
+ # A fresh connection per operation: the per-case work is serialised by
+ # SQLite's own file lock plus busy_timeout, so no Python lock is needed
+ # and there is no cross-thread connection to mismanage. Autocommit
+ # (isolation_level=None) leaves transaction control explicit — reads run
+ # bare, writes wrap in BEGIN IMMEDIATE..COMMIT via `_write`.
+ conn = sqlite3.connect(self.db_path, isolation_level=None)
+ try:
+ conn.row_factory = sqlite3.Row
+ conn.execute("PRAGMA foreign_keys = ON")
+ conn.execute("PRAGMA busy_timeout = 5000")
+ conn.execute("PRAGMA synchronous = FULL")
+ yield conn
+ finally:
+ conn.close()
+
+ def _write(self, op: Callable[[sqlite3.Connection], T]) -> T:
+ """Run `op` inside one immediate transaction, rolling back on error."""
+ with self._connect() as conn:
+ conn.execute("BEGIN IMMEDIATE")
+ try:
+ result = op(conn)
+ conn.execute("COMMIT")
+ return result
+ except BaseException:
+ conn.execute("ROLLBACK")
+ raise
+
+ @staticmethod
+ def _touch(conn: sqlite3.Connection) -> None:
+ conn.execute("UPDATE meta SET value = ? WHERE key = 'updated_at'", (_now(),))
+
+ # -- row <-> dict mapping ----------------------------------------------
+
+ @staticmethod
+ def _entity(row: sqlite3.Row) -> dict[str, Any]:
+ entity: dict[str, Any] = {
+ "id": row["id"],
+ "type": row["type"],
+ "label": row["label"],
+ "attrs": json.loads(row["attrs_json"]),
+ "provenance": {
+ "by": row["prov_by"],
+ "at": row["prov_at"],
+ "status": row["prov_status"],
+ },
+ }
+ if row["prov_source"] is not None:
+ entity["provenance"]["source"] = row["prov_source"]
+ return entity
+
+ @staticmethod
+ def _link(row: sqlite3.Row) -> dict[str, Any]:
+ link: dict[str, Any] = {
+ "id": row["id"],
+ "from": row["from_id"],
+ "to": row["to_id"],
+ "type": row["type"],
+ "provenance": {
+ "by": row["prov_by"],
+ "at": row["prov_at"],
+ "status": row["prov_status"],
+ },
+ }
+ if row["prov_source"] is not None:
+ link["provenance"]["source"] = row["prov_source"]
+ return link
+
+ @staticmethod
+ def _job(row: sqlite3.Row) -> dict[str, Any]:
+ return {
+ "id": row["id"],
+ "kind": row["kind"],
+ "key": row["job_key"],
+ "state": row["state"],
+ "attempts": row["attempts"],
+ "max_attempts": row["max_attempts"],
+ "payload": json.loads(row["payload_json"]),
+ "error": row["error"],
+ "created_at": row["created_at"],
+ "updated_at": row["updated_at"],
+ }
+
+ # -- reads -------------------------------------------------------------
+
+ def snapshot(self) -> dict[str, Any]:
+ with self._connect() as conn:
+ meta = {r["key"]: r["value"] for r in conn.execute("SELECT key, value FROM meta")}
+ entities = [
+ self._entity(r) for r in conn.execute("SELECT * FROM entities ORDER BY rowid")
+ ]
+ links = [self._link(r) for r in conn.execute("SELECT * FROM links ORDER BY rowid")]
+ folders = [
+ r["path"]
+ for r in conn.execute("SELECT path FROM folders ORDER BY path COLLATE NOCASE")
+ ]
+ schema = int(meta.get("schema_version", SQLITE_SCHEMA))
+ return {
+ "azimut": {"schema": schema, "storage": "sqlite"},
+ "name": meta.get("name", ""),
+ "created_at": meta.get("created_at"),
+ "updated_at": meta.get("updated_at"),
+ "folders": folders,
+ "entities": entities,
+ "links": links,
+ }
+
+ def list_entities(self) -> list[dict[str, Any]]:
+ with self._connect() as conn:
+ return [self._entity(r) for r in conn.execute("SELECT * FROM entities ORDER BY rowid")]
+
+ def list_links(self) -> list[dict[str, Any]]:
+ with self._connect() as conn:
+ return [self._link(r) for r in conn.execute("SELECT * FROM links ORDER BY rowid")]
+
+ def links_of(self, entity_id: str) -> list[dict[str, Any]]:
+ with self._connect() as conn:
+ rows = conn.execute(
+ "SELECT * FROM links WHERE from_id = ? OR to_id = ? ORDER BY rowid",
+ (entity_id, entity_id),
+ ).fetchall()
+ return [self._link(r) for r in rows]
+
+ def page_entities(
+ self,
+ *,
+ limit: int = 100,
+ cursor: str | None = None,
+ types: list[str] | None = None,
+ status: EntityStatus | None = None,
+ query: str | None = None,
+ folder: str | None = None,
+ unfiled: bool = False,
+ ) -> dict[str, Any]:
+ """A bounded, cursor-paginated slice of entities in insertion order.
+
+ The cursor keys on ``rowid`` (monotonic, primary-index-backed), so a
+ background import appending rows never shifts a page the analyst already
+ scrolled past — new rows land after the current tail. Filters compose in
+ SQL: ``types`` (an ``IN`` set), ``status``, a case-insensitive ``query``
+ over the label, and folder — either ``unfiled`` (no folder) or an exact
+ ``folder`` path. One extra row is peeked to know whether a further page
+ exists, so ``next_cursor`` is None exactly on the last page.
+ """
+ where: list[str] = []
+ params: list[Any] = []
+ if cursor is not None:
+ where.append("rowid > ?")
+ params.append(_parse_cursor(cursor))
+ if types:
+ where.append(f"type IN ({', '.join('?' * len(types))})")
+ params.extend(types)
+ if status is not None:
+ where.append("prov_status = ?")
+ params.append(status)
+ if unfiled:
+ where.append("folder IS NULL")
+ elif folder is not None:
+ where.append("folder = ?")
+ params.append(folder)
+ if query:
+ where.append("label LIKE ? ESCAPE '\\'")
+ params.append(_like_contains(query))
+ clause = (" WHERE " + " AND ".join(where)) if where else ""
+ params.append(limit + 1)
+ with self._connect() as conn:
+ rows = conn.execute(
+ f"SELECT rowid AS _rowid, * FROM entities{clause} ORDER BY rowid LIMIT ?",
+ params,
+ ).fetchall()
+ has_more = len(rows) > limit
+ rows = rows[:limit]
+ next_cursor = str(rows[-1]["_rowid"]) if has_more and rows else None
+ return {"items": [self._entity(r) for r in rows], "next_cursor": next_cursor}
+
+ def catalog_summary(self) -> dict[str, Any]:
+ """Total plus per-type, per-status and per-folder counts in grouped scans
+ — the catalog's badges without materialising the graph."""
+ with self._connect() as conn:
+ total = conn.execute("SELECT COUNT(*) FROM entities").fetchone()[0]
+ by_type = {
+ r["type"]: r["n"]
+ for r in conn.execute("SELECT type, COUNT(*) AS n FROM entities GROUP BY type")
+ }
+ by_status = {
+ r["prov_status"]: r["n"]
+ for r in conn.execute(
+ "SELECT prov_status, COUNT(*) AS n FROM entities GROUP BY prov_status"
+ )
+ }
+ by_folder = {
+ r["folder"]: r["n"]
+ for r in conn.execute(
+ "SELECT folder, COUNT(*) AS n FROM entities"
+ " WHERE folder IS NOT NULL GROUP BY folder"
+ )
+ }
+ return {
+ "total": total,
+ "by_type": by_type,
+ "by_status": by_status,
+ "by_folder": by_folder,
+ }
+
+ def get_entity(self, entity_id: str) -> dict[str, Any] | None:
+ with self._connect() as conn:
+ row = conn.execute("SELECT * FROM entities WHERE id = ?", (entity_id,)).fetchone()
+ return self._entity(row) if row is not None else None
+
+ def find_entity(self, *, attr: str, value: Any) -> dict[str, Any] | None:
+ # Scan and match in Python so the store stays on core SQL (no JSON1
+ # dependency). A JSON1-indexed lookup is a later optimisation, gated on
+ # per-binary availability like FTS5.
+ with self._connect() as conn:
+ for row in conn.execute("SELECT * FROM entities ORDER BY rowid"):
+ if json.loads(row["attrs_json"]).get(attr) == value:
+ return self._entity(row)
+ return None
+
+ def list_folders(self) -> list[str]:
+ with self._connect() as conn:
+ return [
+ r["path"]
+ for r in conn.execute("SELECT path FROM folders ORDER BY path COLLATE NOCASE")
+ ]
+
+ def count_entities(self) -> int:
+ """Entity total via one indexed count — the case switcher's per-case
+ badge without materialising the graph."""
+ with self._connect() as conn:
+ return conn.execute("SELECT COUNT(*) FROM entities").fetchone()[0]
+
+ def updated_at(self) -> str | None:
+ """Last-activity timestamp, bumped by every mutation. The manifest's own
+ `updated_at` only moves on manifest writes, so this is the truthful sort
+ key for the case switcher once the graph lives in the db."""
+ with self._connect() as conn:
+ row = conn.execute("SELECT value FROM meta WHERE key = 'updated_at'").fetchone()
+ return row["value"] if row is not None else None
+
+ # -- entity mutations --------------------------------------------------
+
+ def add_entity(
+ self,
+ type_: str,
+ label: str,
+ attrs: dict[str, Any] | None = None,
+ *,
+ by: str,
+ status: EntityStatus = "confirmed",
+ source: str | None = None,
+ ) -> dict[str, Any]:
+ entity: dict[str, Any] = {
+ "id": _new_id("e"),
+ "type": type_,
+ "label": label,
+ "attrs": attrs or {},
+ "provenance": {"by": by, "at": _now(), "status": status},
+ }
+ if source:
+ entity["provenance"]["source"] = source
+
+ def op(conn: sqlite3.Connection) -> dict[str, Any]:
+ conn.execute(
+ "INSERT INTO entities"
+ "(id, type, label, attrs_json, folder, prov_by, prov_at, prov_status, prov_source)"
+ " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ (
+ entity["id"],
+ type_,
+ label,
+ json.dumps(entity["attrs"], ensure_ascii=False),
+ _folder_of(entity["attrs"]),
+ by,
+ entity["provenance"]["at"],
+ status,
+ source or None,
+ ),
+ )
+ self._touch(conn)
+ return entity
+
+ return self._write(op)
+
+ def update_entity(self, entity_id: str, patch: dict[str, Any]) -> dict[str, Any]:
+ def op(conn: sqlite3.Connection) -> dict[str, Any]:
+ row = conn.execute("SELECT * FROM entities WHERE id = ?", (entity_id,)).fetchone()
+ if row is None:
+ raise CaseError(f"entity '{entity_id}' not found")
+ entity = self._entity(row)
+ for key in ("type", "label"):
+ if key in patch:
+ entity[key] = patch[key]
+ if "attrs" in patch:
+ entity["attrs"].update(patch["attrs"])
+ if patch.get("status") in ("confirmed", "suggested"):
+ entity["provenance"]["status"] = patch["status"]
+ conn.execute(
+ "UPDATE entities SET type = ?, label = ?, attrs_json = ?, folder = ?,"
+ " prov_status = ? WHERE id = ?",
+ (
+ entity["type"],
+ entity["label"],
+ json.dumps(entity["attrs"], ensure_ascii=False),
+ _folder_of(entity["attrs"]),
+ entity["provenance"]["status"],
+ entity_id,
+ ),
+ )
+ self._touch(conn)
+ return entity
+
+ return self._write(op)
+
+ def remove_entity(self, entity_id: str) -> None:
+ def op(conn: sqlite3.Connection) -> None:
+ if conn.execute("SELECT 1 FROM entities WHERE id = ?", (entity_id,)).fetchone() is None:
+ raise CaseError(f"entity '{entity_id}' not found")
+ # Drop directly incident edges first: foreign keys forbid dangling
+ # links, and this is the repository-level cleanup, not the
+ # dependency-aware deep delete (that lives in engine/links.py).
+ conn.execute(
+ "DELETE FROM links WHERE from_id = ? OR to_id = ?", (entity_id, entity_id)
+ )
+ conn.execute("DELETE FROM entities WHERE id = ?", (entity_id,))
+ self._touch(conn)
+
+ self._write(op)
+
+ # -- link mutations ----------------------------------------------------
+
+ def add_link(
+ self,
+ from_id: str,
+ to_id: str,
+ type_: str,
+ *,
+ by: str,
+ status: EntityStatus = "confirmed",
+ unique: bool = False,
+ ) -> dict[str, Any]:
+ def op(conn: sqlite3.Connection) -> dict[str, Any]:
+ present = {
+ r["id"]
+ for r in conn.execute(
+ "SELECT id FROM entities WHERE id IN (?, ?)", (from_id, to_id)
+ )
+ }
+ for eid in (from_id, to_id):
+ if eid not in present:
+ raise CaseError(f"entity '{eid}' not found")
+ if unique:
+ existing = conn.execute(
+ "SELECT * FROM links WHERE from_id = ? AND to_id = ? AND type = ?"
+ " ORDER BY rowid LIMIT 1",
+ (from_id, to_id, type_),
+ ).fetchone()
+ if existing is not None:
+ return self._link(existing)
+ link: dict[str, Any] = {
+ "id": _new_id("l"),
+ "from": from_id,
+ "to": to_id,
+ "type": type_,
+ "provenance": {"by": by, "at": _now(), "status": status},
+ }
+ conn.execute(
+ "INSERT INTO links"
+ "(id, from_id, to_id, type, prov_by, prov_at, prov_status, prov_source)"
+ " VALUES(?, ?, ?, ?, ?, ?, ?, NULL)",
+ (link["id"], from_id, to_id, type_, by, link["provenance"]["at"], status),
+ )
+ self._touch(conn)
+ return link
+
+ return self._write(op)
+
+ def sync_links(
+ self,
+ from_id: str,
+ type_: str,
+ to_ids: list[str],
+ *,
+ by: str,
+ status: EntityStatus = "confirmed",
+ ) -> list[dict[str, Any]]:
+ def op(conn: sqlite3.Connection) -> list[dict[str, Any]]:
+ if conn.execute("SELECT 1 FROM entities WHERE id = ?", (from_id,)).fetchone() is None:
+ raise CaseError(f"entity '{from_id}' not found")
+ candidates = list(dict.fromkeys(to_ids))
+ present: set[str] = set()
+ if candidates:
+ placeholders = ", ".join("?" * len(candidates))
+ present = {
+ r["id"]
+ for r in conn.execute(
+ f"SELECT id FROM entities WHERE id IN ({placeholders})", candidates
+ )
+ }
+ wanted = [i for i in candidates if i in present and i != from_id]
+ wanted_set = set(wanted)
+ existing = {
+ r["to_id"]: r
+ for r in conn.execute(
+ "SELECT * FROM links WHERE from_id = ? AND type = ?", (from_id, type_)
+ )
+ }
+ # Drop edges no longer wanted; leave the survivors untouched so their
+ # id and timestamp are preserved (restating sources, not rebuilding).
+ stale = [(r["id"],) for to_id, r in existing.items() if to_id not in wanted_set]
+ if stale:
+ conn.executemany("DELETE FROM links WHERE id = ?", stale)
+ for to_id in wanted:
+ if to_id not in existing:
+ conn.execute(
+ "INSERT INTO links"
+ "(id, from_id, to_id, type, prov_by, prov_at, prov_status, prov_source)"
+ " VALUES(?, ?, ?, ?, ?, ?, ?, NULL)",
+ (_new_id("l"), from_id, to_id, type_, by, _now(), status),
+ )
+ self._touch(conn)
+ rows = conn.execute(
+ "SELECT * FROM links WHERE from_id = ? AND type = ? ORDER BY rowid",
+ (from_id, type_),
+ ).fetchall()
+ return [self._link(r) for r in rows]
+
+ return self._write(op)
+
+ def remove_link(self, link_id: str) -> None:
+ def op(conn: sqlite3.Connection) -> None:
+ cur = conn.execute("DELETE FROM links WHERE id = ?", (link_id,))
+ if cur.rowcount == 0:
+ raise CaseError(f"link '{link_id}' not found")
+ self._touch(conn)
+
+ self._write(op)
+
+ # -- folders -----------------------------------------------------------
+
+ def add_folder(self, name: str) -> list[str]:
+ path = Case._normalize_folder(name)
+
+ def op(conn: sqlite3.Connection) -> list[str]:
+ before = conn.total_changes
+ segments = path.split("/")
+ for i in range(1, len(segments) + 1):
+ ancestor = "/".join(segments[:i])
+ conn.execute("INSERT OR IGNORE INTO folders(path) VALUES(?)", (ancestor,))
+ if conn.total_changes > before:
+ self._touch(conn)
+ return [
+ r["path"]
+ for r in conn.execute("SELECT path FROM folders ORDER BY path COLLATE NOCASE")
+ ]
+
+ return self._write(op)
+
+ def remove_folder(self, name: str) -> list[str]:
+ prefix = name + "/"
+
+ def op(conn: sqlite3.Connection) -> list[str]:
+ doomed = [
+ (p["path"],)
+ for p in conn.execute("SELECT path FROM folders")
+ if p["path"] == name or p["path"].startswith(prefix)
+ ]
+ if doomed:
+ conn.executemany("DELETE FROM folders WHERE path = ?", doomed)
+ # Unfile any entity filed under a removed node or its descendants.
+ for row in conn.execute("SELECT id, attrs_json FROM entities").fetchall():
+ attrs = json.loads(row["attrs_json"])
+ folder = attrs.get("folder")
+ if folder is not None and (folder == name or folder.startswith(prefix)):
+ attrs.pop("folder", None)
+ conn.execute(
+ "UPDATE entities SET attrs_json = ?, folder = NULL WHERE id = ?",
+ (json.dumps(attrs, ensure_ascii=False), row["id"]),
+ )
+ self._touch(conn)
+ return [
+ r["path"]
+ for r in conn.execute("SELECT path FROM folders ORDER BY path COLLATE NOCASE")
+ ]
+
+ return self._write(op)
+
+ # -- durable jobs (thumbnail and background-job model) -----------------
+
+ def enqueue_job(
+ self,
+ kind: str,
+ *,
+ key: str | None = None,
+ payload: dict[str, Any] | None = None,
+ max_attempts: int = 3,
+ ) -> dict[str, Any]:
+ """Queue a unit of background work, returning the job row.
+
+ Keyed jobs are idempotent: a second enqueue for the same ``(kind, key)``
+ never stacks a duplicate. A job already ``running`` is left running (the
+ worker owns it); any other prior state — including a finished ``ready``
+ one, so a re-enqueue is how a thumbnail is regenerated — is reset to a
+ fresh ``queued`` attempt. The keyless form is a plain append.
+ """
+ now = _now()
+
+ def op(conn: sqlite3.Connection) -> dict[str, Any]:
+ if key is not None:
+ row = conn.execute(
+ "SELECT * FROM jobs WHERE kind = ? AND job_key = ?", (kind, key)
+ ).fetchone()
+ if row is not None:
+ if row["state"] == "running":
+ return self._job(row)
+ conn.execute(
+ "UPDATE jobs SET state = 'queued', attempts = 0, error = NULL,"
+ " payload_json = ?, max_attempts = ?, updated_at = ? WHERE id = ?",
+ (
+ json.dumps(payload or {}, ensure_ascii=False),
+ max_attempts,
+ now,
+ row["id"],
+ ),
+ )
+ return self._job(
+ conn.execute("SELECT * FROM jobs WHERE id = ?", (row["id"],)).fetchone()
+ )
+ job_id = _new_id("j")
+ conn.execute(
+ "INSERT INTO jobs"
+ "(id, kind, job_key, state, attempts, max_attempts, payload_json,"
+ " error, created_at, updated_at)"
+ " VALUES(?, ?, ?, 'queued', 0, ?, ?, NULL, ?, ?)",
+ (job_id, kind, key, max_attempts, json.dumps(payload or {}, ensure_ascii=False), now, now),
+ )
+ return self._job(conn.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone())
+
+ return self._write(op)
+
+ def claim_job(self, *, kinds: list[str] | None = None) -> dict[str, Any] | None:
+ """Atomically take the oldest ``queued`` job into ``running`` and return
+ it (attempt counted), or None when nothing is queued. One row per call —
+ the single-worker default is enforced by the caller running one at a time.
+ """
+ def op(conn: sqlite3.Connection) -> dict[str, Any] | None:
+ where = "state = 'queued'"
+ params: list[Any] = []
+ if kinds:
+ where += f" AND kind IN ({', '.join('?' * len(kinds))})"
+ params.extend(kinds)
+ row = conn.execute(
+ f"SELECT * FROM jobs WHERE {where} ORDER BY rowid LIMIT 1", params
+ ).fetchone()
+ if row is None:
+ return None
+ conn.execute(
+ "UPDATE jobs SET state = 'running', attempts = attempts + 1, updated_at = ?"
+ " WHERE id = ?",
+ (_now(), row["id"]),
+ )
+ return self._job(conn.execute("SELECT * FROM jobs WHERE id = ?", (row["id"],)).fetchone())
+
+ return self._write(op)
+
+ def complete_job(self, job_id: str) -> None:
+ """Mark a finished job ``ready``."""
+ self._set_job_state(job_id, "ready", error=None)
+
+ def fail_job(self, job_id: str, error: str) -> dict[str, Any]:
+ """Record a failure: back to ``queued`` while attempts remain, else
+ ``failed``. Returns the resulting job row so the worker can see whether a
+ retry is pending."""
+ def op(conn: sqlite3.Connection) -> dict[str, Any]:
+ row = conn.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()
+ if row is None:
+ raise CaseError(f"job '{job_id}' not found")
+ state = "queued" if row["attempts"] < row["max_attempts"] else "failed"
+ conn.execute(
+ "UPDATE jobs SET state = ?, error = ?, updated_at = ? WHERE id = ?",
+ (state, error[:2000], _now(), job_id),
+ )
+ return self._job(conn.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone())
+
+ return self._write(op)
+
+ def cancel_job(self, job_id: str) -> None:
+ self._set_job_state(job_id, "cancelled", error=None)
+
+ def _set_job_state(self, job_id: str, state: str, *, error: str | None) -> None:
+ def op(conn: sqlite3.Connection) -> None:
+ cur = conn.execute(
+ "UPDATE jobs SET state = ?, error = ?, updated_at = ? WHERE id = ?",
+ (state, error, _now(), job_id),
+ )
+ if cur.rowcount == 0:
+ raise CaseError(f"job '{job_id}' not found")
+
+ self._write(op)
+
+ def get_job(self, job_id: str) -> dict[str, Any] | None:
+ with self._connect() as conn:
+ row = conn.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()
+ return self._job(row) if row is not None else None
+
+ def list_jobs(
+ self, *, kind: str | None = None, state: str | None = None
+ ) -> list[dict[str, Any]]:
+ where: list[str] = []
+ params: list[Any] = []
+ if kind is not None:
+ where.append("kind = ?")
+ params.append(kind)
+ if state is not None:
+ where.append("state = ?")
+ params.append(state)
+ clause = (" WHERE " + " AND ".join(where)) if where else ""
+ with self._connect() as conn:
+ rows = conn.execute(f"SELECT * FROM jobs{clause} ORDER BY rowid", params).fetchall()
+ return [self._job(r) for r in rows]
+
+ def count_jobs(self) -> dict[str, int]:
+ """Per-state job counts — the queue's badge without listing every row."""
+ with self._connect() as conn:
+ rows = conn.execute("SELECT state, COUNT(*) AS n FROM jobs GROUP BY state").fetchall()
+ return {r["state"]: r["n"] for r in rows}
+
+ def recover_jobs(self) -> int:
+ """Return jobs left ``running`` by an interrupted process to the queue
+ (or ``failed`` if their retry budget is spent), and report how many.
+
+ Called when a case is opened. A worker that crashed mid-thumbnail leaves
+ a ``running`` row that nothing owns; this reclaims it so the work resumes
+ instead of stalling forever.
+ """
+ def op(conn: sqlite3.Connection) -> int:
+ rows = conn.execute("SELECT * FROM jobs WHERE state = 'running'").fetchall()
+ for row in rows:
+ state = "queued" if row["attempts"] < row["max_attempts"] else "failed"
+ error = None if state == "queued" else "interrupted"
+ conn.execute(
+ "UPDATE jobs SET state = ?, error = ?, updated_at = ? WHERE id = ?",
+ (state, error, _now(), row["id"]),
+ )
+ return len(rows)
+
+ return self._write(op)
+
+ def prune_jobs(self, *, kind: str | None = None) -> int:
+ """Drop terminal (ready/failed/cancelled) job rows, optionally of one
+ kind. Keeps the table from growing without bound across a long session;
+ live (queued/running) work is never touched. Returns how many were dropped.
+ """
+ def op(conn: sqlite3.Connection) -> int:
+ placeholders = ", ".join("?" * len(_JOB_TERMINAL))
+ params: list[Any] = list(_JOB_TERMINAL)
+ clause = f"state IN ({placeholders})"
+ if kind is not None:
+ clause += " AND kind = ?"
+ params.append(kind)
+ cur = conn.execute(f"DELETE FROM jobs WHERE {clause}", params)
+ return cur.rowcount
+
+ return self._write(op)
+
+
+# -- JSON -> SQLite conversion ---------------------------------------------
+
+
+@dataclass
+class MigrationReport:
+ """What a JSON->SQLite conversion imported and found (doc "Migration
+ validation"). Integrity failures abort; missing link endpoints are reported
+ and the offending edge dropped, never erasing an entity."""
+
+ entities: int = 0
+ links: int = 0
+ folders: int = 0
+ missing_endpoints: list[str] = field(default_factory=list)
+ integrity_ok: bool = True
+
+
+def convert_json_to_sqlite(data: dict[str, Any], db_path: Path) -> MigrationReport:
+ """Build `db_path` from a parsed `case.json` graph, atomically.
+
+ Writes a `case.db.tmp` beside the target, imports the whole graph in one
+ transaction, runs `foreign_key_check` / `integrity_check`, then renames it
+ into place. Any failure removes the temporary file and raises, leaving the
+ target untouched (the doc's "a crash before the manifest change leaves the
+ legacy case active"). This is the mechanism; flipping the manifest onto it is
+ Delivery step 4.
+ """
+ db_path = Path(db_path)
+ tmp = db_path.with_name(db_path.name + ".tmp")
+ if tmp.exists():
+ tmp.unlink()
+
+ report = MigrationReport(
+ entities=len(data.get("entities", [])),
+ folders=len(data.get("folders", [])),
+ )
+ store = SqliteCase.create(
+ tmp,
+ name=data.get("name", ""),
+ created_at=data.get("created_at"),
+ updated_at=data.get("updated_at"),
+ )
+ try:
+ with store._connect() as conn:
+ conn.execute("BEGIN IMMEDIATE")
+ try:
+ _import_graph(conn, data, report)
+ fk_problems = conn.execute("PRAGMA foreign_key_check").fetchall()
+ integrity = conn.execute("PRAGMA integrity_check").fetchone()[0]
+ report.integrity_ok = not fk_problems and integrity == "ok"
+ report.links = conn.execute("SELECT COUNT(*) FROM links").fetchone()[0]
+ if not report.integrity_ok:
+ raise CaseError(f"migration integrity check failed for '{db_path.name}'")
+ conn.execute("COMMIT")
+ except BaseException:
+ conn.execute("ROLLBACK")
+ raise
+ except BaseException:
+ tmp.unlink(missing_ok=True)
+ raise
+
+ _replace_with_retry(tmp, db_path)
+ return report
+
+
+def _import_graph(conn: sqlite3.Connection, data: dict[str, Any], report: MigrationReport) -> None:
+ entity_ids: set[str] = set()
+ for entity in data.get("entities", []):
+ prov = entity.get("provenance", {})
+ conn.execute(
+ "INSERT INTO entities"
+ "(id, type, label, attrs_json, folder, prov_by, prov_at, prov_status, prov_source)"
+ " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ (
+ entity["id"],
+ entity.get("type", ""),
+ entity.get("label", ""),
+ json.dumps(entity.get("attrs") or {}, ensure_ascii=False),
+ _folder_of(entity.get("attrs")),
+ prov.get("by", ""),
+ prov.get("at", ""),
+ prov.get("status", "confirmed"),
+ prov.get("source"),
+ ),
+ )
+ entity_ids.add(entity["id"])
+ for link in data.get("links", []):
+ if link["from"] not in entity_ids or link["to"] not in entity_ids:
+ report.missing_endpoints.append(link["id"])
+ continue
+ prov = link.get("provenance", {})
+ conn.execute(
+ "INSERT INTO links"
+ "(id, from_id, to_id, type, prov_by, prov_at, prov_status, prov_source)"
+ " VALUES(?, ?, ?, ?, ?, ?, ?, ?)",
+ (
+ link["id"],
+ link["from"],
+ link["to"],
+ link.get("type", ""),
+ prov.get("by", ""),
+ prov.get("at", ""),
+ prov.get("status", "confirmed"),
+ prov.get("source"),
+ ),
+ )
+ for folder in data.get("folders", []):
+ conn.execute("INSERT OR IGNORE INTO folders(path) VALUES(?)", (folder,))
+
+
+if TYPE_CHECKING:
+ # `SqliteCase` is the SQLite `CaseRepository`; this fails type-check if a
+ # graph method drifts from the boundary contract, exactly as `Case` is held
+ # in workspace.py.
+ def _sqlite_conforms(store: SqliteCase) -> "CaseRepository":
+ return store
diff --git a/src/azimut/workspace.py b/src/azimut/workspace.py
index b264d58..f515691 100644
--- a/src/azimut/workspace.py
+++ b/src/azimut/workspace.py
@@ -18,28 +18,45 @@ from __future__ import annotations
import json
import re
import shutil
+import sqlite3
import threading
import time
import uuid
from datetime import datetime, timezone
from pathlib import Path
-from typing import Any, Callable, Literal
+from typing import TYPE_CHECKING, Any, Callable
from . import config
+from .repository import EntityStatus
-CASE_SUBDIRS = ("media", "proofs", "exports", "inspect", "search")
+if TYPE_CHECKING:
+ from .repository import CaseRepository
+ from .sqlite_backend import SqliteCase
-# On-disk schema for case.json. A newer Azimut opens an older case by running
-# the migrations below up to this number on first open; a case written by a
-# *newer* Azimut (higher schema) is refused rather than mangled (spec §7,
-# forward compatibility). Bump this in the same change that adds a migration.
-CASE_SCHEMA = 1
+CASE_SUBDIRS = ("media", "notes", "proofs", "exports", "inspect", "search")
+
+# On-disk schema. A newer Azimut opens an older case by running the migrations
+# below up to the current number on first open; a case written by a *newer*
+# Azimut (higher schema) is refused rather than mangled (spec §7, forward
+# compatibility). Bump CASE_SCHEMA in the same change that adds a migration.
+#
+# The graph lived inside case.json through schema 2 ("json" storage). Schema 3
+# moves it into a per-case SQLite `case.db` ("sqlite" storage) and shrinks
+# case.json to a manifest. JSON_SCHEMA is the last json-storage schema: migrate()
+# runs the json-shape migrations up to it, then activates SQLite to reach
+# CASE_SCHEMA. An older Azimut that predates schema 3 sees a higher number and
+# refuses, the same guarantee the schema check has always given.
+JSON_SCHEMA = 2
+CASE_SCHEMA = 3
# from_version -> function(data) returning data reshaped for from_version + 1.
# The runner (Case.migrate) owns stamping the new schema number, so a migration
-# only rewrites fields. Empty while we're on the first schema; each future
-# breaking change to case.json lands one entry here plus a fixture pinning it.
-CASE_MIGRATIONS: dict[int, Callable[[dict[str, Any]], dict[str, Any]]] = {}
+# only rewrites fields. These cover json-shape upgrades within case.json (up to
+# JSON_SCHEMA); the storage activation to schema 3 is not a field reshape and is
+# handled specially by migrate() via _activate_sqlite, not through this table.
+CASE_MIGRATIONS: dict[int, Callable[[dict[str, Any]], dict[str, Any]]] = {
+ 1: lambda data: data,
+}
def _case_schema(data: dict[str, Any]) -> int:
@@ -78,8 +95,6 @@ def _case_lock(path: Path) -> threading.RLock:
_case_locks[key] = lock
return lock
-EntityStatus = Literal["confirmed", "suggested"]
-
# Extensible vocabulary (spec §5); free strings are accepted, these are the
# well-known ones the UI knows how to render.
ENTITY_TYPES = (
@@ -147,12 +162,65 @@ class CaseError(Exception):
"""Raised for invalid case operations; maps to HTTP 4xx in the API layer."""
+_UNSET: Any = object()
+
+
+def _parse_cursor(cursor: str | None) -> int:
+ """Parse an opaque pagination cursor to its integer key (0 when absent).
+
+ The cursor is the SQLite backend's ``rowid`` keyset token, round-tripped
+ through the API as a string. A malformed one is a client error, surfaced as
+ `CaseError` (HTTP 400)."""
+ if cursor is None:
+ return 0
+ try:
+ return int(cursor)
+ except (TypeError, ValueError):
+ raise CaseError(f"invalid cursor '{cursor}'") from None
+
+
class Case:
- """Handle over one case directory. All reads/writes go through here."""
+ """Handle over one case directory.
+
+ The filesystem shell (manifest, notes, media, lifecycle, path resolution)
+ lives here. Graph operations — entities, links, folders — are the
+ `CaseRepository` contract, delegated to a `SqliteCase` over `case.db`. A
+ legacy json case (schema ≤ `JSON_SCHEMA`) is converted to sqlite on open
+ (`migrate`), so every live handle is sqlite-backed.
+ """
def __init__(self, path: Path):
self.path = path
self._lock = _case_lock(path)
+ # Resolved lazily from the manifest on first graph access, then cached.
+ self._sqlite_cache: Any = _UNSET
+
+ @property
+ def _sqlite(self) -> "SqliteCase | None":
+ """The SQLite graph backend if this case is on the sqlite storage
+ format, else None (a legacy json case handled in-file).
+
+ The manifest's ``azimut.storage`` field is the discriminator — not the
+ presence of ``case.db`` — so a crash mid-migration (db written, manifest
+ not yet flipped) still opens as json and the orphan db is rebuilt.
+ """
+ if self._sqlite_cache is _UNSET:
+ self._sqlite_cache = self._resolve_sqlite()
+ return self._sqlite_cache
+
+ def _resolve_sqlite(self) -> "SqliteCase | None":
+ from .sqlite_backend import SqliteCase
+
+ try:
+ meta = json.loads(self.json_path.read_text(encoding="utf-8")).get("azimut", {})
+ except (OSError, json.JSONDecodeError):
+ return None
+ if isinstance(meta, dict) and meta.get("storage") == "sqlite":
+ # `.open` (not the bare constructor) so an older `case.db` schema is
+ # upgraded in place on first access — the storage-format equivalent
+ # of `Case.migrate` for the manifest.
+ return SqliteCase.open(self.path / "case.db")
+ return None
# -- identity ---------------------------------------------------------
@@ -168,6 +236,10 @@ class Case:
@classmethod
def create(cls, name: str, *, scratch: bool = False) -> "Case":
+ """Create a new case. Every case is born on the SQLite backend; a legacy
+ json case only ever arrives from disk and is converted on open."""
+ from .sqlite_backend import SqliteCase
+
parent = config.scratch_dir() if scratch else config.cases_dir()
parent.mkdir(parents=True, exist_ok=True)
slug = _new_id("scratch") if scratch else _slugify(name)
@@ -178,15 +250,13 @@ class Case:
for sub in CASE_SUBDIRS:
(path / sub).mkdir()
case = cls(path)
+ case._sqlite_cache = SqliteCase.create(path / "case.db", name=name)
case._write_json(
{
- "azimut": {"schema": 1},
+ "azimut": {"schema": CASE_SCHEMA, "storage": "sqlite"},
"name": name,
"created_at": _now(),
"updated_at": _now(),
- "folders": [],
- "entities": [],
- "links": [],
}
)
(path / "notes.md").write_text(f"# {name}\n\n", encoding="utf-8")
@@ -222,16 +292,45 @@ class Case:
f"case '{self.id}' was made with a newer Azimut "
f"(schema {version} > {CASE_SCHEMA}); update Azimut to open it"
)
+ storage = data.get("azimut", {}).get("storage")
self._backup(f"pre-migrate-v{version}")
- for step in range(version, CASE_SCHEMA):
+ # 1) json-shape migrations, up to the last json-storage schema.
+ for step in range(version, min(CASE_SCHEMA, JSON_SCHEMA)):
migrate = CASE_MIGRATIONS.get(step)
if migrate is None:
raise CaseError(f"no migration for case schema {step}")
data = migrate(data)
data.setdefault("azimut", {})["schema"] = step + 1
+ self._materialize_note_content(data)
self._write_json(data)
+ # 2) storage activation: json graph -> sqlite (case.db), manifest last.
+ if CASE_SCHEMA > JSON_SCHEMA and storage != "sqlite":
+ self._activate_sqlite(self.read())
+ return self.snapshot()
return data
+ def _activate_sqlite(self, data: dict[str, Any]) -> None:
+ """Convert a note-materialized json case (schema JSON_SCHEMA) into the
+ sqlite format: build case.db, then flip case.json to the small manifest.
+
+ The conversion is atomic and the manifest changes last, so a crash
+ before the flip leaves the legacy json case active (the pre-migrate
+ backup is already taken by the caller). Media, proofs and note files are
+ untouched.
+ """
+ from .sqlite_backend import convert_json_to_sqlite
+
+ convert_json_to_sqlite(data, self.path / "case.db")
+ self._write_json(
+ {
+ "azimut": {"schema": CASE_SCHEMA, "storage": "sqlite"},
+ "name": data.get("name", self.id),
+ "created_at": data.get("created_at"),
+ "updated_at": data.get("updated_at") or _now(),
+ }
+ )
+ self._sqlite_cache = _UNSET # re-resolve against the new manifest
+
def _backup(self, tag: str) -> None:
"""Copy case.json aside once, under a ``tag``. Never overwrites an
existing backup — a re-run of the same migration keeps the first copy."""
@@ -260,9 +359,10 @@ class Case:
case = cls(path)
try:
data = case.read()
- except (OSError, json.JSONDecodeError):
+ has_graph = bool(case.list_entities() or case.list_links())
+ except (OSError, json.JSONDecodeError, sqlite3.Error):
continue
- if data.get("entities") or data.get("links"):
+ if has_graph:
continue
stamp = data.get("updated_at") or data.get("created_at") or ""
try:
@@ -296,14 +396,17 @@ class Case:
continue
case = cls(path)
data = case.read()
+ updated_at = data.get("updated_at")
+ if case._sqlite is not None:
+ updated_at = case._sqlite.updated_at() or updated_at
out.append(
{
"id": case.id,
"name": data.get("name", case.id),
"scratch": scratch,
"created_at": data.get("created_at"),
- "updated_at": data.get("updated_at"),
- "entity_count": len(data.get("entities", [])),
+ "updated_at": updated_at,
+ "entity_count": case.entity_count(),
}
)
out.sort(key=lambda c: c.get("updated_at") or "", reverse=True)
@@ -333,6 +436,85 @@ class Case:
tmp.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
_replace_with_retry(tmp, self.json_path)
+ # -- graph reads (CaseRepository boundary) ------------------------------
+ #
+ # The one way engine and API code reads the graph: no caller reaches into
+ # the raw case.json shape any more, so the SQLite backend (Step 2) can
+ # answer these without materialising the whole file. `read()` above stays
+ # the JSON implementation detail, used internally and by storage tests.
+
+ def _graph(self) -> "SqliteCase":
+ """The SQLite graph backend. Every opened case is on the sqlite storage
+ format — a legacy json case is converted on open (`migrate`) — so this is
+ always set for a live handle; it raises only if a graph op is attempted on
+ an unmigrated case, which `open`/`create` never hand out."""
+ backend = self._sqlite
+ if backend is None:
+ raise CaseError(f"case '{self.id}' has no sqlite graph (unmigrated)")
+ return backend
+
+ def snapshot(self) -> dict[str, Any]:
+ """Full case view (manifest + graph) in one consistent read: the small
+ manifest joined to the graph assembled from `case.db`."""
+ manifest = self.read()
+ graph = self._graph().snapshot()
+ return {
+ **manifest, # manifest owns name, created_at and the storage/schema tag
+ # ...but the db tracks last-activity, bumped by every graph mutation.
+ "updated_at": graph.get("updated_at") or manifest.get("updated_at"),
+ "folders": graph["folders"],
+ "entities": graph["entities"],
+ "links": graph["links"],
+ }
+
+ def overview(self) -> dict[str, Any]:
+ """The case-open view without the graph arrays (Step 5).
+
+ Returns the manifest and the folder list — everything the shell needs to
+ open a case — but not the ``entities``/``links`` arrays, which load through
+ the bounded catalog endpoints. ``snapshot()`` still returns the full graph
+ for internal callers (delete planning, export, migration checks).
+ """
+ return {**self.read(), "folders": self._graph().list_folders()}
+
+ def list_entities(self) -> list[dict[str, Any]]:
+ return self._graph().list_entities()
+
+ def page_entities(
+ self,
+ *,
+ limit: int = 100,
+ cursor: str | None = None,
+ types: list[str] | None = None,
+ status: EntityStatus | None = None,
+ query: str | None = None,
+ folder: str | None = None,
+ unfiled: bool = False,
+ ) -> dict[str, Any]:
+ """A bounded, filtered page of the catalog (Step 5), paged with an indexed
+ rowid keyset."""
+ return self._graph().page_entities(
+ limit=limit, cursor=cursor, types=types, status=status,
+ query=query, folder=folder, unfiled=unfiled,
+ )
+
+ def catalog_summary(self) -> dict[str, Any]:
+ """Total plus per-type, per-status and per-folder counts."""
+ return self._graph().catalog_summary()
+
+ def list_links(self) -> list[dict[str, Any]]:
+ return self._graph().list_links()
+
+ def links_of(self, entity_id: str) -> list[dict[str, Any]]:
+ return self._graph().links_of(entity_id)
+
+ def get_entity(self, entity_id: str) -> dict[str, Any] | None:
+ return self._graph().get_entity(entity_id)
+
+ def entity_count(self) -> int:
+ """Entity total for the case switcher — one indexed count."""
+ return self._graph().count_entities()
+
# -- notes -------------------------------------------------------------
@property
@@ -348,6 +530,72 @@ class Case:
def write_notes(self, text: str) -> None:
self.notes_path.write_text(text, encoding="utf-8")
+ @property
+ def note_dir(self) -> Path:
+ return self.path / "notes"
+
+ def _note_entity(self, entity_id: str) -> dict[str, Any]:
+ entity = self.get_entity(entity_id)
+ if entity is None or entity.get("type") != "note":
+ raise CaseError(f"note '{entity_id}' not found")
+ return entity
+
+ def _note_path(self, entity: dict[str, Any]) -> Path:
+ path = entity.get("attrs", {}).get("path")
+ if not isinstance(path, str):
+ raise CaseError(f"note '{entity['id']}' has no file")
+ return self.resolve_inside(path)
+
+ def _materialize_note_content(self, data: dict[str, Any]) -> None:
+ """Move legacy note bodies out of case.json before writing a migration."""
+ for entity in data.get("entities", []):
+ if entity.get("type") != "note":
+ continue
+ attrs = entity.setdefault("attrs", {})
+ content = attrs.pop("content", None)
+ path = attrs.setdefault("path", f"notes/{entity['id']}.md")
+ note_path = self.resolve_inside(path)
+ if content is not None or not note_path.exists():
+ note_path.parent.mkdir(parents=True, exist_ok=True)
+ note_path.write_text(str(content or ""), encoding="utf-8")
+
+ def create_note(
+ self,
+ label: str,
+ folder: str,
+ content: str = "",
+ *,
+ by: str = "user",
+ status: EntityStatus = "confirmed",
+ source: str | None = None,
+ ) -> dict[str, Any]:
+ with self._lock:
+ # The graph row goes to case.db; the body stays a file on the shell.
+ # Add the row to mint an id, write notes/<id>.md, then record its
+ # relative path on the row.
+ graph = self._graph()
+ entity = graph.add_entity(
+ "note", label, {"folder": folder}, by=by, status=status, source=source
+ )
+ rel = f"notes/{entity['id']}.md"
+ note_path = self.resolve_inside(rel)
+ note_path.parent.mkdir(parents=True, exist_ok=True)
+ note_path.write_text(content, encoding="utf-8")
+ return graph.update_entity(entity["id"], {"attrs": {"path": rel}})
+
+ def read_note(self, entity_id: str) -> str:
+ entity = self._note_entity(entity_id)
+ try:
+ return self._note_path(entity).read_text(encoding="utf-8")
+ except OSError:
+ return ""
+
+ 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")
+
# -- lifecycle -----------------------------------------------------------
def rename(self, name: str) -> None:
@@ -385,54 +633,26 @@ class Case:
status: EntityStatus = "confirmed",
source: str | None = None,
) -> dict[str, Any]:
- with self._lock:
- data = self.read()
- entity: dict[str, Any] = {
- "id": _new_id("e"),
- "type": type_,
- "label": label,
- "attrs": attrs or {},
- "provenance": {"by": by, "at": _now(), "status": status},
- }
- if source:
- entity["provenance"]["source"] = source
- data["entities"].append(entity)
- self._write_json(data)
- return entity
+ if type_ == "note":
+ note_attrs = attrs or {}
+ return self.create_note(
+ label,
+ str(note_attrs.get("folder", "")),
+ str(note_attrs.get("content", "")),
+ by=by,
+ status=status,
+ source=source,
+ )
+ return self._graph().add_entity(type_, label, attrs, by=by, status=status, source=source)
def update_entity(self, entity_id: str, patch: dict[str, Any]) -> dict[str, Any]:
- with self._lock:
- data = self.read()
- for entity in data["entities"]:
- if entity["id"] == entity_id:
- for key in ("type", "label"):
- if key in patch:
- entity[key] = patch[key]
- if "attrs" in patch:
- entity["attrs"].update(patch["attrs"])
- if patch.get("status") in ("confirmed", "suggested"):
- entity["provenance"]["status"] = patch["status"]
- self._write_json(data)
- return entity
- raise CaseError(f"entity '{entity_id}' not found")
+ return self._graph().update_entity(entity_id, patch)
def remove_entity(self, entity_id: str) -> None:
- with self._lock:
- data = self.read()
- before = len(data["entities"])
- data["entities"] = [e for e in data["entities"] if e["id"] != entity_id]
- if len(data["entities"]) == before:
- raise CaseError(f"entity '{entity_id}' not found")
- data["links"] = [
- lk for lk in data["links"] if entity_id not in (lk["from"], lk["to"])
- ]
- self._write_json(data)
+ self._graph().remove_entity(entity_id)
def find_entity(self, *, attr: str, value: Any) -> dict[str, Any] | None:
- for entity in self.read()["entities"]:
- if entity["attrs"].get(attr) == value:
- return entity
- return None
+ return self._graph().find_entity(attr=attr, value=value)
def add_link(
self,
@@ -447,30 +667,7 @@ class Case:
"""Add a typed edge. ``unique`` returns the existing identical edge
instead of stacking a duplicate — what a producer wants when its output
can dedupe onto an entity that is already in the case."""
- with self._lock:
- data = self.read()
- ids = {e["id"] for e in data["entities"]}
- for eid in (from_id, to_id):
- if eid not in ids:
- raise CaseError(f"entity '{eid}' not found")
- if unique:
- for existing in data["links"]:
- if (existing["from"], existing["to"], existing["type"]) == (
- from_id,
- to_id,
- type_,
- ):
- return existing
- link = {
- "id": _new_id("l"),
- "from": from_id,
- "to": to_id,
- "type": type_,
- "provenance": {"by": by, "at": _now(), "status": status},
- }
- data["links"].append(link)
- self._write_json(data)
- return link
+ return self._graph().add_link(from_id, to_id, type_, by=by, status=status, unique=unique)
def sync_links(
self,
@@ -488,47 +685,10 @@ class Case:
edges that are no longer true are dropped, new ones are appended. Unknown
targets and a self-reference are ignored.
"""
- with self._lock:
- data = self.read()
- ids = {e["id"] for e in data["entities"]}
- if from_id not in ids:
- raise CaseError(f"entity '{from_id}' not found")
- wanted = [
- i for i in dict.fromkeys(to_ids) if i in ids and i != from_id
- ]
- mine = {
- lk["to"]: lk
- for lk in data["links"]
- if lk["from"] == from_id and lk["type"] == type_
- }
- keep = {mine[to_id]["id"] for to_id in wanted if to_id in mine}
- data["links"] = [
- lk
- for lk in data["links"]
- if lk["from"] != from_id or lk["type"] != type_ or lk["id"] in keep
- ]
- for to_id in wanted:
- if to_id not in mine:
- data["links"].append(
- {
- "id": _new_id("l"),
- "from": from_id,
- "to": to_id,
- "type": type_,
- "provenance": {"by": by, "at": _now(), "status": status},
- }
- )
- self._write_json(data)
- return [lk for lk in data["links"] if lk["from"] == from_id and lk["type"] == type_]
+ return self._graph().sync_links(from_id, type_, to_ids, by=by, status=status)
def remove_link(self, link_id: str) -> None:
- with self._lock:
- data = self.read()
- before = len(data["links"])
- data["links"] = [lk for lk in data["links"] if lk["id"] != link_id]
- if len(data["links"]) == before:
- raise CaseError(f"link '{link_id}' not found")
- self._write_json(data)
+ self._graph().remove_link(link_id)
# -- folders (nested organisational buckets for entities) ----------------
#
@@ -546,41 +706,56 @@ class Case:
return "/".join(parts)
def list_folders(self) -> list[str]:
- return self.read().get("folders", [])
+ return self._graph().list_folders()
def add_folder(self, name: str) -> list[str]:
- path = self._normalize_folder(name)
- with self._lock:
- data = self.read()
- folders = data.setdefault("folders", [])
- # materialise the leaf and every ancestor so the tree stays connected
- segments = path.split("/")
- changed = False
- for i in range(1, len(segments) + 1):
- ancestor = "/".join(segments[:i])
- if ancestor not in folders:
- folders.append(ancestor)
- changed = True
- if changed:
- folders.sort(key=str.lower)
- self._write_json(data)
- return data["folders"]
+ return self._graph().add_folder(name)
def remove_folder(self, name: str) -> list[str]:
- with self._lock:
- data = self.read()
- folders = data.setdefault("folders", [])
- # a folder and its whole subtree go together
- prefix = name + "/"
- doomed = {f for f in folders if f == name or f.startswith(prefix)}
- data["folders"] = [f for f in folders if f not in doomed]
- # unassign any entity filed under a removed node (or its descendants)
- for entity in data.get("entities", []):
- folder = entity.get("attrs", {}).get("folder")
- if folder is not None and (folder == name or folder.startswith(prefix)):
- entity["attrs"].pop("folder", None)
- self._write_json(data)
- return data["folders"]
+ return self._graph().remove_folder(name)
+
+ # -- durable jobs (thumbnail and background-job model) -------------------
+
+ def enqueue_job(
+ self,
+ kind: str,
+ *,
+ key: str | None = None,
+ payload: dict[str, Any] | None = None,
+ max_attempts: int = 3,
+ ) -> dict[str, Any]:
+ return self._graph().enqueue_job(
+ kind, key=key, payload=payload, max_attempts=max_attempts
+ )
+
+ def claim_job(self, *, kinds: list[str] | None = None) -> dict[str, Any] | None:
+ return self._graph().claim_job(kinds=kinds)
+
+ def complete_job(self, job_id: str) -> None:
+ self._graph().complete_job(job_id)
+
+ def fail_job(self, job_id: str, error: str) -> dict[str, Any]:
+ return self._graph().fail_job(job_id, error)
+
+ def cancel_job(self, job_id: str) -> None:
+ self._graph().cancel_job(job_id)
+
+ def get_job(self, job_id: str) -> dict[str, Any] | None:
+ return self._graph().get_job(job_id)
+
+ def list_jobs(
+ self, *, kind: str | None = None, state: str | None = None
+ ) -> list[dict[str, Any]]:
+ return self._graph().list_jobs(kind=kind, state=state)
+
+ def count_jobs(self) -> dict[str, int]:
+ return self._graph().count_jobs()
+
+ def recover_jobs(self) -> int:
+ return self._graph().recover_jobs()
+
+ def prune_jobs(self, *, kind: str | None = None) -> int:
+ return self._graph().prune_jobs(kind=kind)
# -- helpers -------------------------------------------------------------
@@ -595,3 +770,11 @@ class Case:
if not candidate.is_relative_to(self.path.resolve()):
raise CaseError("path escapes the case directory")
return candidate
+
+
+if TYPE_CHECKING:
+ # `Case` conforms to `CaseRepository` (it delegates the graph to `SqliteCase`).
+ # This fails type-check if a graph method ever drifts from the boundary
+ # contract (a missing method, a changed signature).
+ def _case_conforms(case: Case) -> "CaseRepository":
+ return case
diff --git a/tests/bigcase.py b/tests/bigcase.py
new file mode 100644
index 0000000..c164abf
--- /dev/null
+++ b/tests/bigcase.py
@@ -0,0 +1,298 @@
+"""Synthetic large-case generator for the storage/performance baseline.
+
+Step 0 of docs/STORAGE_AND_PERFORMANCE.md: a repeatable fixture that stresses
+the current monolithic ``case.json`` the way a real large investigation would,
+so the JSON baseline (bench/case_baseline.py) and the later JSON-vs-SQLite
+contract tests measure the same shape.
+
+Deliberately built by writing ``case.json`` **once** rather than by calling
+``Case.add_entity`` per item: the whole point of the migration is that each such
+call rewrites the entire file, so building 10k entities that way would itself be
+O(n²). The generator constructs the graph in memory and writes it in one go.
+
+Standard library only, and it lives under ``tests/`` so hatchling never packages
+it into the wheel or the frozen binaries (see the doc's packaging constraints).
+"""
+
+from __future__ import annotations
+
+import json
+import random
+from dataclasses import dataclass, field
+from datetime import datetime, timedelta, timezone
+
+from azimut import config
+from azimut.engine.media import SIDECAR_SUFFIX, THUMB_DIR
+from azimut.workspace import CASE_SUBDIRS, Case, _slugify
+
+# Well-known + deliberately unknown types, so the fixture exercises the "unknown
+# entity/link types stay valid" rule the ontology promises.
+_SEMANTIC_TYPES = (
+ "person", "organization", "account", "email", "phone", "domain", "place",
+ "event", "vehicle", "alias",
+)
+_UNKNOWN_TYPES = ("spacecraft", "widget", "signal")
+_LINK_TYPES = ("appears-in", "located-at", "owns", "mentions", "posted", "same-as")
+
+_BASE_TIME = datetime(2024, 1, 1, tzinfo=timezone.utc)
+
+
+@dataclass
+class BigCaseSummary:
+ """What was planted, so tests and the bench can assert against it."""
+
+ case_id: str
+ entities: int = 0
+ links: int = 0
+ media: int = 0
+ media_files_missing: int = 0
+ notes: int = 0
+ artifacts: int = 0
+ folders: int = 0
+ tombstoned: int = 0
+ derived_from_links: int = 0
+ depends_on_links: int = 0
+ sample_ids: list[str] = field(default_factory=list)
+
+
+_FOLDER_TREE = (
+ "Sources",
+ "Sources/Telegram",
+ "Sources/X",
+ "Sources/Local",
+ "People",
+ "Places",
+ "Work",
+ "Work/Drafts",
+ "Work/Confirmed",
+)
+
+
+def _stamp(offset: int) -> str:
+ return (_BASE_TIME + timedelta(seconds=offset)).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _fake_sha(rng: random.Random) -> str:
+ return "%064x" % rng.getrandbits(256)
+
+
+def build_big_case(
+ *,
+ name: str = "Big synthetic case",
+ entities: int = 10_000,
+ links: int = 20_000,
+ media: int = 5_000,
+ notes: int = 200,
+ artifacts: int = 300,
+ seed: int = 1234,
+ write_media_files: bool = True,
+) -> tuple[Case, BigCaseSummary]:
+ """Create a case under the configured workspace and fill it in one write.
+
+ ``entities`` is the **total** entity count; ``media``/``notes``/``artifacts``
+ are carved out of it and the rest are plain semantic entities. Everything is
+ seeded, so the same arguments always produce byte-identical graph rows.
+ """
+ rng = random.Random(seed)
+ # A legacy json case: build the directory skeleton, then write the whole graph
+ # into case.json in one pass (the migration source, and what the JSON baseline
+ # benchmarks). `Case.create` only makes sqlite cases now, so the skeleton is
+ # built directly; opening this case migrates it to sqlite.
+ parent = config.cases_dir()
+ parent.mkdir(parents=True, exist_ok=True)
+ path = parent / _slugify(name)
+ path.mkdir()
+ for sub in CASE_SUBDIRS:
+ (path / sub).mkdir()
+ (path / "notes.md").write_text(f"# {name}\n\n", encoding="utf-8")
+ case = Case(path)
+
+ media = min(media, entities)
+ notes = min(notes, entities - media)
+ artifacts = min(artifacts, entities - media - notes)
+ plain = entities - media - notes - artifacts
+
+ summary = BigCaseSummary(case_id=case.id)
+ rows: list[dict] = []
+ ids: list[str] = []
+ clock = 0
+
+ def add(entity: dict) -> str:
+ nonlocal clock
+ entity["provenance"] = {
+ "by": "tool" if rng.random() < 0.5 else "user",
+ "at": _stamp(clock),
+ "status": "suggested" if rng.random() < 0.2 else "confirmed",
+ }
+ clock += 1
+ rows.append(entity)
+ ids.append(entity["id"])
+ return entity["id"]
+
+ def pick_folder() -> str | None:
+ # ~30% unfiled, the rest spread across the tree.
+ return None if rng.random() < 0.3 else rng.choice(_FOLDER_TREE)
+
+ media_dir = case.subdir("media")
+ thumb_dir = media_dir / THUMB_DIR
+
+ # -- media entities (+ sidecars, placeholder bytes, thumbnail states) -----
+ media_ids: list[str] = []
+ for i in range(media):
+ eid = f"e_media_{i:06d}"
+ fname = f"img_{i:06d}.jpg"
+ rel = f"media/{fname}"
+ sha = _fake_sha(rng)
+ attrs = {"path": rel, "sha256": sha, "kind": "image"}
+ if rng.random() < 0.4:
+ attrs["source_url"] = f"https://example.invalid/{i}"
+ folder = pick_folder()
+ if folder:
+ attrs["folder"] = folder
+ add({"id": eid, "type": "capture" if rng.random() < 0.3 else "media",
+ "label": fname, "attrs": attrs})
+ media_ids.append(eid)
+
+ # ~10% of media reference a file that isn't on disk (missing source).
+ if rng.random() < 0.1:
+ summary.media_files_missing += 1
+ continue
+ if write_media_files:
+ (media_dir / fname).write_bytes(b"\xff\xd8\xff\xe0synthetic-media")
+ sidecar = {
+ "filename": fname,
+ "kind": "image",
+ "sha256": sha,
+ "size": 16,
+ "added_at": _stamp(clock),
+ "source": {"url": attrs.get("source_url")} if "source_url" in attrs else {},
+ "thumbnail": f"media/{THUMB_DIR}/{fname}.jpg",
+ }
+ (media_dir / (fname + SIDECAR_SUFFIX)).write_text(
+ json.dumps(sidecar, ensure_ascii=False), encoding="utf-8"
+ )
+ roll = rng.random()
+ if roll < 0.7: # ready
+ thumb_dir.mkdir(parents=True, exist_ok=True)
+ (thumb_dir / (fname + ".jpg")).write_bytes(b"\xff\xd8\xff\xe0thumb")
+ elif roll < 0.8: # corrupt: truncated header, decode will fail
+ thumb_dir.mkdir(parents=True, exist_ok=True)
+ (thumb_dir / (fname + ".jpg")).write_bytes(b"\xff\xd8")
+ # else: missing thumbnail — nothing written
+ summary.media = media
+
+ # -- file-backed notes ----------------------------------------------------
+ note_dir = case.note_dir
+ note_dir.mkdir(parents=True, exist_ok=True)
+ for i in range(notes):
+ eid = f"e_note_{i:06d}"
+ rel = f"notes/{eid}.md"
+ (case.path / rel).write_text(f"# Note {i}\n\nSynthetic body {i}.\n", encoding="utf-8")
+ attrs = {"folder": pick_folder() or "", "path": rel}
+ add({"id": eid, "type": "note", "label": f"Note {i}", "attrs": attrs})
+ summary.notes = notes
+
+ # -- plain semantic + unknown-typed entities ------------------------------
+ for i in range(plain):
+ eid = f"e_ent_{i:06d}"
+ etype = (
+ rng.choice(_UNKNOWN_TYPES) if rng.random() < 0.05
+ else rng.choice(_SEMANTIC_TYPES)
+ )
+ attrs: dict = {}
+ folder = pick_folder()
+ if folder:
+ attrs["folder"] = folder
+ if etype in ("place", "event") and rng.random() < 0.5:
+ attrs["lat"] = round(rng.uniform(-60, 60), 6)
+ attrs["lon"] = round(rng.uniform(-180, 180), 6)
+ add({"id": eid, "type": etype, "label": f"{etype.title()} {i}", "attrs": attrs})
+
+ # -- proof / post / inspect artifacts (derivation sources) ----------------
+ artifact_ids: list[str] = []
+ links_rows: list[dict] = []
+ derived = depends = 0
+ lclock = 0
+
+ def add_link(src: str, dst: str, ltype: str) -> None:
+ nonlocal lclock
+ links_rows.append({
+ "id": f"l_{lclock:06d}",
+ "from": src,
+ "to": dst,
+ "type": ltype,
+ "provenance": {"by": "tool", "at": _stamp(lclock), "status": "confirmed"},
+ })
+ lclock += 1
+
+ for i in range(artifacts):
+ kind = rng.choice(("proof", "post", "inspect-session"))
+ eid = f"e_art_{i:06d}"
+ if kind == "proof":
+ attrs = {"spec": f"proofs/proof_{i:06d}.json"}
+ elif kind == "post":
+ attrs = {"draft": f"exports/draft_{i:06d}.json"}
+ else:
+ attrs = {"spec": f"inspect/session_{i:06d}.json"}
+ folder = pick_folder()
+ if folder:
+ attrs["folder"] = folder
+ add({"id": eid, "type": kind, "label": f"{kind} {i}", "attrs": attrs})
+ artifact_ids.append(eid)
+
+ # Wire a real derivation so plan_delete / tombstones have structure:
+ # inspect-session depends-on its media; proof/post derived-from theirs.
+ if media_ids:
+ src = rng.choice(media_ids)
+ if kind == "inspect-session":
+ add_link(eid, src, "depends-on")
+ depends += 1
+ else:
+ add_link(eid, src, "derived-from")
+ derived += 1
+ summary.artifacts = artifacts
+
+ # -- fill the rest of the links budget with semantic edges ----------------
+ while len(links_rows) < links and len(ids) >= 2:
+ a, b = rng.sample(ids, 2)
+ add_link(a, b, rng.choice(_LINK_TYPES))
+ summary.derived_from_links = derived
+ summary.depends_on_links = depends
+
+ # -- a handful of tombstones (missing-source scars) on some artifacts -----
+ for eid in rng.sample(artifact_ids, min(len(artifact_ids), max(1, artifacts // 20))):
+ entity = next(e for e in rows if e["id"] == eid)
+ entity["attrs"]["lost_sources"] = [{
+ "path": f"media/gone_{rng.randrange(10_000):05d}.jpg",
+ "sha256": _fake_sha(rng),
+ "at": _stamp(clock),
+ }]
+ summary.tombstoned += 1
+
+ # -- folders: the tree, plus every folder any entity was filed under ------
+ used = {e["attrs"]["folder"] for e in rows if e["attrs"].get("folder")}
+ folders: set[str] = set(_FOLDER_TREE)
+ for path in used:
+ parts = path.split("/")
+ for j in range(1, len(parts) + 1):
+ folders.add("/".join(parts[:j]))
+ folder_list = sorted(folders, key=str.lower)
+
+ data = {
+ "azimut": {"schema": 2, "storage": "json"},
+ "name": name,
+ "created_at": _stamp(0),
+ "updated_at": _stamp(clock),
+ "folders": folder_list,
+ "entities": rows,
+ "links": links_rows,
+ }
+ case.json_path.write_text(
+ json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
+ )
+
+ summary.entities = len(rows)
+ summary.links = len(links_rows)
+ summary.folders = len(folder_list)
+ summary.sample_ids = ids[:5]
+ return case, summary
diff --git a/tests/graph_read.py b/tests/graph_read.py
new file mode 100644
index 0000000..aebfb0a
--- /dev/null
+++ b/tests/graph_read.py
@@ -0,0 +1,36 @@
+"""Read the full case graph in-process, for test assertions.
+
+The case-open HTTP response no longer ships the entity/link arrays (Step 5 of
+docs/STORAGE_AND_PERFORMANCE.md): production reads them through the bounded
+catalog endpoints (`/catalog/entities`, `/entities/lookup`, `/entities/{id}/chain`
+and `/derivation`). Tests that assert on the whole graph inspect the store
+directly here rather than the open payload — allowed, since tests may inspect
+fixtures and internal state, and it keeps a links-list route (which no UI would
+call) out of the product surface.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from azimut.workspace import Case
+
+
+def entities(cid: str, **attrs: Any) -> list[dict[str, Any]]:
+ """Every entity in the case, or those whose ``attrs`` match all ``attrs``."""
+ rows = Case.open(cid).snapshot()["entities"]
+ if not attrs:
+ return rows
+ return [e for e in rows if all(e.get("attrs", {}).get(k) == v for k, v in attrs.items())]
+
+
+def entity(cid: str, **attrs: Any) -> dict[str, Any] | None:
+ """The first entity whose ``attrs`` match, e.g. ``entity(cid, path='media/a.png')``."""
+ matches = entities(cid, **attrs)
+ return matches[0] if matches else None
+
+
+def links(cid: str, type_: str | None = None) -> list[dict[str, Any]]:
+ """Every link in the case, optionally filtered to one type."""
+ rows = Case.open(cid).snapshot()["links"]
+ return [lk for lk in rows if type_ is None or lk["type"] == type_]
diff --git a/tests/legacy_case.py b/tests/legacy_case.py
new file mode 100644
index 0000000..209b7b6
--- /dev/null
+++ b/tests/legacy_case.py
@@ -0,0 +1,51 @@
+"""Write a legacy json-storage case on disk, for the migration tests.
+
+`Case.create` only makes SQLite cases now — the live in-file JSON graph backend
+was removed once every case runs on `case.db`. The JSON→SQLite importer and the
+on-open migration stay, so a legacy json case still has to be openable; it just
+never originates from the app any more, only from an older release's files. This
+helper writes that file (schema ``JSON_SCHEMA`` by default) so `Case.open` can
+migrate it, and the converter tests can read it.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+from azimut import config
+from azimut.workspace import CASE_SUBDIRS, JSON_SCHEMA, Case, _now, _slugify
+
+
+def write_legacy_json_case(
+ name: str,
+ *,
+ schema: int = JSON_SCHEMA,
+ entities: list[dict[str, Any]] | None = None,
+ links: list[dict[str, Any]] | None = None,
+ folders: list[str] | None = None,
+ scratch: bool = False,
+) -> Case:
+ """Create a case directory holding an old ``storage: "json"`` ``case.json``
+ (graph inline) and return an un-migrated `Case` handle over it. Opening it
+ with `Case.open` converts it to sqlite."""
+ parent = config.scratch_dir() if scratch else config.cases_dir()
+ parent.mkdir(parents=True, exist_ok=True)
+ path = parent / _slugify(name)
+ path.mkdir()
+ for sub in CASE_SUBDIRS:
+ (path / sub).mkdir()
+ (path / "notes.md").write_text(f"# {name}\n\n", encoding="utf-8")
+ data = {
+ "azimut": {"schema": schema, "storage": "json"},
+ "name": name,
+ "created_at": _now(),
+ "updated_at": _now(),
+ "folders": folders or [],
+ "entities": entities or [],
+ "links": links or [],
+ }
+ (path / "case.json").write_text(
+ json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
+ )
+ return Case(path)
diff --git a/tests/test_bigcase.py b/tests/test_bigcase.py
new file mode 100644
index 0000000..02f2cc8
--- /dev/null
+++ b/tests/test_bigcase.py
@@ -0,0 +1,98 @@
+"""The synthetic large-case generator produces a valid, deterministic case.
+
+These pin the fixture itself (Step 0 of docs/STORAGE_AND_PERFORMANCE.md) so the
+JSON baseline and the later JSON-vs-SQLite contract tests all stress the same
+shape. Counts are kept small here; the bench harness runs the real sizes.
+"""
+
+from __future__ import annotations
+
+import json
+
+from azimut.engine import links as link_engine
+from azimut.workspace import Case
+from bigcase import build_big_case
+
+
+def _build(**kw):
+ return build_big_case(
+ entities=300, links=400, media=100, notes=20, artifacts=30, **kw
+ )
+
+
+def test_builds_a_case_that_opens_with_matching_counts(tmp_workspace):
+ _, summary = _build()
+
+ # Opening the legacy json case migrates it to sqlite; the graph is preserved.
+ reopened = Case.open(summary.case_id)
+ data = reopened.snapshot()
+ assert data["azimut"]["storage"] == "sqlite"
+ assert len(data["entities"]) == summary.entities == 300
+ assert len(data["links"]) == summary.links
+ # entity ids are unique
+ ids = [e["id"] for e in data["entities"]]
+ assert len(ids) == len(set(ids))
+
+
+def test_folder_tree_is_well_formed(tmp_workspace):
+ case, _ = _build()
+ data = case.read()
+ folders = set(data["folders"])
+ # every folder an entity is filed under exists as a node
+ for entity in data["entities"]:
+ folder = entity["attrs"].get("folder")
+ if folder:
+ assert folder in folders
+ # and every node carries its ancestors
+ for folder in folders:
+ parts = folder.split("/")
+ for i in range(1, len(parts)):
+ assert "/".join(parts[:i]) in folders
+
+
+def test_notes_are_file_backed_not_inline(tmp_workspace):
+ case, _ = _build()
+ note_entities = [e for e in case.read()["entities"] if e["type"] == "note"]
+ assert note_entities
+ for note in note_entities:
+ assert "content" not in note["attrs"] # body lives on disk, not in the graph
+ rel = note["attrs"]["path"]
+ assert (case.path / rel).read_text(encoding="utf-8").startswith("# Note")
+
+
+def test_media_sidecars_present_and_some_files_missing(tmp_workspace):
+ case, summary = _build(seed=7)
+ # the fixture deliberately models missing source files
+ assert summary.media_files_missing > 0
+ media_dir = case.subdir("media")
+ present = list(media_dir.glob("img_*.jpg"))
+ sidecars = list(media_dir.glob("*.azimut.json"))
+ assert present and len(sidecars) == len(present)
+ assert len(present) == summary.media - summary.media_files_missing
+
+
+def test_derivations_are_valid_and_cascade(tmp_workspace):
+ _, summary = _build(seed=3)
+ assert summary.depends_on_links > 0
+ # open (migrate) the case so the graph API reads it through sqlite
+ case = Case.open(summary.case_id)
+ data = case.snapshot()
+ ids = {e["id"] for e in data["entities"]}
+ for link in data["links"]:
+ assert link["from"] in ids and link["to"] in ids
+
+ dep = next(lk for lk in data["links"] if lk["type"] == "depends-on")
+ session_id, subject_id = dep["from"], dep["to"]
+ plan = link_engine.plan_delete(case, subject_id)
+ assert session_id in {e["id"] for e in plan["cascade"]}
+
+
+def test_generation_is_deterministic_for_a_seed(tmp_workspace):
+ a, _ = build_big_case(name="Case A", entities=200, links=250, media=60,
+ notes=10, artifacts=20, seed=42)
+ b, _ = build_big_case(name="Case B", entities=200, links=250, media=60,
+ notes=10, artifacts=20, seed=42)
+ da, db = a.read(), b.read()
+ # identical graph regardless of the case name
+ assert json.dumps(da["entities"]) == json.dumps(db["entities"])
+ assert json.dumps(da["links"]) == json.dumps(db["links"])
diff --git a/tests/test_binary_smoke.py b/tests/test_binary_smoke.py
new file mode 100644
index 0000000..8dcc477
--- /dev/null
+++ b/tests/test_binary_smoke.py
@@ -0,0 +1,57 @@
+"""Tests for the standalone-binary release smoke test."""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+from pathlib import Path
+
+import pytest
+
+
+SCRIPT = Path(__file__).parents[1] / "scripts" / "smoke_binary.py"
+SPEC = importlib.util.spec_from_file_location("azimut_smoke_binary", SCRIPT)
+assert SPEC is not None and SPEC.loader is not None
+smoke_binary = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(smoke_binary)
+
+
+def test_check_application_exercises_health_frontend_and_bundled_ffmpeg(monkeypatch):
+ responses = {
+ "/api/health": (200, "application/json", json.dumps({"status": "ok"})),
+ "/": (200, "text/html", '<html><div id="app"></div></html>'),
+ "/api/settings/ffmpeg": (
+ 200,
+ "application/json",
+ json.dumps({"available": True, "source": "bundled"}),
+ ),
+ }
+ seen = []
+
+ def request(url):
+ path = url.removeprefix("http://127.0.0.1:8477")
+ seen.append(path)
+ return responses[path]
+
+ monkeypatch.setattr(smoke_binary, "_request", request)
+ smoke_binary.check_application("http://127.0.0.1:8477")
+
+ assert seen == ["/api/health", "/", "/api/settings/ffmpeg"]
+
+
+def test_check_application_rejects_path_ffmpeg(monkeypatch):
+ responses = iter(
+ [
+ (200, "application/json", json.dumps({"status": "ok"})),
+ (200, "text/html", '<div id="app"></div>'),
+ (
+ 200,
+ "application/json",
+ json.dumps({"available": True, "source": "path"}),
+ ),
+ ]
+ )
+ monkeypatch.setattr(smoke_binary, "_request", lambda _url: next(responses))
+
+ with pytest.raises(RuntimeError, match="bundled ffmpeg"):
+ smoke_binary.check_application("http://127.0.0.1:8477")
diff --git a/tests/test_cases_api.py b/tests/test_cases_api.py
index 23438f0..43d615d 100644
--- a/tests/test_cases_api.py
+++ b/tests/test_cases_api.py
@@ -1,14 +1,37 @@
"""Case lifecycle, notes, entities and links through the REST API."""
+import graph_read
+
def test_health(client):
assert client.get("/api/health").json()["status"] == "ok"
+def test_entity_status_is_validated_consistently(client):
+ cid = client.post("/api/cases", json={"name": "Statuses"}).json()["id"]
+ invalid_create = client.post(
+ f"/api/cases/{cid}/entities",
+ json={"type": "person", "label": "Lead", "status": "pending"},
+ )
+ assert invalid_create.status_code == 422
+ assert graph_read.entities(cid) == []
+
+ entity = client.post(
+ f"/api/cases/{cid}/entities",
+ json={"type": "person", "label": "Lead", "status": "suggested"},
+ ).json()
+ invalid_patch = client.patch(
+ f"/api/cases/{cid}/entities/{entity['id']}", json={"status": "pending"}
+ )
+ assert invalid_patch.status_code == 422
+ saved = next(item for item in graph_read.entities(cid) if item["id"] == entity["id"])
+ assert saved["provenance"]["status"] == "suggested"
+
+
def test_case_lifecycle(client):
created = client.post("/api/cases", json={"name": "Kharkiv Strike"}).json()
assert created["id"] == "kharkiv-strike"
- assert created["entities"] == []
+ assert graph_read.entities(created["id"]) == []
# duplicate name → 409
assert client.post("/api/cases", json={"name": "Kharkiv Strike"}).status_code == 409
@@ -83,7 +106,36 @@ def test_notes_roundtrip(client):
assert client.get(f"/api/cases/{case['id']}/notes").json()["text"] == "# hello\n\nworld"
-def test_entities_and_links(client):
+def test_filed_notes_are_markdown_files(client):
+ import azimut.config as cfg
+
+ cid = client.post("/api/cases", json={"name": "Notebook"}).json()["id"]
+ note = client.post(
+ f"/api/cases/{cid}/notes",
+ json={"title": "Lead", "folder": "Research", "content": "# First lead"},
+ ).json()
+
+ assert note["attrs"] == {"folder": "Research", "path": f"notes/{note['id']}.md"}
+ assert (cfg.cases_dir() / cid / note["attrs"]["path"]).read_text(encoding="utf-8") == "# First lead"
+ assert client.get(f"/api/cases/{cid}/notes/{note['id']}").json()["text"] == "# First lead"
+
+ client.put(f"/api/cases/{cid}/notes/{note['id']}", json={"text": "Updated"})
+ assert client.get(f"/api/cases/{cid}/notes/{note['id']}").json()["text"] == "Updated"
+
+
+def test_deleting_filed_note_removes_markdown_file(client):
+ import azimut.config as cfg
+
+ cid = client.post("/api/cases", json={"name": "Notebook delete"}).json()["id"]
+ note = client.post(f"/api/cases/{cid}/notes", json={"title": "Disposable"}).json()
+ path = cfg.cases_dir() / cid / note["attrs"]["path"]
+ assert path.exists()
+
+ client.delete(f"/api/cases/{cid}/entities/{note['id']}")
+ assert not path.exists()
+
+
+def test_entities_and_deletion_cleanup(client):
cid = client.post("/api/cases", json={"name": "Graph"}).json()["id"]
person = client.post(
@@ -102,26 +154,93 @@ def test_entities_and_links(client):
).json()
assert patched["provenance"]["status"] == "confirmed"
- link = client.post(
- f"/api/cases/{cid}/links",
- json={"from_id": person["id"], "to_id": account["id"], "type": "owns"},
- ).json()
- assert link["type"] == "owns"
+ from azimut.workspace import Case
- # unknown entity in a link → 404
- assert (
- client.post(
- f"/api/cases/{cid}/links",
- json={"from_id": person["id"], "to_id": "e_nope", "type": "owns"},
- ).status_code
- == 404
- )
+ link = Case.open(cid).add_link(person["id"], account["id"], "owns", by="user")
+ assert link["type"] == "owns"
# deleting an entity cascades to its links
client.delete(f"/api/cases/{cid}/entities/{account['id']}")
- data = client.get(f"/api/cases/{cid}").json()
- assert len(data["entities"]) == 1
- assert data["links"] == []
+ assert len(graph_read.entities(cid)) == 1
+ assert graph_read.links(cid) == []
+
+
+def test_catalog_pagination_and_summary(client):
+ cid = client.post("/api/cases", json={"name": "Catalog"}).json()["id"]
+ for i in range(5):
+ client.post(f"/api/cases/{cid}/entities", json={"type": "person", "label": f"P{i}"})
+ client.post(
+ f"/api/cases/{cid}/entities",
+ json={"type": "account", "label": "@acct", "status": "suggested"},
+ )
+
+ # walk the whole catalog in bounded pages
+ seen: list[str] = []
+ cursor = None
+ while True:
+ params: dict[str, object] = {"limit": 2}
+ if cursor:
+ params["cursor"] = cursor
+ page = client.get(f"/api/cases/{cid}/catalog/entities", params=params).json()
+ assert len(page["items"]) <= 2
+ seen.extend(e["label"] for e in page["items"])
+ cursor = page["next_cursor"]
+ if not cursor:
+ break
+ assert seen == ["P0", "P1", "P2", "P3", "P4", "@acct"]
+
+ # server-side filters
+ people = client.get(
+ f"/api/cases/{cid}/catalog/entities", params={"type": "person"}
+ ).json()
+ assert {e["label"] for e in people["items"]} == {"P0", "P1", "P2", "P3", "P4"}
+ suggested = client.get(
+ f"/api/cases/{cid}/catalog/entities", params={"status": "suggested"}
+ ).json()
+ assert [e["label"] for e in suggested["items"]] == ["@acct"]
+
+ # summary counts without shipping the graph
+ summary = client.get(f"/api/cases/{cid}/catalog/summary").json()
+ assert summary["total"] == 6
+ assert summary["by_type"] == {"person": 5, "account": 1}
+ assert summary["by_status"] == {"confirmed": 5, "suggested": 1}
+
+
+def test_catalog_filters_by_folder(client):
+ cid = client.post("/api/cases", json={"name": "Foldered"}).json()["id"]
+ client.post(f"/api/cases/{cid}/folders", json={"name": "Alpha"})
+ client.post(
+ f"/api/cases/{cid}/entities",
+ json={"type": "person", "label": "filed", "attrs": {"folder": "Alpha"}},
+ )
+ client.post(f"/api/cases/{cid}/entities", json={"type": "person", "label": "loose"})
+
+ in_alpha = client.get(
+ f"/api/cases/{cid}/catalog/entities", params={"folder": "Alpha"}
+ ).json()
+ assert [e["label"] for e in in_alpha["items"]] == ["filed"]
+
+ unfiled = client.get(
+ f"/api/cases/{cid}/catalog/entities", params={"unfiled": "true"}
+ ).json()
+ assert [e["label"] for e in unfiled["items"]] == ["loose"]
+
+ assert client.get(f"/api/cases/{cid}/catalog/summary").json()["by_folder"] == {"Alpha": 1}
+
+
+def test_catalog_rejects_a_bad_cursor(client):
+ cid = client.post("/api/cases", json={"name": "BadCursor"}).json()["id"]
+ res = client.get(f"/api/cases/{cid}/catalog/entities", params={"cursor": "not-an-int"})
+ assert res.status_code == 400
+
+
+def test_catalog_clamps_the_page_size(client):
+ cid = client.post("/api/cases", json={"name": "Clamp"}).json()["id"]
+ for i in range(3):
+ client.post(f"/api/cases/{cid}/entities", json={"type": "person", "label": f"P{i}"})
+ # a limit below 1 is clamped up to 1 so a page always makes progress
+ page = client.get(f"/api/cases/{cid}/catalog/entities", params={"limit": 0}).json()
+ assert len(page["items"]) == 1 and page["next_cursor"] is not None
# ---------------------------------------------------------------------------
@@ -243,7 +362,7 @@ def test_delete_folder_unassigns_entities(client):
client.delete(f"/api/cases/{cid}/folders", params={"name": "Suspects"})
data = client.get(f"/api/cases/{cid}").json()
assert data["folders"] == []
- entity = next(e for e in data["entities"] if e["id"] == ent["id"])
+ entity = next(e for e in graph_read.entities(cid) if e["id"] == ent["id"])
assert "folder" not in entity["attrs"]
@@ -277,8 +396,7 @@ def test_delete_folder_cascades_subtree(client):
f"/api/cases/{cid}/folders", params={"name": "Sources"}
).json()
assert remaining == []
- data = client.get(f"/api/cases/{cid}").json()
- entity = next(e for e in data["entities"] if e["id"] == deep["id"])
+ entity = next(e for e in graph_read.entities(cid) if e["id"] == deep["id"])
assert "folder" not in entity["attrs"]
@@ -296,7 +414,7 @@ def test_delete_media_entity_removes_file(client):
files={"file": ("frame.png", io.BytesIO(png), "image/png")},
).json()["item"]
entity = next(
- e for e in client.get(f"/api/cases/{cid}").json()["entities"]
+ e for e in graph_read.entities(cid)
if e["type"] == "media"
)
@@ -304,7 +422,7 @@ def test_delete_media_entity_removes_file(client):
client.delete(f"/api/cases/{cid}/entities/{entity['id']}")
assert client.get(f"/files/{cid}/{item['path']}").status_code == 404
assert not any(
- e["type"] == "media" for e in client.get(f"/api/cases/{cid}").json()["entities"]
+ e["type"] == "media" for e in graph_read.entities(cid)
)
diff --git a/tests/test_config.py b/tests/test_config.py
index 94d56f9..d379889 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -54,6 +54,22 @@ def test_load_settings_missing_file_returns_defaults(monkeypatch, tmp_path):
assert loaded is not config.DEFAULT_SETTINGS
+def test_save_settings_is_atomic_when_replace_fails(monkeypatch, tmp_path):
+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))
+ config.save_settings({**config.DEFAULT_SETTINGS, "units": "metric"})
+ before = config.settings_path().read_bytes()
+
+ def fail_replace(_source, _target):
+ raise OSError("replace failed")
+
+ monkeypatch.setattr(config.os, "replace", fail_replace)
+ with pytest.raises(OSError, match="replace failed"):
+ config.save_settings({**config.DEFAULT_SETTINGS, "units": "imperial"})
+
+ assert config.settings_path().read_bytes() == before
+ assert list(tmp_path.glob(".settings.json.*.tmp")) == []
+
+
@pytest.mark.parametrize(
"content",
["[]", "{", '{"schema": 2, "proof": [], "post": []}', '{"schema": 1, "proof": [42], "post": []}'],
diff --git a/tests/test_drafts_api.py b/tests/test_drafts_api.py
index 243d683..7a86822 100644
--- a/tests/test_drafts_api.py
+++ b/tests/test_drafts_api.py
@@ -2,6 +2,8 @@
import pytest
+import graph_read
+
STATE = {
"description": "A formation of 13 helicopters was spotted heading East",
"coordsText": "10.303315, -66.874095",
@@ -52,7 +54,7 @@ def test_draft_filed_as_post_entity_and_updated_on_resave(client):
f"/api/cases/{cid}/drafts",
json={"name": saved["name"], "title": "Renamed draft", "state": STATE},
)
- posts = [e for e in client.get(f"/api/cases/{cid}").json()["entities"] if e["type"] == "post"]
+ posts = [e for e in graph_read.entities(cid) if e["type"] == "post"]
assert len(posts) == 1
assert posts[0]["label"] == "Renamed draft"
assert posts[0]["attrs"]["draft"] == "exports/first-title.json"
@@ -78,7 +80,7 @@ def test_delete_removes_file_and_entity(client):
assert r.json()["status"] == "deleted"
assert client.get(f"/api/cases/{cid}/drafts").json() == []
assert client.get(f"/api/cases/{cid}/drafts/to-delete").status_code == 404
- posts = [e for e in client.get(f"/api/cases/{cid}").json()["entities"] if e["type"] == "post"]
+ posts = [e for e in graph_read.entities(cid) if e["type"] == "post"]
assert posts == []
diff --git a/tests/test_ingest_api.py b/tests/test_ingest_api.py
index 7a0a259..acc5d06 100644
--- a/tests/test_ingest_api.py
+++ b/tests/test_ingest_api.py
@@ -9,6 +9,8 @@ of those walls.
import io
+import graph_read
+
from PIL import Image
from azimut.engine import tiles
@@ -229,7 +231,7 @@ def test_bookmark_files_a_link_entity_without_a_screenshot(client):
assert r.status_code == 200
body = r.json()
assert body["case_id"] == cid and body["title"] == "Leak site"
- ents = client.get(f"/api/cases/{cid}").json()["entities"]
+ ents = graph_read.entities(cid)
bm = [e for e in ents if e["type"] == "bookmark"]
assert len(bm) == 1
assert bm[0]["label"] == "Leak site"
diff --git a/tests/test_inspect_api.py b/tests/test_inspect_api.py
index 6640ba1..4577da3 100644
--- a/tests/test_inspect_api.py
+++ b/tests/test_inspect_api.py
@@ -5,12 +5,18 @@ needs ffmpeg and is skipped when it is unavailable in the environment.
"""
import io
+import subprocess
+import threading
+
+import graph_read
import time
import pytest
from PIL import Image
+from azimut.engine import inspect as inspect_engine
from azimut.engine import media as media_engine
+from azimut.workspace import Case
def _png_bytes(color=(120, 60, 30), size=(80, 60)) -> bytes:
@@ -36,6 +42,68 @@ def test_ops_registry_is_self_describing(client):
assert {a["id"] for a in ops["analyses"]} >= {"histogram", "exif", "ela"}
+def test_video_rotation_filterchain_covers_every_orientation_control():
+ assert inspect_engine._video_filterchain({}, -180) == "hflip,vflip"
+ assert inspect_engine._video_filterchain({}, -90) == "transpose=cclock"
+ assert inspect_engine._video_filterchain({}, 0) is None
+ assert inspect_engine._video_filterchain({}, 90) == "transpose=clock"
+ assert inspect_engine._video_filterchain({}, 180) == "hflip,vflip"
+ with pytest.raises(ValueError, match="video rotation"):
+ inspect_engine._video_filterchain({}, 45)
+
+
+def test_focus_scan_redirects_stderr_and_terminates_a_stalled_decoder(client, monkeypatch):
+ cid = client.post("/api/cases", json={"name": "Scan"}).json()["id"]
+ case = Case.open(cid)
+ video = case.subdir("media") / "clip.mp4"
+ video.write_bytes(b"placeholder")
+ stopped = threading.Event()
+ seen = {}
+
+ class BlockingStdout:
+ def read(self, _size):
+ stopped.wait(timeout=1)
+ return b""
+
+ def close(self):
+ pass
+
+ class FakeProcess:
+ returncode = None
+
+ def __init__(self, *args, stdout=None, stderr=None, **kwargs):
+ seen["stderr"] = stderr
+ self.stdout = BlockingStdout()
+
+ def poll(self):
+ return self.returncode
+
+ def terminate(self):
+ self.returncode = -15
+ stopped.set()
+
+ def kill(self):
+ self.returncode = -9
+ stopped.set()
+
+ def wait(self, timeout=None):
+ if self.returncode is None:
+ raise subprocess.TimeoutExpired("ffmpeg", timeout)
+ return self.returncode
+
+ monkeypatch.setattr(media_engine, "ffmpeg_available", lambda: True)
+ monkeypatch.setattr(inspect_engine, "probe", lambda *_args: {
+ "fps": 25, "duration": 1, "width": 16, "height": 16,
+ })
+ monkeypatch.setattr(inspect_engine, "_scan_timeout", lambda _duration: 0.01)
+ monkeypatch.setattr(inspect_engine.subprocess, "Popen", FakeProcess)
+
+ with pytest.raises(RuntimeError, match="timed out"):
+ inspect_engine.scan_focus(case, "media/clip.mp4")
+ assert stopped.is_set()
+ assert seen["stderr"] is not subprocess.PIPE
+
+
def test_probe_image(client):
cid = client.post("/api/cases", json={"name": "Probe"}).json()["id"]
item = _upload(client, cid, "shot.png", _png_bytes(size=(120, 90)))
@@ -61,7 +129,7 @@ def test_save_frames_files_adjusted_derivative(client):
# filed as a new media with inspect provenance and served
listing = client.get(f"/api/cases/{cid}/media").json()
assert len(listing) == 2
- entities = client.get(f"/api/cases/{cid}").json()["entities"]
+ entities = graph_read.entities(cid)
derived = next(e for e in entities if e["attrs"]["path"] == new_path)
assert derived["provenance"]["by"] == "inspect"
assert client.get(f"/files/{cid}/{new_path}").status_code == 200
@@ -102,6 +170,22 @@ def test_crop_op_reduces_dimensions(client):
assert probe["width"] == 100 and probe["height"] == 50
+def test_rotate_op_saves_image_in_selected_orientation(client):
+ cid = client.post("/api/cases", json={"name": "Rotate image"}).json()["id"]
+ item = _upload(client, cid, "landscape.png", _png_bytes(size=(120, 80)))
+ res = client.post(
+ f"/api/cases/{cid}/inspect/save-frames",
+ json={"items": [{
+ "path": item["path"],
+ "ops": [{"op": "rotate", "params": {"angle": -90}}],
+ }]},
+ ).json()["saved"][0]
+ probe = client.get(
+ f"/api/cases/{cid}/inspect/probe", params={"path": res["item"]["path"]}
+ ).json()
+ assert probe["width"] == 80 and probe["height"] == 120
+
+
def test_compose_combines_images(client):
cid = client.post("/api/cases", json={"name": "Collage"}).json()["id"]
a = _upload(client, cid, "a.png", _png_bytes(color=(10, 20, 30)))
@@ -199,7 +283,7 @@ def test_save_frames_files_selected_images_into_folder(client):
assert len(listing) == before + 1
new_path = saved[0]["item"]["path"]
entity = next(
- e for e in client.get(f"/api/cases/{cid}").json()["entities"]
+ e for e in graph_read.entities(cid)
if e["attrs"].get("path") == new_path
)
assert entity["attrs"]["folder"] == "Frames"
@@ -620,7 +704,7 @@ def test_enhance_video_files_new_video(client, tmp_path):
res = client.post(
f"/api/cases/{cid}/inspect/enhance-video",
json={"path": item["path"], "params": {"brightness": 1.3, "contrast": 1.2},
- "folder": "Enhanced"},
+ "rotation": 90, "folder": "Enhanced"},
).json()
assert res["duplicate"] is False
new_path = res["item"]["path"]
@@ -629,8 +713,11 @@ def test_enhance_video_files_new_video(client, tmp_path):
f"/api/cases/{cid}/inspect/probe", params={"path": new_path}
).json()
assert probe["kind"] == "video"
+ assert probe["width"] == 120 and probe["height"] == 160
+ saved = next(m for m in client.get(f"/api/cases/{cid}/media").json() if m["path"] == new_path)
+ assert saved["source"]["rotation"] == 90
entity = next(
- e for e in client.get(f"/api/cases/{cid}").json()["entities"]
+ e for e in graph_read.entities(cid)
if e["attrs"].get("path") == new_path
)
assert entity["attrs"]["folder"] == "Enhanced"
@@ -669,7 +756,7 @@ def test_session_save_list_load_delete_roundtrip(client):
assert len(listing) == 1 and listing[0]["title"] == "My session" and listing[0]["frames"] == 1
# an inspect-session entity is upserted so it reopens from the sidebar
- entities = client.get(f"/api/cases/{cid}").json()["entities"]
+ entities = graph_read.entities(cid)
ent = next(e for e in entities if e["type"] == "inspect-session")
assert ent["attrs"]["spec"] == "inspect/my-session.json"
@@ -679,12 +766,12 @@ def test_session_save_list_load_delete_roundtrip(client):
# re-saving under the same title updates in place (no duplicate entity)
client.post(f"/api/cases/{cid}/inspect/sessions", json={"title": "My session", "spec": spec})
- entities = client.get(f"/api/cases/{cid}").json()["entities"]
+ entities = graph_read.entities(cid)
assert sum(1 for e in entities if e["type"] == "inspect-session") == 1
client.delete(f"/api/cases/{cid}/inspect/sessions/my-session")
assert client.get(f"/api/cases/{cid}/inspect/sessions").json() == []
- entities = client.get(f"/api/cases/{cid}").json()["entities"]
+ entities = graph_read.entities(cid)
assert not any(e["type"] == "inspect-session" for e in entities)
@@ -734,7 +821,7 @@ def test_session_delete_via_sidebar_entity_removes_spec(client):
spec = {"source": {"path": item["path"], "kind": "image"}, "frames": [], "collage": {"nodes": []}}
client.post(f"/api/cases/{cid}/inspect/sessions", json={"title": "Doomed", "spec": spec})
- entities = client.get(f"/api/cases/{cid}").json()["entities"]
+ entities = graph_read.entities(cid)
ent = next(e for e in entities if e["type"] == "inspect-session")
client.delete(f"/api/cases/{cid}/entities/{ent['id']}")
@@ -763,7 +850,7 @@ def test_session_resave_by_name_overwrites_after_rename(client):
listing = client.get(f"/api/cases/{cid}/inspect/sessions").json()
assert len(listing) == 1
assert listing[0]["name"] == "original" and listing[0]["title"] == "Renamed"
- entities = client.get(f"/api/cases/{cid}").json()["entities"]
+ entities = graph_read.entities(cid)
assert sum(1 for e in entities if e["type"] == "inspect-session") == 1
@@ -788,6 +875,15 @@ def test_enhance_video_rejects_neutral_params(client, tmp_path):
assert res.status_code == 422
+def test_enhance_video_rejects_non_right_angle_rotation(client):
+ cid = client.post("/api/cases", json={"name": "Bad rotation"}).json()["id"]
+ res = client.post(
+ f"/api/cases/{cid}/inspect/enhance-video",
+ json={"path": "media/clip.mp4", "params": {}, "rotation": 45},
+ )
+ assert res.status_code == 422
+
+
@pytest.mark.skipif(not media_engine.ffmpeg_available(), reason="ffmpeg not installed")
def test_frame_capture_from_video(client, tmp_path):
import subprocess
diff --git a/tests/test_links_api.py b/tests/test_links_api.py
index 25c7f3c..e950750 100644
--- a/tests/test_links_api.py
+++ b/tests/test_links_api.py
@@ -12,6 +12,9 @@ import io
from PIL import Image
from azimut.engine import links as link_engine
+from azimut.workspace import Case
+
+import graph_read
def _png_bytes(color=(200, 30, 30), size=(64, 48)) -> bytes:
@@ -31,21 +34,21 @@ def _upload(client, cid, name, data=None):
).json()
-def _case(client, cid):
- return client.get(f"/api/cases/{cid}").json()
-
-
def _entity(client, cid, **attrs):
- """The entity whose attrs match, e.g. _entity(client, cid, path='media/a.png')."""
- for e in _case(client, cid)["entities"]:
- if all(e["attrs"].get(k) == v for k, v in attrs.items()):
- return e
- return None
+ """The entity whose attrs match, e.g. _entity(client, cid, path='media/a.png').
+
+ The case-open response no longer ships the graph (Step 5), so tests read it in
+ process — see tests/graph_read.py.
+ """
+ return graph_read.entity(cid, **attrs)
def _links(client, cid, type_=None):
- links = _case(client, cid)["links"]
- return [lk for lk in links if type_ is None or lk["type"] == type_]
+ return graph_read.links(cid, type_)
+
+
+def _add_link(cid, from_id, to_id, type_):
+ return Case.open(cid).add_link(from_id, to_id, type_, by="user")
def _new_case(client, name):
@@ -253,9 +256,9 @@ def test_missing_sources_are_tombstoned_in_one_case_update():
self.read_count = 0
self.updates = []
- def read(self):
+ def get_entity(self, entity_id):
self.read_count += 1
- return {"entities": [{"id": "post", "attrs": {}}]}
+ return {"id": entity_id, "attrs": {}}
def update_entity(self, entity_id, changes):
self.updates.append((entity_id, changes))
@@ -373,11 +376,7 @@ def test_cascade_is_transitive_through_depends_on(client):
f"/api/cases/{cid}/entities",
json={"type": "inspect-session", "label": "S2", "attrs": {"spec": "inspect/s2.json"}},
).json()
- made = client.post(
- f"/api/cases/{cid}/links",
- json={"from_id": s2["id"], "to_id": s1["id"], "type": "depends-on"},
- )
- assert made.status_code == 200, made.text
+ _add_link(cid, s2["id"], s1["id"], "depends-on")
client.delete(f"/api/cases/{cid}/entities/{_entity(client, cid, path=a)['id']}")
@@ -392,15 +391,12 @@ def test_a_session_over_a_frame_survives_the_frames_video_going(client):
cid = _new_case(client, "Frame session")
video = _upload(client, cid, "v.png", _png_bytes((9, 9, 9)))["item"]["path"]
frame = _upload(client, cid, "f.png", _png_bytes((8, 8, 8)))["item"]["path"]
- made = client.post(
- f"/api/cases/{cid}/links",
- json={
- "from_id": _entity(client, cid, path=frame)["id"],
- "to_id": _entity(client, cid, path=video)["id"],
- "type": "derived-from",
- },
+ _add_link(
+ cid,
+ _entity(client, cid, path=frame)["id"],
+ _entity(client, cid, path=video)["id"],
+ "derived-from",
)
- assert made.status_code == 200, made.text
_save_session(client, cid, "On the video", video, name="onvideo")
_save_session(client, cid, "On the frame", frame, name="onframe")
@@ -464,7 +460,7 @@ def test_the_satellite_delete_honours_the_graph(client):
def test_a_tool_delete_still_drops_an_unfiled_artifact(client):
# An artifact with no entity has no graph to honour, but its file must go.
cid = _new_case(client, "Orphan")
- case = _case(client, cid)
+ case = client.get(f"/api/cases/{cid}").json()
client.post(f"/api/cases/{cid}/proofs", json={"title": "P", "spec": {"panels": []}, "name": "p"})
proof = _entity(client, cid, spec="proofs/p.json")
client.delete(f"/api/cases/{cid}/entities/{proof['id']}") # entity + files gone
@@ -506,3 +502,77 @@ def test_dependents_endpoint_is_empty_for_a_lone_entity(client):
def test_dependents_endpoint_404s_on_an_unknown_entity(client):
cid = _new_case(client, "Ghost")
assert client.get(f"/api/cases/{cid}/entities/e_nope/dependents").status_code == 404
+
+
+# ── the derivation chain the Details panel reads ───────────────────────────
+
+
+def test_chain_endpoint_reads_sources_and_dependents(client):
+ cid = _new_case(client, "Chain")
+ a = _upload(client, cid, "a.png")["item"]["path"]
+ _save_proof(client, cid, "P", [a], name="p")
+
+ media = _entity(client, cid, path=a)
+ proof = _entity(client, cid, spec="proofs/p.json")
+
+ proof_chain = client.get(f"/api/cases/{cid}/entities/{proof['id']}/chain").json()
+ assert proof_chain["entity"]["id"] == proof["id"]
+ assert len(proof_chain["sources"]) == 1
+ src = proof_chain["sources"][0]
+ assert src["entity"]["id"] == media["id"] and src["type"] == "derived-from"
+ assert proof_chain["dependents"] == [] and proof_chain["empty"] is False
+
+ # the mirror: the media sees the proof among its dependents
+ media_chain = client.get(f"/api/cases/{cid}/entities/{media['id']}/chain").json()
+ assert [d["entity"]["id"] for d in media_chain["dependents"]] == [proof["id"]]
+ assert media_chain["sources"] == []
+
+
+def test_chain_endpoint_includes_lost_sources_and_404s(client):
+ cid = _new_case(client, "Chain lost")
+ a = _upload(client, cid, "a.png")["item"]["path"]
+ client.delete(f"/api/cases/{cid}/media?path={a}")
+ _save_proof(client, cid, "P", [a], name="p") # source gone → tombstone, no edge
+
+ proof = _entity(client, cid, spec="proofs/p.json")
+ chain = client.get(f"/api/cases/{cid}/entities/{proof['id']}/chain").json()
+ assert [t["path"] for t in chain["lost"]] == [a]
+ assert chain["empty"] is False
+
+ assert client.get(f"/api/cases/{cid}/entities/e_nope/chain").status_code == 404
+
+
+def test_chain_endpoint_is_empty_for_a_lone_entity(client):
+ cid = _new_case(client, "Chain lone")
+ a = _upload(client, cid, "a.png")["item"]["path"]
+ chain = client.get(
+ f"/api/cases/{cid}/entities/{_entity(client, cid, path=a)['id']}/chain"
+ ).json()
+ assert chain["sources"] == [] and chain["dependents"] == [] and chain["lost"] == []
+ assert chain["empty"] is True
+
+
+def test_lookup_endpoint_resolves_an_entity_by_attr(client):
+ cid = _new_case(client, "Lookup")
+ a = _upload(client, cid, "a.png")["item"]["path"]
+ ent = _entity(client, cid, path=a)
+
+ hit = client.get(f"/api/cases/{cid}/entities/lookup?attr=path&value={a}").json()
+ assert hit["entity"]["id"] == ent["id"]
+ miss = client.get(f"/api/cases/{cid}/entities/lookup?attr=path&value=media/none.jpg").json()
+ assert miss["entity"] is None
+
+
+def test_derivation_endpoint_returns_the_closure_and_404s(client):
+ cid = _new_case(client, "Derivation")
+ a = _upload(client, cid, "a.png", _png_bytes((1, 2, 3)))["item"]["path"]
+ b = _upload(client, cid, "b.png", _png_bytes((4, 5, 6)))["item"]["path"]
+ _save_proof(client, cid, "P", [a, b], name="p")
+ proof = _entity(client, cid, spec="proofs/p.json")
+
+ sub = client.get(f"/api/cases/{cid}/entities/{proof['id']}/derivation").json()
+ ids = {e["id"] for e in sub["entities"]}
+ assert ids == {proof["id"], _entity(client, cid, path=a)["id"], _entity(client, cid, path=b)["id"]}
+ assert len(sub["links"]) == 2 and all(lk["type"] == "derived-from" for lk in sub["links"])
+
+ assert client.get(f"/api/cases/{cid}/entities/e_nope/derivation").status_code == 404
diff --git a/tests/test_media_api.py b/tests/test_media_api.py
index 57f2204..e306b4c 100644
--- a/tests/test_media_api.py
+++ b/tests/test_media_api.py
@@ -1,6 +1,8 @@
"""Media Library: upload, dedupe, listing, file serving, deletion."""
import io
+
+import graph_read
import time
from PIL import Image
@@ -32,15 +34,63 @@ def test_upload_and_list(client):
assert [m["filename"] for m in listed] == ["frame one.png"]
# media entity was filed with provenance
- case = client.get(f"/api/cases/{cid}").json()
- assert case["entities"][0]["type"] == "media"
- assert case["entities"][0]["provenance"]["by"] == "media-library"
+ entities = graph_read.entities(cid)
+ assert entities[0]["type"] == "media"
+ assert entities[0]["provenance"]["by"] == "media-library"
# the file and its thumbnail are served
assert client.get(f"/files/{cid}/{item['path']}").status_code == 200
assert client.get(f"/files/{cid}/{item['thumbnail']}").status_code == 200
+def test_media_list_reports_thumb_state(client):
+ cid = client.post("/api/cases", json={"name": "Thumbs"}).json()["id"]
+ _upload(client, cid, "shot.png", _png_bytes())
+
+ item = client.get(f"/api/cases/{cid}/media").json()[0]
+ assert item["thumb_state"] == "ready" # image thumbnails render inline
+
+
+def test_video_thumbnail_is_queued_then_regenerated(client, monkeypatch):
+ from azimut.engine import thumbnails
+ from azimut.workspace import Case
+
+ # drive the queue by hand: disable the background worker, force a rendering
+ # that always succeeds so the test never depends on a real ffmpeg.
+ monkeypatch.setattr(thumbnails, "start_workers", False)
+ monkeypatch.setattr(
+ thumbnails, "_render", lambda mp, out, kind: (out.write_bytes(b"\xff\xd8jpg"), True)[1]
+ )
+ cid = client.post("/api/cases", json={"name": "Video"}).json()["id"]
+ client.post(
+ f"/api/cases/{cid}/media/upload",
+ files={"file": ("clip.mp4", io.BytesIO(b"bytes"), "video/mp4")},
+ )
+
+ item = client.get(f"/api/cases/{cid}/media").json()[0]
+ assert item["thumbnail"] is None and item["thumb_state"] == "queued"
+
+ thumbnails.drain(Case.open(cid)) # the worker's work, run synchronously
+ item = client.get(f"/api/cases/{cid}/media").json()[0]
+ assert item["thumb_state"] == "ready" and item["thumbnail"]
+
+
+def test_regenerate_queues_missing_thumbnails(client, monkeypatch):
+ from azimut.engine import thumbnails
+
+ monkeypatch.setattr(thumbnails, "start_workers", False)
+ cid = client.post("/api/cases", json={"name": "Regen"}).json()["id"]
+ # an image whose cached thumbnail is then removed (as budget eviction would)
+ item = _upload(client, cid, "shot.png", _png_bytes()).json()["item"]
+ from azimut.workspace import Case
+
+ Case.open(cid).resolve_inside(item["thumbnail"]).unlink()
+
+ res = client.post(f"/api/cases/{cid}/media/thumbnails/regenerate", json={}).json()
+ assert res["queued"] == 1 # the now-missing thumbnail is re-queued
+ assert client.get(f"/api/cases/{cid}/media").json()[0]["thumb_state"] == "queued"
+
+
def test_listing_carries_category_fields(client):
"""The Media Library groups items into facets (Images/Videos/Imports/…) purely
from ``kind`` and ``source`` — guard that both survive upload + listing."""
@@ -67,7 +117,7 @@ def test_delete_media_removes_entity(client):
item = _upload(client, cid, "x.png", _png_bytes()).json()["item"]
client.delete(f"/api/cases/{cid}/media", params={"path": item["path"]})
assert client.get(f"/api/cases/{cid}/media").json() == []
- assert client.get(f"/api/cases/{cid}").json()["entities"] == []
+ assert graph_read.entities(cid) == []
assert client.get(f"/files/{cid}/{item['path']}").status_code == 404
@@ -97,13 +147,13 @@ def test_update_media_notes_and_folder(client):
assert listing[0]["folder"] == "ukraine"
# folder + notes mirrored onto the media entity (so the sidebar sees them)
- entity = client.get(f"/api/cases/{cid}").json()["entities"][0]
+ entity = graph_read.entities(cid)[0]
assert entity["attrs"]["folder"] == "ukraine"
assert entity["attrs"]["notes"] == "found at coordinates"
# clearing the folder mirrors an empty value on the entity
client.patch(f"/api/cases/{cid}/media", json={"path": item["path"], "folder": ""})
- entity = client.get(f"/api/cases/{cid}").json()["entities"][0]
+ entity = graph_read.entities(cid)[0]
assert entity["attrs"]["folder"] == ""
@@ -119,7 +169,7 @@ def test_update_media_title(client):
assert updated["title"] == "Strike video — Kharkiv"
# the entity label mirrors the title so the case sidebar stays in sync
- entities = client.get(f"/api/cases/{cid}").json()["entities"]
+ entities = graph_read.entities(cid)
assert entities[0]["label"] == "Strike video — Kharkiv"
# clearing the title reverts to no custom title
@@ -130,7 +180,7 @@ def test_update_media_title(client):
# the entity label falls back to the filename — it must not freeze on the
# old title once that title is gone
- entities = client.get(f"/api/cases/{cid}").json()["entities"]
+ entities = graph_read.entities(cid)
assert entities[0]["label"] == item["path"].rsplit("/", 1)[-1]
@@ -288,7 +338,7 @@ def test_download_reports_multi_without_downloading(client, monkeypatch):
{"index": 3, "title": "p3", "thumbnail": None, "kind": "video"},
],
}
- assert case.read()["entities"] == []
+ assert case.list_entities() == []
assert client.get(f"/api/cases/{cid}/media").json() == []
@@ -473,7 +523,7 @@ def test_gallery_dl_fallback_multi_images(client, monkeypatch):
{"index": 2, "title": "b", "thumbnail": items[1][0], "kind": "image"},
],
}
- assert case.read()["entities"] == []
+ assert case.list_entities() == []
picked = media_engine.download_url(case, "https://x.com/u/status/2", index=2)
assert picked["multi"] is False
@@ -568,7 +618,7 @@ def test_download_merges_telegram_video_and_photos(client, monkeypatch):
(3, "image"),
(4, "image"),
]
- assert case.read()["entities"] == [] # detection only — nothing downloaded
+ assert case.list_entities() == [] # detection only — nothing downloaded
def test_download_picks_telegram_photo_from_mixed_post(client, monkeypatch):
@@ -671,7 +721,7 @@ def test_concurrent_downloads_dont_lose_entities(client, monkeypatch):
t.join()
assert errors == [], "\n\n".join(errors)
- assert len(case.read()["entities"]) == n
+ assert len(case.list_entities()) == n
assert len(client.get(f"/api/cases/{cid}/media").json()) == n
diff --git a/tests/test_migrations.py b/tests/test_migrations.py
index 3c40786..39763bf 100644
--- a/tests/test_migrations.py
+++ b/tests/test_migrations.py
@@ -7,6 +7,7 @@ migrations to prove the runners, and pin the "same schema doesn't rewrite" and
import json
import pytest
+from legacy_case import write_legacy_json_case
from azimut import config, workspace
from azimut.workspace import Case, CaseError
@@ -39,7 +40,10 @@ def test_open_newer_schema_is_refused(tmp_workspace):
def test_open_older_schema_migrates_and_backs_up(tmp_workspace, monkeypatch):
- case = Case.create("Legacy") # written at schema 1
+ case = Case.create("Legacy")
+ data = case.read() # stamp it back down to the first schema
+ data["azimut"]["schema"] = 1
+ case._write_json(data)
def to_v2(data):
data.setdefault("attrs", {})["migrated"] = True
@@ -60,6 +64,9 @@ def test_open_older_schema_migrates_and_backs_up(tmp_workspace, monkeypatch):
def test_migration_backup_is_not_overwritten(tmp_workspace, monkeypatch):
"""A second migration run keeps the first pre-migration copy."""
case = Case.create("Legacy")
+ data = case.read() # stamp it back down to the first schema
+ data["azimut"]["schema"] = 1
+ case._write_json(data)
monkeypatch.setattr(workspace, "CASE_SCHEMA", 2)
monkeypatch.setattr(workspace, "CASE_MIGRATIONS", {1: lambda d: d})
@@ -76,6 +83,105 @@ def test_migration_backup_is_not_overwritten(tmp_workspace, monkeypatch):
assert backup.read_text() == first
+def test_note_bodies_migrate_out_of_case_json(tmp_workspace):
+ case = write_legacy_json_case(
+ "Legacy notes",
+ schema=1,
+ entities=[{
+ "id": "e_note", "type": "note", "label": "Lead",
+ "attrs": {"folder": "Research", "content": "# Saved lead"},
+ "provenance": {"by": "user", "at": "2026-01-01T00:00:00Z", "status": "confirmed"},
+ }],
+ )
+
+ migrated = Case.open(case.id).snapshot()
+
+ note = migrated["entities"][0]
+ assert note["attrs"] == {"folder": "Research", "path": "notes/e_note.md"}
+ assert (case.path / "notes/e_note.md").read_text(encoding="utf-8") == "# Saved lead"
+ assert (case.path / "case.pre-migrate-v1.json").exists()
+
+
+# -- storage activation: legacy json -> sqlite on open --------------------
+
+
+def test_open_activates_sqlite_and_preserves_the_graph(tmp_workspace):
+ """A legacy json case is converted to the sqlite storage format on open,
+ keeping its graph and leaving a recoverable backup."""
+ prov = {"by": "user", "at": "2026-01-01T00:00:00Z", "status": "confirmed"}
+ legacy = write_legacy_json_case(
+ "To migrate",
+ entities=[
+ {"id": "e_a", "type": "person", "label": "Ada", "attrs": {"handle": "@ada"}, "provenance": prov},
+ {"id": "e_b", "type": "account", "label": "acct", "attrs": {}, "provenance": prov},
+ ],
+ links=[{"id": "l_1", "from": "e_a", "to": "e_b", "type": "owns", "provenance": prov}],
+ folders=["Sources", "Sources/Telegram"],
+ )
+
+ opened = Case.open(legacy.id)
+
+ manifest = opened.read()
+ assert manifest["azimut"] == {"schema": workspace.CASE_SCHEMA, "storage": "sqlite"}
+ assert "entities" not in manifest # case.json is a manifest now
+ assert (opened.path / "case.db").exists()
+ assert (opened.path / "case.pre-migrate-v2.json").exists()
+
+ snap = opened.snapshot()
+ assert {e["id"] for e in snap["entities"]} == {"e_a", "e_b"}
+ assert len(snap["links"]) == 1
+ assert "Sources/Telegram" in snap["folders"]
+ # and the migrated case now takes the fast path on further edits
+ opened.add_entity("email", "[email protected]", by="user")
+ assert len(Case.open(legacy.id).list_entities()) == 3
+
+
+def test_switcher_timestamp_tracks_the_db_not_the_stale_manifest(tmp_workspace):
+ """Graph edits bump the db, not the small manifest, so the case switcher must
+ read last-activity from the db for a sqlite case."""
+ case = Case.create("Active") # sqlite
+ case.add_entity("person", "Ada", by="user")
+ db_time = case._sqlite.updated_at()
+ assert case.snapshot()["updated_at"] == db_time
+
+ # deliberately stale the manifest; the switcher must still show real activity
+ manifest = case.read()
+ manifest["updated_at"] = "2000-01-01T00:00:00Z"
+ case._write_json(manifest)
+ row = next(c for c in Case.list_all() if c["id"] == case.id)
+ assert row["updated_at"] == db_time != "2000-01-01T00:00:00Z"
+
+
+def test_failed_activation_leaves_the_json_case_usable(tmp_workspace, monkeypatch):
+ prov = {"by": "user", "at": "2026-01-01T00:00:00Z", "status": "confirmed"}
+ legacy = write_legacy_json_case(
+ "Fragile",
+ entities=[{"id": "e_a", "type": "person", "label": "Ada", "attrs": {}, "provenance": prov}],
+ )
+
+ def boom(conn, data, report):
+ raise RuntimeError("conversion blew up")
+
+ from azimut import sqlite_backend
+
+ real_import = sqlite_backend._import_graph
+ monkeypatch.setattr(sqlite_backend, "_import_graph", boom)
+ with pytest.raises(RuntimeError):
+ Case.open(legacy.id)
+
+ # the manifest never flipped, no half-built db is left, the file still reads
+ reopened_json = json.loads(legacy.json_path.read_text(encoding="utf-8"))
+ assert reopened_json["azimut"]["storage"] == "json"
+ assert reopened_json["entities"][0]["label"] == "Ada"
+ assert not (legacy.path / "case.db").exists()
+
+ # with the fault cleared (restore just the converter, not the whole
+ # monkeypatch — undo() would also revert tmp_workspace's AZIMUT_HOME), a
+ # retry migrates it and the graph survives
+ monkeypatch.setattr(sqlite_backend, "_import_graph", real_import)
+ assert [e["label"] for e in Case.open(legacy.id).list_entities()] == ["Ada"]
+
+
# -- settings.json --------------------------------------------------------
diff --git a/tests/test_proofs_api.py b/tests/test_proofs_api.py
index 629ccb5..0033ca0 100644
--- a/tests/test_proofs_api.py
+++ b/tests/test_proofs_api.py
@@ -1,6 +1,8 @@
"""Proofs: save spec+PNG, list, reload, entity upsert, delete."""
import base64
+
+import graph_read
import io
from PIL import Image
@@ -67,7 +69,7 @@ def test_save_load_roundtrip(client):
f"/api/cases/{cid}/proofs",
json={"name": saved["name"], "title": "Renamed proof", "spec": SPEC},
)
- entities = [e for e in client.get(f"/api/cases/{cid}").json()["entities"] if e["type"] == "proof"]
+ entities = [e for e in graph_read.entities(cid) if e["type"] == "proof"]
assert len(entities) == 1
assert entities[0]["label"] == "Renamed proof"
@@ -80,7 +82,7 @@ def test_resave_with_png_adds_the_path_to_the_entity(client):
f"/api/cases/{cid}/proofs", json={"title": "Draft proof", "spec": SPEC}
).json()
entity = next(
- e for e in client.get(f"/api/cases/{cid}").json()["entities"] if e["type"] == "proof"
+ e for e in graph_read.entities(cid) if e["type"] == "proof"
)
assert "path" not in entity["attrs"]
@@ -91,7 +93,7 @@ def test_resave_with_png_adds_the_path_to_the_entity(client):
json={"name": saved["name"], "title": "Draft proof", "spec": SPEC, "png_base64": _png_b64()},
)
entity = next(
- e for e in client.get(f"/api/cases/{cid}").json()["entities"] if e["type"] == "proof"
+ e for e in graph_read.entities(cid) if e["type"] == "proof"
)
assert entity["attrs"]["path"] == f"proofs/{saved['name']}.png"
@@ -114,4 +116,4 @@ def test_delete_proof(client):
client.delete(f"/api/cases/{cid}/proofs/{saved['name']}")
assert client.get(f"/api/cases/{cid}/proofs").json() == []
assert client.get(f"/api/cases/{cid}/proofs/{saved['name']}").status_code == 404
- assert [e for e in client.get(f"/api/cases/{cid}").json()["entities"] if e["type"] == "proof"] == []
+ assert [e for e in graph_read.entities(cid) if e["type"] == "proof"] == []
diff --git a/tests/test_relaunch.py b/tests/test_relaunch.py
new file mode 100644
index 0000000..1f7362b
--- /dev/null
+++ b/tests/test_relaunch.py
@@ -0,0 +1,75 @@
+from __future__ import annotations
+
+import importlib.util
+import os
+import threading
+from pathlib import Path
+
+import pytest
+
+
+SCRIPT = Path(__file__).parents[1] / "scripts" / "relaunch.py"
+SPEC = importlib.util.spec_from_file_location("azimut_relaunch", SCRIPT)
+assert SPEC is not None and SPEC.loader is not None
+relaunch = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(relaunch)
+
+
+def test_control_socket_stops_only_the_matching_launcher(tmp_path: Path):
+ state_path = tmp_path / "state.json"
+ control = relaunch._ControlServer(state_path)
+ control.start()
+
+ def close_after_request() -> None:
+ assert control.stop_requested.wait(timeout=2)
+ control.close()
+
+ closer = threading.Thread(target=close_after_request)
+ closer.start()
+ assert relaunch._stop_previous(state_path, timeout=2) is True
+ closer.join(timeout=2)
+
+ assert not closer.is_alive()
+ assert not state_path.exists()
+
+
+def test_stale_state_is_removed_without_stopping_a_process(tmp_path: Path):
+ state_path = tmp_path / "state.json"
+ state_path.write_text('{"port": 1, "token": "' + "a" * 64 + '"}', encoding="utf-8")
+
+ assert relaunch._stop_previous(state_path, timeout=0.1) is False
+ assert not state_path.exists()
+
+
+ ("platform", "relative"),
+ [("posix", Path(".venv/bin/python")), ("nt", Path(".venv/Scripts/python.exe"))],
+)
+def test_virtualenv_python_is_platform_specific(
+ tmp_path: Path, platform: str, relative: Path
+):
+ python = tmp_path / relative
+ python.parent.mkdir(parents=True)
+ python.touch()
+
+ assert relaunch._venv_python(tmp_path, platform) == python
+
+
+def test_missing_virtualenv_has_an_actionable_error(tmp_path: Path):
+ with pytest.raises(RuntimeError, match="create .venv first"):
+ relaunch._venv_python(tmp_path, "posix")
+
+
+def test_windows_npm_wrapper_uses_cmd(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(relaunch.shutil, "which", lambda _name: r"C:\Tools\npm.cmd")
+ monkeypatch.setenv("COMSPEC", r"C:\Windows\System32\cmd.exe")
+
+ assert relaunch._npm_build_command("nt") == [
+ os.environ["COMSPEC"],
+ "/d",
+ "/s",
+ "/c",
+ r"C:\Tools\npm.cmd",
+ "run",
+ "build",
+ ]
diff --git a/tests/test_release_gate.py b/tests/test_release_gate.py
new file mode 100644
index 0000000..87c0252
--- /dev/null
+++ b/tests/test_release_gate.py
@@ -0,0 +1,202 @@
+"""Release gate for the storage migration (docs/STORAGE_AND_PERFORMANCE.md
+step 7).
+
+The doc's release gate is part manual (record the reference-machine numbers, dry-
+run real disposable cases) and part automatable. This file pins the automatable
+checks so they run on the CI matrix (three OSes + the 3.11 floor) on every change:
+
+- a legacy json case migrates and every current workflow still answers;
+- a *closed* case folder copy opens identically — the "case bundle / copy is
+ complete" guarantee (rollback journal, no WAL to checkpoint);
+- a large migrated case opens through bounded queries, never shipping its graph;
+- the frozen-binary packaging constraints hold (static bundled, dev tooling out,
+ no new runtime dependency, case.db under the workspace root).
+"""
+
+from __future__ import annotations
+
+import shutil
+import tomllib
+from pathlib import Path
+
+from bigcase import build_big_case
+from legacy_case import write_legacy_json_case
+
+from azimut import workspace
+from azimut.engine import links as link_engine
+from azimut.engine import media as media_engine
+from azimut.engine import thumbnails
+from azimut.workspace import Case
+
+_PROV = {"by": "user", "at": "2026-01-01T00:00:00Z", "status": "confirmed"}
+
+
+# -- functional + migration -------------------------------------------------
+
+
+def test_legacy_json_case_migrates_and_every_workflow_answers(tmp_workspace):
+ """A legacy json case (unicode, folders, a derivation chain, a media sidecar)
+ migrates on open and every read path — snapshot, bounded catalog, neighbour
+ chain, media listing, durable jobs — works on the result, with a recoverable
+ backup left behind."""
+ legacy = write_legacy_json_case(
+ "Réunion", # non-ASCII survives the round trip
+ entities=[
+ {"id": "e_p", "type": "person", "label": "Ada", "attrs": {"folder": "People"}, "provenance": _PROV},
+ {"id": "e_m", "type": "media", "label": "shot", "attrs": {"path": "media/shot.jpg", "sha256": "a" * 64, "kind": "image"}, "provenance": _PROV},
+ {"id": "e_pr", "type": "proof", "label": "Proof", "attrs": {"spec": "proofs/p.json"}, "provenance": _PROV},
+ ],
+ links=[{"id": "l1", "from": "e_pr", "to": "e_m", "type": "derived-from", "provenance": _PROV}],
+ folders=["People"],
+ )
+ # a real media file + sidecar so the media listing has something to read
+ (legacy.path / "media" / "shot.jpg").write_bytes(b"\xff\xd8\xff\xe0jpeg")
+ (legacy.path / "media" / ("shot.jpg" + media_engine.SIDECAR_SUFFIX)).write_text(
+ '{"filename": "shot.jpg", "kind": "image", "sha256": "%s", "size": 5,'
+ ' "added_at": "2026-01-01T00:00:00Z", "source": {}, "thumbnail": null}' % ("a" * 64),
+ encoding="utf-8",
+ )
+
+ case = Case.open(legacy.id) # migrates json -> sqlite
+
+ # storage flipped, graph preserved, backup recoverable
+ assert case.read()["azimut"] == {"schema": workspace.CASE_SCHEMA, "storage": "sqlite"}
+ assert (case.path / "case.pre-migrate-v2.json").exists()
+ assert {e["id"] for e in case.snapshot()["entities"]} == {"e_p", "e_m", "e_pr"}
+
+ # bounded reads
+ assert "entities" not in case.overview() and "links" not in case.overview()
+ assert case.catalog_summary()["total"] == 3
+ people = case.page_entities(types=["person"])
+ assert [e["id"] for e in people["items"]] == ["e_p"]
+ chain = link_engine.chain_of(case, "e_pr")
+ assert [s["entity"]["id"] for s in chain["sources"]] == ["e_m"]
+
+ # media + durable jobs both live on the migrated case
+ assert media_engine.list_media(case)[0]["filename"] == "shot.jpg"
+ case.enqueue_job("thumbnail", key="media/shot.jpg")
+ assert case.count_jobs() == {"queued": 1}
+
+
+def test_a_closed_case_folder_copy_opens_identically(tmp_workspace):
+ """Copying a closed case directory yields a complete, openable case — the
+ doc's "case bundle / manual copy is guaranteed when the case is closed". The
+ rollback journal (no WAL) means no checkpoint is owed, so a plain folder copy
+ carries the whole graph."""
+ src = Case.create("Bundle")
+ p = src.add_entity("person", "Ada", {"handle": "@ada"}, by="user")
+ m = src.add_entity("media", "shot", {"path": "media/x.jpg"}, by="user")
+ src.add_link(p["id"], m["id"], "depicts", by="user")
+ src.add_folder("People/Kyiv")
+ src.enqueue_job("thumbnail", key="media/x.jpg") # a live job travels too
+ original = src.snapshot()
+
+ dest = workspace.config.cases_dir() / "bundle-copy"
+ shutil.copytree(src.path, dest)
+ copy = Case.open("bundle-copy")
+
+ copied = copy.snapshot()
+ assert copied["entities"] == original["entities"]
+ assert copied["links"] == original["links"]
+ assert copied["folders"] == original["folders"]
+ assert copy.count_jobs() == {"queued": 1}
+
+
+# -- load: bounded loading on a large migrated case -------------------------
+
+
+def test_large_migrated_case_opens_through_bounded_queries(tmp_workspace):
+ case, summary = build_big_case(
+ name="Load", entities=600, links=800, media=150, notes=30, artifacts=40,
+ write_media_files=False,
+ )
+ opened = Case.open(summary.case_id) # migrate json -> sqlite
+
+ # case-open ships the manifest + folders, never the graph arrays
+ overview = opened.overview()
+ assert "entities" not in overview and "links" not in overview
+
+ # the catalog is read in bounded pages, not one materialised list
+ page = opened.page_entities(limit=100)
+ assert len(page["items"]) == 100 and page["next_cursor"] is not None
+ walked, cursor = 0, None
+ while True:
+ pg = opened.page_entities(limit=250, cursor=cursor)
+ walked += len(pg["items"])
+ cursor = pg["next_cursor"]
+ if cursor is None:
+ break
+ assert walked == summary.entities == opened.catalog_summary()["total"]
+
+
+# -- packaging: frozen-binary constraints -----------------------------------
+
+
+def _pyproject() -> dict:
+ root = Path(__file__).resolve().parent.parent
+ return tomllib.loads((root / "pyproject.toml").read_text(encoding="utf-8"))
+
+
+def test_wheel_bundles_the_frontend_and_leaves_dev_tooling_out():
+ cfg = _pyproject()
+ assert "src/azimut/static/**" in cfg["tool"]["hatch"]["build"]["artifacts"]
+ assert cfg["tool"]["hatch"]["build"]["targets"]["wheel"]["packages"] == ["src/azimut"]
+ # the synthetic fixture and the benchmark live outside the packaged tree, so
+ # hatchling never ships them (doc "dev-only tooling stays out of the artifact")
+ root = Path(__file__).resolve().parent.parent
+ assert (root / "tests" / "bigcase.py").exists()
+ assert not (root / "src" / "azimut" / "bigcase.py").exists()
+ assert (root / "bench").is_dir() and not (root / "src" / "azimut" / "bench").exists()
+
+
+def test_storage_and_jobs_add_no_new_runtime_dependency():
+ """The store, the durable queue and the thumbnail worker stay on the standard
+ library plus deps already declared — nothing that would need a new wheel on
+ the three release binaries."""
+ declared = " ".join(_pyproject()["project"]["dependencies"]).lower()
+ # sqlite3/threading/subprocess are stdlib; Pillow (declared) does the imaging.
+ assert "pillow" in declared
+ src = Path(__file__).resolve().parent.parent / "src" / "azimut"
+ text = (src / "sqlite_backend.py").read_text() + (src / "engine" / "thumbnails.py").read_text()
+ assert "import sqlite3" in (src / "sqlite_backend.py").read_text()
+ for banned in ("import numpy", "import pandas", "import redis", "import celery"):
+ assert banned not in text # no heavyweight queue/DB dependency slipped in
+
+
+def test_case_db_lives_under_the_workspace_root(tmp_workspace):
+ case = Case.create("Where")
+ assert case.path.is_relative_to(workspace.config.workspace_root())
+ assert (case.path / "case.db").exists() # beside the case, never beside the binary
+ # thumbnails cache under the case's media dir, also inside the workspace
+ assert thumbnails._thumb_dir(case).is_relative_to(workspace.config.workspace_root())
+
+
+def test_release_tooling_is_bounded_and_built_from_the_lock():
+ cfg = _pyproject()
+ assert cfg["build-system"]["requires"] == ["hatchling>=1.27,<2"]
+ release = cfg["dependency-groups"]["release"]
+ assert any(dep.startswith("build>=") and "<2" in dep for dep in release)
+ assert any(dep.startswith("hatchling>=") and "<2" in dep for dep in release)
+ assert any(dep.startswith("pyinstaller>=") and "<7" in dep for dep in release)
+
+ root = Path(__file__).resolve().parent.parent
+ workflow = (root / ".github" / "workflows" / "release.yml").read_text(encoding="utf-8")
+ assert "pipx run build" not in workflow
+ assert "uv pip install . pyinstaller" not in workflow
+ assert "python -m build --no-isolation" in workflow
+ assert "--group release" in workflow
+ assert workflow.count('node-version: "20.20.2"') == 2
+ assert "--no-build-isolation" in workflow
+ assert "--no-editable" in workflow
+ assert "uv run python" not in workflow
+
+
+def test_release_binary_runs_the_application_smoke_test():
+ root = Path(__file__).resolve().parent.parent
+ workflow = (root / ".github" / "workflows" / "release.yml").read_text(encoding="utf-8")
+ smoke = (root / "scripts" / "smoke_binary.py").read_text(encoding="utf-8")
+
+ assert "scripts/smoke_binary.py" in workflow
+ assert "/api/health" in smoke
+ assert "/api/settings/ffmpeg" in smoke
+ assert 'ffmpeg.get("source") != "bundled"' in smoke
diff --git a/tests/test_repository.py b/tests/test_repository.py
new file mode 100644
index 0000000..ca6c37e
--- /dev/null
+++ b/tests/test_repository.py
@@ -0,0 +1,336 @@
+"""The CaseRepository graph contract (Step 1 of docs/STORAGE_AND_PERFORMANCE.md).
+
+These exercise the storage boundary directly, not through the HTTP API, so they
+pin the behaviour the SQLite backend must reproduce. The ``repo`` fixture is a
+fresh `Case`, which delegates the graph to `SqliteCase` — the only live backend
+now that the in-file JSON path is gone (legacy json cases convert to sqlite on
+open; see tests/test_migrations.py).
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from azimut.workspace import Case, CaseError
+
+
+def repo(tmp_workspace):
+ """A fresh case through `Case`, which delegates the graph to `SqliteCase` —
+ the only backend now that the live in-file JSON path is gone (legacy json
+ cases are converted to sqlite on open, covered in tests/test_migrations.py)."""
+ return Case.create("Contract")
+
+
+def test_add_get_and_list_entities(repo):
+ e = repo.add_entity("person", "Ada", {"handle": "@ada"}, by="user")
+ assert repo.get_entity(e["id"]) == e
+ assert e in repo.list_entities()
+ assert repo.get_entity("nope") is None
+
+
+def test_reads_do_not_expose_stored_state_for_mutation(repo):
+ repo.add_entity("person", "Ada", by="user")
+ repo.list_entities().clear() # mutating a read must not touch the store
+ assert len(repo.list_entities()) == 1
+
+
+def test_update_entity_patches_label_attrs_and_status(repo):
+ e = repo.add_entity("place", "Kyiv", {"lat": 50.4}, by="user")
+ updated = repo.update_entity(e["id"], {"label": "Kyiv Oblast", "attrs": {"lon": 30.5}})
+ assert updated["label"] == "Kyiv Oblast"
+ # attrs merge rather than replace
+ assert updated["attrs"] == {"lat": 50.4, "lon": 30.5}
+
+ repo.update_entity(e["id"], {"status": "suggested"})
+ assert repo.get_entity(e["id"])["provenance"]["status"] == "suggested"
+
+
+def test_remove_entity_drops_its_incident_links(repo):
+ a = repo.add_entity("person", "A", by="user")
+ b = repo.add_entity("account", "B", by="user")
+ repo.add_link(a["id"], b["id"], "owns", by="user")
+
+ repo.remove_entity(b["id"])
+ assert repo.get_entity(b["id"]) is None
+ assert repo.list_links() == [] # the dangling edge went with it
+
+ with pytest.raises(CaseError):
+ repo.remove_entity("missing")
+
+
+def test_add_link_validates_endpoints_and_dedupes(repo):
+ a = repo.add_entity("person", "A", by="user")
+ b = repo.add_entity("account", "B", by="user")
+
+ with pytest.raises(CaseError):
+ repo.add_link(a["id"], "ghost", "owns", by="user")
+
+ first = repo.add_link(a["id"], b["id"], "owns", by="user", unique=True)
+ again = repo.add_link(a["id"], b["id"], "owns", by="user", unique=True)
+ assert first["id"] == again["id"] # unique returns the existing edge
+ assert len(repo.list_links()) == 1
+
+
+def test_sync_links_restates_a_source_set(repo):
+ src = repo.add_entity("proof", "P", {"spec": "proofs/p.json"}, by="user")
+ m1 = repo.add_entity("media", "m1", by="user")
+ m2 = repo.add_entity("media", "m2", by="user")
+ m3 = repo.add_entity("media", "m3", by="user")
+
+ repo.sync_links(src["id"], "derived-from", [m1["id"], m2["id"]], by="user")
+ assert {lk["to"] for lk in repo.list_links()} == {m1["id"], m2["id"]}
+
+ # restating drops m1, keeps m2 (same edge id), adds m3
+ kept = next(lk for lk in repo.list_links() if lk["to"] == m2["id"])
+ repo.sync_links(src["id"], "derived-from", [m2["id"], m3["id"]], by="user")
+ tos = {lk["to"] for lk in repo.list_links()}
+ assert tos == {m2["id"], m3["id"]}
+ still = next(lk for lk in repo.list_links() if lk["to"] == m2["id"])
+ assert still["id"] == kept["id"]
+
+
+def test_remove_link(repo):
+ a = repo.add_entity("person", "A", by="user")
+ b = repo.add_entity("account", "B", by="user")
+ lk = repo.add_link(a["id"], b["id"], "owns", by="user")
+ repo.remove_link(lk["id"])
+ assert repo.list_links() == []
+ with pytest.raises(CaseError):
+ repo.remove_link("missing")
+
+
+def test_links_of_returns_only_incident_edges(repo):
+ a = repo.add_entity("person", "A", by="user")
+ b = repo.add_entity("account", "B", by="user")
+ c = repo.add_entity("media", "C", by="user")
+ ab = repo.add_link(a["id"], b["id"], "owns", by="user")
+ ca = repo.add_link(c["id"], a["id"], "derived-from", by="user")
+ repo.add_link(b["id"], c["id"], "mentions", by="user") # touches neither a's pair directly
+
+ incident = {lk["id"] for lk in repo.links_of(a["id"])}
+ assert incident == {ab["id"], ca["id"]} # both endpoints, nothing else
+ assert repo.links_of("ghost") == []
+
+
+def test_derivation_subgraph_walks_the_derived_from_closure(repo):
+ from azimut.engine import links as link_engine
+
+ proof = repo.add_entity("proof", "P", {"spec": "proofs/p.json"}, by="user")
+ frame = repo.add_entity("media", "frame", {"path": "media/f.jpg"}, by="user")
+ video = repo.add_entity("media", "clip", {"path": "media/c.mp4"}, by="user")
+ other = repo.add_entity("media", "unrelated", {"path": "media/o.jpg"}, by="user")
+ repo.add_link(proof["id"], frame["id"], "derived-from", by="user")
+ repo.add_link(frame["id"], video["id"], "derived-from", by="user")
+ repo.add_link(proof["id"], other["id"], "mentions", by="user") # not a derivation
+
+ sub = link_engine.derivation_subgraph(repo, proof["id"])
+ ids = {e["id"] for e in sub["entities"]}
+ assert ids == {proof["id"], frame["id"], video["id"]} # closure, not the mentions edge
+ assert other["id"] not in ids
+ assert {(lk["from"], lk["to"]) for lk in sub["links"]} == {
+ (proof["id"], frame["id"]),
+ (frame["id"], video["id"]),
+ }
+ assert link_engine.derivation_subgraph(repo, "ghost") is None
+
+
+def test_find_entity_by_attr(repo):
+ repo.add_entity("media", "photo", {"path": "media/x.jpg"}, by="user")
+ found = repo.find_entity(attr="path", value="media/x.jpg")
+ assert found is not None and found["label"] == "photo"
+ assert repo.find_entity(attr="path", value="media/none.jpg") is None
+
+
+def test_folders_materialize_ancestors_and_removal_unfiles(repo):
+ repo.add_folder("Sources/Telegram")
+ assert set(repo.list_folders()) >= {"Sources", "Sources/Telegram"}
+
+ e = repo.add_entity("media", "m", {"folder": "Sources/Telegram"}, by="user")
+ repo.remove_folder("Sources")
+ assert repo.list_folders() == []
+ # the entity survives but is unfiled
+ assert "folder" not in repo.get_entity(e["id"])["attrs"]
+
+
+def test_page_entities_walks_the_whole_catalog_in_order(repo):
+ ids = [repo.add_entity("person", f"P{i}", by="user")["id"] for i in range(5)]
+
+ seen: list[str] = []
+ cursor = None
+ while True:
+ page = repo.page_entities(limit=2, cursor=cursor)
+ assert len(page["items"]) <= 2 # the page size is honoured
+ seen.extend(e["id"] for e in page["items"])
+ cursor = page["next_cursor"]
+ if cursor is None:
+ break
+
+ assert seen == ids # every entity once, in insertion order, no duplicates
+
+
+def test_page_entities_filters_by_type_status_and_query(repo):
+ p = repo.add_entity("person", "Ada Lovelace", by="user")
+ repo.add_entity("account", "@ada", by="user")
+ sugg = repo.add_entity("person", "Alan Turing", by="user", status="suggested")
+
+ people = repo.page_entities(limit=50, types=["person"])
+ assert {e["id"] for e in people["items"]} == {p["id"], sugg["id"]}
+
+ suggested = repo.page_entities(limit=50, status="suggested")
+ assert [e["id"] for e in suggested["items"]] == [sugg["id"]]
+
+ hits = repo.page_entities(limit=50, query="lovelace") # case-insensitive label search
+ assert [e["id"] for e in hits["items"]] == [p["id"]]
+
+
+def test_page_entities_cursor_is_stable_when_an_import_appends(repo):
+ first = [repo.add_entity("person", f"P{i}", by="user")["id"] for i in range(3)]
+ page1 = repo.page_entities(limit=2)
+ assert [e["id"] for e in page1["items"]] == first[:2]
+
+ # a background import lands a new entity between the two page reads
+ late = repo.add_entity("person", "Late", by="user")["id"]
+
+ page2 = repo.page_entities(limit=2, cursor=page1["next_cursor"])
+ rest = [e["id"] for e in page2["items"]]
+ # the page already seen is not reshuffled, and the late row is not lost
+ assert first[2] in rest
+ assert first[0] not in rest and first[1] not in rest
+
+ seen = [e["id"] for e in page1["items"]] + rest
+ cursor = page2["next_cursor"]
+ while cursor is not None:
+ page = repo.page_entities(limit=2, cursor=cursor)
+ seen.extend(e["id"] for e in page["items"])
+ cursor = page["next_cursor"]
+ assert sorted(seen) == sorted(first + [late]) and len(seen) == len(set(seen))
+
+
+def test_catalog_summary_counts_by_type_and_status(repo):
+ repo.add_entity("person", "A", by="user")
+ repo.add_entity("person", "B", by="user", status="suggested")
+ repo.add_entity("account", "C", by="user")
+
+ summary = repo.catalog_summary()
+ assert summary["total"] == 3
+ assert summary["by_type"] == {"person": 2, "account": 1}
+ assert summary["by_status"] == {"confirmed": 2, "suggested": 1}
+
+
+def test_page_entities_filters_by_folder_and_unfiled(repo):
+ repo.add_folder("Sources/Telegram")
+ filed = repo.add_entity("media", "m1", {"folder": "Sources/Telegram"}, by="user")
+ loose = repo.add_entity("media", "m2", by="user")
+
+ in_folder = repo.page_entities(limit=50, folder="Sources/Telegram")
+ assert [e["id"] for e in in_folder["items"]] == [filed["id"]]
+
+ unfiled = repo.page_entities(limit=50, unfiled=True)
+ assert [e["id"] for e in unfiled["items"]] == [loose["id"]]
+
+
+def test_page_entities_folder_filter_follows_an_edit(repo):
+ e = repo.add_entity("media", "m", {"folder": "A"}, by="user")
+ repo.add_entity("media", "other", {"folder": "B"}, by="user")
+
+ repo.update_entity(e["id"], {"attrs": {"folder": "B"}}) # move it A -> B
+ assert e["id"] in {x["id"] for x in repo.page_entities(limit=50, folder="B")["items"]}
+ assert repo.page_entities(limit=50, folder="A")["items"] == []
+
+
+def test_catalog_summary_counts_by_folder(repo):
+ repo.add_entity("media", "a", {"folder": "X"}, by="user")
+ repo.add_entity("media", "b", {"folder": "X"}, by="user")
+ repo.add_entity("media", "c", by="user") # unfiled — not counted under a folder
+
+ assert repo.catalog_summary()["by_folder"] == {"X": 2}
+
+
+def test_snapshot_carries_manifest_and_graph(repo):
+ repo.add_entity("person", "Ada", by="user")
+ snap = repo.snapshot()
+ assert snap["name"] == "Contract"
+ assert isinstance(snap["entities"], list) and len(snap["entities"]) == 1
+ assert isinstance(snap["links"], list)
+ assert isinstance(snap["folders"], list)
+
+
+# -- durable jobs (thumbnail and background-job model) ---------------------
+
+
+def test_enqueue_is_idempotent_on_key(repo):
+ first = repo.enqueue_job("thumbnail", key="media/a.jpg", payload={"path": "media/a.jpg"})
+ again = repo.enqueue_job("thumbnail", key="media/a.jpg")
+ assert first["id"] == again["id"] # a keyed re-enqueue never stacks a duplicate
+ assert repo.count_jobs() == {"queued": 1}
+ # a different key is a distinct job
+ repo.enqueue_job("thumbnail", key="media/b.jpg")
+ assert repo.count_jobs() == {"queued": 2}
+
+
+def test_claim_takes_one_queued_job_oldest_first(repo):
+ a = repo.enqueue_job("thumbnail", key="media/a.jpg")
+ repo.enqueue_job("thumbnail", key="media/b.jpg")
+
+ claimed = repo.claim_job(kinds=["thumbnail"])
+ assert claimed["id"] == a["id"] # oldest first
+ assert claimed["state"] == "running" and claimed["attempts"] == 1
+
+ # kind filter excludes other kinds
+ repo.enqueue_job("exif", key="media/a.jpg")
+ assert repo.claim_job(kinds=["nonesuch"]) is None
+
+
+def test_fail_retries_until_the_budget_then_fails(repo):
+ job = repo.enqueue_job("thumbnail", key="media/a.jpg", max_attempts=2)
+ c1 = repo.claim_job()
+ after1 = repo.fail_job(c1["id"], "boom")
+ assert after1["state"] == "queued" # attempt 1 of 2 — retry
+ c2 = repo.claim_job()
+ after2 = repo.fail_job(c2["id"], "boom again")
+ assert after2["state"] == "failed" and after2["attempts"] == 2
+ assert after2["error"] == "boom again"
+ assert repo.claim_job() is None # nothing queued once it has failed for good
+ assert job["id"] == after2["id"]
+
+
+def test_complete_and_cancel_are_terminal(repo):
+ a = repo.enqueue_job("thumbnail", key="media/a.jpg")
+ b = repo.enqueue_job("thumbnail", key="media/b.jpg")
+ repo.claim_job() # a -> running
+ repo.complete_job(a["id"])
+ repo.cancel_job(b["id"])
+ assert repo.get_job(a["id"])["state"] == "ready"
+ assert repo.get_job(b["id"])["state"] == "cancelled"
+ assert repo.claim_job() is None
+
+
+def test_reenqueue_resurrects_a_finished_job(repo):
+ a = repo.enqueue_job("thumbnail", key="media/a.jpg")
+ repo.claim_job()
+ repo.complete_job(a["id"])
+ again = repo.enqueue_job("thumbnail", key="media/a.jpg") # regenerate
+ assert again["id"] == a["id"] and again["state"] == "queued" and again["attempts"] == 0
+
+
+def test_recover_returns_interrupted_running_jobs(repo):
+ a = repo.enqueue_job("thumbnail", key="media/a.jpg")
+ b = repo.enqueue_job("thumbnail", key="media/b.jpg", max_attempts=1)
+ repo.claim_job() # a -> running, attempts 1 (< max, recoverable)
+ # b has spent its single attempt already
+ repo.claim_job() # b -> running, attempts 1 (== max, unrecoverable)
+
+ assert repo.recover_jobs() == 2
+ assert repo.get_job(a["id"])["state"] == "queued"
+ assert repo.get_job(b["id"])["state"] == "failed"
+
+
+def test_prune_drops_only_terminal_jobs(repo):
+ done = repo.enqueue_job("thumbnail", key="media/a.jpg")
+ repo.claim_job()
+ repo.complete_job(done["id"])
+ live = repo.enqueue_job("thumbnail", key="media/b.jpg")
+
+ assert repo.prune_jobs() == 1 # the ready one goes, the queued one stays
+ assert [j["id"] for j in repo.list_jobs()] == [live["id"]]
diff --git a/tests/test_satellite_api.py b/tests/test_satellite_api.py
index 97eb511..e5fa2f8 100644
--- a/tests/test_satellite_api.py
+++ b/tests/test_satellite_api.py
@@ -1,6 +1,8 @@
"""Satellite capture API: bearing is honored and persisted with provenance."""
import pytest
+
+import graph_read
from PIL import Image
from azimut.engine import tiles
@@ -52,7 +54,7 @@ def _capture(client, cid, lat, lon, zoom=16):
def _of_type(client, cid, etype):
- return [e for e in client.get(f"/api/cases/{cid}").json()["entities"]
+ return [e for e in graph_read.entities(cid)
if e["type"] == etype]
@@ -78,6 +80,7 @@ def test_capture_creates_capture_entity_not_place(client, monkeypatch):
assert caps[0]["label"] == "48.858400, 2.294500"
assert caps[0]["attrs"]["zoom"] == 16
assert caps[0]["attrs"]["bearing"] == 0.0
+ assert caps[0]["attrs"]["provider"] == "esri-world-imagery"
# capturing files it straight away — no confirm step
assert caps[0]["provenance"]["status"] == "confirmed"
@@ -156,6 +159,22 @@ def test_imagery_date_service_down_is_graceful(client, monkeypatch):
assert out == {"supported": True, "date": None, "source": None}
+ "params",
+ [
+ {"lat": -91, "lon": 0, "zoom": 10},
+ {"lat": 91, "lon": 0, "zoom": 10},
+ {"lat": 0, "lon": -181, "zoom": 10},
+ {"lat": 0, "lon": 181, "zoom": 10},
+ {"lat": 0, "lon": 0, "zoom": -1},
+ {"lat": 0, "lon": 0, "zoom": 23},
+ ],
+)
+def test_imagery_date_rejects_out_of_range_inputs_before_provider_call(client, monkeypatch, params):
+ monkeypatch.setattr(tiles, "esri_capture_date", lambda *_args: pytest.fail("provider called"))
+ assert client.get("/api/satellite/imagery-date", params=params).status_code == 422
+
+
def test_save_place_creates_place_without_image(client):
cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]
place = client.post(
@@ -358,7 +377,7 @@ def test_capture_title_follows_the_coordinate_format(client, monkeypatch):
# provenance is never re-expressed: a later reader still gets the numbers
assert listed["lat"] == pytest.approx(48.8583701)
assert listed["lon"] == pytest.approx(2.2944813)
- entity = client.get(f"/api/cases/{cid}").json()["entities"][0]
+ entity = graph_read.entities(cid)[0]
assert entity["attrs"]["coords"] == "48.858370, 2.294481"
@@ -492,11 +511,28 @@ def test_screenshot_capture_refused_for_tile_providers(client):
assert r.status_code == 422
+def test_screenshot_capture_has_the_same_size_limit_as_extension_ingest(client, monkeypatch):
+ from azimut.api import satellite
+
+ monkeypatch.setattr(satellite, "MAX_IMAGE_BYTES", 100)
+ client.put("/api/settings/keys", json={"google_js": "AIza.js"})
+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]
+ r = client.post(
+ f"/api/cases/{cid}/satellite/screenshot",
+ files={"image": ("shot.png", _png_bytes(), "image/png")},
+ data={"lat": "0", "lon": "0", "zoom": "10", "provider": "google-js"},
+ )
+ assert r.status_code == 413
+ assert graph_read.entities(cid) == []
+
+
def test_tile_proxy_rejects_out_of_range_coordinates(client):
# a negative z used to reach `1 << z` and 500; bad input is a 422, not a crash
assert client.get("/api/tiles/esri-world-imagery/-1/0/0").status_code == 422
assert client.get("/api/tiles/esri-world-imagery/2/4/0").status_code == 422
assert client.get("/api/tiles/esri-world-imagery/2/0/-1").status_code == 422
+ # The zoom is rejected before exponentiation, so an absurd path value stays cheap.
+ assert client.get("/api/tiles/esri-world-imagery/1000000/0/0").status_code == 422
def test_tile_proxy_reuses_one_pooled_client(client, monkeypatch):
@@ -656,6 +692,39 @@ def test_search_grid_missing_is_404(client):
assert client.get(f"/api/cases/{cid}/search-grids/nope").status_code == 404
+def test_search_grid_corruption_is_skipped_in_picker_and_reported_on_open(client):
+ from azimut.workspace import Case
+
+ cid = client.post("/api/cases", json={"name": "Grid"}).json()["id"]
+ path = Case.open(cid).subdir("search") / "broken.json"
+ path.write_text('["not", "an", "object"]', encoding="utf-8")
+
+ assert client.get(f"/api/cases/{cid}/search-grids").json() == []
+ opened = client.get(f"/api/cases/{cid}/search-grids/broken")
+ assert opened.status_code == 422
+ assert "corrupt grid" in opened.json()["detail"]
+
+
+def test_search_grid_write_is_atomic(client, monkeypatch):
+ from azimut.api import satellite
+ from azimut.workspace import Case
+
+ cid = client.post("/api/cases", json={"name": "Grid"}).json()["id"]
+ client.put(f"/api/cases/{cid}/search-grids/g", json=_rect_grid(title="Before"))
+ path = Case.open(cid).subdir("search") / "g.json"
+ before = path.read_bytes()
+
+ def fail_replace(_source, _target):
+ raise OSError("replace failed")
+
+ monkeypatch.setattr(satellite.os, "replace", fail_replace)
+ with pytest.raises(OSError, match="replace failed"):
+ satellite._write_grid_atomic(path, {**_rect_grid(title="After")["spec"], "title": "After"})
+
+ assert path.read_bytes() == before
+ assert list(path.parent.glob(".g.json.*.tmp")) == []
+
+
def test_search_grid_delete_one(client):
cid = client.post("/api/cases", json={"name": "Grid"}).json()["id"]
client.put(f"/api/cases/{cid}/search-grids/a", json=_rect_grid(title="A"))
@@ -671,4 +740,4 @@ def test_search_grids_are_not_entities(client):
cid = client.post("/api/cases", json={"name": "Grid"}).json()["id"]
client.put(f"/api/cases/{cid}/search-grids/g", json=_rect_grid())
# grids are working aids, filed under search/, never in the case graph
- assert client.get(f"/api/cases/{cid}").json()["entities"] == []
+ assert graph_read.entities(cid) == []
diff --git a/tests/test_sentinel.py b/tests/test_sentinel.py
index f8dab84..19155a5 100644
--- a/tests/test_sentinel.py
+++ b/tests/test_sentinel.py
@@ -3,9 +3,11 @@
from __future__ import annotations
import json
+import io
import httpx
import pytest
+from PIL import Image
from azimut.engine import sentinel
@@ -229,6 +231,72 @@ def test_dates_raises_rather_than_report_an_empty_sky():
sentinel.dates("inst-uuid", 48.0, 2.0, "2026-05-01", "2026-05-31", get=get)
+# -- rendered coverage --------------------------------------------------------
+
+
+def _mask_response(url, values):
+ image = Image.new("L", (8, 8))
+ image.putdata(values)
+ payload = io.BytesIO()
+ image.save(payload, format="PNG")
+ return httpx.Response(
+ 200, content=payload.getvalue(), request=httpx.Request("GET", url)
+ )
+
+
+def test_coverage_uses_the_selected_layer_and_day():
+ captured = {}
+
+ def get(url, params=None, **kwargs):
+ captured["url"] = url
+ captured["params"] = params
+ return _mask_response(url, [0] * 63 + [255])
+
+ result = sentinel.coverage(
+ "inst-uuid", 48.8584, 2.2945, "SWIR", "2026-05-11", get=get
+ )
+
+ assert result == {
+ "available": True,
+ "coverage": 0.016,
+ "date": "2026-05-11",
+ "layer": "SWIR",
+ }
+ assert captured["url"].endswith("/ogc/wms/inst-uuid")
+ assert captured["params"]["LAYERS"] == "SWIR"
+ assert captured["params"]["TIME"] == "2026-05-11/2026-05-11"
+ assert captured["params"]["FORMAT"] == "image/png"
+ assert captured["params"]["EVALSCRIPT"]
+
+
+def test_coverage_reports_no_source_pixels():
+ result = sentinel.coverage(
+ "inst-uuid", 48.8584, 2.2945, "TRUE_COLOR", "2026-05-11",
+ get=lambda url, **kwargs: _mask_response(url, [0] * 64),
+ )
+ assert result["available"] is False
+ assert result["coverage"] == 0.0
+
+
+ ("layer", "day"),
+ [("../SWIR", "2026-05-11"), ("SWIR", "2026-02-30")],
+)
+def test_coverage_rejects_malformed_layer_or_day(layer, day):
+ with pytest.raises(ValueError):
+ sentinel.coverage("inst-uuid", 48.0, 2.0, layer, day)
+
+
+def test_coverage_rejects_a_non_image_response():
+ def get(url, **kwargs):
+ return _response(url, text="<ExceptionReport />")
+
+ with pytest.raises(sentinel.CoverageError, match="no readable image"):
+ sentinel.coverage(
+ "inst-uuid", 48.0, 2.0, "TRUE_COLOR", "2026-05-11", get=get
+ )
+
+
# -- layer discovery -----------------------------------------------------------
_CAPABILITIES = """<?xml version="1.0"?>
diff --git a/tests/test_settings_api.py b/tests/test_settings_api.py
index bacd012..5f5e1ff 100644
--- a/tests/test_settings_api.py
+++ b/tests/test_settings_api.py
@@ -3,7 +3,7 @@
import httpx
from azimut import config
-from azimut.engine import google_tiles, scrapers
+from azimut.engine import google_tiles, scrapers, sentinel
def test_get_settings_defaults(client):
@@ -525,6 +525,61 @@ def test_sentinel_dates_without_a_key_is_a_404(client):
).status_code == 404
+def test_sentinel_coverage_checks_the_layer_and_counts_the_request(client, monkeypatch):
+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
+ calls = []
+
+ def check(instance, lat, lon, layer, day):
+ calls.append((instance, lat, lon, layer, day))
+ return {
+ "available": False,
+ "coverage": 0.0,
+ "date": day,
+ "layer": layer,
+ }
+
+ monkeypatch.setattr(sentinel, "coverage", check)
+ body = client.get(
+ "/api/satellite/sentinel/coverage"
+ "?lat=48.8584&lon=2.2945&layer=SWIR&date=2026-05-11"
+ ).json()
+
+ assert body["available"] is False
+ assert calls == [("inst-uuid", 48.8584, 2.2945, "SWIR", "2026-05-11")]
+ settings = client.get("/api/settings").json()
+ assert settings["usage"]["sentinelhub"][settings["month"]] == 1
+
+
+def test_sentinel_coverage_rejects_bad_input_without_counting(client, monkeypatch):
+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
+
+ def reject(*args):
+ raise ValueError("malformed Sentinel-2 layer")
+
+ monkeypatch.setattr(sentinel, "coverage", reject)
+ response = client.get(
+ "/api/satellite/sentinel/coverage"
+ "?lat=48.8584&lon=2.2945&layer=bad&date=2026-05-11"
+ )
+ assert response.status_code == 422
+ assert client.get("/api/settings").json()["usage"] == {}
+
+
+def test_sentinel_coverage_failure_is_upstream_error(client, monkeypatch):
+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
+
+ def fail(*args):
+ raise sentinel.CoverageError("no readable image")
+
+ monkeypatch.setattr(sentinel, "coverage", fail)
+ response = client.get(
+ "/api/satellite/sentinel/coverage"
+ "?lat=48.8584&lon=2.2945&layer=SWIR&date=2026-05-11"
+ )
+ assert response.status_code == 502
+ assert client.get("/api/settings").json()["usage"] == {}
+
+
def test_free_tier_defaults_to_the_provisioned_sentinel_allowance(client):
body = client.get("/api/settings").json()
# Copernicus documents 10k but provisions 30k to a General account
diff --git a/tests/test_settings_backup.py b/tests/test_settings_backup.py
index a51c3e8..ec25353 100644
--- a/tests/test_settings_backup.py
+++ b/tests/test_settings_backup.py
@@ -1,5 +1,7 @@
"""Settings backup (export/import) and the lazy pairing-token mint."""
+import pytest
+
from azimut import config
@@ -42,3 +44,50 @@ def test_import_ignores_unknown_keys(client):
stored = config.load_settings()
assert "evil" not in stored
assert stored["units"] == "imperial"
+
+
+def test_import_canonicalizes_known_fields_and_ignores_future_provider_keys(client):
+ response = client.post(
+ "/api/settings/import",
+ json={
+ "settings": {
+ "api_keys": {"mapbox": " pk.restored ", "empty": " "},
+ "providers_enabled": {"mapbox": False, "future": True},
+ "eco_max_zooms": {"mapbox": 12, "future": 4},
+ "post_mention": " @account ",
+ }
+ },
+ )
+ assert response.status_code == 200
+ stored = config.load_settings()
+ assert stored["api_keys"] == {"mapbox": "pk.restored"}
+ assert stored["providers_enabled"] == {"mapbox": False}
+ assert stored["eco_max_zooms"] == {"mapbox": 12}
+ assert stored["post_mention"] == "@account"
+
+
+ "field,value",
+ [
+ ("api_keys", ["bad"]),
+ ("free_tiers", ["bad"]),
+ ("free_tiers", {"mapbox": 0}),
+ ("usage", {"mapbox": {"2026-13": 1}}),
+ ("usage", {"mapbox": {"2026-07": -1}}),
+ ("home_view", {"lat": 91.0, "lon": 0.0, "zoom": 12}),
+ ("eco_max_zoom", 99),
+ ("coord_format", "utm"),
+ ("post_target", "threads"),
+ ("update_check_on_start", 1),
+ ("tile_providers", [{"id": "bad id", "url": "https://tiles/{z}/{x}/{y}"}]),
+ ],
+)
+def test_import_rejects_malformed_known_fields_without_partial_write(client, field, value):
+ before = config.settings_path().read_bytes()
+ response = client.post(
+ "/api/settings/import",
+ json={"settings": {"units": "imperial", field: value}},
+ )
+ assert response.status_code == 422
+ assert config.settings_path().read_bytes() == before
+ assert config.load_settings()["units"] == "metric"
diff --git a/tests/test_sqlite_backend.py b/tests/test_sqlite_backend.py
new file mode 100644
index 0000000..c466d10
--- /dev/null
+++ b/tests/test_sqlite_backend.py
@@ -0,0 +1,287 @@
+"""SQLite backend and JSON->SQLite converter (Step 3 of
+docs/STORAGE_AND_PERFORMANCE.md).
+
+The graph contract itself is covered by `tests/test_repository.py`, which runs
+the same suite against both `Case` and `SqliteCase`. This file pins the
+store-specific behaviour the contract can't reach: create/open, forward-compat
+refusal, foreign-key enforcement, transaction rollback, and the atomic converter
+that must never leave a half-built database or touch the legacy `case.json`.
+"""
+
+from __future__ import annotations
+
+import sqlite3
+
+import pytest
+from bigcase import build_big_case
+from legacy_case import write_legacy_json_case
+
+from azimut.sqlite_backend import SqliteCase, convert_json_to_sqlite
+from azimut.workspace import CaseError
+
+
+def _entity(eid, **over):
+ ent = {
+ "id": eid,
+ "type": "person",
+ "label": eid,
+ "attrs": {},
+ "provenance": {"by": "user", "at": "2026-01-01T00:00:00Z", "status": "confirmed"},
+ }
+ ent.update(over)
+ return ent
+
+
+def _json_case(**over):
+ data = {
+ "azimut": {"schema": 2},
+ "name": "Legacy",
+ "created_at": "2026-01-01T00:00:00Z",
+ "updated_at": "2026-01-02T00:00:00Z",
+ "folders": [],
+ "entities": [],
+ "links": [],
+ }
+ data.update(over)
+ return data
+
+
+# -- create / open ---------------------------------------------------------
+
+
+def test_create_then_open_roundtrips(tmp_path):
+ store = SqliteCase.create(tmp_path / "case.db", name="Contract")
+ e = store.add_entity("person", "Ada", {"handle": "@ada"}, by="user")
+
+ reopened = SqliteCase.open(tmp_path / "case.db")
+ assert reopened.get_entity(e["id"]) == e
+ assert reopened.snapshot()["name"] == "Contract"
+
+
+def test_create_refuses_existing_db(tmp_path):
+ SqliteCase.create(tmp_path / "case.db", name="One")
+ with pytest.raises(CaseError, match="already exists"):
+ SqliteCase.create(tmp_path / "case.db", name="Two")
+
+
+def test_open_missing_db_raises(tmp_path):
+ with pytest.raises(CaseError, match="not found"):
+ SqliteCase.open(tmp_path / "nope.db")
+
+
+def test_open_refuses_newer_schema(tmp_path):
+ db = tmp_path / "case.db"
+ SqliteCase.create(db, name="From the future")
+ with sqlite3.connect(db) as conn:
+ conn.execute("UPDATE meta SET value = ? WHERE key = 'schema_version'", ("99",))
+ with pytest.raises(CaseError, match="newer Azimut"):
+ SqliteCase.open(db)
+
+
+# -- database behaviour ----------------------------------------------------
+
+
+def test_foreign_keys_forbid_a_dangling_link(tmp_path):
+ """A raw insert bypassing add_entity validation still can't dangle: the FK
+ pragma is on for every connection."""
+ db = tmp_path / "case.db"
+ store = SqliteCase.create(db, name="FK")
+ a = store.add_entity("person", "A", by="user")
+ with store._connect() as conn: # exercising the connection policy directly
+ with pytest.raises(sqlite3.IntegrityError):
+ conn.execute(
+ "INSERT INTO links"
+ "(id, from_id, to_id, type, prov_by, prov_at, prov_status)"
+ " VALUES('l_x', ?, 'ghost', 'owns', 'user', '2026', 'confirmed')",
+ (a["id"],),
+ )
+
+
+def test_write_rolls_back_on_error(tmp_path):
+ store = SqliteCase.create(tmp_path / "case.db", name="Rollback")
+ store.add_entity("person", "A", by="user")
+
+ def boom(conn):
+ conn.execute(
+ "INSERT INTO entities(id, type, label, prov_by, prov_at)"
+ " VALUES('e_x', 'person', 'B', 'user', '2026')"
+ )
+ raise RuntimeError("mid-transaction failure")
+
+ with pytest.raises(RuntimeError):
+ store._write(boom) # exercising the transaction helper directly
+
+ # the aborted insert left no trace
+ assert store.get_entity("e_x") is None
+ assert len(store.list_entities()) == 1
+
+
+_SCHEMA_V1 = """
+CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
+CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL);
+CREATE TABLE entities (
+ id TEXT PRIMARY KEY, type TEXT NOT NULL, label TEXT NOT NULL,
+ attrs_json TEXT NOT NULL DEFAULT '{}',
+ prov_by TEXT NOT NULL, prov_at TEXT NOT NULL,
+ prov_status TEXT NOT NULL DEFAULT 'confirmed', prov_source TEXT
+);
+CREATE TABLE links (
+ id TEXT PRIMARY KEY, from_id TEXT NOT NULL REFERENCES entities(id),
+ to_id TEXT NOT NULL REFERENCES entities(id), type TEXT NOT NULL,
+ prov_by TEXT NOT NULL, prov_at TEXT NOT NULL,
+ prov_status TEXT NOT NULL DEFAULT 'confirmed', prov_source TEXT
+);
+CREATE TABLE folders (path TEXT PRIMARY KEY);
+INSERT INTO meta(key, value) VALUES('schema_version', '1');
+INSERT INTO entities(id, type, label, attrs_json, prov_by, prov_at)
+ VALUES('e1', 'media', 'm', '{"folder": "Sources/Telegram"}', 'user', '2026');
+INSERT INTO entities(id, type, label, attrs_json, prov_by, prov_at)
+ VALUES('e2', 'media', 'loose', '{}', 'user', '2026');
+"""
+
+
+def test_open_upgrades_a_v1_db_through_every_migration(tmp_path):
+ """A schema-1 case.db is upgraded on open through the whole chain: the folder
+ column is added and backfilled (1->2) and the jobs table is created (2->3),
+ reaching the current schema — and a second open re-applies nothing."""
+ db = tmp_path / "case.db"
+ with sqlite3.connect(db) as conn:
+ conn.executescript(_SCHEMA_V1)
+
+ store = SqliteCase.open(db) # runs 1 -> 2 -> 3 in place
+
+ # 1 -> 2: the folder column is backfilled and pages by folder.
+ assert [e["id"] for e in store.page_entities(folder="Sources/Telegram")["items"]] == ["e1"]
+ assert [e["id"] for e in store.page_entities(unfiled=True)["items"]] == ["e2"]
+ # 2 -> 3: the durable jobs table exists and works.
+ store.enqueue_job("thumbnail", key="media/x.jpg")
+ assert store.count_jobs() == {"queued": 1}
+ with sqlite3.connect(db) as conn:
+ assert conn.execute("SELECT value FROM meta WHERE key='schema_version'").fetchone()[0] == "3"
+ applied = {
+ r[0] for r in conn.execute("SELECT version FROM schema_migrations").fetchall()
+ }
+ assert {2, 3} <= applied
+
+ SqliteCase.open(db) # idempotent — the second open applies nothing
+ with sqlite3.connect(db) as conn:
+ for version in (2, 3):
+ assert conn.execute(
+ "SELECT COUNT(*) FROM schema_migrations WHERE version = ?", (version,)
+ ).fetchone()[0] == 1
+
+
+def test_pagination_keys_on_rowid_so_a_deletion_does_not_skip(tmp_path):
+ """The cursor keys on rowid, not an offset, so removing an already-seen row
+ between page fetches never makes the next page skip a live entity."""
+ store = SqliteCase.create(tmp_path / "case.db", name="Keyset")
+ ids = [store.add_entity("person", f"P{i}", by="user")["id"] for i in range(4)]
+
+ page1 = store.page_entities(limit=2)
+ assert [e["id"] for e in page1["items"]] == ids[:2]
+
+ store.remove_entity(ids[0]) # a row before the cursor disappears
+
+ page2 = store.page_entities(limit=2, cursor=page1["next_cursor"])
+ assert [e["id"] for e in page2["items"]] == ids[2:] # nothing skipped
+
+
+# -- converter -------------------------------------------------------------
+
+
+def test_convert_matches_the_source_graph(tmp_path):
+ src = _json_case(
+ folders=["Sources", "Sources/Telegram"],
+ entities=[
+ _entity("e_a", type="person", label="Ada"),
+ _entity("e_b", type="account", label="@ada", attrs={"handle": "@ada"}),
+ _entity("e_c", type="media", label="photo", attrs={"path": "media/x.jpg"}),
+ ],
+ links=[
+ {
+ "id": "l_1",
+ "from": "e_a",
+ "to": "e_b",
+ "type": "owns",
+ "provenance": {"by": "user", "at": "2026-01-01T00:00:00Z", "status": "confirmed"},
+ }
+ ],
+ )
+
+ report = convert_json_to_sqlite(src, tmp_path / "case.db")
+ assert (report.entities, report.links, report.folders) == (3, 1, 2)
+ assert report.integrity_ok and report.missing_endpoints == []
+
+ store = SqliteCase.open(tmp_path / "case.db")
+ assert {e["id"] for e in store.list_entities()} == {"e_a", "e_b", "e_c"}
+ assert store.get_entity("e_b")["attrs"] == {"handle": "@ada"}
+ assert store.list_folders() == ["Sources", "Sources/Telegram"]
+ assert store.find_entity(attr="path", value="media/x.jpg")["id"] == "e_c"
+ snap = store.snapshot()
+ assert snap["name"] == "Legacy" and snap["created_at"] == "2026-01-01T00:00:00Z"
+
+
+def test_convert_reports_and_drops_dangling_links(tmp_path):
+ src = _json_case(
+ entities=[_entity("e_a")],
+ links=[
+ {
+ "id": "l_ghost",
+ "from": "e_a",
+ "to": "e_missing",
+ "type": "owns",
+ "provenance": {"by": "user", "at": "2026", "status": "confirmed"},
+ }
+ ],
+ )
+
+ report = convert_json_to_sqlite(src, tmp_path / "case.db")
+ assert report.missing_endpoints == ["l_ghost"]
+ assert report.integrity_ok # a dropped edge is not an integrity failure
+
+ store = SqliteCase.open(tmp_path / "case.db")
+ assert store.list_links() == []
+ assert store.get_entity("e_a") is not None # the entity is never erased
+
+
+def test_convert_rolls_back_and_leaves_no_db_on_failure(tmp_path):
+ src = _json_case(entities=[_entity("e_dup"), _entity("e_dup")]) # duplicate primary key
+ db = tmp_path / "case.db"
+
+ with pytest.raises(sqlite3.IntegrityError):
+ convert_json_to_sqlite(src, db)
+
+ assert not db.exists()
+ assert not (tmp_path / "case.db.tmp").exists()
+
+
+def test_convert_writes_only_the_target_db(tmp_workspace, tmp_path):
+ prov = {"by": "user", "at": "2026-01-01T00:00:00Z", "status": "confirmed"}
+ case = write_legacy_json_case(
+ "Live",
+ entities=[{"id": "e_a", "type": "person", "label": "Ada", "attrs": {}, "provenance": prov}],
+ )
+ before = case.json_path.read_bytes()
+
+ convert_json_to_sqlite(case.read(), tmp_path / "case.db")
+
+ # the converter only reads the graph; it never rewrites the source case.json
+ assert case.json_path.read_bytes() == before
+ assert (tmp_path / "case.db").exists()
+
+
+def test_convert_a_large_case_is_intact(tmp_workspace, tmp_path):
+ case, summary = build_big_case(
+ name="Big", entities=300, links=400, media=100, notes=20, artifacts=30,
+ write_media_files=False,
+ )
+ report = convert_json_to_sqlite(case.read(), tmp_path / "case.db")
+
+ assert report.integrity_ok
+ assert report.entities == summary.entities
+ store = SqliteCase.open(tmp_path / "case.db")
+ assert len(store.list_entities()) == summary.entities
+ # every surviving link resolves to real endpoints
+ ids = {e["id"] for e in store.list_entities()}
+ for link in store.list_links():
+ assert link["from"] in ids and link["to"] in ids
diff --git a/tests/test_thumbnails.py b/tests/test_thumbnails.py
new file mode 100644
index 0000000..8a308bd
--- /dev/null
+++ b/tests/test_thumbnails.py
@@ -0,0 +1,208 @@
+"""Thumbnail cache and its durable job model (doc step 6, "Thumbnail and
+background-job model").
+
+Pins the guarantees the doc asks for: cheap image thumbnails render inline while
+the CPU-heavy video path is queued to the single worker; generation is atomic and
+content-addressed; a failure retries then fails without looping; the cache is
+budgeted (LRU) and repairable; and a shared thumbnail survives one of its media
+being deleted. `_render` is monkeypatched where a test must not depend on a real
+ffmpeg being installed.
+"""
+
+from __future__ import annotations
+
+import io
+import time
+
+import pytest
+from PIL import Image
+
+from azimut.engine import media as media_engine
+from azimut.engine import thumbnails
+from azimut.workspace import Case
+
+
+def case(tmp_workspace, monkeypatch):
+ """A fresh case with the background worker disabled, so tests drain the queue
+ explicitly and deterministically."""
+ monkeypatch.setattr(thumbnails, "start_workers", False)
+ return Case.create("Thumbs")
+
+
+def _png(color=(200, 30, 30), size=(80, 60)) -> io.BytesIO:
+ buf = io.BytesIO()
+ Image.new("RGB", size, color).save(buf, "PNG")
+ buf.seek(0)
+ return buf
+
+
+def _register_video(case: Case, name="clip.mp4") -> dict:
+ path = case.subdir("media") / name
+ path.write_bytes(b"not a real video, just bytes")
+ return media_engine._register(case, path, {"type": "upload"})
+
+
+# -- inline images vs queued video ----------------------------------------
+
+
+def test_image_thumbnail_renders_inline_and_is_content_addressed(case):
+ res = media_engine.import_stream(case, "photo.png", _png())
+ item = res["item"]
+ assert item["thumbnail"] == thumbnails.thumb_relpath(item["sha256"], "image")
+ assert case.resolve_inside(item["thumbnail"]).exists()
+ # no job was needed for the fast path
+ assert case.list_jobs(kind=thumbnails.THUMB_KIND) == []
+
+
+def test_video_thumbnail_is_queued_not_inline(case):
+ res = _register_video(case)
+ assert res["item"]["thumbnail"] is None # nothing rendered inline
+ jobs = case.list_jobs(kind=thumbnails.THUMB_KIND)
+ assert [(j["state"], j["key"]) for j in jobs] == [("queued", "media/clip.mp4")]
+
+
+# -- draining the queue ----------------------------------------------------
+
+
+def test_drain_generates_the_queued_thumbnail_and_updates_the_sidecar(case, monkeypatch):
+ def fake_render(media_path, out_path, kind):
+ out_path.write_bytes(b"\xff\xd8\xff\xe0jpeg")
+ return True
+
+ monkeypatch.setattr(thumbnails, "_render", fake_render)
+ item = _register_video(case)["item"]
+
+ assert thumbnails.drain(case) == 1
+ job = case.list_jobs(kind=thumbnails.THUMB_KIND)[0]
+ assert job["state"] == "ready"
+ # the sidecar now points at the freshly generated, content-addressed file
+ refreshed = media_engine.read_item(case, item["path"])
+ assert refreshed["thumbnail"] == thumbnails.thumb_relpath(item["sha256"], "video")
+ assert case.resolve_inside(refreshed["thumbnail"]).exists()
+
+
+def test_a_failing_render_retries_then_fails_without_looping(case, monkeypatch):
+ monkeypatch.setattr(thumbnails, "_render", lambda *a: False) # produces nothing
+ _register_video(case)
+
+ handled = thumbnails.drain(case) # claims, fails, requeues, up to the budget
+ assert handled == 3 # default max_attempts
+ job = case.list_jobs(kind=thumbnails.THUMB_KIND)[0]
+ assert job["state"] == "failed" and job["attempts"] == 3
+
+
+def test_drain_cancels_a_job_whose_media_is_gone(case):
+ _register_video(case)
+ (case.subdir("media") / "clip.mp4").unlink()
+ (case.subdir("media") / ("clip.mp4" + media_engine.SIDECAR_SUFFIX)).unlink()
+
+ thumbnails.drain(case)
+ assert case.list_jobs(kind=thumbnails.THUMB_KIND)[0]["state"] == "cancelled"
+
+
+# -- atomicity + content key ----------------------------------------------
+
+
+def test_generate_leaves_no_partial_or_temp_on_failure(case, monkeypatch):
+ path = case.subdir("media") / "clip.mp4"
+ path.write_bytes(b"bytes")
+ monkeypatch.setattr(thumbnails, "_render", lambda *a: False)
+
+ with pytest.raises(thumbnails.ThumbnailError):
+ thumbnails.generate(case, "media/clip.mp4", "deadbeef" * 8, "video")
+
+ thumb_dir = case.subdir("media") / thumbnails.THUMB_DIR
+ leftovers = list(thumb_dir.iterdir()) if thumb_dir.is_dir() else []
+ assert leftovers == [] # neither a final file nor a .tmp.jpg is left behind
+
+
+def test_content_key_folds_in_the_generator_version(case, monkeypatch):
+ first = thumbnails.thumb_relpath("a" * 64, "image")
+ monkeypatch.setattr(thumbnails, "THUMB_GEN", thumbnails.THUMB_GEN + 1)
+ bumped = thumbnails.thumb_relpath("a" * 64, "image")
+ assert first != bumped # a new generator maps the same original to a new file
+ assert thumbnails.thumb_relpath("a" * 64, "audio") is None # not thumbnailed
+
+
+# -- budget + repair -------------------------------------------------------
+
+
+def test_prune_cache_evicts_least_recently_used_over_budget(case):
+ thumbs = case.subdir("media") / thumbnails.THUMB_DIR
+ thumbs.mkdir(parents=True, exist_ok=True)
+ files = []
+ for i in range(3):
+ f = thumbs / f"{i:024d}-g1.jpg"
+ f.write_bytes(b"x" * 100)
+ import os
+
+ os.utime(f, (1000 + i, 1000 + i)) # oldest first
+ files.append(f)
+
+ evicted = thumbnails.prune_cache(case, budget_bytes=250) # room for 2 of 3
+ assert evicted == 1
+ assert not files[0].exists() # the oldest went
+ assert files[1].exists() and files[2].exists()
+
+
+def test_repair_removes_orphan_and_temp_files_only(case):
+ item = media_engine.import_stream(case, "keep.png", _png())["item"]
+ thumbs = case.subdir("media") / thumbnails.THUMB_DIR
+ (thumbs / "orphan-g1.jpg").write_bytes(b"stale")
+ (thumbs / ".half.tmp.jpg").write_bytes(b"partial")
+
+ assert thumbnails.repair(case) == 2 # orphan + temp
+ assert case.resolve_inside(item["thumbnail"]).exists() # the referenced one stays
+
+
+def test_deleting_one_of_two_media_sharing_a_thumbnail_keeps_it(case):
+ # dedupe=False keeps two entities for identical bytes (satellite re-captures),
+ # so both sidecars point at the same content-addressed thumbnail.
+ img = Image.new("RGB", (40, 40), (10, 20, 30))
+ a = media_engine.import_image(case, img, "a.png", {"type": "satellite"}, dedupe=False)["item"]
+ b = media_engine.import_image(case, img, "b.png", {"type": "satellite"}, dedupe=False)["item"]
+ assert a["thumbnail"] == b["thumbnail"]
+ thumb = case.resolve_inside(a["thumbnail"])
+
+ media_engine.delete_media_files(case, a["path"])
+ assert thumb.exists() # still referenced by b
+ media_engine.delete_media_files(case, b["path"])
+ assert not thumb.exists() # last reference gone
+
+
+# -- the background worker -------------------------------------------------
+
+
+def test_startup_recovers_interrupted_jobs(case, monkeypatch):
+ """The server's startup pass returns a job an earlier run left `running` back
+ to the queue, so pending thumbnail work resumes instead of stalling."""
+ from azimut import server
+
+ _register_video(case)
+ running = case.claim_job() # simulate a crash mid-render
+ assert running["state"] == "running"
+
+ server._recover_jobs() # what create_app runs on boot (worker disabled here)
+ assert case.get_job(running["id"])["state"] == "queued"
+
+
+def test_worker_wakes_and_drains_in_the_background(tmp_workspace, monkeypatch):
+ monkeypatch.setattr(thumbnails, "start_workers", True)
+
+ def fake_render(media_path, out_path, kind):
+ out_path.write_bytes(b"\xff\xd8\xff\xe0jpeg")
+ return True
+
+ monkeypatch.setattr(thumbnails, "_render", fake_render)
+ c = Case.create("Worker")
+ item = _register_video(c)["item"] # enqueues + wakes the worker
+
+ deadline = time.time() + 5
+ while time.time() < deadline:
+ if media_engine.read_item(c, item["path"])["thumbnail"]:
+ break
+ time.sleep(0.05)
+ refreshed = media_engine.read_item(c, item["path"])
+ assert refreshed["thumbnail"] and c.resolve_inside(refreshed["thumbnail"]).exists()
+ assert thumbnails.wait_until_idle()
diff --git a/uv.lock b/uv.lock
index 4757004..d6fe949 100644
--- a/uv.lock
+++ b/uv.lock
@@ -7,6 +7,15 @@ resolution-markers = [
"python_full_version < '3.12'",
]
+[[package]]
+name = "altgraph"
+version = "0.17.5"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/7e/f8/97fdf103f38fed6792a1601dbc16cc8aac56e7459a9fff08c812d8ae177a/altgraph-0.17.5.tar.gz", hash = "sha256:c87b395dd12fabde9c99573a9749d67da8d29ef9de0125c7f536699b4a9bc9e7", size = 48428, upload-time = "2025-11-21T20:35:50.583Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a9/ba/000a1996d4308bc65120167c21241a3b205464a2e0b58deda26ae8ac21d1/altgraph-0.17.5-py2.py3-none-any.whl", hash = "sha256:f3a22400bce1b0c701683820ac4f3b159cd301acab067c51c653e06961600597", size = 21228, upload-time = "2025-11-21T20:35:49.444Z" },
+]
+
[[package]]
name = "annotated-doc"
version = "0.0.4"
@@ -108,6 +117,13 @@ dev = [
{ name = "ruff" },
]
+[package.dev-dependencies]
+release = [
+ { name = "build" },
+ { name = "hatchling" },
+ { name = "pyinstaller" },
+]
+
[package.metadata]
requires-dist = [
{ name = "fastapi", specifier = ">=0.111,<1.0" },
@@ -130,6 +146,27 @@ requires-dist = [
]
provides-extras = ["dev"]
+[package.metadata.requires-dev]
+release = [
+ { name = "build", specifier = ">=1.2,<2" },
+ { name = "hatchling", specifier = ">=1.27,<2" },
+ { name = "pyinstaller", specifier = ">=6,<7" },
+]
+
+[[package]]
+name = "build"
+version = "1.5.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "colorama", marker = "os_name == 'nt'" },
+ { name = "packaging" },
+ { name = "pyproject-hooks" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/78/e0/df5e171f685f82f37b12e1f208064e24244911079d7b767447d1af7e0d70/build-1.5.0.tar.gz", hash = "sha256:302c22c3ba2a0fd5f3911918651341ebb3896176cbdec15bd421f80b1afc7647", size = 89796, upload-time = "2026-04-30T03:18:25.17Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/0d/fe/6bea5c9162869c5beba5d9c8abbed835ec85bf1ec1fba05a3822325c45f3/build-1.5.0-py3-none-any.whl", hash = "sha256:13f3eecb844759ab66efec90ca17639bbf14dc06cb2fdf37a9010322d9c50a6f", size = 26018, upload-time = "2026-04-30T03:18:23.644Z" },
+]
+
[[package]]
name = "certifi"
version = "2026.6.17"
@@ -271,6 +308,21 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" },
]
+[[package]]
+name = "hatchling"
+version = "1.31.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "packaging" },
+ { name = "pathspec" },
+ { name = "pluggy" },
+ { name = "trove-classifiers" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/25/e2/dfa73fe78f773018dcaebc6d09b819bc10d328ff5a6b4a66efa1e3d71f52/hatchling-1.31.0.tar.gz", hash = "sha256:6b48ad4068a482ed7239b3a8215bc55b47aad3345d58dfc94e553c5d2d46211b", size = 57208, upload-time = "2026-07-08T01:48:32.237Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/64/e2/2c0af0a52d16be74a4f194564fcdc417521ed863e9b65e4bc9052dacba6f/hatchling-1.31.0-py3-none-any.whl", hash = "sha256:aac80bec8b6fe35e8480f1c335be8910fa210a0e6f735a139be205dadcacb544", size = 77747, upload-time = "2026-07-08T01:48:31.024Z" },
+]
+
[[package]]
name = "httpcore"
version = "1.0.9"
@@ -464,6 +516,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/5f/5d/3dcec2884ba1b0806d1408612555c38dd5d68e90156b59f75f6e36435c3a/librt-0.13.0-cp314-cp314t-win_arm64.whl", hash = "sha256:2f281549a4c52ac7bb97997f14353f8bd0e53a34ca0dad1c905cfd0b4a58ae99", size = 110771, upload-time = "2026-07-08T12:26:12.303Z" },
]
+[[package]]
+name = "macholib"
+version = "1.16.4"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "altgraph" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/10/2f/97589876ea967487978071c9042518d28b958d87b17dceb7cdc1d881f963/macholib-1.16.4.tar.gz", hash = "sha256:f408c93ab2e995cd2c46e34fe328b130404be143469e41bc366c807448979362", size = 59427, upload-time = "2025-11-22T08:28:38.373Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/c7/d1/a9f36f8ecdf0fb7c9b1e78c8d7af12b8c8754e74851ac7b94a8305540fc7/macholib-1.16.4-py2.py3-none-any.whl", hash = "sha256:da1a3fa8266e30f0ce7e97c6a54eefaae8edd1e5f86f3eb8b95457cae90265ea", size = 38117, upload-time = "2025-11-22T08:28:36.939Z" },
+]
+
[[package]]
name = "mypy"
version = "2.3.0"
@@ -699,6 +763,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/f1/d9/7fb5aa316bc299258e68c73ba3bddbc499654a07f151cba08f6153988714/pathspec-1.1.1-py3-none-any.whl", hash = "sha256:a00ce642f577bf7f473932318056212bc4f8bfdf53128c78bbd5af0b9b20b189", size = 57328, upload-time = "2026-04-27T01:46:07.06Z" },
]
+[[package]]
+name = "pefile"
+version = "2024.8.26"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/03/4f/2750f7f6f025a1507cd3b7218691671eecfd0bbebebe8b39aa0fe1d360b8/pefile-2024.8.26.tar.gz", hash = "sha256:3ff6c5d8b43e8c37bb6e6dd5085658d658a7a0bdcd20b6a07b1fcfc1c4e9d632", size = 76008, upload-time = "2024-08-26T20:58:38.155Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/54/16/12b82f791c7f50ddec566873d5bdd245baa1491bac11d15ffb98aecc8f8b/pefile-2024.8.26-py3-none-any.whl", hash = "sha256:76f8b485dcd3b1bb8166f1128d395fa3d87af26360c2358fb75b80019b957c6f", size = 74766, upload-time = "2024-08-26T21:01:02.632Z" },
+]
+
[[package]]
name = "pillow"
version = "12.3.0"
@@ -919,6 +992,55 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/f4/7e/a72dd26f3b0f4f2bf1dd8923c85f7ceb43172af56d63c7383eb62b332364/pygments-2.20.0-py3-none-any.whl", hash = "sha256:81a9e26dd42fd28a23a2d169d86d7ac03b46e2f8b59ed4698fb4785f946d0176", size = 1231151, upload-time = "2026-03-29T13:29:30.038Z" },
]
+[[package]]
+name = "pyinstaller"
+version = "6.21.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "altgraph" },
+ { name = "macholib", marker = "sys_platform == 'darwin'" },
+ { name = "packaging" },
+ { name = "pefile", marker = "sys_platform == 'win32'" },
+ { name = "pyinstaller-hooks-contrib" },
+ { name = "pywin32-ctypes", marker = "sys_platform == 'win32'" },
+ { name = "setuptools" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/d5/4d/ec706c3fcf39e26888c35b39615ff4d5865d184069666c47492cff1fbe50/pyinstaller-6.21.0.tar.gz", hash = "sha256:bb9fab705983e393a2d1cac77d6972513057ad800215fd861dc15ff5272e98fd", size = 4061519, upload-time = "2026-06-13T14:15:06.25Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/0c/4a/53cf98bf66daed012dc9cd78c8203f19a675d696f2fc12afcf8c5049a0e0/pyinstaller-6.21.0-py3-none-macosx_10_13_universal2.whl", hash = "sha256:327d132389f37912609e01be62810cf96b5aa95b613903e4b8692e0d12fb0eda", size = 1052350, upload-time = "2026-06-13T14:13:55.88Z" },
+ { url = "https://files.pythonhosted.org/packages/30/83/b591295c352ef464c50b4c6ffff1c4f771d875c9e833f578d1b9f564f6b3/pyinstaller-6.21.0-py3-none-manylinux2014_aarch64.whl", hash = "sha256:7071d4b094d5b40deeef5fa3d3b98a1b846087f7562b49209663d5f9281fe251", size = 748477, upload-time = "2026-06-13T14:14:00.327Z" },
+ { url = "https://files.pythonhosted.org/packages/3d/8f/88fff4e403873b1e22286911350e75ff00db014aa08e57045da9d4328993/pyinstaller-6.21.0-py3-none-manylinux2014_i686.whl", hash = "sha256:6b6374d652107dd4a2eeece903ff82bb4045bb5e1006c5a158a6dcdbefe84bf2", size = 760877, upload-time = "2026-06-13T14:14:04.836Z" },
+ { url = "https://files.pythonhosted.org/packages/8a/13/f0e48fbdfd1d05d948157121cea8b1b823dcb89efe6934b71fdd8bdb3f0f/pyinstaller-6.21.0-py3-none-manylinux2014_ppc64le.whl", hash = "sha256:4e3108b3f02384560da70e39b8bf22b0ad597d02bd68a40d76ea91c1cfa00cad", size = 759194, upload-time = "2026-06-13T14:14:10.61Z" },
+ { url = "https://files.pythonhosted.org/packages/dd/d5/ea7878cf9924ed30d946d8288777424e6d069d94f5bde56b4d0890069664/pyinstaller-6.21.0-py3-none-manylinux2014_s390x.whl", hash = "sha256:697532279f535ad572bda613db4f821540e235c7854ca6da4d3bf0373f4415ee", size = 754979, upload-time = "2026-06-13T14:14:15.226Z" },
+ { url = "https://files.pythonhosted.org/packages/9f/09/51b8905714b733bac66dbc041a7821372d70d888d273ae474c4037d4202d/pyinstaller-6.21.0-py3-none-manylinux2014_x86_64.whl", hash = "sha256:605169523a6b5ace39f13dfbff21add9f2bc43df99c7daf9394fefb2c45e8b6f", size = 754812, upload-time = "2026-06-13T14:14:20.264Z" },
+ { url = "https://files.pythonhosted.org/packages/4b/43/d77779439d8c6c2e27a77bcfbd1d5cc0f568ebb611bb472b11af81b5f177/pyinstaller-6.21.0-py3-none-musllinux_1_1_aarch64.whl", hash = "sha256:5fa56746c1e76f93634d018502301378a2d0c382553d37d8c3c34ff436c12dd1", size = 753887, upload-time = "2026-06-13T14:14:25.268Z" },
+ { url = "https://files.pythonhosted.org/packages/51/8f/c22df1f6837784ac349057ba693f08e7b1ca7a0e06f9c33c63bc6280007b/pyinstaller-6.21.0-py3-none-musllinux_1_1_x86_64.whl", hash = "sha256:42395ec76df8e8120c36b13339d9db8cab83e316a12839ee303cc00fc941bb74", size = 753779, upload-time = "2026-06-13T14:14:29.445Z" },
+ { url = "https://files.pythonhosted.org/packages/c9/76/1ce8a27ce62ba8cf3a87c9ce6d575610f4e55d7cb0123e7512fc3f4b921a/pyinstaller-6.21.0-py3-none-win32.whl", hash = "sha256:c6b28d30d8fd99ce162ff3aab5013ed44dbfb747566b1f01b9bed7964d7c14e9", size = 1336462, upload-time = "2026-06-13T14:14:35.785Z" },
+ { url = "https://files.pythonhosted.org/packages/c1/fa/ca1d7e5257dd8566a9dfc0dfb02f8a8075eeb53d4b2d3c579f1276759042/pyinstaller-6.21.0-py3-none-win_amd64.whl", hash = "sha256:7fae06c494ce0ebfe6bd3055c0e409def884f63af2e3705d06bd431ad9237fc7", size = 1397487, upload-time = "2026-06-13T14:14:42.328Z" },
+ { url = "https://files.pythonhosted.org/packages/dc/75/21b51523ce8d96629b71311775a0a65f5f5a872124ab0de33e5c848f8bff/pyinstaller-6.21.0-py3-none-win_arm64.whl", hash = "sha256:f13c95c9c03fb567217135919f93815c305813126780b0ed6e0123cb8acaf025", size = 1346094, upload-time = "2026-06-13T14:14:48.914Z" },
+]
+
+[[package]]
+name = "pyinstaller-hooks-contrib"
+version = "2026.6"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "packaging" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/94/5b/c9fe0db5e83ee1c39b2258fa21d23b15e1a60786b6c5990ee5074ead8bb6/pyinstaller_hooks_contrib-2026.6.tar.gz", hash = "sha256:bef5002c32f4f50bd55b005da12cff64eca8783e7eaf86a06a62410164bab725", size = 173354, upload-time = "2026-06-08T22:37:16.152Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e7/31/f2d7343d8ed5f7c4678377886f6ce533e6eaaa131b252ce950114c2a7efa/pyinstaller_hooks_contrib-2026.6-py3-none-any.whl", hash = "sha256:fd13b8ac126b35361175edacd41a0d97080b75dd5f4b594ecefefff969509dd3", size = 457159, upload-time = "2026-06-08T22:37:14.722Z" },
+]
+
+[[package]]
+name = "pyproject-hooks"
+version = "1.2.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/e7/82/28175b2414effca1cdac8dc99f76d660e7a4fb0ceefa4b4ab8f5f6742925/pyproject_hooks-1.2.0.tar.gz", hash = "sha256:1e859bd5c40fae9448642dd871adf459e5e2084186e8d2c2a79a824c970da1f8", size = 19228, upload-time = "2024-09-29T09:24:13.293Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/bd/24/12818598c362d7f300f18e74db45963dbcb85150324092410c8b49405e42/pyproject_hooks-1.2.0-py3-none-any.whl", hash = "sha256:9e5c6bfa8dcc30091c74b0cf803c81fdd29d94f01992a7707bc97babb1141913", size = 10216, upload-time = "2024-09-29T09:24:11.978Z" },
+]
+
[[package]]
name = "pytest"
version = "9.0.3"
@@ -966,6 +1088,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/e1/04/e8135ebd1ad02c56ec633277529b2602ff99ff634be76cdba5744cf554fd/python_multipart-0.0.32-py3-none-any.whl", hash = "sha256:ff6d3f776f16878c894e52e107296ffc890e913c611b1a4ec6c44e2821fe2e23", size = 30042, upload-time = "2026-06-04T16:18:57.319Z" },
]
+[[package]]
+name = "pywin32-ctypes"
+version = "0.2.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/85/9f/01a1a99704853cb63f253eea009390c88e7131c67e66a0a02099a8c917cb/pywin32-ctypes-0.2.3.tar.gz", hash = "sha256:d162dc04946d704503b2edc4d55f3dba5c1d539ead017afa00142c38b9885755", size = 29471, upload-time = "2024-08-14T10:15:34.626Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/de/3d/8161f7711c017e01ac9f008dfddd9410dff3674334c233bde66e7ba65bbf/pywin32_ctypes-0.2.3-py3-none-any.whl", hash = "sha256:8a1513379d709975552d202d942d9837758905c8d01eb82b8bcc30918929e7b8", size = 30756, upload-time = "2024-08-14T10:15:33.187Z" },
+]
+
[[package]]
name = "pyyaml"
version = "6.0.3"
@@ -1061,6 +1192,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/57/c9/e69b1ff4c8b69093ef08b8919ab767af0569666865b39c30a8795d88d3c6/ruff-0.15.22-py3-none-win_arm64.whl", hash = "sha256:e1168075b72158510839f250027659cdd78476f40507dd517892304c41318661", size = 11298172, upload-time = "2026-07-16T15:14:10.51Z" },
]
+[[package]]
+name = "setuptools"
+version = "83.0.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/34/26/f5d29e25ffdb535afef2d35cdb55b325298f96debd670da4c325e08d70f4/setuptools-83.0.0.tar.gz", hash = "sha256:025bccbbf0fa05b6192bc64ae1e7b16e001fd6d6d4d5de03c97b1c1ade523bef", size = 1154254, upload-time = "2026-07-04T15:31:22.699Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/5d/40/e1e72872c6354b306daef1703549e8e83b4d43cfea356311bf722a043752/setuptools-83.0.0-py3-none-any.whl", hash = "sha256:29b23c360f22f414dc7336bb39178cc7bcbf6021ed2733cde173f09dba19abb3", size = 1008090, upload-time = "2026-07-04T15:31:20.885Z" },
+]
+
[[package]]
name = "starlette"
version = "1.3.1"
@@ -1074,6 +1214,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/ec/bb/2799cc2ede3ed41131f8975621e7213dfc7ef4acbbaadfa440f32500c370/starlette-1.3.1-py3-none-any.whl", hash = "sha256:c7372aae11c3c3f26a42df7bd626cec2f47d03483d261d369516a615a53714c6", size = 73632, upload-time = "2026-06-12T09:23:10.017Z" },
]
+[[package]]
+name = "trove-classifiers"
+version = "2026.6.1.19"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/c2/e3/7ca82ee24c82d344584abd5b8637b3bd056f2900226e8d82fc22f1184b92/trove_classifiers-2026.6.1.19.tar.gz", hash = "sha256:c5132b4b61a829d11cfbd2d72e97f20a45ed6edb95e45c5efdeb5e00836b2745", size = 17059, upload-time = "2026-06-01T19:41:34.649Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7c/a4/81502f486f01db95bc8320646a8a12511f5e556cb63d5e224d91816605c4/trove_classifiers-2026.6.1.19-py3-none-any.whl", hash = "sha256:ab4c4ec93cc4a4e7815fa759906e05e6bb3f2fbd92ea0f897288c6a43efd15b3", size = 14211, upload-time = "2026-06-01T19:41:33.434Z" },
+]
+
[[package]]
name = "truststore"
version = "0.10.4"