The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.
JavaScript
feat: improve saved-work browsing and evidence organization (#33)
OsintMeThat3fcf0d87c41e
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex ed8aef2..ed90f5c 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -82,13 +82,15 @@ jobs:include:- os: ubuntu-latestasset: azimut-linux-x86_64+ ffmpeg_target: linux-x86_64- os: windows-latestasset: azimut-windows-x86_64.exe+ ffmpeg_target: windows-x86_64- os: macos-latestasset: azimut-macos-arm64- # macos-latest is Apple Silicon. We don't ship an Intel binary: the- # last Intel runner (macos-13) is deprecated and its queue stalls- # releases. Intel Macs are covered by `pip install azimut` instead.+ ffmpeg_target: macos-arm64+ # macos-latest is Apple Silicon. Intel remains a documented Python+ # package install rather than a standalone release asset.steps:- uses: actions/checkout@v4- uses: actions/setup-node@v4@@ -106,40 +108,13 @@ jobs:run: |uv sync --frozen --no-dev --group release --no-install-projectuv 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- # runtime). One host, one arch per runner; each zip holds a single binary.+ # ffmpeg is a native program, not a Python dep. The helper pins and hashes+ # each upstream archive, then extracts only the expected tools.- name: Vendor static ffmpeg + ffprobe into the binary- shell: bash- run: |- mkdir -p packaging/vendor- if [ "${{ runner.os }}" = "Windows" ]; then- # martin-riedl.de stopped publishing Windows builds; BtbN's- # "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 --no-sync python -c "- import zipfile- zf = zipfile.ZipFile('ffmpeg.zip')- for n in zf.namelist():- tail = n.rsplit('/', 1)[-1]- if tail in ('ffmpeg.exe', 'ffprobe.exe'):- open('packaging/vendor/' + tail, 'wb').write(zf.read(n))- "- else- case "${{ runner.os }}" in- Linux) plat=linux/amd64 ;;- macOS) plat=macos/arm64 ;;- esac- 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 --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+ run: >-+ uv run --no-sync python scripts/vendor_ffmpeg.py+ "${{ matrix.ffmpeg_target }}"+ --output packaging/vendor- name: Build single-file binaryrun: uv run --no-sync pyinstaller packaging/azimut.spec --distpath dist-bin --workpath build-bin- name: Smoke-test the binarydiff --git a/.gitignore b/.gitignoreindex 8a89c8d..a9c670e 100644--- a/.gitignore+++ b/.gitignore@@ -48,6 +48,7 @@ CLAUDE.md.claude/AGENTS.md.codex/+.agents/.cheatsheet# PyInstaller local outputdiff --git a/README.md b/README.mdindex 710fe4d..f03b20b 100644--- a/README.md+++ b/README.md@@ -9,9 +9,7 @@ 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 alongto fix a point on the map.*-## v0.2.2: Login-walled downloads--> v0.2.3 is a bug-fix release: it corrects the version the v0.2.2 binary reported, which made its startup update check falsely announce an update to everyone already on v0.2.2. No feature changes.+## v0.2.4: Saved work and scalable browsing| Tool | What it does ||------|--------------|@@ -31,15 +29,18 @@ extension, and cross-platform binaries with a bundled ffmpeg.Every tool works one-shot (a scratch session, no setup) or inside a case, aplain directory holding the whole investigation.-New in v0.2.2:+New in v0.2.4:-- Downloads now handle login-walled media. The first attempt is always- cookie-less; only when a post turns out to need an account does Media offer to- borrow a signed-in browser's session or an exported `cookies.txt`. The session- is used for that download, kept 0600 in the workspace, and never leaves the- machine. Chromium on Windows can't be read, so it points you to the file route.-- The Geo Proof toolbar reflows to fit narrow screens instead of overflowing,- and remembers the color and stroke width you last drew with.+- Saved places, captures, filed screenshots and proofs are easier to find,+ preview and place on the map.+- The case sidebar and Files now support search, filters, folder browsing,+ multi-select filing and a details list.+- Media and Files use bounded SQLite queries, including complete category+ counts and search results beyond the first page.+- Inspect, Geo Proof and Geo Report use named saves. Their pickers can search+ and browse folders.+- Release binaries now fetch pinned, SHA-256-verified ffmpeg archives. Images+ above 100 MP are rejected before decode.## Install & run@@ -65,12 +66,9 @@ 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` |+| macOS (Intel, 14+) | 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 themopen:- **macOS**: right-click the file → **Open** → **Open** (Gatekeeper only@@ -80,10 +78,10 @@ open:info** → **Run anyway**.- **Linux**: mark it executable with `chmod +x azimut-linux-x86_64`.-To update, **Settings → About → Check for updates** tells you when a newer-release is out and links the download; replace the old file with the new one.-To uninstall, delete the file. Either way `~/Azimut` stays put, so your cases-open unchanged in the new version.+Azimut checks for a newer release on startup by default and links the download.+Settings can disable that check, and **Settings → About → Check for updates**+runs it manually. Replace the old binary with the new one. To uninstall, delete+the binary. Either way `~/Azimut` stays put, so cases open unchanged.The downloadable binaries bundle a static **ffmpeg** (and ffprobe), so videothumbnails, frame scans, video enhancement, and downloads that merge separate@@ -199,7 +197,7 @@ wheel + Windows/Linux/macOS binaries, attaches them to a GitHub release, andpublishes to PyPI. **Don't publish by hand.**```bash-git tag v0.2.3 && git push origin v0.2.3+git tag v0.2.4 && git push origin v0.2.4```One-time setup: register the repo as a@@ -208,17 +206,14 @@ One-time setup: register the repo as a## Principles-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.** 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.+1. No account, telemetry or automatic upload. The server binds to+ `127.0.0.1`, and Azimut never posts on your behalf.+2. A case contains the investigation's files and SQLite graph. A closed case+ folder is complete and portable; ZIP import/export is planned.3. One tab = one tool, useful in 30 seconds.-4. **Orchestrator, not replacer.** Integrate specialized services rather than- cloning them.-5. Tools emit facts; the analyst decides. No automated "magic button".-6. **Honest output.** Every artifact records how it was produced.+4. Azimut integrates specialized services instead of recreating them.+5. The analyst decides; tools do not produce automated verdicts.+6. Every artifact records how it was produced.7. Free and open source. No paid key is ever required; bring your own formore basemaps.diff --git a/bench/case_baseline.py b/bench/case_baseline.pydeleted file mode 100644index b2146e3..0000000--- a/bench/case_baseline.py+++ /dev/null@@ -1,149 +0,0 @@-#!/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/ONTOLOGY.md b/docs/ONTOLOGY.mdindex 164ca64..83ff495 100644--- a/docs/ONTOLOGY.md+++ b/docs/ONTOLOGY.md@@ -7,7 +7,8 @@**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.+a manifest schema bump and migration. The internal SQLite schema is version 4;+it adds search and media browse indexes without changing this logical model.Legend: ✅ implemented in code · 🔶 machinery exists, unused · ⬜ proposed.@@ -26,8 +27,9 @@ presents it as this logical shape:- **Links** are typed directed edges. Every save records its inputs; see §3. ✅- **Folders** are `/`-nested analyst buckets in `attrs.folder`, not semanticlinks. ✅-- Media sidecars hold kind, size, uploader, duration and thumbnail data. Entities- retain only what the graph needs for identity, links and deduplication.+- Media sidecars hold kind, size, uploader, duration and thumbnail data. A+ SQLite browse index mirrors searchable fields. Entities retain only what the+ graph needs for identity, links and deduplication.## 2. Entity@@ -43,13 +45,22 @@ presents it as this logical shape:`type` is extensible: unknown strings are stored but receive no custom renderer.`label` is editable and never defines identity.+`geo` is the country a saved point falls in, resolved once and kept:+`{state, country_code, country, region?, region_en?}` with `state` one of `ok`,+`nocoords` (no position to look up), `nocountry` (open sea) or `failed` (the+lookup did not answer — the only state a later pass retries). `country` and+`region` are the local-language names; `region_en` is a second lookup in English+and is absent when it failed or matched the native name. Continent and the+English country name are *not* stored: both are derived from `country_code` at+read time, so extending those tables repairs existing cases with no migration.+### Entity type registry| Type | State | Produced by | Key `attrs` | File-backed ||---|---|---|---|---|| `media` | ✅ | media-library | `path`, `sha256`, `source_url?` | yes (+ sidecar) |-| `capture` | ✅ | satellite | `coords`, `lat`, `lon`, `plus_code`, `zoom`, `bearing`, `path` | yes (image) |-| `place` | ✅ | satellite | `coords`, `lat`, `lon`, `plus_code`, `zoom`, `bearing`, `notes?` | no (a point) |+| `capture` | ✅ | satellite | `coords`, `lat`, `lon`, `plus_code`, `zoom`, `bearing`, `path`, `geo?` | yes (image) |+| `place` | ✅ | satellite, ingest | `coords`, `lat`, `lon`, `plus_code`, `zoom`, `bearing`, `notes?`, `geo?`, `source_url?`, `site?` | no (a point) || `proof` | ✅ | proof-composer | `spec` (json), `path` (png) | yes || `post` | ✅ | post-composer | `draft` (json) | yes || `inspect-session` | ✅ | inspect | `spec` (json) | yes |@@ -67,6 +78,11 @@ New types coming from the roadmap (declare here when built): `panorama`,Per-type attribute schemas remain open work. Today attribute keys are conventions,not a validated contract between tools.+The file-backed pointers of `proof`, `post` and `inspect-session` (`spec`,+`draft`, `path`) are not stable: the file's name follows the label, so renaming+one in its tool rewrites the pointer on the same entity. Look these up by id, or+re-read the pointer — never cache one across a save.+## 3. Link```jsonc@@ -106,6 +122,13 @@ A tool selects one of two deletion behaviours through its link type:- `derived-from` never cascades into an output. A post keeps its text when itsproof is deleted; a frame keeps its pixels when its video is deleted.+- It is also read backwards, as geography. The Saved panel counts the proofs+ hanging off each saved point through this edge, and a proof with no point of+ its own is placed at the point of every capture it composes, one hop back.+ A proof does carry its own point first, though: `coordsText` (what the analyst+ typed, in any supported format) then `coords` (what the panels gave it, frozen+ at save). That is what keeps a proof on the map once its capture is deleted —+ a tombstone records the path, the sha256 and the URL, never coordinates.- `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@@ -133,6 +156,9 @@ How it is wired (`engine/links.py`):resolves path → entity and emits the edge.- Every save restates sources through `sync`. Removing a panel removes its edge;repeated saves keep one edge per panel.+- A proof's pasted images are read as decoration, not sources: they carry no case+ path, so they file no entity and earn no edge. Only panels put a proof in a+ chain.- A missing source path produces a tombstone instead of a link.- Media derivatives are all filed through one registration point, so any futuretool producing imagery gets its chain for free. A derivative that **dedupes**diff --git a/docs/RELEASE_NOTES.md b/docs/RELEASE_NOTES.mdindex f9e94e4..fcbdf96 100644--- a/docs/RELEASE_NOTES.md+++ b/docs/RELEASE_NOTES.md@@ -1,20 +1,61 @@-# Azimut v0.2.3+# Azimut v0.2.4## OSINT toolkit at a glance-- **Sources:** import or download media, reach login-walled posts with your own browser session, record hashes and provenance, inspect frames, crops, collages, panoramas and ELA, then prepare reverse-image searches.-- **Maps:** convert coordinates, geocode places, capture attributed imagery, compare providers, rotate and measure maps, save references and review AOI grids.-- **Evidence:** organise media, places, proofs and notes in portable cases with folders, links, Markdown notebooks and PDF output.-- **Publishing:** build annotated Geo Proofs and prepare evidence-linked Geo Reports for X, Bluesky or Mastodon without posting automatically.+- **Sources:** import or download media, use an existing login when a post+ requires it, record hashes and provenance, inspect frames, crops, collages,+ panoramas and ELA, then prepare reverse-image searches.+- **Maps:** convert coordinates, geocode places, capture attributed imagery,+ compare providers, rotate and measure maps, save references and review AOI+ grids.+- **Evidence:** organise media, places, proofs and notes in portable cases with+ folders, links, Markdown notebooks and PDF output.+- **Publishing:** build annotated Geo Proofs and prepare evidence-linked Geo+ Reports for X, Bluesky or Mastodon without posting automatically.## What changed-- **Bug fix (from v0.2.2).** The v0.2.2 binary reported itself as an older version, so its startup update check wrongly announced that v0.2.2 was available to anyone already running it. Fixed here, with a release-time guard so the version can't drift again. Upgrade to stop the false prompt.-- **Gated downloads.** Downloads now get past a login wall. Public media is still fetched without any session; only when a post turns out to need an account does Media offer to borrow a signed-in browser's cookies or an exported `cookies.txt`. The session is used for that download, kept private in your workspace, and never leaves the machine. Chromium on Windows can't be read, so Azimut points you to the file route instead.-- **Responsive Geo Proof toolbar.** The proof toolbar reflows to fit narrow screens instead of overflowing, and remembers the colour and stroke width you last drew with.+- **Saved work on the map.** Places, captures and filed screenshots can be+ browsed by geography or case folder, searched in English or the local name,+ previewed and shown on the map. Proofs appear at their own coordinates or at+ the captures they use.+- **Case organisation.** The sidebar adds search, type and status filters,+ multi-select filing and a details drawer. Files adds Small, Large and List+ views with sortable columns and complete folder browsing.+- **Named work.** Inspect, Geo Proof and Geo Report name their documents in the+ header and keep that name when saved or renamed. Inspect's save dialog can+ name a batch and attach one note.+- **Faster browsing.** Media and Files now query a SQLite browse index. Search,+ folder filters and Media category counts cover the complete case instead of+ only the first 200 items. Files requests thumbnail metadata only for paths it+ can display.+- **Better pickers and proofs.** Inspect, Reverse Search, Geo Proof and Notebook+ pickers can search and browse folders. Geo Proof supports coloured panel+ frames, layer controls and pasted overlays stored with that proof.+- **Capture extension.** A map point can be saved as a place, and any page can+ be saved as a bookmark. Map captures keep their source metadata and+ attribution.+- **Case-switch fix.** Saved Satellite items and Media thumbnail state are+ cleared before a different case loads, so data from the previous case no+ longer remains until refresh.+- **Release and security hardening.** Release builds use pinned, SHA-256-checked+ ffmpeg archives and extract only the expected tools. Images above 100 MP are+ rejected before decode. SQLite schema 4 adds the media browse index and+ upgrades existing cases automatically.++The read-only GitHub release check still runs on startup by default. It can be+disabled in Settings, and offline failures remain silent.## Install or upgrade-Download the ready-to-run asset for Windows, Linux x86_64 or Apple Silicon macOS from this release and run it. Each binary includes the browser UI, `ffmpeg` and `ffprobe`; no Python or system FFmpeg is needed. Intel Macs are supported through `pipx install azimut` or `pip install azimut`.+Download the ready-to-run asset for Windows x86_64, Linux x86_64 or Apple+Silicon macOS and run it. Each binary includes the browser UI, `ffmpeg` and+`ffprobe`; no Python or system FFmpeg is needed.++Intel Macs require macOS 14 or newer and the Python package:+`pipx install azimut` or `pip install azimut`.++The binaries are unsigned. Follow the operating system prompt described in the+README on first launch.-Existing cases open in place; no manual export or import is required.+Existing cases upgrade in place. No manual export or import is required.diff --git a/docs/SPEC.md b/docs/SPEC.mdindex 961dfb8..fdc9fef 100644--- a/docs/SPEC.md+++ b/docs/SPEC.md@@ -50,8 +50,8 @@ notes.md # free-form case notes (markdown)notes/ # filed note bodies (Markdown)media/ # source + captured + extracted media, with metadata + sha256proofs/ # composed proofs: exported PNGs + editable JSON specs+ # <name>.assets/ holds images pasted into that proof onlyexports/ # post drafts, reports, shared bundles-evidence.jsonl # append-only journal (v4)inspect/ # saved Inspect session specs```@@ -88,11 +88,12 @@ proof for publication.| ✅ **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. |+| ✅ **Saved work navigation** | Groups a case's places, captures and filed screenshots by continent/country/region (labelled in English and the local language) or by My-work folder, searchable in either spelling with previews and shown on the map. |+| ✅ **Geo Proof** | Composes templated grid or free-layout panels with annotations, coloured frames and pasted overlays that stay out of the case, 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. |+| ✅ **Case sidebar** | Searches and filters the case, manages notes, suggestions, folders, multi-row filing, a details drawer and synchronized artifact deletion. || ✅ **Imagery providers** | Supports Esri, OSM, OpenTopoMap, Sentinel-2 and optional Mapbox/Google with usage controls. |-| ✅ **Capture extension** | Files user-initiated map screenshots with URL metadata, attribution and provenance. |+| ✅ **Capture extension** | Files user-initiated map screenshots with URL metadata, attribution and provenance; also saves a map's point as a place, or any page as a bookmark. || ✅ **Distribution** | Bundles the browser UI, launcher, cross-platform binaries, ffmpeg, locked builds and server hardening. |### v2 GEOINT suite (shipped as GitHub `v0.2.0+`)@@ -108,6 +109,11 @@ proof for publication.| ✅ **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. || ✅ **Gated downloads** | Fetches login-walled media by borrowing a browser session or cookies.txt, cookie-less by default and prompted only on a wall. |+| ✅ **Find at scale** | Bounded, paged loading with a shared search box and sort across the Media Library and Files, plus case-name search in the switcher. |+| ✅ **Searchable pickers** | Pickers in Inspect, Reverse Search, Geo Proof and the Notebook notes menu search past six entries and browse case folders behind the "…". |+| ✅ **Named saves** | Inspect's Save gate names each item or numbers a batch from one base name, carries a shared note, and gives the file on disk the same name; a collage keeps one name across its tab and the gate. |+| ✅ **Named documents** | Inspect, Geo Proof and Geo Report name their work in the tool header ("Inspect 1", "Proof 1", "Post 1" until renamed), save under that name in one click, and move the file when it is renamed. |+| ✅ **Proofs on the map** | A fourth position of the Saved switch places each proof by its own coordinates, then by the captures it composes; `All` marks a worked capture with a dot rather than doubling it. |---@@ -118,6 +124,22 @@ 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: still to finish (next `v0.2.x`)++| Tool | What it does |+|------|--------------|+| **Case bundle** | Exports a case to one ZIP (clean SQLite copy, keys excluded) and imports it back. |+| **Trash** | Undoes a delete and holds removed artifacts before they go for good. |+| **Import enrichment** | Queues EXIF/GPS, perceptual hash and OCR on import; results arrive as Suggestions. |+| **EXIF in Media** | Shows parsed GPS in the Media list and turns it into a place in one click. |+| **Case Board / Relations** | Browses, creates and merges entities; typed links; graph view over the schema filled since v1. |+| **Case Sheet** | The same case as a table: a row is an entity, columns are its attributes plus free ones the analyst adds, sorted, filtered and edited in place. Imports a CSV as loose rows that stay out of the graph until promoted, and exports back to CSV or GeoJSON. |+| **Camera Resection (GCP)** | Marks matching points photo↔map, then solves camera position, viewing azimuth and rough FOV (OpenCV `solvePnP`) and saves the match as evidence. |+| **Command palette** | Ctrl+K reaches a tool, a case or an artifact. |+| **Sun and local time** | Local time, sunrise/sunset and solar azimuth for a point and date, in Coordinates. |+| **Capture scale and north** | Preference-controlled scale bar, north arrow and graticule on app and extension captures. |+| **Report an issue** | Opens a pre-filled GitHub issue with version, OS and recent log lines. |+### v3: GEOINT expansion| Tool | What it does |@@ -125,59 +147,80 @@ Each version delivers one complete daily workflow. Firm ideas move here from| **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 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 to estimate possible capture times; show sun times and azimuth for a place and date; pair with weather/METAR history. |+| **Edit Provenance** | Reads a rendered video's own edit history: which source clips it was cut from, in what order, and the GPS, dates and cameras those clips still carry. |+| **Shadow Clock** | Mark a shadow to estimate possible capture times, and render the year as a day × hour heatmap of the slots that fit. |+| **Imagery Wayback** | Esri World Imagery archive as a date slider: one view across every published release, key-less. |+| **Event layers** | Date-stamped overlays that support or contradict an event: NASA FIRMS thermal hotspots, archived weather and METAR. |+| **Shot contact sheet** | Splits a video into shots (ffmpeg scene detection) and picks frames from a clickable grid of timecodes. || **OCR** | Read signs/plates (tesseract), detect script/language. || **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 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. |-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.+Edit Provenance rests on three facts about Adobe renders, kept here so the tool+can be rebuilt from the spec alone:++- A Premiere or After Effects export carries an XMP `Ingredients` array: one row+ per source asset, with its original file path, document and instance IDs,+ `From Part` (the range taken from the source) and `To Part` (where it sits in+ the render), counted in ticks of 254,016,000,000 per second.+- `Pantry` blocks embed each source asset's own XMP — GPS, capture date, camera,+ lens — and, when that asset was itself a sequence or comp, its own+ `Ingredients`, which project into render time under an assumed linear playback.+- `To Part` values may be elapsed render time, absolute display timecode, or the+ coordinates of a longer sequence the export was cut from; the origin has to be+ detected before anything is drawn.++The result is one track per source file over the render's timecode, with+GPS-tagged clips promotable to places.++Toward v3: GIF maker; curated tool links; full-text case search; clipboard+image/URL capture with provenance; EXIF/GPS import suggestions for place and+time.### 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** | Track SHA-256, timestamps, source and notes; archive with Wayback and export `evidence.jsonl`. |+| **Evidence Locker** | Track SHA-256, timestamps, source and notes; archive with Wayback; export `evidence.jsonl` under a hash-chained manifest, so any later edit to an exported file is detectable. || **Timeline Builder** | Timestamped events from mixed sources aligned on timeline + map. |-| **Report Builder** | Assemble proofs/maps/timeline/entities/notes into HTML/PDF. |+| **Report Builder** | Assemble proofs/maps/timeline/entities/notes into PDF or one self-contained HTML file with its media embedded, readable offline. |+| **Case Sync (Git)** | Push a case to a private or public Git remote, pull it back, and diff two revisions, so two analysts can work the same case. |Toward v4: dependency-aware delete (partly done);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.+extension; provenance stamp on exports (short hash, optionally visible) that+re-identifies a shared PNG in its case;+Sentinel-2 change detection with an NDVI difference over a date range; source+location pattern-of-life map and timeline; cross-case handle/coordinate/face+search; optional quota-aware X publishing.### v5: orchestration and advanced| Tool | What it does ||------|--------------|| **Search Orchestrator** | Run username/alias/email across services, analyst selects → entities. Integrations, not clones. |-| **OSM Query (Overpass)** | Form-based feature search → map, no Overpass QL. |+| **OSM Query (Overpass)** | Feature search from a form, and a described pattern ("filling station, roundabout, railway within 300 m") turned into candidates on the map; clicking a point looks it up in OSM, Wikidata and geolocated Commons photos. No Overpass QL. || **Viewshed / Line of Sight** | What terrain is visible from a point (public DEM tiles). |-| **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. |+| **Skyline Matching** | Trace a horizon in a photo, compare it against the DEM profile seen from candidate points. |+| **Vessel and Aircraft Tracks** | Historic ADS-B and AIS tracks on the map for a date, plus a watchlist that follows chosen callsigns or MMSIs. || **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** | 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). |-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.+Toward v5: real-world measurement from a resected photo and its GCP camera pose;+satellite-pass search from public TLEs.### After the MapLibre migrationPhase 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.+capture tests that verify the pixels. Phase 2 makes the map itself 3D — pitch,+public DEM terrain, extruded OSM buildings — and captures obliques with pitch and+bearing in provenance. Later work covers 3D satellite capture and user-keyed+Google Photorealistic 3D Tiles.## 7. Loose ideas@@ -192,6 +235,8 @@ stops making sense.- No cloud, accounts, hosted service, or telemetry.- No automated geolocation verdict; Azimut files facts for the analyst.- No rebuilding specialized OSINT services; Azimut orchestrates them.+- No spreadsheet engine. The Case Sheet is a view of the graph, not a workbook:+ no formulas, no cell types, no second copy of the case.- No block-evasion scraping. User session cookies are in scope; third-partydownloader 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,@@ -200,8 +245,8 @@ stops making sense.## 9. Architecture-- **Backend**: Python 3.11+, FastAPI on `localhost`; all processing (ffmpeg,- yt-dlp, gallery-dl, OpenCV, tesseract) runs server-side.+- **Backend**: Python 3.11+, FastAPI on `localhost`; current processing (ffmpeg,+ yt-dlp, gallery-dl, OpenCV) runs server-side.- **Frontend**: Svelte + Leaflet (→ MapLibre) + Konva/canvas, served by thebackend, opened in the default browser. Rail = workspaces in pipeline order,tools are tabs inside them (see [UI.md](UI.md)).@@ -211,9 +256,9 @@ stops making sense."don't show again"). Display preferences affect presentation only; artifacts keepdecimal degrees + metres on disk.- **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`.+ for Windows x86_64, Linux x86_64 and Apple Silicon macOS. Binaries bundle a+ static ffmpeg/ffprobe; pip installs still want ffmpeg on `PATH`. Intel macOS+ uses the Python package.- **Dependencies:** ranges in `pyproject.toml`, exact pins in `uv.lock`; yt-dlp+ gallery-dl unbounded on purpose; scraper self-update keeps an old binary useful.- **Storage:** per-case SQLite `case.db` is the authoritative graph (files for@@ -222,14 +267,17 @@ stops making sense.background work run through a durable, recoverable per-case job queue drained byone 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+ guard (DNS rebinding), 0600/0700 perms, hard 100 MP Pillow limit, content-hashed+ names for images pasted into a proof (no client-chosen path), token-gated+ ingest island for the extension. Accepted risks recorded here: cleartext keys overlocalhost, the hash-verified scraper updater, and tile/media URL fetches (SSRFonly matters if the localhost assumption breaks). The startup update check isthe one on-mount network call: opt-out and read-only against GitHub's releasesfeed, notes rendered as text (no HTML injection). Remote images embedded in aNotebook note contact their host whenever the preview opens; Notebook warns- about that behavior and local Case media avoids it.+ about that behavior and local Case media avoids it. User-initiated imports,+ downloads and generated files have no app quota and can fill the workspace+ filesystem; disk capacity remains the user's responsibility.## 10. Open questionsdiff --git a/docs/STORAGE_AND_PERFORMANCE.md b/docs/STORAGE_AND_PERFORMANCE.mdindex e11d1ba..a1405dd 100644--- a/docs/STORAGE_AND_PERFORMANCE.md+++ b/docs/STORAGE_AND_PERFORMANCE.md@@ -30,6 +30,13 @@ structured state (entities, links, folders, jobs). The files under `media/`,`proofs/`, `exports/`, `inspect/` and `notes/` are the source of truth for theirown content.+Under `proofs/`, `exports/` and `inspect/`, a file's stem is the name shown at the+top of its tool, slugified (`api/naming.slugify`, mirrored in `lib/naming.js`).+Renaming therefore moves the file: the save carries the slug it was bound to, and+the endpoint writes the new one, moves the proof's PNG with it, rebinds the same+entity and deletes the old file. A rename onto a name another item holds is+refused (409) — two entities pointing at one spec has no sane merge.+Every mutation used to re-read and rewrite the whole `case.json` under a per-caselock. At 10k entities that rewrote megabytes per edit and shipped the entiregraph to the browser on open. SQLite removes both ceilings: a single edit touches@@ -53,10 +60,12 @@ carry enough information to detect staleness.|---|---|---|| Case name and storage version | `case.json` | Small manifest, atomically replaced || Entities, links and folders | `case.db` | Transactional and versioned |-| Mutable titles and notes | `case.db` | Never duplicated into a writable sidecar |+| Entity labels and notes | `case.db` | Indexed for catalog search |+| Media title, notes and folder | Media sidecar | Mirrored to the graph and browse index || 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 |+| Media browse fields | `case.db` (`media_items`) | Search index mirrored from sidecars || 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 |@@ -79,9 +88,8 @@ Windows, macOS and Linux:- **`case.db` lives under the workspace root**, inside the case folder, neverbeside 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.+ (`tests/bigcase.py`) lives outside `src/azimut/`, so hatchling never packages+ it, and uses only the standard library.## The storage boundary@@ -101,7 +109,7 @@ review.## Database shape-`case.db` is at SQLite schema 3. The schema counter is independent of the JSON+`case.db` is at SQLite schema 4. The schema counter is independent of the JSON`CASE_SCHEMA`: the manifest's `azimut.storage` field selects the backend, and eachformat counts its own shape upgrades.@@ -115,7 +123,8 @@ format counts its own shape upgrades.`entities`: `id`, `type`, `label`, `attrs_json`, an indexed `folder` (denormalised from- `attrs.folder`), provenance fields and status. Unknown types and attributes stay+ `attrs.folder`), denormalised search text, provenance fields and status.+ Search covers label, type, folder and notes. Unknown types and attributes stayvalid.`links`@@ -132,15 +141,26 @@ format counts its own shape upgrades.`attempts`, `max_attempts`, `payload_json`, `error` and timestamps. See"Thumbnails and background jobs".+`media_items`+: Queryable browse metadata mirrored from each media sidecar. It indexes path,+ kind, folder, display name, size, date, source and imagery mode. The original+ files and sidecars remain the file-level records.+### Indexes and migrations-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+Indexes cover entity type/status/folder, link source/target/type and media browse+fields. Job state and a partial unique index on `(kind, job_key)` keep a keyed+job from being enqueued twice. `SqliteCase.open` upgrades an older `case.db` in placethrough `_SQLITE_MIGRATIONS`, each step in its own immediate transaction, re-readingthe 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).+newer schema is refused rather than mangled. The shipped migrations add the+indexed `folder` column (1→2), the `jobs` table (2→3), then entity search text and+the media browse index (3→4).++The schema-4 media backfill scans sidecars once on first open. Its completion+marker and index rows commit together, so an interrupted backfill retries safely.+Normal media creation, edits, thumbnail changes and deletion keep the index in+sync.Geographic, temporal and full-text projections are deferred until a query needsthem. Each projection requires its own migration and tests.@@ -185,8 +205,8 @@ endpoints:- `GET /api/cases/{id}/catalog/entities` returns `{items, next_cursor}` in stableinsertion 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+ comma-separated `type` set, `status`, `q` over label/type/folder/notes, and+ folder (`unfiled=true` or an exact path, with optional descendants). The cursor keys on `rowid`, so abackground import appending rows never shifts a page already scrolled past, and adeletion before the cursor never skips a live row.- `GET /api/cases/{id}/catalog/summary` returns `{total, by_type, by_status,@@ -208,7 +228,7 @@ the single-entity and closure cases. These helpers live inresponse.Deferred to their first consumer: date filters (a timeline filter), links-pagination (a relations/graph view), and notes/label full-text search (gated on+pagination (a relations/graph view), and ranked full-text search (gated onper-binary FTS5).## Thumbnails and background jobs@@ -254,7 +274,8 @@ content-addressed thumbnail can be shared by identical-bytes captures, so deletione media file drops the cached thumbnail only when no surviving sidecar stillpoints at it.-The media listing tags each item with a `thumb_state` (`ready`, `queued`,+The media listing and the satellite capture listing both tag 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 thatreports once and does not retry per render), a "Generating…" placeholder while@@ -263,6 +284,52 @@ queued, and a retry affordance on failure. `POSTretry) or every missing/failed one; the grid polls the listing while anything ispending, and stops on its own once nothing is.+Every picker cell shows the cached thumbnail or a placeholder, never the+original: a proof panel picker rendering full-size captures in 150px cells was+the slowest surface in the app. The proof pickers poll the listing while+anything is pending, like the grid does.++A saved proof's export is thumbnailed through the same cache: `POST+/cases/{id}/proofs` renders one from the bytes it just wrote and records it in+the spec, and `GET /cases/{id}/proofs` backfills any proof that has none (saved+before this existed, or evicted) at the cost of one hash of the export. The open+dialog falls back to the export itself when no thumbnail could be produced.+Proof thumbnails count as referenced by `repair`, which otherwise sweeps+anything no media sidecar points at.++`GET /files/{case}/{path}` serves with an ETag and answers a matching+`If-None-Match` with a 304, so reopening a picker revalidates instead of+refetching. Thumbnail URLs fold in the content hash and the generator version,+so they can never change meaning and are served `immutable` — the browser stops+asking for them at all.++The Media Library and Files browse media through `GET+/api/cases/{id}/media/page`, a bounded SQLite query with `q`, `kind`,+source-derived `category`, `folder`, `sort`, `limit` and `cursor`. It returns+`total` plus full-result kind, folder and category facets. Large cases load one+page and search without opening or sorting every sidecar. Files requests+thumbnail, kind and size metadata only for paths it can render through `POST+/api/cases/{id}/media/metadata`. The unbounded `GET /api/cases/{id}/media`+stays for consumers that genuinely need the whole index, such as composer+pickers, satellite crops and derivation traces.++The Map's Saved panel opens on `GET /api/cases/{id}/satellite/index`: one compact+row per place, capture and filed screenshot — id, kind, title, coordinates,+geography, thumbnail, provider, dates, notes, and nothing else. The tree, the+search modal and the map overlay all read that one response, so hundreds of saved+items cost tens of KB instead of every capture's full media row and full-size+image. Rows come newest first on a single normalised timestamp, and the endpoint+makes no network call. Geography rides on the entity's `attrs.geo`+(`ok`/`nocoords`/`nocountry`/`failed`); continent is never stored, it is derived+from the country code at read time (`engine/continents.py`), so correcting that+table repairs existing cases with no migration. Countries that span two+continents (Russia, Kazakhstan, Turkey) are split by the point's own+coordinates, so a Vladivostok capture files under Asia. Saving resolves the country+inline, bounded by a short timeout; `POST /api/cases/{id}/satellite/locate?limit=N`+backfills up to 25 at a time, waiting ~1.1s between lookups for Nominatim's rate+limit, and reports `remaining` so the client can loop. Progress is the stored+geography itself, which makes the pass resumable and idempotent.+## Filesystem and database consistencySQLite cannot atomically commit a filesystem rename, so file-backed operations are@@ -274,15 +341,11 @@ closed case is always complete.## Performance-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.+The deterministic large-case fixture (`tests/bigcase.py`) builds entities,+links, media, nested folders, notes, suggestions, unknown types, mixed thumbnail+states, proof/post/Inspect artifacts, missing files and tombstones. Storage and+release tests open that fixture through the SQLite migration boundary. The same+arguments produce byte-identical graph rows.Interaction budgets on the reference machine:@@ -295,20 +358,9 @@ Interaction budgets 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: 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.+These are interaction budgets, not release claims. Shared CI hardware varies,+so the automated suites enforce bounded queries, result sizes, and mounted-row+limits instead of machine-specific timings.## How it is verified@@ -319,8 +371,8 @@ reference-machine capture remains a manual release step.(SQLite-backed).- **Store specifics** (`tests/test_sqlite_backend.py`): create/open, newer-schemarefusal, 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, keyset paging, media browse search/facets, 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, backuprecoverability, a failed activation leaving the json case usable, forward-compatrefusal.@@ -329,13 +381,18 @@ reference-machine capture remains a manual release step.by generator version, drain + retry-then-fail, cancel on missing media, LRUbudget eviction, orphan/temp repair, shared-thumbnail delete safety, thebackground worker, startup recovery, and the `thumb_state` + regenerate API.+- **File serving** (`tests/test_files_api.py`): revalidation to 304, immutable+ thumbnails, and an edited original invalidating its own ETag.+- **Proof exports** (`tests/test_proofs_api.py`): a thumbnail on save, the+ listing backfilling an older proof and recording it, the fallback when none+ can be rendered, and `repair` leaving proof thumbnails alone.- **Release gate** (`tests/test_release_gate.py`): a legacy case migrates and everyworkflow answers, a closed-case folder copy opens identically, a large migratedcase opens through bounded queries, and the frozen-binary packaging constraintshold.- **Frontend** (vitest + svelte-check + the production build): first-page paging,- request cancellation on case switch, and the thumbnail placeholder/failure/retry- markup.+ complete server search, full-result media facets, request cancellation on case+ switch, scoped metadata loading and thumbnail placeholder/failure/retry markup.The backend suite runs on Python 3.11 and the three release operating systems.diff --git a/docs/UI.md b/docs/UI.mdindex e77e11e..6c8d81c 100644--- a/docs/UI.md+++ b/docs/UI.md@@ -20,10 +20,10 @@ in `frontend/src/lib/workspaces.js` and appear as tabs, never as new rail entrie| Workspace | Tools today | Future tools land here ||---|---|---|| **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 |+| **Examine** | Inspect (Selection / Frame / Collage / Analyze) | EXIF, Edit Provenance, Shot contact sheet, OCR, Image Compare, Hints, Shadow Clock, audio |+| **Map** | Satellite, Coordinates | **one map, many modes**: Compare, Imagery Wayback, Event layers, Ground Imagery, Measures, Viewshed, OSM Query, Map Board || **Compose** | Geo Proof, Geo Report, Notebook | Report Builder, GIF maker |-| *(Case)* | Sidebar | v4: Notes, Relations, Timeline; v5: Orchestrator |+| *(Case)* | Sidebar | v2: Relations, Sheet; v4: Notes, Timeline; v5: Orchestrator |Rules:@@ -37,23 +37,114 @@ Rules:## Case sidebar-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 has three zones: a fixed header, one scrolling body, and a details+drawer over both. 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 isremembered 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`.+- **Header** — the case name (its id is a tooltip), a **Notes** button opening+ `notes.md` in the Notebook, a search field, and one filter chip per entity type+ present, counted from the catalog summary. The chips wrap; past the fifth they+ fold behind `+N`, and the active one always shows.+- **Body** — one rule: no filter shows the tree, a query or a chip shows a flat+ result list. A filtered tree would have to badge folders with per-type counts+ the summary cannot give, so the modes are exclusive. Result rows carry their+ folder as meta, and clearing the filter restores the tree with the same folders+ still open. Search matches labels (plus folder and type in a case small enough+ to filter in memory), not note contents — the **Files** tab searches those.+ Browse order is **Suggestions** (tool-proposed entities to confirm or dismiss,+ a node only when non-empty), the analyst's nested folders, then the **Unfiled**+ inbox. `+ Folder` and `+ Note` sit above them.+- **Filing** — drag rows onto a folder, or drop them on Unfiled to unfile.+ Ctrl/cmd-click and shift-click select several rows first, and the drag carries+ all of them; folders are targets, never cargo. The tree scrolls itself when the+ pointer nears an edge mid-drag, since a native drag swallows the wheel.+ Unfiling does not delete data. The **Files** tab presents the same tree with+ tiles, multi-select and context actions.+- **Details** — a drawer over the sidebar, closed with the back arrow or Escape,+ so selecting a row never pushes the case out of view. It edits an artifact's+ preview, title, notes, provenance, derivation chain and folder, and provides+ open, locate and delete actions. The sidebar and Media Library modal share+ `EntityDetails.svelte`.++## Map++Saved work — places, captures and screenshots filed by the extension — lives in+one right-hand **Saved** panel, grouped by geography rather than by date. The+tree's depth follows the case: one country opens straight on its regions, a+worldwide case opens on continents. A filter and an+`All / Places / Captures | Proofs` switch stay pinned above it; a screenshot+counts as a capture. The first three positions filter, and `All` shows+everything: a proof usually stands on the capture it composes, so that capture+wears a dot rather than carrying a second mark. **Proofs** past the rule is a+mode — it swaps the panel to the proofs index (`GET /proofs/index`, read the first time+that position is opened) and hides places and captures so the two never stack.+A proof is placed by the coordinates written in its own spec — the composer's+coordinate field first, then the point its panels gave it — and only failing+that by every capture it composes, which is why deleting a capture does not+unpin the proofs built on it. A proof is filed in My work like any other+artifact, so the folder grouping works there too; **Locate** does not appear,+since a proof states or borrows its point and the pass has nothing to look up.+Items with+no country collect under **Unlocated**, where **Locate** looks them up a batch at+a time and can be stopped mid-pass. Its left edge resizes from 260 to 560 px,+capped at 40% of the window, and the width is remembered locally.++Branches read `English (native)` — `Russia (Россия)` — and search matches either+spelling. Proofs and posts keep the native name only.++Saving a place or a capture resolves its country as part of the save, so the item+appears already grouped. Offline it lands under Unlocated for a later Locate.++A globe/folder switch beside the filter regroups the same set by My-work folder:+the case's whole folder tree, empty folders included, with unfiled items under+**Unfiled**. The filter and the kind switch keep working, counts cover the whole+subtree, and the mode is remembered locally. Only there are rows draggable —+dropping one on a folder files it, dropping it on **Unfiled** unfiles it.++The `…` button beside the filter opens the same set at full width, with previews,+search across title, note, place and provider, and three sorts. It is a modal, so+it works over a fullscreen map. Folder browsing lives in the panel, not here.++Editing a place or a capture (**Edit** on any row) sets its title, note and+My-work folder in one dialog, and is the only place a new folder is created from+the map.++Map controls sit in two clusters. **Tools** (measure, grid search, reference+image) float top-left. **View** — fullscreen, OSM labels, saved work — continues+the zoom column beneath `+`/`−`, because none of them changes what you are doing,+only what you see. The saved-work layer is off by default and session-only:+places draw as outlined pins, captures and screenshots as filled ones, items at+the same spot collapse into one counted mark, and clicking any mark opens a card+with its preview, provider, dates and note. A mark whose capture carries proofs+wears a dot up-left; its card names the count and offers **Show proofs**, which+switches the panel and the layer to the proofs view. In that view the card opens+the proof in Geo Proof and lists the saved posts written from it. Two post titles+fit directly in the card; additional posts expand in place, and selecting one+opens its draft in Geo Report. Hovering a card, a tree row or a search result+lights the others.++## Geo Proof++A proof is composed of panels: case images, each carrying its source. Two things+in the composer are not panels.++**Overlays.** Ctrl+V, a drop on the canvas, or `+ Add overlay` put an image+straight into the proof. It lands in the `Overlays` section of the side column,+sits above the panels and the legend, and is moved,+resized from its corners and framed like anything else on the canvas — you can+annotate it too. It claims no source: no media is filed, no entity, no+`derived-from` edge. The file lives in `proofs/<name>.assets/` under its own+content hash, travels with a rename, and goes when the proof does. A proof needs+a panel first, since the panels are what give the document its size — moving an+overlay never resizes the export.++**Frames.** Any panel or overlay takes a coloured border, its own colour and+thickness, drawn inset so the layout does not shift. A frame is decoration: it+stays out of the legend, which is still built from annotation colours alone.## Notebookdiff --git a/extension/README.md b/extension/README.mdindex c84431a..cab0761 100644--- a/extension/README.md+++ b/extension/README.md@@ -1,31 +1,21 @@-# Azimut Capture — browser extension+# Azimut Capture browser extension-Files the map you are looking at into [Azimut](https://github.com/OsintMeThat/azimut)-as a `capture` with provenance: one screenshot per explicit click, coordinates-read from the page **URL only** (never scraped from the page), source URL +-site + timestamp always recorded, attribution burned into the image footer by-the app.+Files map captures, places and bookmarks into+[Azimut](https://github.com/OsintMeThat/azimut). Captures retain their source+URL, timestamp, parsed coordinates when available and visible attribution.-The extension is deliberately thin: it screenshots and it sends the URL —-**all URL parsing (sites, coordinates, place names, imagery dates) happens in-the Azimut app**, so when a map site changes its URL format, updating Azimut-fixes it and the extension never needs a reinstall.+The extension sends the screenshot and page URL. Azimut parses supported sites,+coordinates, place names and imagery dates, so URL-format fixes ship with the+app.-It serves two flows:+It supports three flows:-- **External map sites** — Google Maps, Google Earth (web), Bing Maps, Yandex- Maps, OpenStreetMap, Apple Maps, Zoom Earth, Copernicus Browser,- Satellites.pro, and- whatever Azimut learns to recognize later. Click the toolbar icon (or- `Alt+Shift+A`): a popup shows what Azimut parsed from the URL (correctable),- a case picker, and one button — drag the area to capture. The result- appears in the open app instantly.-- **Any other page** — no screenshot (capture is maps only), but the popup- offers to file the page as a **bookmark**: a saved link with its title and- source site, nothing downloaded. It lands in the case as a `bookmark` entity.-- **Azimut's own Google (Maps JS) basemap** — the app's Capture button asks- the extension for the tab's pixels instead of prompting for a screen share.- No pairing needed for this: the app files everything itself, same-origin.+- On a supported map site, the popup can capture a selected area or save its+ coordinates as a place.+- On another page, it can save the URL and title as a bookmark without+ downloading the page.+- On Azimut's Google basemap, the in-app Capture button requests the current+ tab image without a screen-share prompt.## Install@@ -34,11 +24,11 @@ folder directly from a repo checkout), unzip it somewhere permanent, then:- **Chrome / Edge / Brave** (Windows, macOS, Linux): open`chrome://extensions`, enable **Developer mode** (top right), click- **Load unpacked**, pick the unzipped folder. The folder must stay in place —- Chrome loads it from there on every start.+ **Load unpacked**, then pick the unzipped folder. Keep the folder in place+ because Chrome loads it there on every start.- **Firefox**: open `about:debugging#/runtime/this-firefox`, click**Load Temporary Add-on…**, pick `manifest.json` inside the unzipped folder.- Firefox drops temporary add-ons when it closes — reload it next session, or+ Firefox drops temporary add-ons when it closes. Reload it next session, oruse Firefox Developer Edition / ESR with `xpinstall.signatures.required`set to `false` in `about:config` for a permanent install.@@ -48,18 +38,19 @@ folder directly from a repo checkout), unzip it somewhere permanent, then:2. Extension options (right-click the toolbar icon → Options) → paste thetoken → **Save & test**.-The token only authorizes filing captures into your local Azimut-(`127.0.0.1`) — nothing ever leaves your machine. Rotate it from Azimut-Settings at any time; every paired extension then needs the new one.+The token allows this extension to file captures through the local Azimut+server. Rotate it in Settings to revoke existing pairings.-## Permissions, and why+## Permissions| Permission | Why ||---|---|-| `activeTab` | read the URL + screenshot the tab you pressed the button on — granted per click, per tab. This is also why the **first** capture from Azimut's own Capture button on a fresh tab asks you to click the extension icon once: browsers refuse tab screenshots (`captureVisibleTab`) until the extension has been invoked on that tab, and the alternative — the `<all_urls>` permission — would mean "read all data on all websites", which this extension will never request |-| `scripting` | inject the area-selection overlay when you choose "Select area" |-| `storage` | the backend URL, pairing token and last-used case |-| `notifications` | report the result of an area capture (the popup has closed by then) |-| `http://127.0.0.1/*`, `http://localhost/*` | talk to the local Azimut app and answer its Capture button |--No history access, no reading pages, no remote servers.+| `activeTab` | Reads the current URL and captures the tab only after you click the extension. |+| `scripting` | Shows the area-selection overlay. |+| `storage` | Stores the local app URL, pairing token and last-used case. |+| `notifications` | Reports an area capture after the popup closes. |+| `http://127.0.0.1/*`, `http://localhost/*` | Connects to the local Azimut app. |++The in-app Capture button may require one initial toolbar click for a new tab.+Browsers require that gesture before allowing a tab screenshot. The extension+does not request `<all_urls>`, history access or remote-server access.diff --git a/extension/manifest.json b/extension/manifest.jsonindex 4f04bd3..b6ac7de 100644--- a/extension/manifest.json+++ b/extension/manifest.json@@ -1,7 +1,7 @@{"manifest_version": 3,"name": "Azimut Capture",- "version": "0.2.3",+ "version": "0.2.4","description": "File into Azimut: screenshot the map you are looking at (coordinates from the URL), or save any other page as a bookmark.","permissions": ["activeTab", "scripting", "storage", "notifications"],"host_permissions": ["http://127.0.0.1/*", "http://localhost/*"],diff --git a/extension/options.html b/extension/options.htmlindex 45c5dec..a341ecc 100644--- a/extension/options.html+++ b/extension/options.html@@ -7,9 +7,8 @@<body class="options"><h1>Pair with Azimut</h1><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.+ Paste the token from <strong>Settings → Capture extension</strong> to pair+ this extension with the local app.</p><div class="row"><label for="backendUrl">Azimut URL</label>diff --git a/extension/popup.html b/extension/popup.htmlindex 34cf840..f615c32 100644--- a/extension/popup.html+++ b/extension/popup.html@@ -33,11 +33,9 @@</section><section id="state-azimut" hidden>- <p>This is Azimut. Use the app's own <strong>Capture</strong> button.</p>+ <p>Permission granted for this tab.</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 will not need to return here.+ Return to Azimut and use <strong>Capture</strong>.</p></section>@@ -61,18 +59,17 @@<input id="title" type="text" placeholder="optional" /></div><p id="coords-note" class="muted" hidden>- No coordinates were found in this URL. The capture is filed without them and can be fixed later- in Azimut's sidebar).+ No coordinates found. Enter them now or add them later in Azimut.</p>- <div class="actions">+ <div class="actions stacked"><button id="capture-area" class="primary">Select area to capture…</button>+ <button id="save-place">Save this place</button></div></section><p id="status" class="status" hidden></p><footer><a id="open-options" href="#">Extension options</a>- <span class="muted">· one screenshot per click, URL only</span></footer><script type="module" src="popup.js"></script>diff --git a/extension/popup.js b/extension/popup.jsindex c573058..ba06e31 100644--- a/extension/popup.js+++ b/extension/popup.js@@ -156,6 +156,45 @@ async function init() {const paired = await loadCases($("case"), stored);+ // Saving the point needs no pixels — only a position. It stays out of reach+ // until both coordinates are there, parsed from the URL or typed above.+ const placeBtn = $("save-place");+ const syncPlaceButton = () => {+ placeBtn.disabled =+ !paired || numOrNull("lat") === null || numOrNull("lon") === null;+ };+ for (const id of ["lat", "lon"]) $(id).addEventListener("input", syncPlaceButton);+ syncPlaceButton();++ placeBtn.addEventListener("click", async () => {+ placeBtn.disabled = true;+ const body = new FormData();+ body.append("url", tab.url);+ body.append("case_id", $("case").value);+ body.append("title", $("title").value.trim());+ for (const k of ["lat", "lon", "zoom", "bearing"]) {+ const v = numOrNull(k);+ if (v !== null) body.append(k, String(v));+ }+ body.append("extension", api.runtime.getManifest().version);+ try {+ const r = await fetch(`${stored.backendUrl}/api/ingest/place`, {+ method: "POST",+ headers: { "X-Azimut-Token": stored.token },+ body,+ });+ if (!r.ok) throw new Error((await r.json().catch(() => ({}))).detail || `HTTP ${r.status}`);+ // reuse whatever case this landed in, including a freshly minted scratch+ const saved = await r.json().catch(() => ({}));+ if (saved.case_id) api.storage.local.set({ lastCaseId: saved.case_id });+ status("Place saved.", "ok");+ setTimeout(() => window.close(), 700);+ } catch (e) {+ syncPlaceButton();+ status(`Could not save: ${e.message}`, "error");+ }+ });+$("capture-area").addEventListener("click", async () => {if (!paired) return;// half a coordinate would 422 server-side; catch it where it's fixablediff --git a/extension/ui.css b/extension/ui.cssindex 2c13e6e..126fc8a 100644--- a/extension/ui.css+++ b/extension/ui.css@@ -54,6 +54,9 @@ p { margin: 6px 0; }.row input:focus, .row select:focus { outline: 1px solid var(--accent); }.actions { display: flex; gap: 8px; margin-top: 12px; }+/* two full-width choices for the same page, stacked so neither label truncates */+.actions.stacked { flex-direction: column; }+.actions.stacked button { width: 100%; }button {padding: 6px 12px;background: var(--bg-2);diff --git a/frontend/e2e/app.fixture.js b/frontend/e2e/app.fixture.jsindex 2244735..953ff9f 100644--- a/frontend/e2e/app.fixture.js+++ b/frontend/e2e/app.fixture.js@@ -28,6 +28,10 @@ const media = [{notes: '',}];+// Saved work as the Map panel reads it (GET /satellite/index). Empty by+// default: each spec that needs saved items overrides this route itself.+const savedIndex = [];+const caseOverview = {id: CASE_ID,name: 'Browser Test',@@ -75,10 +79,18 @@ function json(route, body, status = 200) {* 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) {+export async function installAppFixture(page, options = {}) {const unexpected = [];const captures = [];const proofSaves = [];+ const fixtureSavedIndex = options.savedIndex ?? savedIndex;+ const fixtureProofIndex = options.proofIndex ?? [];+ const fixtureCases = options.cases ?? [caseOverview];+ const fixtureSavedIndexes = options.savedIndexes ?? { [CASE_ID]: fixtureSavedIndex };+ const fixtureProofIndexes = options.proofIndexes ?? { [CASE_ID]: fixtureProofIndex };+ const savedIndexDelays = options.savedIndexDelays ?? {};+ const proofIndexDelays = options.proofIndexDelays ?? {};+ const fixtureDrafts = options.drafts ?? {};await page.addInitScript((caseId) => {localStorage.setItem('azimut:lastCase', caseId);@@ -114,22 +126,54 @@ export async function installAppFixture(page) {}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`) {+ if (path === '/api/cases') {+ return json(route, fixtureCases.map((item) => ({ entity_count: 1, ...item })));+ }+ const overview = fixtureCases.find((item) => path === `/api/cases/${item.id}`);+ if (overview) return json(route, overview);+ const caseId = fixtureCases.find((item) => path.startsWith(`/api/cases/${item.id}/`))?.id;+ if (caseId && path === `/api/cases/${caseId}/satellite/index`) {+ if (savedIndexDelays[caseId]) {+ await new Promise((resolve) => setTimeout(resolve, savedIndexDelays[caseId]));+ }+ return json(route, fixtureSavedIndexes[caseId] ?? []);+ }+ if (caseId && path === `/api/cases/${caseId}/proofs/index`) {+ if (proofIndexDelays[caseId]) {+ await new Promise((resolve) => setTimeout(resolve, proofIndexDelays[caseId]));+ }+ return json(route, fixtureProofIndexes[caseId] ?? []);+ }+ if (caseId && path === `/api/cases/${caseId}/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`) {+ if (caseId && path === `/api/cases/${caseId}/catalog/entities`) {return json(route, { items: [], next_cursor: null });}+ if (caseId && path === `/api/cases/${caseId}/search-grids`) return json(route, []);+ if (path === `/api/cases/${CASE_ID}/media`) return json(route, media);+ // Two different reads: the capture shelf (pickers list it beside media) and+ // the geo index the Map panel groups. Both are needed — a picker whose+ // shelf 404s shows no panels at all.+ if (path === `/api/cases/${CASE_ID}/satellite`) return json(route, []);+ if (path === `/api/cases/${CASE_ID}/drafts`) {+ return json(route, Object.entries(fixtureDrafts).map(([name, draft]) => ({+ name,+ title: draft.title,+ updated_at: draft.updated_at,+ target: draft.state?.target,+ })));+ }+ if (path.startsWith(`/api/cases/${CASE_ID}/drafts/`)) {+ const name = path.slice(path.lastIndexOf('/') + 1);+ const draft = fixtureDrafts[name];+ return draft ? json(route, draft) : json(route, { detail: 'Draft not found' }, 404);+ }+ if (path === `/api/cases/${CASE_ID}/notes`) return json(route, { text: '' });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 });}diff --git a/frontend/e2e/proof-canvas.spec.js b/frontend/e2e/proof-canvas.spec.jsindex 61deccf..e854919 100644--- a/frontend/e2e/proof-canvas.spec.js+++ b/frontend/e2e/proof-canvas.spec.js@@ -32,7 +32,7 @@ test('a real Konva panel remains interactive after click and drag', async ({ pagawait page.mouse.move(x + 45, y + 28, { steps: 6 });await page.mouse.up();- await page.getByRole('button', { name: 'Save', exact: true }).click();+ await page.getByRole('button', { name: 'Save proof', 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);@@ -94,7 +94,7 @@ test('a picked colour becomes the default for the next drawn shape', async ({ paawait page.mouse.up();await expect(page.locator('.shape-row')).toHaveCount(2);- await page.getByRole('button', { name: 'Save', exact: true }).click();+ await page.getByRole('button', { name: 'Save proof', exact: true }).click();await expect.poll(() => fixture.proofSaves.length).toBe(1);const shapes = fixture.proofSaves[0].spec.shapes;expect(shapes[1].color).toBe('#40c4ff');@@ -128,7 +128,7 @@ test('a picked stroke width becomes the default for the next drawn shape', asyncawait page.mouse.up();await expect(page.locator('.shape-row')).toHaveCount(2);- await page.getByRole('button', { name: 'Save', exact: true }).click();+ await page.getByRole('button', { name: 'Save proof', exact: true }).click();await expect.poll(() => fixture.proofSaves.length).toBe(1);const shapes = fixture.proofSaves[0].spec.shapes;expect(shapes[1].strokeWidth).toBe(11);@@ -153,3 +153,111 @@ test('the layout overflow flyout opens and closes on outside click', async ({ paawait expect(freeBtn).toBeHidden();fixture.expectNoUnexpectedRequests();});++// A pasted image goes through the real browser path: clipboard event, Web Crypto+// hash, decode, Konva render. What must hold is that it lands as an image and not+// as a panel, and that its bytes ride along with the save exactly once.+async function pasteScreenshot(page, { via = 'paste' } = {}) {+ return page.evaluate(async (kind) => {+ const canvas = document.createElement('canvas');+ canvas.width = 400;+ canvas.height = 300;+ const ctx = canvas.getContext('2d');+ ctx.fillStyle = '#c0392b';+ ctx.fillRect(0, 0, 400, 300);+ const blob = await new Promise((resolve) => canvas.toBlob(resolve, 'image/png'));+ const transfer = new DataTransfer();+ transfer.items.add(new File([blob], 'shot.png', { type: 'image/png' }));+ if (kind === 'drop') {+ document.querySelector('.konva').dispatchEvent(+ new DragEvent('drop', { dataTransfer: transfer, bubbles: true, cancelable: true })+ );+ } else {+ window.dispatchEvent(+ new ClipboardEvent('paste', { clipboardData: transfer, bubbles: true, cancelable: true })+ );+ }+ }, via);+}++test('pastes a screenshot into the proof without filing it as a panel', async ({ page, browserName }) => {+ // Firefox drops the clipboardData of a synthetic ClipboardEvent, so only the+ // real shortcut can drive it there. The drop test below covers the same insert+ // path on both engines.+ test.skip(browserName === 'firefox', 'synthetic paste carries no clipboardData in Firefox');+ const fixture = await installAppFixture(page);+ await openProofWithPanel(page);++ await pasteScreenshot(page);+ await expect(page.locator('.paste-row')).toHaveCount(1);+ await expect(page.locator('.paste-row')).toHaveClass(/selected/); // ready to place+ await expect(page.locator('.panel-row:not(.paste-row)')).toHaveCount(1); // still one panel++ await page.getByRole('button', { name: 'Save proof', exact: true }).click();+ await expect.poll(() => fixture.proofSaves.length).toBe(1);+ const saved = fixture.proofSaves[0];++ expect(saved.spec.panels).toHaveLength(1); // the paste is not evidence+ expect(saved.spec.pastes).toHaveLength(1);+ const paste = saved.spec.pastes[0];+ expect(paste.asset).toMatch(/^[0-9a-f]{16}\.png$/); // named by its own bytes+ expect(paste.natural).toEqual([400, 300]);+ expect(paste.frame).toBeNull();+ // the pixels ride along with this save, and only this one+ expect(saved.assets.map((a) => a.name)).toEqual([paste.asset]);+ expect(saved.assets[0].data.length).toBeGreaterThan(0);+ fixture.expectNoUnexpectedRequests();+});++test('a dropped image is pasted, and its frame survives the save', async ({ page }) => {+ const fixture = await installAppFixture(page);+ await openProofWithPanel(page);++ await pasteScreenshot(page, { via: 'drop' });+ await expect(page.locator('.paste-row')).toHaveCount(1);++ // picking a border colour is what turns a frame on, on a paste or on a panel+ await page.locator('.paste-row input[aria-label="border color"]').fill('#40c4ff');+ await expect(page.locator('.paste-row input[aria-label="border thickness"]')).toBeVisible();+ await page.locator('.panel-row:not(.paste-row) input[aria-label="border color"]').fill('#69f0ae');++ await page.getByRole('button', { name: 'Save proof', exact: true }).click();+ await expect.poll(() => fixture.proofSaves.length).toBe(1);+ const { spec } = fixture.proofSaves[0];++ expect(spec.pastes[0].frame).toEqual({ color: '#40c4ff', width: 6 });+ expect(spec.panels[0].frame).toEqual({ color: '#69f0ae', width: 6 });+ fixture.expectNoUnexpectedRequests();+});++test('a pasted image hosts its own annotations and leaves with them', async ({ page }) => {+ const fixture = await installAppFixture(page);+ await openProofWithPanel(page);+ await pasteScreenshot(page, { via: 'drop' });+ await expect(page.locator('.paste-row')).toHaveCount(1);++ // the image lands centred on the view, so the centre of the canvas is over it+ const canvas = page.locator('.konva canvas').first();+ const box = await canvas.boundingBox();+ const cx = box.x + box.width / 2;+ const cy = box.y + box.height / 2;++ await page.getByTitle('Box (r)').click();+ await page.mouse.move(cx - 12, cy - 8);+ await page.mouse.down();+ await page.mouse.move(cx + 14, cy + 9, { steps: 6 });+ await page.mouse.up();+ await expect(page.locator('.shape-row')).toHaveCount(1);++ await page.getByRole('button', { name: 'Save proof', exact: true }).click();+ await expect.poll(() => fixture.proofSaves.length).toBe(1);+ const { spec } = fixture.proofSaves[0];+ // the annotation is bound to the pasted image, not to the panel behind it+ expect(spec.shapes[0].panel).toBe(spec.pastes[0].id);++ // removing the image takes its annotation with it+ await page.locator('.paste-row').getByTitle('Remove overlay').click();+ await expect(page.locator('.paste-row')).toHaveCount(0);+ await expect(page.locator('.shape-row')).toHaveCount(0);+ fixture.expectNoUnexpectedRequests();+});diff --git a/frontend/e2e/saved-linked-posts.spec.js b/frontend/e2e/saved-linked-posts.spec.jsnew file mode 100644index 0000000..e11338f--- /dev/null+++ b/frontend/e2e/saved-linked-posts.spec.js@@ -0,0 +1,125 @@+import { test, expect } from '@playwright/test';+import { CASE_ID, installAppFixture } from './app.fixture.js';++const linkedPosts = [+ { id: 'post-1', name: 'panorama-publication', title: 'Panorama publication', target: 'x' },+ { id: 'post-2', name: 'source-follow-up', title: 'Follow-up with sources', target: 'bluesky' },+ { id: 'post-3', name: 'later-note', title: 'Later note', target: 'mastodon' },+];++const point = {+ lat: 48.8584,+ lon: 2.2945,+ geo: { state: 'ok', country_code: 'fr', country: 'France' },+ continent: 'Europe',+ country_en: 'France',+};++test('shows every linked post from a proof popup and opens the selected draft', async ({ page }) => {+ const fixture = await installAppFixture(page, {+ savedIndex: [{+ id: 'capture-1',+ key: 'capture-1',+ kind: 'capture',+ title: 'Source capture',+ path: 'media/source.png',+ fetched_at: '2026-07-24T08:00:00Z',+ proofs: 1,+ ...point,+ }],+ proofIndex: [{+ id: 'proof-1',+ key: '[email protected],2.2945',+ kind: 'proof',+ name: 'panorama-proof',+ title: 'Panorama autostitch test',+ path: 'proofs/panorama-proof.png',+ fetched_at: '2026-07-24T09:00:00Z',+ posts: linkedPosts.length,+ linked_posts: linkedPosts,+ ...point,+ }],+ drafts: {+ 'later-note': {+ title: 'Later note',+ updated_at: '2026-07-24T10:00:00Z',+ state: { target: 'mastodon', tweet1: 'Later context' },+ },+ },+ });++ await page.goto('/#satellite');+ await expect(page.locator('.map')).toHaveClass(/leaflet-container/);+ await page.getByRole('button', { name: 'Proofs', exact: true }).click();+ await expect(page.getByText('Panorama autostitch test')).toBeVisible();++ await page.getByRole('button', { name: 'Show saved work on the map' }).click();+ await page.locator('.saved-mark-proof').click();++ const popup = page.locator('.saved-popup');+ await expect(popup.getByText('Linked posts · 3')).toBeVisible();+ await expect(popup.getByText('Panorama publication')).toBeVisible();+ await expect(popup.getByText('Follow-up with sources')).toBeVisible();+ await expect(popup.getByText('Later note')).toHaveCount(0);++ await popup.getByRole('button', { name: '+ 1 more' }).click();+ await expect(popup.getByText('Later note')).toBeVisible();+ await popup.getByRole('button', { name: /Later note/ }).click();++ await expect(page.getByRole('button', { name: 'Geo Report', exact: true })).toHaveClass(/active/);+ await expect(page.getByLabel('Post name')).toHaveValue('Later note');+ fixture.expectNoUnexpectedRequests();+});++test('clears capture rows before a different case index arrives', async ({ page }) => {+ const secondId = 'browser-test-b';+ const fixture = await installAppFixture(page, {+ cases: [+ { id: CASE_ID, name: 'Case A', scratch: false, folders: [] },+ { id: secondId, name: 'Case B', scratch: false, folders: [] },+ ],+ savedIndexes: {+ [CASE_ID]: [{ id: 'capture-a', key: 'capture-a', kind: 'capture', title: 'Capture A', ...point }],+ [secondId]: [{ id: 'capture-b', key: 'capture-b', kind: 'capture', title: 'Capture B', ...point }],+ },+ savedIndexDelays: { [secondId]: 1200 },+ });++ await page.goto('/#satellite');+ const savedPanel = page.locator('.captures');+ await expect(savedPanel.getByText('Capture A', { exact: true })).toBeVisible();+ await page.getByRole('button', { name: 'Show saved work on the map' }).click();+ await expect(page.locator('.saved-mark-capture')).toHaveCount(1);+ await page.getByTitle('Switch case').click();+ await page.locator('.menu .item').filter({ hasText: 'Case B' }).click();++ await expect(savedPanel.getByText('Capture A', { exact: true })).toBeHidden({ timeout: 500 });+ await expect(page.locator('.saved-mark-capture')).toBeHidden({ timeout: 500 });+ await expect(savedPanel.getByText('Capture B', { exact: true })).toBeVisible();+ fixture.expectNoUnexpectedRequests();+});++test('clears proof rows before a different case proof index arrives', async ({ page }) => {+ const secondId = 'browser-test-b';+ const fixture = await installAppFixture(page, {+ cases: [+ { id: CASE_ID, name: 'Case A', scratch: false, folders: [] },+ { id: secondId, name: 'Case B', scratch: false, folders: [] },+ ],+ proofIndexes: {+ [CASE_ID]: [{ id: 'proof-a', key: 'proof-a', kind: 'proof', name: 'proof-a', title: 'Proof A', ...point }],+ [secondId]: [{ id: 'proof-b', key: 'proof-b', kind: 'proof', name: 'proof-b', title: 'Proof B', ...point }],+ },+ proofIndexDelays: { [secondId]: 1200 },+ });++ await page.goto('/#satellite');+ await page.getByRole('button', { name: 'Proofs', exact: true }).click();+ await expect(page.getByText('Proof A')).toBeVisible();+ await page.getByTitle('Switch case').click();+ await page.locator('.menu .item').filter({ hasText: 'Case B' }).click();++ await expect(page.getByText('Proof A')).toBeHidden({ timeout: 500 });+ await expect(page.getByText('Proof B')).toBeVisible();+ fixture.expectNoUnexpectedRequests();+});diff --git a/frontend/src/App.svelte b/frontend/src/App.svelteindex e90094a..e8eb136 100644--- a/frontend/src/App.svelte+++ b/frontend/src/App.svelte@@ -125,6 +125,10 @@toast(`Bookmark saved: ${ev.title}`, 'ok', 5000);if (caseState.current?.id === ev.case_id) reloadCase();});+ onEvent('place', (ev) => {+ toast(`Place saved from ${ev.site}: ${ev.title}`, 'ok', 5000);+ if (caseState.current?.id === ev.case_id) reloadCase();+ });</script><div class="shell">diff --git a/frontend/src/app.css b/frontend/src/app.cssindex a8ce6a1..ef4f175 100644--- a/frontend/src/app.css+++ b/frontend/src/app.css@@ -261,6 +261,28 @@ a:hover {border-color: transparent;}+.btn-ok {+ background: var(--ok);+ border-color: transparent;+ color: var(--accent-text);+ font-weight: 600;+}+.btn-ok:hover:not(:disabled, .disabled) {+ background: color-mix(in srgb, var(--ok) 84%, white);+ border-color: transparent;+}++.btn-info {+ background: var(--info);+ border-color: transparent;+ color: var(--bg-1);+ font-weight: 600;+}+.btn-info:hover:not(:disabled, .disabled) {+ background: color-mix(in srgb, var(--info) 84%, white);+ border-color: transparent;+}+.btn-danger {color: var(--danger);}@@ -409,6 +431,13 @@ a:hover {font-size: var(--fs-sm);color: var(--text-3);}+/* The name of what the tool is editing, next to the tool's own title. Inspect,+ the Proof Composer and the Post Composer all name their work this way, and+ the name is the filename it saves under. */+.tool-header .title-input {+ width: min(320px, 26vw);+ font-weight: 600;+}.tool-body {flex: 1;min-height: 0;diff --git a/frontend/src/components/CaseSidebar.svelte b/frontend/src/components/CaseSidebar.svelteindex 00c7be7..327dda6 100644--- a/frontend/src/components/CaseSidebar.svelte+++ b/frontend/src/components/CaseSidebar.svelte@@ -10,49 +10,21 @@persistSidebarWidth,} from '../lib/state.svelte.js';import { DEFAULT_W } from '../lib/sidebar.js';- import { buildTree, subtreeCountFrom, flattenPaths, folderOf } from '../lib/folderTree.js';+ import { buildTree, flattenPaths } from '../lib/folderTree.js';import { buildCatalogQuery, settleCatalogSummary } from '../lib/catalog.js';- import { assignFolder as fileEntity } from '../lib/filing.js';+ import { createPagedList } from '../lib/pagedList.svelte.js';+ import { filterEntities, isFiltering, typeChips } from '../lib/sidebarSearch.js';+ import { assignFolder as fileEntity, assignFolderBatch } from '../lib/filing.js';import { createNote } from '../lib/notes.js';- import { openEntity, gotoCapture, openNotebook, ENTITY_TOOL } from '../lib/navigate.js';+ import { openEntity, openNotebook } 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',- organization: 'layers',- alias: 'user',- account: 'globe',- email: 'note',- phone: 'hash',- place: 'pin',- capture: 'satellite',- event: 'clock',- media: 'image',- proof: 'proof',- post: 'post',- domain: 'globe',- ip: 'hash',- vehicle: 'grip',- note: 'note',- 'inspect-session': 'inspect',- };-- 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- // that attr existed.- function isVideo(e) {- if (e.attrs?.kind) return e.attrs.kind === 'video';- const ext = e.attrs?.path?.split('.').pop()?.toLowerCase();- return !!ext && VIDEO_EXTS.has(ext);- }- const entityIcon = (e) => (e.type === 'media' && isVideo(e) ? 'video' : ENTITY_ICONS[e.type] ?? 'note');-- let section = $state({ notes: false, suggestions: true, mywork: true });+ import SidebarHeader from './sidebar/SidebarHeader.svelte';+ import SidebarTree from './sidebar/SidebarTree.svelte';+ import SidebarResults from './sidebar/SidebarResults.svelte';+ import DetailsDrawer from './sidebar/DetailsDrawer.svelte';// ── bounded catalog loading (docs/STORAGE_AND_PERFORMANCE.md, Step 5) ───────// The sidebar no longer holds the whole graph. It builds the folder tree from@@ -72,7 +44,6 @@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;@@ -126,8 +97,10 @@expanded = {};folderData = {};unfiledOpen = false;- addingUnder = undefined;+ suggestedOpen = false;infoEntity = null;+ query = '';+ typeFilter = null;suggestedData = emptySection();unfiledData = emptySection();}@@ -147,6 +120,46 @@untrack(() => refreshAll(id));});+ // ── search: one rule, browse or results (lib/sidebarSearch.js) ─────────────+ // No filter shows the tree; a text query or a type chip shows a flat list.+ // The list is only fetched once something is actually filtered — opening a+ // case still costs the same bounded pages it did before.+ let query = $state('');+ let typeFilter = $state(null);+ const filtering = $derived(isFiltering({ query, type: typeFilter }));+ const chips = $derived(typeChips(summary));++ const results = createPagedList({+ fetchPage: ({ query: q, cursor }) =>+ api.get(+ buildCatalogQuery(caseState.current?.id, {+ query: q,+ types: typeFilter ? [typeFilter] : null,+ limit: CATALOG_PAGE,+ cursor,+ })+ ),+ });+ // In client mode the fetched page is the whole case, so the term filters in+ // memory; in server mode the request already carries it.+ const resultRows = $derived(+ results.serverMode ? results.items : filterEntities(results.items, { query, type: typeFilter })+ );++ let resultsKey = null; // non-reactive: only the load effect reads/writes it+ $effect(() => {+ const id = caseState.current?.id;+ const rev = caseState.rev; // a filing elsewhere changes a row's folder meta+ const key = filtering && id ? `${id}|${typeFilter ?? ''}|${rev}` : null;+ if (key === resultsKey) return;+ resultsKey = key;+ if (!key) results.clear();+ else results.reload();+ });+ $effect(() => {+ results.setQuery(query);+ });+async function confirmEntity(entity) {await api.patch(`/api/cases/${caseState.current.id}/entities/${entity.id}`, {status: 'confirmed',@@ -162,22 +175,17 @@}// Clicking a row opens its owning workspace; notes share the Notebook.+ // openEntity / gotoCapture live in lib/navigate.js — the case sidebar and the+ // Details editor send an analyst to the same place.function onEntityActivate(entity) {if (entity.type === 'capture') return openInfo(entity);openEntity(entity);}- // openEntity / gotoCapture live in lib/navigate.js — the case sidebar and the- // Details editor send an analyst to the same place.-// ── My work: the analyst's own nested folder tree ('/'-separated paths) ────- let newFolder = $state(''); // top-level create input- let addingUnder = $state(undefined); // folder path currently gaining a child- let newSubName = $state('');+ let newFolderOpen = $state(false);+ let newFolder = $state('');let expanded = $state({}); // path -> bool (absent = collapsed)- 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 hoveredconst caseFolders = $derived(caseState.current?.folders ?? []);@@ -187,40 +195,32 @@const tree = $derived(buildTree([...new Set([...caseFolders, ...Object.keys(byFolder)])], []));const allFolders = $derived(flattenPaths(tree));let unfiledOpen = $state(false);+ let suggestedOpen = $state(false);- const isExpanded = (path) => expanded[path] === true;function toggle(path) {- expanded[path] = !isExpanded(path);+ expanded[path] = expanded[path] !== true;if (expanded[path]) loadFolder(path);}- function focus(node) { node.focus(); }+ function focusInput(node) { node.focus(); }- async function createFolder(fullName) {- const name = (fullName ?? newFolder).trim();- if (!name) return;- if (fullName == null) newFolder = '';+ async function createFolder(name) {+ const clean = (name ?? '').trim();+ if (!clean) return;try {- await api.post(`/api/cases/${caseState.current.id}/folders`, { name });+ await api.post(`/api/cases/${caseState.current.id}/folders`, { name: clean });let acc = '';- for (const seg of name.split('/')) { acc = acc ? `${acc}/${seg}` : seg; expanded[acc] = true; }+ for (const seg of clean.split('/')) { acc = acc ? `${acc}/${seg}` : seg; expanded[acc] = true; }await reloadCase();} catch (e) {toast(e.message, 'danger');}}- function startAddSub(path) {- addingUnder = path;- newSubName = '';- expanded[path] = true;- }- async function submitAddSub() {- const name = newSubName.trim();- const parent = addingUnder;- addingUnder = undefined;- newSubName = '';- if (!name || parent === undefined) return;- await createFolder(parent ? `${parent}/${name}` : name);+ function submitNewFolder() {+ const name = newFolder;+ newFolder = '';+ newFolderOpen = false;+ createFolder(name);}// File (or unfile, with folder='') an entity into a My-work folder, then@@ -231,20 +231,54 @@await reloadCase();}- // drag & drop wiring- function onDragStart(ev, entity) {- dragEntityId = entity.id;- dragEntity = entity;- ev.dataTransfer.effectAllowed = 'move';- ev.dataTransfer.setData('text/plain', entity.id);+ // A drop carries whatever was selected — one row, or a ctrl/shift-picked run.+ // Filed in order, then one refresh for the batch.+ async function onFileDrop(entities, folder) {+ try {+ await assignFolderBatch(caseState.current.id, entities, folder);+ await reloadCase();+ if (entities.length > 1)+ toast(folder ? `Filed ${entities.length} items in ${folder}` : `Unfiled ${entities.length} items`, 'ok', 1600);+ } catch (e) {+ toast(e.message, 'danger');+ }}- function onDropFolder(ev, folder) {++ // ── scrolling while a drag is in flight ───────────────────────────────────+ // A native drag swallows the wheel in Chromium, so the tree scrolls itself+ // when the pointer nears an edge. Firefox does deliver the wheel, and the+ // handler below uses it when it arrives.+ let bodyEl = $state(null);+ let dragActive = $state(false);+ const EDGE = 44;+ const EDGE_SPEED = 12;+ let edgeDir = 0;+ let edgeRaf = 0;++ function stepEdgeScroll() {+ if (!edgeDir || !bodyEl) { edgeRaf = 0; return; }+ bodyEl.scrollTop += edgeDir * EDGE_SPEED;+ edgeRaf = requestAnimationFrame(stepEdgeScroll);+ }+ function setEdgeScroll(dir) {+ edgeDir = dir;+ if (dir && !edgeRaf) edgeRaf = requestAnimationFrame(stepEdgeScroll);+ }+ function onBodyDragOver(ev) {+ if (!bodyEl) return;+ const box = bodyEl.getBoundingClientRect();+ if (ev.clientY < box.top + EDGE) setEdgeScroll(-1);+ else if (ev.clientY > box.bottom - EDGE) setEdgeScroll(1);+ else setEdgeScroll(0);+ }+ function onBodyWheel(ev) {+ if (!dragActive || !bodyEl) return; // otherwise the browser scrolls it itselfev.preventDefault();- dragOverFolder = undefined;- const entity = dragEntity;- dragEntityId = null;- dragEntity = null;- if (entity) assignFolder(entity, folder).catch((e) => toast(e.message, 'danger'));+ bodyEl.scrollTop += ev.deltaY;+ }+ function onDragActive(active) {+ dragActive = active;+ if (!active) setEdgeScroll(0);}// ── confirmation dialog (replaces browser confirm()) ──────────────────────@@ -301,27 +335,28 @@};}- // ── details panel (docs/UI.md §4) ─────────────────────────────────────────+ // ── details drawer (docs/UI.md §Case sidebar) ─────────────────────────────// The editor body lives in EntityDetails.svelte (shared with the Media- // Library modal). The sidebar only tracks which entity is selected and- // scrolls it into view.+ // Library modal). It opens over the sidebar instead of growing under the+ // tree, so selecting a row never pushes the case out of the viewport.let infoEntity = $state(null);- let detailsEl = $state(null);+ let returnFocusEl = null;function openInfo(entity) {+ returnFocusEl = document.activeElement;infoEntity = entity;- requestAnimationFrame(() => detailsEl?.scrollIntoView({ behavior: 'smooth', block: 'start' }));+ }++ function closeInfo() {+ infoEntity = null;+ returnFocusEl?.focus?.();+ returnFocusEl = null;}// ── note entities ─────────────────────────────────────────────────────────- let noteModal = $state(null);- // shape: { entity: obj|null, title: string, folder: string, content: string }+ let noteModal = $state(null); // { title, folder }let noteModalSaving = $state(false);- function openNewNote() {- noteModal = { title: '', folder: '' };- }-async function saveNote() {if (!noteModal) return;const { title, folder } = noteModal;@@ -380,7 +415,10 @@$effect(() => {const onWindowResize = () => setSidebarWidth(uiState.sidebarW);window.addEventListener('resize', onWindowResize);- return () => window.removeEventListener('resize', onWindowResize);+ return () => {+ window.removeEventListener('resize', onWindowResize);+ cancelAnimationFrame(edgeRaf);+ };});</script>@@ -404,295 +442,105 @@<p>Tools work without one. Create a case to keep the investigation together.</p></div>{:else}- <div class="case-head">- <h3>{caseState.current.name}</h3>- <span class="path mono">{caseState.current.id}</span>- </div>-- <div class="sections">-- <!-- 1 · Case Notes (single notes.md) -->- <button class="section-head" onclick={() => openNotebook()}>- <Icon name="note" size={13} />- <span>Case Notes</span>- <span class="open-note">Open</span>- </button>-- <!-- 2 · Suggestions (tool-suggested entities: confirm or dismiss) -->- {#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">{suggestedCount}</span>- </button>- {#if section.suggestions}- {#each suggestedData.items as e (e.id)}- <div class="entity suggested">- <Icon name={entityIcon(e)} size={14} />- <div class="e-body">- <span class="e-label">{e.label}</span>- <span class="e-meta">{e.type} · {e.provenance?.by}</span>- </div>- <button class="btn btn-ghost btn-sm" title="Confirm" onclick={() => confirmEntity(e)}>- <Icon name="check" size={13} />- </button>- <button class="btn btn-ghost btn-sm" title="Dismiss" onclick={() => dismissSuggestion(e)}>- <Icon name="x" size={13} />- </button>- </div>- {/each}- {#if !suggestedData.done}- <button class="more" onclick={() => loadSuggested(true)} disabled={suggestedData.loading}>- Show more- </button>- {/if}- {/if}- {/if}+ <SidebarHeader+ caseName={caseState.current.name}+ caseId={caseState.current.id}+ bind:query+ type={typeFilter}+ {chips}+ total={summary?.total ?? 0}+ resultCount={filtering ? resultRows.length : null}+ onnotes={() => openNotebook()}+ onselecttype={(t) => (typeFilter = t)}+ />- <!-- 3 · My work (your own folders; file items from their details panel) -->- <div class="section-head-row">- <button class="section-head" onclick={() => (section.mywork = !section.mywork)}>- <Icon name={section.mywork ? 'chevronDown' : 'chevronRight'} size={13} />- <span>My work</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} />- </button>- </div>-- {#if section.mywork}- <!-- create a top-level folder -->- <form class="new-folder" onsubmit={(e) => { e.preventDefault(); createFolder(); }}>- <input class="input" placeholder="New folder…" bind:value={newFolder} />- <button class="btn btn-sm" type="submit" title="Create folder" disabled={!newFolder.trim()}>- <Icon name="plus" size={13} />+ <!-- the drag handlers here only auto-scroll; the drop targets are the+ folder rows inside, which carry their own roles -->+ <!-- svelte-ignore a11y_no_static_element_interactions -->+ <div+ class="body"+ bind:this={bodyEl}+ ondragover={onBodyDragOver}+ ondragleave={() => setEdgeScroll(0)}+ ondrop={() => setEdgeScroll(0)}+ onwheel={onBodyWheel}+ >+ {#if filtering}+ <SidebarResults+ rows={resultRows}+ caseId={caseState.current.id}+ loading={results.loading}+ hasMore={results.serverMode && results.hasMore}+ onmore={() => results.loadMore()}+ onactivate={onEntityActivate}+ oninfo={openInfo}+ onunfile={askRemoveFromMyWork}+ />+ {:else}+ <div class="actions">+ <button class="act-btn" onclick={() => (newFolderOpen = !newFolderOpen)}>+ <Icon name="plus" size={12} /><Icon name="folder" size={13} /><span>Folder</span>+ </button>+ <button class="act-btn" onclick={() => (noteModal = { title: '', folder: '' })}>+ <Icon name="plus" size={12} /><Icon name="note" size={13} /><span>Note</span></button>- </form>-- <div class="tree">- {#each tree as node (node.path)}- {@render folderNode(node, 0)}- {/each}-- {#if unfiledData.items.length > 0}- <div- class="frow"- role="button"- tabindex="0"- onclick={() => (unfiledOpen = !unfiledOpen)}- onkeydown={(e) => e.key === 'Enter' && (unfiledOpen = !unfiledOpen)}- >- <Icon name={unfiledOpen ? 'chevronDown' : 'chevronRight'} size={12} />- <Icon name="layers" size={13} />- <span class="fname">Unfiled</span>- <span class="fcount">{unfiledData.items.length}{unfiledData.done ? '' : '+'}</span>- </div>- {#if unfiledOpen}- {#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 && unfiledData.items.length === 0}- <div class="none">- Everything you save lands here; create folders to organize it.- </div>- {/if}</div>- {/if}--- <!-- 4 · Details (selection editor — docs/UI.md §4; shared body) -->- {#if infoEntity}- <div bind:this={detailsEl}>- <div class="section-head-row">- <div class="section-head static">- <Icon name="note" size={13} />- <span>Details</span>- </div>- <button class="btn btn-ghost btn-sm" title="Close details" onclick={() => (infoEntity = null)}>- <Icon name="x" size={13} />- </button>- </div>- <div class="details">- <EntityDetails- entityId={infoEntity.id}- onclose={() => (infoEntity = null)}- ondeleted={() => (infoEntity = null)}+ {#if newFolderOpen}+ <form class="new-folder" onsubmit={(e) => { e.preventDefault(); submitNewFolder(); }}>+ <input+ class="input"+ placeholder="New folder…"+ bind:value={newFolder}+ use:focusInput+ onkeydown={(e) => e.key === 'Escape' && (newFolderOpen = false)}/>- </div>- </div>- {/if}-- </div>- {/if}-</aside>+ <button class="btn btn-sm" type="submit" title="Create folder" disabled={!newFolder.trim()}>+ <Icon name="plus" size={13} />+ </button>+ </form>+ {/if}-<!-- one folder node + its subtree (recursive) -->-{#snippet folderNode(node, depth)}- <div- class="frow"- class:dropping={dragOverFolder === node.path}- style="padding-left: {8 + depth * 14}px"- role="button"- tabindex="0"- ondragover={(e) => { e.preventDefault(); dragOverFolder = node.path; }}- ondragleave={() => (dragOverFolder = undefined)}- ondrop={(e) => onDropFolder(e, node.path)}- onclick={() => toggle(node.path)}- onkeydown={(e) => e.key === 'Enter' && toggle(node.path)}- >- <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">{subtreeCountFrom(node, byFolder)}</span>- <span- class="fact"- role="button"- tabindex="0"- title="Add subfolder"- onclick={(e) => { e.stopPropagation(); startAddSub(node.path); }}- onkeydown={(e) => e.key === 'Enter' && (e.stopPropagation(), startAddSub(node.path))}- >- <Icon name="plus" size={12} />- </span>- <span- class="fact fdel"- role="button"- tabindex="0"- title="Remove folder"- onclick={(e) => { e.stopPropagation(); askDeleteFolder(node.path); }}- onkeydown={(e) => e.key === 'Enter' && (e.stopPropagation(), askDeleteFolder(node.path))}- >- <Icon name="folderMinus" size={12} />- </span>- </div>- {#if isExpanded(node.path)}- {#if addingUnder === node.path}- <form- class="new-folder sub"- style="padding-left: {8 + (depth + 1) * 14}px"- onsubmit={(e) => { e.preventDefault(); submitAddSub(); }}- >- <input- class="input"- placeholder="Subfolder…"- bind:value={newSubName}- use:focus- onkeydown={(e) => e.key === 'Escape' && (addingUnder = undefined)}+ <SidebarTree+ {tree}+ {byFolder}+ {expanded}+ {folderData}+ unfiled={unfiledData}+ {unfiledOpen}+ suggested={suggestedData}+ {suggestedCount}+ {suggestedOpen}+ caseId={caseState.current.id}+ ontoggle={toggle}+ onmorefolder={(path) => loadFolder(path, true)}+ ontoggleunfiled={() => (unfiledOpen = !unfiledOpen)}+ onmoreunfiled={() => loadUnfiled(true)}+ ontogglesuggested={() => (suggestedOpen = !suggestedOpen)}+ onmoresuggested={() => loadSuggested(true)}+ oncreatefolder={createFolder}+ onremovefolder={askDeleteFolder}+ onfile={onFileDrop}+ onactivate={onEntityActivate}+ oninfo={openInfo}+ onunfile={askRemoveFromMyWork}+ onconfirm={confirmEntity}+ ondismiss={dismissSuggestion}+ ondragactive={onDragActive}/>- <button class="btn btn-sm" type="submit" title="Create" disabled={!newSubName.trim()}>- <Icon name="plus" size={13} />- </button>- </form>- {/if}- {#each node.children as child (child.path)}- {@render folderNode(child, 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}- class:dragging={dragEntityId === e.id}- style="padding-left: {8 + depth * 14}px"- draggable="true"- ondragstart={(ev) => onDragStart(ev, e)}- ondragend={() => { dragEntityId = null; dragEntity = null; dragOverFolder = undefined; }}- onclick={() => onEntityActivate(e)}- role={isClickable ? 'button' : undefined}- tabindex={isClickable ? 0 : undefined}- onkeydown={(ev) => ev.key === 'Enter' && onEntityActivate(e)}- >- <Icon name="grip" size={13} />- <Icon name={entityIcon(e)} size={14} />- <div class="e-body">- <span class="e-label">{e.label}</span>- <span class="e-meta">{e.type}</span></div>- {#if e.type === 'capture' && e.attrs?.lat != null}- <button- class="btn btn-ghost btn-sm act"- title="Go to these coordinates on the map"- onclick={(ev) => { ev.stopPropagation(); gotoCapture(e); }}- >- <Icon name="crosshair" size={13} />- </button>- {/if}- {#if e.type === 'media' && e.attrs?.path}- <a- class="btn btn-ghost btn-sm act"- title="Open in new tab"- href={`/files/${caseState.current.id}/${e.attrs.path}`}- target="_blank"- rel="noreferrer"- onclick={(ev) => ev.stopPropagation()}- >- <Icon name="external" size={13} />- </a>- {/if}- <button- class="btn btn-ghost btn-sm act"- title="Info"- onclick={(ev) => { ev.stopPropagation(); openInfo(e); }}- >- <Icon name="note" size={13} />- </button>- {#if folderOf(e)}- <button- class="btn btn-ghost btn-sm act del"- title="Unfile from this folder"- onclick={(ev) => { ev.stopPropagation(); askRemoveFromMyWork(e); }}- >- <Icon name="folderMinus" size={13} />- </button>++ {#if infoEntity}+ <DetailsDrawer entity={infoEntity} onclose={closeInfo} ondeleted={closeInfo} />{/if}- </div>-{/snippet}+ {/if}+</aside>-<!-- Note edit / create modal -->+<!-- Note create modal -->{#if noteModal}- <Modal- title="New note"- onclose={() => (noteModal = null)}- width="580px"- >+ <Modal title="New note" onclose={() => (noteModal = null)} width="580px"><label class="modal-label" for="note-title">Title</label>- <input- id="note-title"- class="input"- placeholder="Note title…"- bind:value={noteModal.title}- />+ <input id="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={allFolders} emptyLabel="My work (root)" />@@ -707,7 +555,6 @@</Modal>{/if}-<!-- Confirmation dialog (remove from My work / remove folder) -->{#if confirmState}<ConfirmDialog@@ -758,130 +605,23 @@.sidebar.resizing {user-select: none;}- .case-head {- padding: 16px 16px 12px;- border-bottom: 1px solid var(--border);- }- .case-head h3 {- font-size: var(--fs-md);- font-weight: 700;- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;- }- .path { font-size: var(--fs-xs); color: var(--text-3); }- .sections { flex: 1; overflow-y: auto; padding: 8px; }- .section-head {- display: flex;- align-items: center;- gap: 6px;- width: 100%;- padding: 8px 8px 6px;- font-size: var(--fs-xs);- font-weight: 700;- text-transform: uppercase;- letter-spacing: 0.07em;- color: var(--text-2);- }- .section-head:hover { color: var(--text-1); }- .section-head-row { display: flex; align-items: center; }- .section-head-row .section-head { flex: 1; }- .new-note-btn {- color: var(--text-3);- padding: 4px 6px;- margin-right: 4px;- display: flex;- 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; }- /* tool group header (Saved work) */- /* folder tree */- .new-folder { display: flex; gap: 6px; padding: 2px 8px 8px; }- .new-folder.sub { padding: 2px 8px 4px; }- .new-folder .input { flex: 1; font-size: var(--fs-xs); }- .tree { display: flex; flex-direction: column; gap: 1px; padding: 0 4px 4px; }- .frow {+ /* one scroll region: the header stays put, the drawer covers this */+ .body { flex: 1; min-height: 0; overflow-y: auto; padding: 6px 4px; }+ .actions { display: flex; gap: 4px; padding: 2px 8px 6px; }+ .act-btn {display: flex;align-items: center;- gap: 7px;- width: 100%;- padding: 6px 8px;+ gap: 3px;+ padding: 3px 8px;border-radius: var(--r-sm);- color: var(--text-2);- font-size: var(--fs-sm);- border: 1px solid transparent;- cursor: pointer;- text-align: left;- }- .frow:hover { background: var(--bg-2); }- .frow.dropping { border-color: var(--accent); background: var(--accent-soft); }- .frow > :global(svg:first-child) { color: var(--text-3); flex-shrink: 0; }- .fname { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }- .fcount { color: var(--text-3); font-size: var(--fs-xs); font-weight: 600; }- .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); }- .more {- align-self: flex-start;- margin: 2px 8px 6px;- padding: 3px 10px;+ color: var(--text-3);font-size: var(--fs-xs);font-weight: 600;- color: var(--text-2);- background: var(--bg-2);- border: 1px solid var(--border);- border-radius: var(--r-sm);cursor: pointer;}- .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 {- display: flex;- align-items: center;- gap: 7px;- padding: 6px 8px;- border-radius: var(--r-sm);- color: var(--text-2);- }- .entity:hover { background: var(--bg-2); }- .entity.clickable { cursor: pointer; }- .entity.dragging { opacity: 0.5; }- .entity > :global(svg:first-child) { color: var(--text-3); cursor: grab; flex-shrink: 0; }- .entity.suggested {- background: var(--accent-soft);- border: 1px dashed var(--accent);- margin-bottom: 4px;- }- .e-body { flex: 1; min-width: 0; display: flex; flex-direction: column; }- .e-label {- font-size: var(--fs-sm);- color: var(--text-1);- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;- }- .e-meta {- display: flex;- align-items: center;- gap: 3px;- font-size: var(--fs-xs);- color: var(--text-3);- }- .act { opacity: 0; flex-shrink: 0; }- .entity:hover .act { opacity: 1; }- .del:hover { color: var(--danger, #e55); }- .none { font-size: var(--fs-xs); color: var(--text-3); padding: 4px 8px 12px; line-height: 1.45; }- /* note modal */+ .act-btn:hover { color: var(--text-1); background: var(--bg-2); }+ .new-folder { display: flex; gap: 6px; padding: 2px 8px 8px; }+ .new-folder .input { flex: 1; font-size: var(--fs-xs); }.modal-label { display: block; font-size: var(--fs-xs); color: var(--text-3); margin: 8px 0 4px; }- .section-head.static { cursor: default; }- .details {- padding: 4px 8px 10px;- border-bottom: 1px solid var(--border);- font-size: var(--fs-sm);- }.modal-row { display: flex; align-items: center; gap: 8px; margin-top: 14px; }</style>diff --git a/frontend/src/components/CaseSidebar.test.js b/frontend/src/components/CaseSidebar.test.jsnew file mode 100644index 0000000..f909b32--- /dev/null+++ b/frontend/src/components/CaseSidebar.test.js@@ -0,0 +1,202 @@+import { describe, expect, it } from 'vitest';+import { readFileSync } from 'node:fs';++const read = (name) => readFileSync(new URL(name, import.meta.url), 'utf8');+const shell = read('./CaseSidebar.svelte');+const header = read('./sidebar/SidebarHeader.svelte');+const tree = read('./sidebar/SidebarTree.svelte');+const results = read('./sidebar/SidebarResults.svelte');+const row = read('./sidebar/EntityRow.svelte');+const drawer = read('./sidebar/DetailsDrawer.svelte');++describe('sidebar shell', () => {+ it('is three zones over five units, not one component', () => {+ for (const unit of [+ 'SidebarHeader',+ 'SidebarTree',+ 'SidebarResults',+ 'DetailsDrawer',+ ]) {+ expect(shell).toContain(`import ${unit} from './sidebar/${unit}.svelte'`);+ }+ // the header never scrolls; the body is the one scroll region+ expect(shell).toContain('.body { flex: 1; min-height: 0; overflow-y: auto;');+ });++ it('builds the tree from folders plus summary keys, with no entities attached', () => {+ expect(shell).toContain(+ 'buildTree([...new Set([...caseFolders, ...Object.keys(byFolder)])], [])'+ );+ });++ it('keeps bounded per-section loading and the stale-response guard', () => {+ expect(shell).toContain('const CATALOG_PAGE = 200');+ expect(shell).toContain('if (mySeq !== seq) return;');+ expect(shell).toContain("loadSection(folderData[path], { status: 'confirmed', folder: path }");+ });++ it('resets every section, the filter and the drawer on a case change', () => {+ const reset = shell.slice(shell.indexOf('if (id !== loadedCaseId)'), shell.indexOf('if (!id) {'));+ for (const line of [+ 'summary = null',+ 'expanded = {}',+ 'folderData = {}',+ 'infoEntity = null',+ "query = ''",+ 'typeFilter = null',+ 'suggestedData = emptySection()',+ 'unfiledData = emptySection()',+ ]) {+ expect(reset).toContain(line);+ }+ });+});++describe('browse vs. results', () => {+ it('shows the tree until something is filtered, then a flat list', () => {+ expect(shell).toContain('const filtering = $derived(isFiltering({ query, type: typeFilter }))');+ expect(shell).toContain('{#if filtering}');+ expect(shell).toContain('<SidebarResults');+ expect(shell).toContain('{:else}');+ expect(shell).toContain('<SidebarTree');+ });++ it('reuses the shared paged list rather than a second search primitive', () => {+ expect(shell).toContain("import { createPagedList } from '../lib/pagedList.svelte.js'");+ expect(shell).toContain('buildCatalogQuery(caseState.current?.id, {');+ expect(shell).toContain('types: typeFilter ? [typeFilter] : null');+ expect(shell).toContain('results.setQuery(query)');+ expect(shell).toContain('results.loadMore()');+ });++ it('fetches the result page only while a filter is active', () => {+ expect(shell).toContain('const key = filtering && id ? `${id}|${typeFilter ?? \'\'}|${rev}` : null');+ expect(shell).toContain('if (!key) results.clear();');+ expect(shell).toContain('else results.reload();');+ });++ it('filters in memory in client mode and trusts the server otherwise', () => {+ expect(shell).toContain(+ 'results.serverMode ? results.items : filterEntities(results.items, { query, type: typeFilter })'+ );+ });++ it('never collapses what the analyst opened: `expanded` is untouched by a search', () => {+ // the only writes are the declaration, the case reset, a toggle and a create+ const writes = shell.match(/expanded(\[[^\]]+\])? =/g) ?? [];+ expect(writes).toHaveLength(4);+ });++ it('says so plainly when nothing matches', () => {+ expect(results).toContain('No match in this case.');+ });+});++describe('header', () => {+ it('demotes the case id to a tooltip and gives search the full width', () => {+ expect(header).toContain('<h3 title={caseId}>{caseName}</h3>');+ expect(header).toContain('width="100%"');+ expect(header).toContain("import SearchInput from '../SearchInput.svelte'");+ });++ it('filters from the type chips, and All clears the filter', () => {+ expect(header).toContain('onclick={() => onselecttype(null)}');+ expect(header).toContain('onselecttype(type === chip.type ? null : chip.type)');+ });++ it('wraps the chips and hides the tail behind +N rather than off the edge', () => {+ expect(header).toContain('flex-wrap: wrap');+ expect(header).toContain('const VISIBLE_CHIPS = 5');+ expect(header).toContain('{#each shownChips as chip (chip.type)}');+ expect(header).toContain('+{hiddenChips}');+ // the active chip stays visible even when it sits past the cut+ expect(header).toContain('active && !head.includes(active) ? [...head, active] : head');+ });+});++describe('tree', () => {+ it('renders Suggestions as a node in one grammar, only when it has rows', () => {+ expect(tree).toContain('{#if suggestedCount > 0}');+ const node = tree.slice(tree.indexOf('{#if suggestedCount > 0}'), tree.indexOf('{#each tree as node'));+ expect(node).toContain('class="frow"');+ expect(node).toContain('<span class="fname">Suggestions</span>');+ });++ it('files the dragged rows into the folder they were dropped on', () => {+ expect(tree).toContain('ondrop={(e) => onDropFolder(e, node.path)}');+ expect(tree).toContain('onfile(rows, folder);');+ // dropping on Unfiled clears the filing instead+ expect(tree).toContain("ondrop={(e) => onDropFolder(e, '')}");+ expect(shell).toContain('assignFolderBatch(caseState.current.id, entities, folder)');+ });++ it('multi-selects entity rows only, and drags the whole selection', () => {+ expect(tree).toContain("import { dragPayload, rangeSelected, toggleSelected } from '../../lib/rowSelect.js'");+ expect(tree).toContain('if (ev?.shiftKey)');+ expect(tree).toContain('if (ev?.ctrlKey || ev?.metaKey)');+ expect(tree).toContain('dragRows = dragPayload(visibleRows, selected, entity)');+ // folder rows carry no selection state — they are drop targets+ expect(tree).not.toContain('selectedFolder');+ });++ it('drops a selection that scrolled out of the tree', () => {+ expect(tree).toContain('const live = new Set(visibleRows.map((r) => r.id))');+ });++ it('scrolls the tree while a drag is in flight', () => {+ // Chromium withholds the wheel during a native drag, so the edges scroll+ expect(shell).toContain('function onBodyDragOver(ev)');+ expect(shell).toContain('setEdgeScroll(-1)');+ expect(shell).toContain('setEdgeScroll(1)');+ expect(shell).toContain('requestAnimationFrame(stepEdgeScroll)');+ expect(shell).toContain('cancelAnimationFrame(edgeRaf)');+ // and the wheel is used where it is delivered+ expect(shell).toContain('function onBodyWheel(ev)');+ expect(shell).toContain('if (!dragActive || !bodyEl) return;');+ });++ it('pages a folder in on expand instead of listing it whole', () => {+ expect(tree).toContain('onclick={() => onmorefolder(node.path)}');+ expect(tree).toContain('{#if !sec.done}');+ });+});++describe('entity row', () => {+ it('is one component shared by both bodies', () => {+ expect(tree).toContain("import EntityRow from './EntityRow.svelte'");+ expect(results).toContain("import EntityRow from './EntityRow.svelte'");+ expect(results).toContain('meta={resultMeta(e)}');+ });++ it('keeps the tool actions, and swaps them for triage on a suggestion', () => {+ expect(row).toContain('title="Go to these coordinates on the map"');+ expect(row).toContain('title="Open in new tab"');+ expect(row).toContain('title="Unfile from this folder"');+ expect(row).toContain('title="Confirm"');+ expect(row).toContain('title="Dismiss"');+ });+});++describe('details drawer', () => {+ it('covers the sidebar instead of growing under the tree', () => {+ expect(drawer).toContain('position: absolute;');+ expect(drawer).toContain('inset: 0;');+ expect(shell).not.toContain('scrollIntoView');+ expect(shell).not.toContain('detailsEl');+ });++ it('closes on Escape, on the back arrow and on delete', () => {+ expect(drawer).toContain("onkeydown={(e) => e.key === 'Escape' && onclose()}");+ expect(drawer).toContain('title="Back to the case"');+ expect(shell).toContain('<DetailsDrawer entity={infoEntity} onclose={closeInfo} ondeleted={closeInfo} />');+ });++ it('hands focus back to the row it was opened from', () => {+ expect(shell).toContain('returnFocusEl = document.activeElement');+ expect(shell).toContain('returnFocusEl?.focus?.()');+ });++ it('shares the editor body with the Media Library modal', () => {+ expect(drawer).toContain("import EntityDetails from '../EntityDetails.svelte'");+ });+});diff --git a/frontend/src/components/CaseSwitcher.svelte b/frontend/src/components/CaseSwitcher.svelteindex 61c78e1..ddbaccb 100644--- a/frontend/src/components/CaseSwitcher.svelte+++ b/frontend/src/components/CaseSwitcher.svelte@@ -12,8 +12,10 @@} from '../lib/state.svelte.js';import Icon from './Icon.svelte';import Modal from './Modal.svelte';+ import SearchInput from './SearchInput.svelte';let open = $state(false);+ let search = $state('');let modal = $state(null); // 'create' | 'promote' | 'rename' | nulllet nameInput = $state('');let busy = $state(false);@@ -56,9 +58,26 @@async function toggle() {open = !open;- if (open) await refreshCaseList();+ if (open) {+ search = '';+ await refreshCaseList();+ }}+ // Search the case list: client-filter the loaded list for instant feedback,+ // and debounce a server query so it still finds a case in a long list the+ // first page didn't hold. Both paths key on the case name.+ const matchesSearch = (c) =>+ (c.name ?? c.id ?? '').toLowerCase().includes(search.trim().toLowerCase());+ let searchTimer;+ $effect(() => {+ const q = search;+ if (!open) return;+ clearTimeout(searchTimer);+ searchTimer = setTimeout(() => refreshCaseList({ q }), 200);+ return () => clearTimeout(searchTimer);+ });+async function pick(id) {open = false;await openCase(id);@@ -90,6 +109,10 @@const named = $derived(caseState.list.filter((c) => !c.scratch));const scratches = $derived(caseState.list.filter((c) => c.scratch));+ // Filtered views for the menu list (the unfiltered `named` still backs the+ // duplicate-name guard below, which must see every case).+ const visibleNamed = $derived(named.filter(matchesSearch));+ const visibleScratches = $derived(scratches.filter(matchesSearch));// Guard against duplicate names (case-insensitive) — the backend enforces// this too, but flag it early so the button disables instead of erroring.@@ -145,9 +168,14 @@<Icon name="x" size={15} /> Close case (one-shot mode)</button>{/if}- {#if named.length}+ {#if named.length + scratches.length > 6 || search.trim()}+ <div class="search-row">+ <SearchInput bind:value={search} placeholder="Find a case…" width="100%" />+ </div>+ {/if}+ {#if visibleNamed.length}<div class="section">Cases</div>- {#each named as c (c.id)}+ {#each visibleNamed as c (c.id)}<div class="row" class:active={c.id === caseState.current?.id}><button class="item" onclick={() => pick(c.id)}><Icon name="folder" size={15} />@@ -163,9 +191,9 @@</div>{/each}{/if}- {#if scratches.length}+ {#if visibleScratches.length}<div class="section">Scratch sessions</div>- {#each scratches as c (c.id)}+ {#each visibleScratches as c (c.id)}<div class="row" class:active={c.id === caseState.current?.id}><button class="item" onclick={() => pick(c.id)}><Icon name="clock" size={15} />@@ -179,6 +207,8 @@{/if}{#if !named.length && !scratches.length}<div class="hint">No cases yet. Tools work without one.</div>+ {:else if !visibleNamed.length && !visibleScratches.length}+ <div class="hint">No case matches “{search.trim()}”.</div>{/if}</div>{/if}@@ -234,8 +264,7 @@You will lose everything in “{delTarget.name}”.</p><p class="warn-body">- This permanently deletes the whole case folder, including its media,- satellite crops, proofs, exports and notes. It cannot be undone.+ This deletes the case folder and all its contents; it cannot be undone.</p></div></div>@@ -314,6 +343,9 @@box-shadow: var(--shadow-2);padding: 6px;}+ .search-row {+ padding: 6px 6px 8px;+ }.section {font-size: var(--fs-xs);font-weight: 700;diff --git a/frontend/src/components/CaseSwitcher.test.js b/frontend/src/components/CaseSwitcher.test.jsnew file mode 100644index 0000000..b8c4199--- /dev/null+++ b/frontend/src/components/CaseSwitcher.test.js@@ -0,0 +1,48 @@+import { describe, expect, it, vi } from 'vitest';+import { readFileSync } from 'node:fs';++const source = readFileSync(new URL('./CaseSwitcher.svelte', import.meta.url), 'utf8');++describe('CaseSwitcher search', () => {+ it('offers a shared SearchInput once the list is long enough', () => {+ expect(source).toContain("import SearchInput from './SearchInput.svelte'");+ expect(source).toContain('named.length + scratches.length > 6');+ expect(source).toContain('bind:value={search}');+ });++ it('renders the filtered views but guards duplicate-name against the full list', () => {+ expect(source).toContain('visibleNamed');+ expect(source).toContain('visibleScratches');+ // the unfiltered `named` still backs the duplicate-name check+ expect(source).toContain('named.some(');+ });++ it('debounces a server query so a long list is searchable end to end', () => {+ expect(source).toContain('refreshCaseList({ q })');+ });++ it('keeps the search box while a query is active, even if it filters below the threshold', () => {+ // the server query rewrites caseState.list to the filtered result, so a+ // gate reading only the (now-shrunk) list would hide its own box mid-search+ expect(source).toContain('named.length + scratches.length > 6 || search.trim()');+ });+});++describe('refreshCaseList', () => {+ it('passes a name query through to the API, or omits it when empty', async () => {+ vi.resetModules();+ const get = vi.fn().mockResolvedValue([]);+ vi.doMock('../lib/api.js', () => ({ api: { get, post: vi.fn(), del: vi.fn() } }));+ const { refreshCaseList } = await import('../lib/state.svelte.js');++ await refreshCaseList();+ expect(get).toHaveBeenLastCalledWith('/api/cases');++ await refreshCaseList({ q: 'kharkiv strike' });+ expect(get).toHaveBeenLastCalledWith('/api/cases?q=kharkiv%20strike');++ await refreshCaseList({ q: ' ' });+ expect(get).toHaveBeenLastCalledWith('/api/cases');+ vi.doUnmock('../lib/api.js');+ });+});diff --git a/frontend/src/components/EntityDetails.svelte b/frontend/src/components/EntityDetails.svelteindex 62abd7f..efe73ab 100644--- a/frontend/src/components/EntityDetails.svelte+++ b/frontend/src/components/EntityDetails.svelte@@ -175,8 +175,8 @@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.',+ ? 'Deletes the underlying files from disk and cannot be undone.'+ : 'Removes it from the case and cannot be undone.',consequences,action: async () => {await api.del(`/api/cases/${caseState.current.id}/entities/${e.id}`);@@ -288,6 +288,14 @@{#if infoData?.imagery_date}<div class="info-row"><span class="info-k">Imagery</span><span class="mono">{infoData.imagery_date}</span></div>{/if}+ {#if infoData?.source_url}+ <div class="info-row">+ <span class="info-k">Source page</span>+ <a class="mono src" href={infoData.source_url} target="_blank" rel="noreferrer">+ {infoData.source_url}+ </a>+ </div>+ {/if}{:else if entity.type === 'bookmark' && entity.attrs?.url}<div class="info-row"><span class="info-k">URL</span>diff --git a/frontend/src/components/EntityDetails.test.js b/frontend/src/components/EntityDetails.test.jsnew file mode 100644index 0000000..525e239--- /dev/null+++ b/frontend/src/components/EntityDetails.test.js@@ -0,0 +1,13 @@+import { describe, expect, it } from 'vitest';+import { readFileSync } from 'node:fs';++const source = readFileSync(new URL('./EntityDetails.svelte', import.meta.url), 'utf8');++describe('capture details', () => {+ it('shows the recorded external capture page as a link', () => {+ expect(source).toContain('{#if infoData?.source_url}');+ expect(source).toContain('<span class="info-k">Source page</span>');+ expect(source).toContain('href={infoData.source_url}');+ expect(source).toContain('target="_blank" rel="noreferrer"');+ });+});diff --git a/frontend/src/components/FolderBrowser.svelte b/frontend/src/components/FolderBrowser.sveltenew file mode 100644index 0000000..d896504--- /dev/null+++ b/frontend/src/components/FolderBrowser.svelte@@ -0,0 +1,142 @@+<script>+ // The read-only folder view the modal pickers drop into when the analyst+ // presses "…": crumbs, the folders at this level, then the entries filed+ // there. Every picker (Inspect sources and sessions, Reverse Search media,+ // Proof panels and saved proofs) renders the same two-line-free rows, so the+ // markup and styling live here and each picker keeps only its own callbacks.+ //+ // `entries` are the picker's items already narrowed by its own chips/filters,+ // each carrying `id` and `attrs.folder`; `matches` then hides the ones the+ // search box excludes without collapsing the folders around them. A picker+ // with a richer flat row (Satellite's saved work) passes it as the `row`+ // snippet instead of settling for icon + label.+ import Icon from './Icon.svelte';+ import { buildTree } from '../lib/folderTree.js';+ import { browseCrumbs, browserView } from '../lib/folderBrowse.js';++ let {+ entries,+ path = '',+ rootLabel,+ selectedId = null,+ isSelected = (entry) => selectedId != null && entry.id === selectedId,+ mark = false, // tick the selected rows (the multi-select pickers)+ matches = () => true,+ emptyText = 'Nothing here.',+ icon = () => 'file',+ label = (entry) => entry.label ?? '',+ // A picker whose flat list has its own row (thumbnail, actions) passes it+ // here rather than dropping to icon+label the moment you open a folder.+ row = null,+ onnavigate,+ onselect,+ onconfirm,+ } = $props();++ const tree = $derived(buildTree(entries.map((e) => e.attrs?.folder).filter(Boolean), entries));+ const view = $derived(browserView(tree, entries, path));+ const files = $derived(view.entities.filter(matches));+ const crumbs = $derived(browseCrumbs(path));+</script>++<div class="browse-crumbs">+ <button type="button" class:active={!path} onclick={() => onnavigate('')}>{rootLabel}</button>+ {#each crumbs as crumb (crumb.path)}+ <span>/</span><button type="button" class:active={path === crumb.path} onclick={() => onnavigate(crumb.path)}>{crumb.name}</button>+ {/each}+</div>++<div class="browser-list">+ {#each view.children as folder (folder.path)}+ <button type="button" class="browser-row folder-row" onclick={() => onnavigate(folder.path)} ondblclick={() => onnavigate(folder.path)}>+ <Icon name="folder" size={18} /><span>{folder.name}</span>+ </button>+ {/each}+ {#each files as entry (entry.id)}+ {#if row}+ {@render row(entry)}+ {:else}+ <button+ type="button"+ class="browser-row"+ class:selected={isSelected(entry)}+ aria-pressed={mark ? isSelected(entry) : undefined}+ onclick={() => onselect?.(entry)}+ ondblclick={() => onconfirm?.(entry)}+ >+ <Icon name={icon(entry)} size={18} /><span>{label(entry)}</span>+ {#if mark && isSelected(entry)}<Icon name="check" size={14} />{/if}+ </button>+ {/if}+ {/each}+ {#if view.children.length === 0 && files.length === 0}+ <p class="browser-empty">{emptyText}</p>+ {/if}+</div>++<style>+ .browse-crumbs {+ display: flex;+ align-items: center;+ gap: 5px;+ min-width: 0;+ overflow-x: auto;+ color: var(--text-3);+ font-size: var(--fs-xs);+ white-space: nowrap;+ }+ .browse-crumbs button {+ padding: 2px 0;+ color: inherit;+ }+ .browse-crumbs button:hover,+ .browse-crumbs button.active {+ color: var(--text-1);+ }+ .browser-list {+ display: flex;+ flex-direction: column;+ min-height: 160px;+ max-height: min(48vh, 420px);+ overflow: auto;+ border: 1px solid var(--border);+ border-radius: var(--r-md);+ }+ .browser-row {+ display: flex;+ align-items: center;+ gap: 8px;+ width: 100%;+ min-height: 36px;+ padding: 7px 9px;+ border-radius: 0;+ color: var(--text-2);+ text-align: left;+ }+ .browser-row :global(svg) {+ flex-shrink: 0;+ }+ .browser-row > span {+ flex: 1;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .browser-row + .browser-row {+ border-top: 1px solid var(--border);+ }+ .browser-row:hover,+ .browser-row.selected {+ background: var(--bg-3);+ color: var(--text-1);+ }+ .folder-row {+ color: var(--text-1);+ }+ .browser-empty {+ padding: 10px;+ color: var(--text-3);+ font-size: var(--fs-sm);+ }+</style>diff --git a/frontend/src/components/FolderBrowser.test.js b/frontend/src/components/FolderBrowser.test.jsnew file mode 100644index 0000000..181300a--- /dev/null+++ b/frontend/src/components/FolderBrowser.test.js@@ -0,0 +1,79 @@+import { describe, expect, it } from 'vitest';+import { createRawSnippet } from 'svelte';+import { render } from 'svelte/server';+import FolderBrowser from './FolderBrowser.svelte';+import { UNFILED } from '../lib/folderBrowse.js';++const entries = [+ { id: 'a', label: 'Loose photo', attrs: { folder: '' } },+ { id: 'b', label: 'Bridge', attrs: { folder: 'field' } },+ { id: 'c', label: 'Roof', attrs: { folder: 'field/day-1' } },+];++const at = (path, props = {}) =>+ render(FolderBrowser, { props: { entries, path, rootLabel: 'Case media', onnavigate: () => {}, ...props } }).body;++describe('FolderBrowser', () => {+ it('shows the folders at the root, not the entries', () => {+ const body = at('');++ expect(body).toContain('Unfiled');+ expect(body).toContain('field');+ expect(body).not.toContain('Bridge');+ expect(body).toContain('Case media');+ });++ it('lists what is filed in the folder it is pointed at', () => {+ expect(at('field')).toContain('Bridge');+ expect(at('field/day-1')).toContain('Roof');+ expect(at(UNFILED)).toContain('Loose photo');+ });++ it('hides the entries the search excludes, keeping the folders', () => {+ const body = at('', { matches: () => false });++ expect(body).toContain('field');++ expect(at('field', { matches: () => false })).not.toContain('Bridge');+ expect(at('field/day-1', { matches: () => false })).toContain('Nothing here.');+ });++ it('says what an empty folder is empty of', () => {+ expect(at('field/day-9', { emptyText: 'This folder has no matching media.' })).toContain(+ 'This folder has no matching media.'+ );+ });++ it('marks the single selection, and every selected row when multi-select', () => {+ expect(at('field', { selectedId: 'b' })).toContain('selected');++ const multi = at('field', { mark: true, isSelected: (entry) => entry.id === 'b' });+ expect(multi).toContain('aria-pressed="true"');+ });++ it('renders the caller’s icon and label per row', () => {+ const body = at('field', { icon: () => 'satellite', label: (entry) => `${entry.label}!` });++ expect(body).toContain('Bridge!');+ });++ it('hands the entries to the caller’s row snippet when it passes one', () => {+ const row = createRawSnippet((entry) => ({+ render: () => `<div class="rich-row">${entry().label} with a thumbnail</div>`,+ }));++ const body = at('field', { row });++ expect(body).toContain('Bridge with a thumbnail');+ expect(body).not.toContain('browser-row"'); // the default entry button stays out+ });++ it('keeps its own folders and crumbs around a caller’s rows', () => {+ const row = createRawSnippet((entry) => ({ render: () => `<div>${entry().label}</div>` }));++ const body = at('field', { row });++ expect(body).toContain('folder-row'); // field/day-1+ expect(body).toContain('Case media');+ });+});diff --git a/frontend/src/components/Icon.svelte b/frontend/src/components/Icon.svelteindex f00883d..4fb3f10 100644--- a/frontend/src/components/Icon.svelte+++ b/frontend/src/components/Icon.svelte@@ -1,8 +1,8 @@-<script>- /** Inline icon set (24×24, stroke-based, lucide-style). No external assets. */- let { name, size = 18, stroke = 1.8 } = $props();-- const paths = {+<script module>+ /** Inline icon set (24×24, stroke-based, lucide-style). No external assets.+ * Exported so code that has to build SVG outside a component (the Leaflet+ * marker icons) draws from this one set instead of copying paths. */+ export const paths = {// navigation / toolsmedia: 'M4 5h16a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1Zm0 11 4.5-4.5a1 1 0 0 1 1.4 0L14 15.5m-1.5-1.5 2.6-2.6a1 1 0 0 1 1.4 0L21 15M9 9.5h.01',satellite: 'M9 4.2 3.6 6.4a1 1 0 0 0-.6.9v11.2a1 1 0 0 0 1.4.9L9 17.4l6 2.4 5.4-2.2a1 1 0 0 0 .6-.9V5.5a1 1 0 0 0-1.4-.9L15 6.6 9 4.2Zm0 0v13.2M15 6.6v13.2',@@ -68,6 +68,7 @@hand: 'M8 12V6a1.5 1.5 0 0 1 3 0v5m0-6.5a1.5 1.5 0 0 1 3 0V11m0-5a1.5 1.5 0 0 1 3 0v9a6 6 0 0 1-6 6h-1a6 6 0 0 1-5-2.7L3.5 15A1.6 1.6 0 0 1 6 13.2l2 1.8',inspect: 'M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14Zm9 16-4.35-4.35M8 11h6m-3-3v6',crop: 'M6 2v14a2 2 0 0 0 2 2h14M2 6h14a2 2 0 0 1 2 2v14',+ screen: 'M4 5h16a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1Zm5 15h6m-3-4v4',reset: 'M4 9a8 8 0 1 1-1.6 4.7M4 9H1m3 0V6',undo: 'M8 5 4 9l4 4M4 9h10a6 6 0 0 1 0 12h-4',redo: 'm16 5 4 4-4 4m4-4H10a6 6 0 0 0 0 12h4',@@ -84,6 +85,10 @@};</script>+<script>+ let { name, size = 18, stroke = 1.8 } = $props();+</script>+<svgwidth={size}height={size}diff --git a/frontend/src/components/SearchInput.svelte b/frontend/src/components/SearchInput.sveltenew file mode 100644index 0000000..89f78d0--- /dev/null+++ b/frontend/src/components/SearchInput.svelte@@ -0,0 +1,72 @@+<script>+ import Icon from './Icon.svelte';++ let {+ value = $bindable(''),+ placeholder = 'Search…',+ count = null,+ width = '180px',+ onclear = () => {},+ } = $props();++ function clear() {+ value = '';+ onclear();+ }+</script>++<div class="search-box">+ <Icon name="search" size={13} />+ <input+ class="search-input"+ style:width+ {placeholder}+ bind:value+ aria-label={placeholder}+ />+ {#if count != null}<span class="search-count">{count}</span>{/if}+ {#if value}+ <button class="search-clear" onclick={clear} aria-label="Clear search">+ <Icon name="x" size={12} />+ </button>+ {/if}+</div>++<style>+ .search-box {+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 4px 8px;+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ background: var(--bg-2);+ color: var(--text-3);+ flex-shrink: 0;+ }+ .search-box:focus-within {+ border-color: var(--accent);+ }+ .search-input {+ border: none;+ background: none;+ outline: none;+ color: var(--text-1);+ font-size: var(--fs-xs);+ }+ .search-count {+ font-size: var(--fs-xs);+ color: var(--text-3);+ white-space: nowrap;+ }+ .search-clear {+ display: inline-flex;+ color: var(--text-3);+ padding: 1px;+ border-radius: 50%;+ }+ .search-clear:hover {+ color: var(--text-1);+ background: var(--bg-3);+ }+</style>diff --git a/frontend/src/components/SearchInput.test.js b/frontend/src/components/SearchInput.test.jsnew file mode 100644index 0000000..90330af--- /dev/null+++ b/frontend/src/components/SearchInput.test.js@@ -0,0 +1,17 @@+import { describe, expect, it } from 'vitest';+import { render } from 'svelte/server';+import SearchInput from './SearchInput.svelte';++describe('SearchInput', () => {+ it('renders the placeholder and no clear button when empty', () => {+ const { body } = render(SearchInput, { props: { placeholder: 'Find a file…', value: '' } });+ expect(body).toContain('Find a file…');+ expect(body).not.toContain('Clear search');+ });++ it('shows the clear button and a count when a value is present', () => {+ const { body } = render(SearchInput, { props: { value: 'bridge', count: '3 shown' } });+ expect(body).toContain('Clear search');+ expect(body).toContain('3 shown');+ });+});diff --git a/frontend/src/components/sidebar/DetailsDrawer.svelte b/frontend/src/components/sidebar/DetailsDrawer.sveltenew file mode 100644index 0000000..2bf65c6--- /dev/null+++ b/frontend/src/components/sidebar/DetailsDrawer.svelte@@ -0,0 +1,63 @@+<script>+ // Zone 3: the selection editor, over the sidebar rather than under the tree.+ // The body is EntityDetails, unchanged — the Media Library modal shares it.+ import Icon from '../Icon.svelte';+ import EntityDetails from '../EntityDetails.svelte';++ let { entity, onclose = () => {}, ondeleted = () => {} } = $props();++ function focus(node) { node.focus(); }+</script>++<svelte:window onkeydown={(e) => e.key === 'Escape' && onclose()} />++<div class="drawer">+ <div class="drawer-head">+ <button class="btn btn-ghost btn-sm" title="Back to the case" onclick={onclose} use:focus>+ <Icon name="chevronLeft" size={14} />+ </button>+ <span class="label">{entity.label}</span>+ <button class="btn btn-ghost btn-sm" title="Close details" onclick={onclose}>+ <Icon name="x" size={13} />+ </button>+ </div>+ <div class="drawer-body">+ <EntityDetails entityId={entity.id} {onclose} {ondeleted} />+ </div>+</div>++<style>+ .drawer {+ position: absolute;+ inset: 0;+ z-index: 1;+ display: flex;+ flex-direction: column;+ background: var(--bg-1);+ }+ .drawer-head {+ flex-shrink: 0;+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 10px 10px 8px;+ border-bottom: 1px solid var(--border);+ }+ .label {+ flex: 1;+ min-width: 0;+ font-size: var(--fs-sm);+ font-weight: 600;+ color: var(--text-1);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .drawer-body {+ flex: 1;+ min-height: 0;+ overflow-y: auto;+ padding: 6px 10px 12px;+ font-size: var(--fs-sm);+ }+</style>diff --git a/frontend/src/components/sidebar/EntityRow.svelte b/frontend/src/components/sidebar/EntityRow.sveltenew file mode 100644index 0000000..b5587c0--- /dev/null+++ b/frontend/src/components/sidebar/EntityRow.svelte@@ -0,0 +1,141 @@+<script>+ // One entity row. The folder tree and the result list render the same row, so+ // it is a component rather than a snippet owned by either of them.+ import { ENTITY_TOOL, gotoCapture } from '../../lib/navigate.js';+ import { folderOf } from '../../lib/folderTree.js';+ import { entityIcon } from '../../lib/entityIcon.js';+ import Icon from '../Icon.svelte';++ let {+ entity,+ caseId,+ depth = 0,+ meta = null,+ suggested = false,+ dragging = false,+ selected = false,+ onactivate = () => {},+ oninfo = () => {},+ onunfile = () => {},+ onconfirm = () => {},+ ondismiss = () => {},+ ondragstart = () => {},+ ondragend = () => {},+ } = $props();++ const isClickable = $derived(+ entity.type === 'note' || entity.type === 'capture' || !!ENTITY_TOOL[entity.type]+ );+</script>++<!-- The role and tab stop deliberately exist only for activatable entity types. -->+<!-- svelte-ignore a11y_no_noninteractive_tabindex -->+<div+ class="entity"+ class:suggested+ class:clickable={isClickable}+ class:dragging+ class:selected+ style="padding-left: {8 + depth * 14}px"+ draggable={!suggested}+ ondragstart={(ev) => ondragstart(ev, entity)}+ ondragend={() => ondragend()}+ onclick={(ev) => onactivate(entity, ev)}+ role={isClickable ? 'button' : undefined}+ tabindex={isClickable ? 0 : undefined}+ onkeydown={(ev) => ev.key === 'Enter' && onactivate(entity, ev)}+>+ {#if !suggested}<Icon name="grip" size={13} />{/if}+ <Icon name={entityIcon(entity)} size={14} />+ <div class="e-body">+ <span class="e-label">{entity.label}</span>+ <span class="e-meta">{meta ?? entity.type}</span>+ </div>++ {#if suggested}+ <button class="btn btn-ghost btn-sm" title="Confirm" onclick={(ev) => { ev.stopPropagation(); onconfirm(entity); }}>+ <Icon name="check" size={13} />+ </button>+ <button class="btn btn-ghost btn-sm" title="Dismiss" onclick={(ev) => { ev.stopPropagation(); ondismiss(entity); }}>+ <Icon name="x" size={13} />+ </button>+ {:else}+ {#if entity.type === 'capture' && entity.attrs?.lat != null}+ <button+ class="btn btn-ghost btn-sm act"+ title="Go to these coordinates on the map"+ onclick={(ev) => { ev.stopPropagation(); gotoCapture(entity); }}+ >+ <Icon name="crosshair" size={13} />+ </button>+ {/if}+ {#if entity.type === 'media' && entity.attrs?.path}+ <a+ class="btn btn-ghost btn-sm act"+ title="Open in new tab"+ href={`/files/${caseId}/${entity.attrs.path}`}+ target="_blank"+ rel="noreferrer"+ onclick={(ev) => ev.stopPropagation()}+ >+ <Icon name="external" size={13} />+ </a>+ {/if}+ <button+ class="btn btn-ghost btn-sm act"+ title="Details"+ onclick={(ev) => { ev.stopPropagation(); oninfo(entity); }}+ >+ <Icon name="note" size={13} />+ </button>+ {#if folderOf(entity)}+ <button+ class="btn btn-ghost btn-sm act del"+ title="Unfile from this folder"+ onclick={(ev) => { ev.stopPropagation(); onunfile(entity); }}+ >+ <Icon name="folderMinus" size={13} />+ </button>+ {/if}+ {/if}+</div>++<style>+ .entity {+ display: flex;+ align-items: center;+ gap: 7px;+ padding: 6px 8px;+ border-radius: var(--r-sm);+ color: var(--text-2);+ }+ .entity:hover { background: var(--bg-2); }+ .entity.clickable { cursor: pointer; }+ .entity.dragging { opacity: 0.5; }+ .entity.selected { background: var(--accent-soft); box-shadow: inset 2px 0 0 var(--accent); }+ .entity > :global(svg:first-child) { color: var(--text-3); flex-shrink: 0; }+ .entity:not(.suggested) > :global(svg:first-child) { cursor: grab; }+ .entity.suggested {+ background: var(--accent-soft);+ border: 1px dashed var(--accent);+ margin-bottom: 4px;+ }+ .e-body { flex: 1; min-width: 0; display: flex; flex-direction: column; }+ .e-label {+ font-size: var(--fs-sm);+ color: var(--text-1);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .e-meta {+ font-size: var(--fs-xs);+ color: var(--text-3);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .act { opacity: 0; flex-shrink: 0; }+ .entity:hover .act { opacity: 1; }+ .del:hover { color: var(--danger, #e55); }+</style>diff --git a/frontend/src/components/sidebar/SidebarHeader.svelte b/frontend/src/components/sidebar/SidebarHeader.sveltenew file mode 100644index 0000000..b6c8bbe--- /dev/null+++ b/frontend/src/components/sidebar/SidebarHeader.svelte@@ -0,0 +1,130 @@+<script>+ // Zone 1: identity, search, type chips. Fixed — it never scrolls away.+ import Icon from '../Icon.svelte';+ import SearchInput from '../SearchInput.svelte';++ let {+ caseName,+ caseId,+ query = $bindable(''),+ type = null,+ chips = [],+ total = 0,+ resultCount = null,+ onnotes = () => {},+ onselecttype = () => {},+ } = $props();++ // A case with a dozen entity types would push its rarest chips off a single+ // line, so the row wraps and only the busiest few show until "+N" is pressed.+ // The active chip is always in view, even when it sits past the cut.+ const VISIBLE_CHIPS = 5;+ let chipsOpen = $state(false);+ const shownChips = $derived.by(() => {+ if (chipsOpen) return chips;+ const head = chips.slice(0, VISIBLE_CHIPS);+ const active = chips.find((c) => c.type === type);+ return active && !head.includes(active) ? [...head, active] : head;+ });+ const hiddenChips = $derived(chips.length - shownChips.length);+</script>++<div class="head">+ <div class="identity">+ <h3 title={caseId}>{caseName}</h3>+ <button class="btn btn-ghost btn-sm" title="Open case notes" onclick={onnotes}>+ <Icon name="note" size={13} />+ <span>Notes</span>+ </button>+ </div>++ <SearchInput+ bind:value={query}+ placeholder="Search this case…"+ width="100%"+ count={resultCount == null ? null : `${resultCount}`}+ />++ {#if chips.length > 1}+ <div class="chips">+ <button class="chip" class:active={type === null} onclick={() => onselecttype(null)}>+ All <span class="n">{total}</span>+ </button>+ {#each shownChips as chip (chip.type)}+ <button+ class="chip"+ class:active={type === chip.type}+ onclick={() => onselecttype(type === chip.type ? null : chip.type)}+ >+ {chip.type} <span class="n">{chip.count}</span>+ </button>+ {/each}+ {#if hiddenChips > 0}+ <button class="chip more" onclick={() => (chipsOpen = true)}>+{hiddenChips}</button>+ {:else if chipsOpen}+ <button class="chip more" onclick={() => (chipsOpen = false)}>Less</button>+ {/if}+ </div>+ {/if}+</div>++<style>+ .head {+ flex-shrink: 0;+ display: flex;+ flex-direction: column;+ gap: 8px;+ padding: 12px 10px 10px;+ border-bottom: 1px solid var(--border);+ }+ .identity {+ display: flex;+ align-items: center;+ gap: 6px;+ }+ .identity h3 {+ flex: 1;+ min-width: 0;+ font-size: var(--fs-md);+ font-weight: 700;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .identity .btn {+ flex-shrink: 0;+ display: flex;+ align-items: center;+ gap: 4px;+ color: var(--text-3);+ font-size: var(--fs-xs);+ }+ .identity .btn:hover { color: var(--text-1); }+ /* wraps instead of scrolling: a chip that runs off the edge is a chip nobody+ finds, and at 240px that is most of them */+ .chips {+ display: flex;+ flex-wrap: wrap;+ gap: 4px;+ }+ .chip {+ flex-shrink: 0;+ display: flex;+ align-items: center;+ gap: 4px;+ padding: 2px 8px;+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ background: var(--bg-2);+ color: var(--text-3);+ font-size: var(--fs-xs);+ cursor: pointer;+ }+ .chip:hover { color: var(--text-1); border-color: var(--border-strong); }+ .chip.active {+ color: var(--text-1);+ border-color: var(--accent);+ background: var(--accent-soft);+ }+ .n { font-weight: 600; }+</style>diff --git a/frontend/src/components/sidebar/SidebarResults.svelte b/frontend/src/components/sidebar/SidebarResults.sveltenew file mode 100644index 0000000..7456750--- /dev/null+++ b/frontend/src/components/sidebar/SidebarResults.svelte@@ -0,0 +1,51 @@+<script>+ // Zone 2, results mode: a flat list, whatever the filing. Each row carries its+ // folder as meta, which answers "where is this filed?" without expanding a+ // single node.+ import { resultMeta } from '../../lib/sidebarSearch.js';+ import EntityRow from './EntityRow.svelte';++ let {+ rows = [],+ caseId,+ loading = false,+ hasMore = false,+ onmore = () => {},+ onactivate = () => {},+ oninfo = () => {},+ onunfile = () => {},+ } = $props();+</script>++<div class="results">+ {#each rows as e (e.id)}+ <EntityRow entity={e} {caseId} meta={resultMeta(e)} {onactivate} {oninfo} {onunfile} />+ {/each}++ {#if hasMore}+ <button class="more" onclick={onmore} disabled={loading}>Show more</button>+ {/if}++ {#if rows.length === 0 && !loading}+ <div class="none">No match in this case.</div>+ {/if}+</div>++<style>+ .results { display: flex; flex-direction: column; gap: 1px; padding: 4px; }+ .more {+ align-self: flex-start;+ margin: 2px 8px 6px;+ padding: 3px 10px;+ font-size: var(--fs-xs);+ font-weight: 600;+ color: var(--text-2);+ background: var(--bg-2);+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ cursor: pointer;+ }+ .more:hover { color: var(--text-1); border-color: var(--border-strong); }+ .more:disabled { opacity: 0.5; cursor: default; }+ .none { font-size: var(--fs-xs); color: var(--text-3); padding: 8px; }+</style>diff --git a/frontend/src/components/sidebar/SidebarTree.svelte b/frontend/src/components/sidebar/SidebarTree.sveltenew file mode 100644index 0000000..7f24207--- /dev/null+++ b/frontend/src/components/sidebar/SidebarTree.svelte@@ -0,0 +1,336 @@+<script>+ // Zone 2, browse mode: one grammar — chevron, icon, name, count — for every+ // foldable row. Suggestions is a node here, not a section above the tree, so+ // nothing below it shifts when its count crosses zero.+ import { subtreeCountFrom } from '../../lib/folderTree.js';+ import { dragPayload, rangeSelected, toggleSelected } from '../../lib/rowSelect.js';+ import Icon from '../Icon.svelte';+ import EntityRow from './EntityRow.svelte';++ let {+ tree = [],+ byFolder = {},+ expanded = {},+ folderData = {},+ unfiled,+ unfiledOpen = false,+ suggested,+ suggestedCount = 0,+ suggestedOpen = false,+ caseId,+ ontoggle = () => {},+ onmorefolder = () => {},+ ontoggleunfiled = () => {},+ onmoreunfiled = () => {},+ ontogglesuggested = () => {},+ onmoresuggested = () => {},+ oncreatefolder = () => {},+ onremovefolder = () => {},+ onfile = () => {},+ onactivate = () => {},+ oninfo = () => {},+ onunfile = () => {},+ onconfirm = () => {},+ ondismiss = () => {},+ ondragactive = () => {},+ } = $props();++ let addingUnder = $state(undefined); // folder path currently gaining a child+ let newSubName = $state('');+ let dragEntityId = $state(null); // for the dragging visual+ let dragRows = null; // the entities being dragged (no full-graph lookup on drop)+ let dragOverFolder = $state(undefined); // folder path being hovered++ // ── multi-select (lib/rowSelect.js) ───────────────────────────────────────+ // Ctrl/cmd-click picks rows one by one, shift-click takes a run of them, and+ // the drag moves the lot. The range needs the rows in display order, so this+ // walks the tree exactly as the markup renders it: an expanded node's+ // children first, then its own entities, with Unfiled last.+ let selected = $state(new Set());+ let anchorId = null;++ const visibleRows = $derived.by(() => {+ const out = [];+ const walk = (nodes) => {+ for (const node of nodes) {+ if (expanded[node.path] !== true) continue;+ walk(node.children);+ const sec = folderData[node.path];+ if (sec) out.push(...sec.items);+ }+ };+ walk(tree);+ if (unfiledOpen) out.push(...unfiled.items);+ return out;+ });++ // A row that scrolled out of the tree (folder collapsed, case reloaded) must+ // not keep a selection nobody can see or drop.+ $effect(() => {+ const live = new Set(visibleRows.map((r) => r.id));+ const stale = [...selected].filter((id) => !live.has(id));+ if (stale.length) selected = new Set([...selected].filter((id) => live.has(id)));+ });++ function onRowClick(entity, ev) {+ if (ev?.shiftKey) {+ selected = rangeSelected(visibleRows.map((r) => r.id), anchorId ?? entity.id, entity.id);+ return;+ }+ if (ev?.ctrlKey || ev?.metaKey) {+ selected = toggleSelected(selected, entity.id);+ anchorId = entity.id;+ return;+ }+ selected = new Set();+ anchorId = entity.id;+ onactivate(entity);+ }++ const isExpanded = (path) => expanded[path] === true;+ function focus(node) { node.focus(); }++ function startAddSub(path) {+ addingUnder = path;+ newSubName = '';+ if (!isExpanded(path)) ontoggle(path);+ }+ function submitAddSub() {+ const name = newSubName.trim();+ const parent = addingUnder;+ addingUnder = undefined;+ newSubName = '';+ if (!name || parent === undefined) return;+ oncreatefolder(parent ? `${parent}/${name}` : name);+ }++ function onDragStart(ev, entity) {+ dragRows = dragPayload(visibleRows, selected, entity);+ dragEntityId = entity.id;+ ev.dataTransfer.effectAllowed = 'move';+ ev.dataTransfer.setData('text/plain', dragRows.map((r) => r.id).join(' '));+ ondragactive(true);+ }+ function onDragEnd() {+ dragEntityId = null;+ dragRows = null;+ dragOverFolder = undefined;+ ondragactive(false);+ }+ function onDropFolder(ev, folder) {+ ev.preventDefault();+ const rows = dragRows;+ onDragEnd();+ if (!rows?.length) return;+ selected = new Set();+ onfile(rows, folder);+ }+ // The whole selection dims, not just the row under the cursor. Keyed on+ // `dragEntityId` because `dragRows` is deliberately non-reactive.+ const isDragging = (id) => dragEntityId === id || (dragEntityId !== null && selected.has(id));+</script>++<div class="tree">+ {#if suggestedCount > 0}+ <div+ class="frow"+ role="button"+ tabindex="0"+ onclick={ontogglesuggested}+ onkeydown={(e) => e.key === 'Enter' && ontogglesuggested()}+ >+ <Icon name={suggestedOpen ? 'chevronDown' : 'chevronRight'} size={12} />+ <Icon name="wand" size={13} />+ <span class="fname">Suggestions</span>+ <span class="fcount">{suggestedCount}</span>+ </div>+ {#if suggestedOpen}+ {#each suggested.items as e (e.id)}+ <EntityRow entity={e} {caseId} depth={1} suggested {onconfirm} {ondismiss} />+ {/each}+ {#if !suggested.done}+ <button class="more" onclick={onmoresuggested} disabled={suggested.loading}>Show more</button>+ {/if}+ {/if}+ {/if}++ {#each tree as node (node.path)}+ {@render folderNode(node, 0)}+ {/each}++ {#if unfiled.items.length > 0}+ <div+ class="frow"+ role="button"+ tabindex="0"+ ondragover={(e) => { e.preventDefault(); dragOverFolder = ''; }}+ ondragleave={() => (dragOverFolder = undefined)}+ ondrop={(e) => onDropFolder(e, '')}+ class:dropping={dragOverFolder === ''}+ onclick={ontoggleunfiled}+ onkeydown={(e) => e.key === 'Enter' && ontoggleunfiled()}+ >+ <Icon name={unfiledOpen ? 'chevronDown' : 'chevronRight'} size={12} />+ <Icon name="layers" size={13} />+ <span class="fname">Unfiled</span>+ <span class="fcount">{unfiled.items.length}{unfiled.done ? '' : '+'}</span>+ </div>+ {#if unfiledOpen}+ {#each unfiled.items as e (e.id)}+ <EntityRow+ entity={e}+ {caseId}+ depth={1}+ dragging={isDragging(e.id)}+ selected={selected.has(e.id)}+ ondragstart={onDragStart}+ ondragend={onDragEnd}+ onactivate={onRowClick}+ {oninfo}+ {onunfile}+ />+ {/each}+ {#if !unfiled.done}+ <button class="more" onclick={onmoreunfiled} disabled={unfiled.loading}>Show more</button>+ {/if}+ {/if}+ {/if}++ {#if tree.length === 0 && unfiled.items.length === 0 && suggestedCount === 0}+ <div class="none">Everything you save lands here; create folders to organize it.</div>+ {/if}+</div>++<!-- one folder node + its subtree (recursive) -->+{#snippet folderNode(node, depth)}+ <div+ class="frow"+ class:dropping={dragOverFolder === node.path}+ style="padding-left: {8 + depth * 14}px"+ role="button"+ tabindex="0"+ ondragover={(e) => { e.preventDefault(); dragOverFolder = node.path; }}+ ondragleave={() => (dragOverFolder = undefined)}+ ondrop={(e) => onDropFolder(e, node.path)}+ onclick={() => ontoggle(node.path)}+ onkeydown={(e) => e.key === 'Enter' && ontoggle(node.path)}+ >+ <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">{subtreeCountFrom(node, byFolder)}</span>+ <span+ class="fact"+ role="button"+ tabindex="0"+ title="Add subfolder"+ onclick={(e) => { e.stopPropagation(); startAddSub(node.path); }}+ onkeydown={(e) => e.key === 'Enter' && (e.stopPropagation(), startAddSub(node.path))}+ >+ <Icon name="plus" size={12} />+ </span>+ <span+ class="fact fdel"+ role="button"+ tabindex="0"+ title="Remove folder"+ onclick={(e) => { e.stopPropagation(); onremovefolder(node.path); }}+ onkeydown={(e) => e.key === 'Enter' && (e.stopPropagation(), onremovefolder(node.path))}+ >+ <Icon name="folderMinus" size={12} />+ </span>+ </div>+ {#if isExpanded(node.path)}+ {#if addingUnder === node.path}+ <form+ class="new-folder"+ style="padding-left: {8 + (depth + 1) * 14}px"+ onsubmit={(e) => { e.preventDefault(); submitAddSub(); }}+ >+ <input+ class="input"+ placeholder="Subfolder…"+ bind:value={newSubName}+ use:focus+ onkeydown={(e) => e.key === 'Escape' && (addingUnder = undefined)}+ />+ <button class="btn btn-sm" type="submit" title="Create" disabled={!newSubName.trim()}>+ <Icon name="plus" size={13} />+ </button>+ </form>+ {/if}+ {#each node.children as child (child.path)}+ {@render folderNode(child, depth + 1)}+ {/each}+ {@const sec = folderData[node.path]}+ {#if sec}+ {#each sec.items as e (e.id)}+ <EntityRow+ entity={e}+ {caseId}+ depth={depth + 1}+ dragging={isDragging(e.id)}+ selected={selected.has(e.id)}+ ondragstart={onDragStart}+ ondragend={onDragEnd}+ onactivate={onRowClick}+ {oninfo}+ {onunfile}+ />+ {/each}+ {#if !sec.done}+ <button+ class="more"+ style="margin-left: {8 + (depth + 1) * 14}px"+ onclick={() => onmorefolder(node.path)}+ disabled={sec.loading}+ >+ Show more+ </button>+ {/if}+ {/if}+ {/if}+{/snippet}++<style>+ .tree { display: flex; flex-direction: column; gap: 1px; padding: 0 4px 8px; }+ .frow {+ display: flex;+ align-items: center;+ gap: 7px;+ width: 100%;+ padding: 6px 8px;+ border-radius: var(--r-sm);+ color: var(--text-2);+ font-size: var(--fs-sm);+ border: 1px solid transparent;+ cursor: pointer;+ text-align: left;+ }+ .frow:hover { background: var(--bg-2); }+ .frow.dropping { border-color: var(--accent); background: var(--accent-soft); }+ .frow > :global(svg:first-child) { color: var(--text-3); flex-shrink: 0; }+ .fname { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .fcount { color: var(--text-3); font-size: var(--fs-xs); font-weight: 600; }+ .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); }+ .frow:hover .fact { opacity: 1; }+ .new-folder { display: flex; gap: 6px; padding: 2px 8px 4px; }+ .new-folder .input { flex: 1; font-size: var(--fs-xs); }+ .more {+ align-self: flex-start;+ margin: 2px 8px 6px;+ padding: 3px 10px;+ font-size: var(--fs-xs);+ font-weight: 600;+ color: var(--text-2);+ background: var(--bg-2);+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ cursor: pointer;+ }+ .more:hover { color: var(--text-1); border-color: var(--border-strong); }+ .more:disabled { opacity: 0.5; cursor: default; }+ .none { font-size: var(--fs-xs); color: var(--text-3); padding: 4px 8px 12px; line-height: 1.45; }+</style>diff --git a/frontend/src/lib/catalog.js b/frontend/src/lib/catalog.jsindex 9ac6ea0..e0762b1 100644--- a/frontend/src/lib/catalog.js+++ b/frontend/src/lib/catalog.js@@ -10,7 +10,7 @@ export function settleCatalogSummary(current, next, isCurrent) {* `unfiled` (no folder) wins over an exact `folder` path when both are given. */export function buildCatalogQuery(caseId,- { cursor, limit, types, status, query, folder, unfiled } = {}+ { cursor, limit, types, status, query, folder, unfiled, recursive } = {}) {const params = new URLSearchParams();if (limit != null) params.set('limit', String(limit));@@ -20,6 +20,7 @@ export function buildCatalogQuery(if (query) params.set('q', query);if (unfiled) params.set('unfiled', 'true');else if (folder != null) params.set('folder', folder);+ if (recursive) params.set('recursive', 'true');const qs = params.toString();return `/api/cases/${caseId}/catalog/entities${qs ? `?${qs}` : ''}`;}@@ -35,13 +36,15 @@ export function buildCatalogQuery(*/export async function fetchAllEntities(caseId,- { types, status, query, get = api.get, signal, pageSize = 500 } = {}+ { types, status, query, folder, unfiled, recursive, 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 path = buildCatalogQuery(caseId, {+ cursor, limit: pageSize, types, status, query, folder, unfiled, recursive,+ });const page = await get(path, signal ? { signal } : undefined);out.push(...(page.items ?? []));cursor = page.next_cursor ?? null;diff --git a/frontend/src/lib/catalog.test.js b/frontend/src/lib/catalog.test.jsindex 0388174..99428f5 100644--- a/frontend/src/lib/catalog.test.js+++ b/frontend/src/lib/catalog.test.js@@ -26,6 +26,9 @@ describe('buildCatalogQuery', () => {expect(buildCatalogQuery('c1', { unfiled: true, folder: 'ignored' })).toBe('/api/cases/c1/catalog/entities?unfiled=true');+ expect(buildCatalogQuery('c1', { folder: 'Sources', recursive: true })).toBe(+ '/api/cases/c1/catalog/entities?folder=Sources&recursive=true'+ );});});@@ -70,6 +73,47 @@ describe('fetchAllEntities — the full bounded slice', () => {expect(paths[0]).toContain('status=confirmed');expect(await fetchAllEntities(null, { get })).toEqual([]);});++ it('pages an exact folder or the unfiled bucket', async () => {+ const paths = [];+ const get = async (path) => {+ paths.push(path);+ return { items: [], next_cursor: null };+ };+ await fetchAllEntities('c1', {+ folder: 'Research/Images', recursive: true, status: 'confirmed', get,+ });+ await fetchAllEntities('c1', { unfiled: true, status: 'confirmed', get });+ expect(paths[0]).toContain('folder=Research%2FImages');+ expect(paths[0]).toContain('recursive=true');+ expect(paths[0]).toContain('status=confirmed');+ expect(paths[1]).toContain('unfiled=true');+ });++ it('walks every page inside a folder instead of stopping at the first page', async () => {+ const paths = [];+ const labels = ['Alpha', 'Bravo', 'Charlie', 'Delta', 'Echo'];+ const get = async (path) => {+ paths.push(path);+ const url = new URL(path, 'http://x');+ const cursor = Number(url.searchParams.get('cursor') ?? 0);+ const limit = Number(url.searchParams.get('limit'));+ const items = labels.slice(cursor, cursor + limit).map((label) => ({ id: label, label }));+ return {+ items,+ next_cursor: cursor + limit < labels.length ? String(cursor + limit) : null,+ };+ };++ const all = await fetchAllEntities('c1', {+ folder: 'Research/Images',+ pageSize: 2,+ get,+ });+ expect(all.map((entity) => entity.label)).toEqual(labels);+ expect(paths).toHaveLength(3);+ expect(paths.every((path) => path.includes('folder=Research%2FImages'))).toBe(true);+ });});describe('lookupEntity / fetchDerivation', () => {diff --git a/frontend/src/lib/composer.js b/frontend/src/lib/composer.jsindex 08489ee..66cbe05 100644--- a/frontend/src/lib/composer.js+++ b/frontend/src/lib/composer.js@@ -1,15 +1,8 @@/**- * Proof composer document logic — pure functions, no Konva/DOM here.+ * Pure proof-document logic with no Konva or DOM dependency.*- * Document space: panels share a common height (PANEL_H doc units) within a- * row, and rows stack vertically. Each panel carries a `row` index (default 0);- * panels of the same row sit side by side (array order = left→right), rows are- * centered and stacked top→bottom. A single-row document (all row 0) is exactly- * the classic side-by-side strip. Stacking rows keeps the composite closer to a- * square so it survives a tweet's centre-crop instead of being a wide bandeau.- *- * Shape coordinates are stored in each panel's *natural image pixels* so the- * spec stays valid regardless of layout or zoom (re-editable forever).+ * Panels share a row height and rows stack vertically. Shape coordinates use+ * each panel's natural pixels so layout and zoom do not invalidate the spec.*/import { formatCoords as renderCoords } from './coords.js';@@ -118,42 +111,12 @@ export function newId(prefix) {return `${prefix}${Date.now().toString(36)}${(idSeq++).toString(36)}`;}-// Title a fresh proof carries until the analyst renames it. Two proofs left at-// this title auto-number on save (see uniqueProofName) instead of clobbering.-export const DEFAULT_PROOF_TITLE = 'Untitled proof';--/** URL-safe proof filename from free text — mirror of the backend `_slug`. */-export function proofSlug(text) {- const slug = (text ?? '')- .toLowerCase()- .replace(/[^a-z0-9]+/g, '-')- .replace(/^-+|-+$/g, '');- return slug.slice(0, 80) || 'proof';-}--/**- * A proof title that doesn't collide with `taken` (existing proof titles):- * `base` when free, else `base 2`, `base 3`, … A new proof left at the default- * title gets numbered so two never-renamed proofs read apart in the case, and- * the filename simply follows the title (proofSlug). `taken` is a Set or array.- */-export function uniqueProofTitle(base, taken) {- const set = taken instanceof Set ? taken : new Set(taken);- if (!set.has(base)) return base;- let n = 2;- while (set.has(`${base} ${n}`)) n += 1;- return `${base} ${n}`;-}--/** Prefill a new proof from its case name without colliding with a saved proof. */-export function proofTitleFromCase(caseName, taken = []) {- const base = String(caseName ?? '').trim() || DEFAULT_PROOF_TITLE;- return uniqueProofTitle(base, taken);-}-/*** Search and category filter for the proof panel picker. Satellite captures* carry `kind: satellite`; every other case image carries `kind: media`.+ * The search reads the title the analyst gave the image (its `label`) and the+ * folder it sits in, not the file name on disk — a downloaded photo keeps a+ * name nobody chose, so matching it drowns the titles that mean something.*/export function filterProofPanelItems(items, query = '', category = 'all') {const needle = String(query).trim().toLocaleLowerCase();@@ -163,7 +126,7 @@ export function filterProofPanelItems(items, query = '', category = 'all') {if (!needle) return true;const text = [item.label,- item.src,+ item.folder,item.meta?.provider,item.meta?.date,item.meta?.imagery_date,@@ -172,6 +135,23 @@ export function filterProofPanelItems(items, query = '', category = 'all') {});}+/**+ * What a panel picker cell should show for a case image.+ *+ * Only the cached thumbnail is small enough for a 150px cell: falling back to+ * the original meant every open of the picker downloaded and decoded the+ * full-resolution captures. `thumbnail` is null unless the listing found the+ * cached file, so a missing one is a placeholder, and a queued or running+ * thumbnail job is a pending one the caller can poll on.+ */+export function panelPreview(item) {+ const state = item?.thumb_state;+ return {+ thumb: state === 'ready' ? (item.thumbnail ?? null) : null,+ thumbPending: state === 'queued' || state === 'running',+ };+}+/** A proof has nothing to render until it contains at least one panel. */export function hasProofCanvasContent(proof) {return Array.isArray(proof?.panels) && proof.panels.length > 0;@@ -732,6 +712,121 @@ export function signatureOffset(sig, docW, docH, natural, x, y) {};}+// ---- frames & pasted images --------------------------------------------------++export const FRAME_WIDTH = 6; // default border thickness, in the surface's own pixels+export const FRAME_WIDTH_MAX = 60;+export const FRAME_COLOR = ANNO_COLORS[0];++/**+ * A coloured border around a panel or a pasted image, or `null` for none.+ * Decoration only: unlike a drawn shape, a frame never enters the legend, so it+ * is not something the analyst has to explain. Drawn inset on the surface, so it+ * costs the layout nothing. Width 0 is how the UI turns a frame off.+ */+export function normalizeFrame(frame) {+ if (!frame || typeof frame !== 'object' || Array.isArray(frame)) return null;+ const width = Math.round(boundedNumber(frame.width, 0, 0, FRAME_WIDTH_MAX));+ return width ? { color: normalizedColor(frame.color, FRAME_COLOR), width } : null;+}++export function newFrame() {+ return { color: FRAME_COLOR, width: FRAME_WIDTH };+}++export const PASTE_SCALE_MIN = 0.02;+export const PASTE_SCALE_MAX = 8;+export const PASTE_SHARE = 0.4; // insertion width, as a share of the document++/**+ * A pasted image: pixels that live in this proof and nowhere else. It carries no+ * `src`, so nothing in the case claims it and the save files no derived-from+ * edge for it — `asset` is a file name inside the proof's own assets folder.+ */+export function newPaste(asset, natural, { x = 0, y = 0, scale = 1 } = {}) {+ return {+ id: newId('x'),+ asset,+ natural: [natural[0], natural[1]],+ x,+ y,+ scale: clampPasteScale(scale),+ frame: null,+ };+}++export function clampPasteScale(scale) {+ const v = Number.isFinite(scale) ? scale : 1;+ return Math.round(clamp(v, PASTE_SCALE_MIN, PASTE_SCALE_MAX) * 1000) / 1000;+}++/** Insertion scale: a share of the document width, never larger than life size. */+export function pasteInsertScale(natural, docW, share = PASTE_SHARE) {+ const w = natural?.[0];+ if (!w || !docW) return 1;+ return clampPasteScale(Math.min(1, Math.round(((docW * share) / w) * 1000) / 1000));+}++/**+ * Layout boxes for pasted images, in the same shape as panel boxes so a shape+ * can bind to either. A paste sits at its own doc position, and its `scale` maps+ * natural pixels straight to doc pixels (1 = life size). `baseScale` is 1, which+ * puts stroke widths in natural pixels — so an annotation drawn on a paste grows+ * with it exactly as one drawn on a panel grows with the panel.+ */+export function pasteBoxes(pastes) {+ return (pastes ?? []).map((p) => {+ const scale = clampPasteScale(p.scale);+ return {+ x: p.x ?? 0,+ y: p.y ?? 0,+ w: p.natural[0] * scale,+ h: p.natural[1] * scale,+ scale,+ baseScale: 1,+ row: 0,+ };+ });+}++/**+ * Everything an annotation can be drawn on, front→back: pasted images first+ * (they float above the composition), then the panels in their own z-order.+ * Each entry is `{ id, kind, item, box, index }`, `index` being the item's+ * position inside its own array — what the mutating helpers take.+ */+export function surfaces(proof) {+ const panels = proof?.panels ?? [];+ const pastes = proof?.pastes ?? [];+ const panelBox = layoutPanels(panels, proof?.captionSize, proof?.layout, proof?.space);+ const pasteBox = pasteBoxes(pastes);+ return [+ ...pastes.map((item, index) => ({ id: item.id, kind: 'paste', item, box: pasteBox[index], index })),+ ...panels.map((item, index) => ({ id: item.id, kind: 'panel', item, box: panelBox[index], index })),+ ];+}++/** Topmost surface under a doc-space point, with the point in its own pixels. */+export function surfaceHitTest(list, point) {+ const hit = panelHitTest(list.map((s) => s.box), point);+ return hit ? { ...list[hit.index], nx: hit.nx, ny: hit.ny } : null;+}++/**+ * Keep a pasted image inside the document. The document is sized by its panels+ * alone, so a paste can never grow it — dragged to the edge, it stops there. One+ * bigger than the document is held so it covers the whole of it.+ */+export function clampPaste(paste, docW, docH) {+ const scale = clampPasteScale(paste.scale);+ const w = paste.natural[0] * scale;+ const h = paste.natural[1] * scale;+ return {+ x: clamp(paste.x ?? 0, Math.min(0, docW - w), Math.max(0, docW - w)),+ y: clamp(paste.y ?? 0, Math.min(0, docH - h), Math.max(0, docH - h)),+ };+}+/** Serializable spec from runtime state (drops live image objects). */export function toSpec(proof) {return {@@ -776,6 +871,18 @@ export function toSpec(proof) {y: p.y ?? null,natural: p.natural,meta: p.meta ?? {},+ frame: normalizeFrame(p.frame), // decorative border; null → none+ })),+ // Pasted images, front→back. They have no `src`: the case holds nothing for+ // them beyond the file in the proof's own assets folder.+ pastes: (proof.pastes ?? []).map((p) => ({+ id: p.id, // kept so shapes stay bound to their paste on reload+ asset: p.asset,+ natural: p.natural,+ x: p.x ?? 0,+ y: p.y ?? 0,+ scale: clampPasteScale(p.scale),+ frame: normalizeFrame(p.frame),})),shapes: proof.shapes.map((s) => ({ ...s })),};@@ -948,16 +1055,6 @@ export function mediaPanelInput(m, mediaList = []) {};}-/**- * True when a media listing item is a satellite capture — mirrors the backend's- * `satellite.is_capture`. A capture *is* a media image (one file in `media/`),- * flagged by its sidecar `source.type`, so it surfaces in both the /media and- * /satellite listings; callers use this to avoid listing it under both.- */-export function isSatelliteCapture(item) {- return (item?.source ?? {}).type === 'satellite';-}-/*** Collapse picker items that share a `src` down to their first occurrence.* The picker builds its list so no `src` repeats, but a duplicate key would@@ -1208,32 +1305,6 @@ export function canReassignLegendNote(notes, oldColor, newColor, shapes, moving));}-// ---- saved-proof case queries ------------------------------------------------/** Filed proof entities in a case (those whose `attrs.spec` is `proofs/*.json`). */-export function savedProofEntities(entities) {- return (entities ?? []).filter((e) => {- const s = e.attrs?.spec;- return typeof s === 'string' && s.startsWith('proofs/') && s.endsWith('.json');- });-}--/** Slugs (filename without `proofs/….json`) of every saved proof — the collision set. */-export function savedProofSlugs(entities) {- return new Set(savedProofEntities(entities).map((e) => e.attrs.spec.slice(7, -5)));-}--/** Titles of every saved proof, so a fresh title can read apart from them. */-export function savedProofTitles(entities) {- return new Set(savedProofEntities(entities).map((e) => e.label ?? ''));-}--/** Title of the saved proof with slug `name`, for the overwrite prompt. */-export function savedProofTitle(entities, name) {- const e = savedProofEntities(entities).find((x) => x.attrs.spec === `proofs/${name}.json`);- return e?.label ?? name;-}-export function loadImage(url) {return new Promise((resolve, reject) => {const img = new Image();diff --git a/frontend/src/lib/composer.test.js b/frontend/src/lib/composer.test.jsindex c6f1647..3fedea4 100644--- a/frontend/src/lib/composer.test.js+++ b/frontend/src/lib/composer.test.js@@ -6,19 +6,20 @@ import {docSize, legendColumns, legendRowCount, toSpec, offsetShape, copyShapeSpec, autoLayoutRows, TWEET_GUIDES,autoCoords, formatCoords, resolveSourceUrls, autoSource, autoSourceUrls,proofCoordsText, proofSource, orderedFeatureColors, legendLines,- dedupeBySrc, isSatelliteCapture, satPanelInput, mediaPanelInput,+ dedupeBySrc, satPanelInput, mediaPanelInput,SIG_MARGIN, SIG_SCALE, newSignature, signatureBox, signatureOffset, signaturePairPositions,- proofSlug, uniqueProofTitle, proofTitleFromCase, DEFAULT_PROOF_TITLE,- filterProofPanelItems, hasProofCanvasContent,+ filterProofPanelItems, hasProofCanvasContent, panelPreview,remapPanelXY, panelHitTest, groupNeighborIndex, hasGroupNeighbor,denseRowValues, clampPanelScale, trimClosingDuplicate, smoothFreehandPoints,freehandShape, canReassignLegendNote,- savedProofEntities, savedProofSlugs, savedProofTitles, savedProofTitle,BG, ANNO_COLORS, MAX_ANNO_COLORS, normSpace, isLightColor, textColors,normalizePreferredColors, replacePreferredColor,TEXT_MAIN, TEXT_MAIN_LIGHT, templateFromProof, applyProofStyle, normalizeProofStyle,anchoredPos, anchoredOffset, newSignatureText, SIG_TEXT_SIZE,orientFirstPanels, proofExportOptions,+ normalizeFrame, newFrame, FRAME_COLOR, FRAME_WIDTH, FRAME_WIDTH_MAX,+ newPaste, pasteBoxes, pasteInsertScale, clampPasteScale, clampPaste,+ surfaces, surfaceHitTest, PASTE_SCALE_MAX, PASTE_SHARE,} from './composer.js';// natural is [width, height]; PANEL_H drives the per-row scale.@@ -737,27 +738,6 @@ describe('dedupeBySrc — picker items collapse on shared src', () => {});});-describe('isSatelliteCapture — a capture is a media image flagged by its source', () => {- it('is true for a media item whose source.type is satellite', () => {- expect(isSatelliteCapture({ kind: 'image', source: { type: 'satellite' } })).toBe(true);- });-- it('is false for an ordinary image, and tolerates a missing source', () => {- expect(isSatelliteCapture({ kind: 'image', source: { type: 'download' } })).toBe(false);- expect(isSatelliteCapture({ kind: 'image' })).toBe(false);- expect(isSatelliteCapture({})).toBe(false);- });-- it('lets the picker drop captures from the media half so nothing double-lists', () => {- const media = [- { path: 'media/sat_1.png', kind: 'image', source: { type: 'satellite' } },- { path: 'media/photo.jpg', kind: 'image', source: { type: 'download' } },- ];- const kept = media.filter((m) => m.kind === 'image' && !isSatelliteCapture(m));- expect(kept.map((m) => m.path)).toEqual(['media/photo.jpg']);- });-});-describe('coordinate format threading — the reader’s format reaches captions, not provenance', () => {const capture = {path: 'media/sat_1.png',@@ -901,50 +881,6 @@ describe('orientFirstPanels — template direction', () => {});});-describe('proofSlug — mirrors the backend _slug', () => {- it('lowercases, hyphenates runs of non-alphanumerics, trims edges', () => {- expect(proofSlug('Untitled proof')).toBe('untitled-proof');- expect(proofSlug(' Rooftop! @ 12:30 ')).toBe('rooftop-12-30');- expect(proofSlug('Café déjà')).toBe('caf-d-j');- });-- it('falls back to "proof" when nothing survives, and caps at 80 chars', () => {- expect(proofSlug('')).toBe('proof');- expect(proofSlug('!!!')).toBe('proof');- expect(proofSlug(null)).toBe('proof');- expect(proofSlug('a'.repeat(200))).toHaveLength(80);- });-});--describe('uniqueProofTitle — a fresh proof reads apart from the case', () => {- it('returns the base when no proof carries it', () => {- expect(uniqueProofTitle(DEFAULT_PROOF_TITLE, new Set())).toBe('Untitled proof');- expect(uniqueProofTitle(DEFAULT_PROOF_TITLE, ['Rooftop'])).toBe('Untitled proof');- });-- it('numbers past the base and any run already taken', () => {- expect(uniqueProofTitle(DEFAULT_PROOF_TITLE, new Set(['Untitled proof']))).toBe('Untitled proof 2');- const taken = ['Untitled proof', 'Untitled proof 2', 'Untitled proof 3'];- expect(uniqueProofTitle(DEFAULT_PROOF_TITLE, taken)).toBe('Untitled proof 4');- });-- it('the numbered title still slugs to a distinct filename', () => {- expect(proofSlug(uniqueProofTitle(DEFAULT_PROOF_TITLE, ['Untitled proof']))).toBe('untitled-proof-2');- });-});--describe('proofTitleFromCase — new-proof name', () => {- it('uses the trimmed case name and keeps it unique among saved proofs', () => {- expect(proofTitleFromCase(' Harbour review ', [])).toBe('Harbour review');- expect(proofTitleFromCase('Harbour review', ['Harbour review'])).toBe('Harbour review 2');- });-- it('falls back to the normal untitled name when no case name is available', () => {- expect(proofTitleFromCase('', [])).toBe(DEFAULT_PROOF_TITLE);- expect(proofTitleFromCase(null, [DEFAULT_PROOF_TITLE])).toBe('Untitled proof 2');- });-});-describe('filterProofPanelItems — new-proof panel selector', () => {const items = [{@@ -953,24 +889,30 @@ describe('filterProofPanelItems — new-proof panel selector', () => {kind: 'satellite',meta: { provider: 'Esri World Imagery', imagery_date: '2026-07-01' },},- { src: 'media/storefront.jpg', label: 'Storefront.jpg', kind: 'media', meta: {} },- { src: 'media/roof.png', label: 'Red roof.png', kind: 'media', meta: {} },+ { src: 'media/IMG_4821.jpg', label: 'Storefront', folder: 'street', kind: 'media', meta: {} },+ { src: 'media/roof.png', label: 'Red roof', kind: 'media', meta: {} },];it('filters satellite captures independently from other images', () => {expect(filterProofPanelItems(items, '', 'satellite').map((item) => item.src)).toEqual(['media/satellite-city.png']);expect(filterProofPanelItems(items, '', 'media').map((item) => item.src))- .toEqual(['media/storefront.jpg', 'media/roof.png']);+ .toEqual(['media/IMG_4821.jpg', 'media/roof.png']);});- it('searches the active category by label, path, and satellite metadata', () => {+ it('searches the active category by title, folder, and satellite metadata', () => {expect(filterProofPanelItems(items, 'roof', 'media').map((item) => item.src)).toEqual(['media/roof.png']);+ expect(filterProofPanelItems(items, 'street', 'media').map((item) => item.src))+ .toEqual(['media/IMG_4821.jpg']);expect(filterProofPanelItems(items, 'esri', 'satellite').map((item) => item.src)).toEqual(['media/satellite-city.png']);expect(filterProofPanelItems(items, 'storefront', 'satellite')).toEqual([]);});++ it('ignores the file name, so a camera name cannot crowd out the titles', () => {+ expect(filterProofPanelItems(items, 'img_4821', 'all')).toEqual([]);+ });});describe('hasProofCanvasContent — empty template-only proof', () => {@@ -1128,33 +1070,6 @@ describe('canReassignLegendNote — move a note with a recolored shape', () => {});});-describe('saved-proof case queries', () => {- const entities = [- { label: 'Rooftop', attrs: { spec: 'proofs/rooftop.json' } },- { label: 'Bridge', attrs: { spec: 'proofs/bridge.json' } },- { label: 'A place', attrs: { spec: 'places/x.json' } }, // not a proof- { label: 'No spec' },- ];-- it('picks only entities filed as proofs/*.json', () => {- expect(savedProofEntities(entities).map((e) => e.label)).toEqual(['Rooftop', 'Bridge']);- expect(savedProofEntities(undefined)).toEqual([]);- });-- it('lists the slugs (filename without proofs/ and .json)', () => {- expect(savedProofSlugs(entities)).toEqual(new Set(['rooftop', 'bridge']));- });-- it('lists the titles', () => {- expect(savedProofTitles(entities)).toEqual(new Set(['Rooftop', 'Bridge']));- });-- it('resolves a title by slug, falling back to the slug itself', () => {- expect(savedProofTitle(entities, 'bridge')).toBe('Bridge');- expect(savedProofTitle(entities, 'unknown')).toBe('unknown');- });-});-describe('isLightColor + textColors — text tracks the proof background', () => {it('reads dark backgrounds as dark and pale ones as light', () => {expect(isLightColor('#0d1117')).toBe(false);@@ -1609,3 +1524,145 @@ describe('anchoredPos / anchoredOffset — the text-signature placement', () =>expect(s).not.toHaveProperty('text');});});++describe('panelPreview', () => {+ it('uses the cached thumbnail, never the full-size original', () => {+ const preview = panelPreview({+ path: 'media/big.jpg',+ thumbnail: 'media/.thumbs/abc-g2.jpg',+ thumb_state: 'ready',+ });++ expect(preview).toEqual({ thumb: 'media/.thumbs/abc-g2.jpg', thumbPending: false });+ });++ it('reports a thumbnail the worker has not produced yet as pending', () => {+ for (const state of ['queued', 'running']) {+ expect(panelPreview({ path: 'media/clip.mp4', thumbnail: null, thumb_state: state }))+ .toEqual({ thumb: null, thumbPending: true });+ }+ });++ it('offers no preview at all when the thumbnail failed or cannot exist', () => {+ for (const state of ['failed', 'none']) {+ expect(panelPreview({ path: 'media/x.wav', thumbnail: null, thumb_state: state }))+ .toEqual({ thumb: null, thumbPending: false });+ }+ });++ it('treats an untagged item as having no preview rather than showing the original', () => {+ // an older listing (or one that lost its cached file) must not make the+ // picker decode a multi-megabyte capture per cell+ expect(panelPreview({ path: 'media/sat.png' })).toEqual({ thumb: null, thumbPending: false });+ });+});++describe('frames', () => {+ it('a frame is a colour and a thickness, and width 0 means no frame', () => {+ expect(newFrame()).toEqual({ color: FRAME_COLOR, width: FRAME_WIDTH });+ expect(normalizeFrame({ color: '#40C4FF', width: 4 })).toEqual({ color: '#40c4ff', width: 4 });+ expect(normalizeFrame({ color: '#40c4ff', width: 0 })).toBeNull();+ expect(normalizeFrame(null)).toBeNull();+ });++ it('falls back on a garbled colour and bounds the thickness', () => {+ expect(normalizeFrame({ color: 'red', width: 3 })).toEqual({ color: FRAME_COLOR, width: 3 });+ expect(normalizeFrame({ color: '#ffffff', width: 999 }).width).toBe(FRAME_WIDTH_MAX);+ expect(normalizeFrame({ color: '#ffffff', width: 2.6 }).width).toBe(3);+ });++ it('stays out of the legend: framing a panel explains nothing on its own', () => {+ const shapes = [{ id: 's1', panel: 'p1', kind: 'rect', color: '#ff5252' }];+ const framed = [{ ...landscape(), id: 'p1', frame: { color: '#69f0ae', width: 8 } }];+ const spec = toSpec({ title: 'x', panels: framed, shapes, notes: {} });++ expect(spec.panels[0].frame).toEqual({ color: '#69f0ae', width: 8 });+ expect(orderedFeatureColors(spec.shapes)).toEqual(['#ff5252']); // not the frame colour+ });+});++describe('pasted images', () => {+ const paste = (extra = {}) => ({ id: 'x1', asset: 'a1.png', natural: [800, 400], x: 0, y: 0, scale: 1, ...extra });++ it('a paste carries no source, so nothing in the case can claim it', () => {+ const p = newPaste('deadbeefdeadbeef.png', [640, 480]);+ expect(p).toMatchObject({ asset: 'deadbeefdeadbeef.png', natural: [640, 480], scale: 1, frame: null });+ expect(p).not.toHaveProperty('src');+ expect(p.id).toBeTruthy();+ });++ it('lands at a share of the document width, never blown up past life size', () => {+ expect(pasteInsertScale([2000, 1000], 1000)).toBeCloseTo((1000 * PASTE_SHARE) / 2000, 3);+ expect(pasteInsertScale([100, 100], 4000)).toBe(1); // small image stays 1:1+ expect(clampPasteScale(99)).toBe(PASTE_SCALE_MAX);+ expect(clampPasteScale(undefined)).toBe(1);+ });++ it('boxes look like panel boxes, so an annotation binds to either', () => {+ const [box] = pasteBoxes([paste({ x: 40, y: 60, scale: 0.5 })]);+ expect(box).toEqual({ x: 40, y: 60, w: 400, h: 200, scale: 0.5, baseScale: 1, row: 0 });+ });++ it('stays inside the document however far it is dragged', () => {+ const inside = clampPaste(paste({ x: 5000, y: -300, scale: 1 }), 1000, 800);+ expect(inside).toEqual({ x: 200, y: 0 }); // 1000-800 wide, 800-400 tall → pinned at the edge++ // one wider than the document is held so it covers the whole of it+ const wide = clampPaste(paste({ x: 500, y: 0, natural: [2000, 400] }), 1000, 800);+ expect(wide.x).toBe(0);+ expect(clampPaste(paste({ x: -5000, y: 0, natural: [2000, 400] }), 1000, 800).x).toBe(-1000);+ });++ it('sits in front of the panels for hit-testing', () => {+ const proof = {+ captionSize: 20,+ layout: 'grid',+ panels: [{ ...landscape(1000, 500), id: 'p1' }],+ pastes: [paste({ x: PAD, y: PAD, natural: [200, 200] })],+ };+ const list = surfaces(proof);+ expect(list.map((s) => s.kind)).toEqual(['paste', 'panel']);++ // a point over both resolves to the paste, in the paste's own pixels+ const hit = surfaceHitTest(list, { x: PAD + 10, y: PAD + 20 });+ expect(hit.kind).toBe('paste');+ expect(hit.id).toBe('x1');+ expect([hit.nx, hit.ny]).toEqual([10, 20]);++ // a point past the paste still finds the panel underneath+ expect(surfaceHitTest(list, { x: PAD + 500, y: PAD + 300 }).kind).toBe('panel');+ expect(surfaceHitTest(list, { x: -50, y: -50 })).toBeNull();+ });++ it('never changes the size of the document', () => {+ const panels = [{ ...landscape(1000, 500), id: 'p1', row: 0 }];+ const bare = docSize(panels, [], {}, {}, [], 'grid');+ // a paste is not passed to docSize at all — it cannot grow or move the doc+ expect(docSize(panels, [], {}, {}, [], 'grid')).toEqual(bare);+ expect(pasteBoxes([paste({ x: 9999 })])[0].x).toBe(9999); // stored as-is; clamping is the caller's+ });++ it('round-trips through the spec with its frame and its z-order', () => {+ const spec = toSpec({+ title: 'x',+ panels: [{ ...landscape(), id: 'p1' }],+ shapes: [{ id: 's1', panel: 'x1', kind: 'rect', color: '#ff5252' }],+ pastes: [+ paste({ id: 'x1', x: 12, y: 34, scale: 0.25, frame: { color: '#ffd740', width: 5 } }),+ paste({ id: 'x2', asset: 'b2.png' }),+ ],+ notes: {},+ });++ expect(spec.pastes).toEqual([+ { id: 'x1', asset: 'a1.png', natural: [800, 400], x: 12, y: 34, scale: 0.25, frame: { color: '#ffd740', width: 5 } },+ { id: 'x2', asset: 'b2.png', natural: [800, 400], x: 0, y: 0, scale: 1, frame: null },+ ]);+ // a shape bound to a paste survives, exactly like one bound to a panel+ expect(spec.shapes[0].panel).toBe('x1');+ });++ it('a proof with no pastes still writes an empty list, so reloads are uniform', () => {+ expect(toSpec({ title: 'x', panels: [], shapes: [], notes: {} }).pastes).toEqual([]);+ });+});diff --git a/frontend/src/lib/entityIcon.js b/frontend/src/lib/entityIcon.jsnew file mode 100644index 0000000..2fc174b--- /dev/null+++ b/frontend/src/lib/entityIcon.js@@ -0,0 +1,35 @@+/** Icon name for a case entity, shared by the sidebar rows and result list. */++export const ENTITY_ICONS = {+ person: 'user',+ organization: 'layers',+ alias: 'user',+ account: 'globe',+ email: 'note',+ phone: 'hash',+ place: 'pin',+ capture: 'satellite',+ event: 'clock',+ media: 'image',+ proof: 'proof',+ post: 'post',+ domain: 'globe',+ ip: 'hash',+ vehicle: 'grip',+ note: 'note',+ 'inspect-session': 'inspect',+};++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+ * that attr existed. */+export function isVideoEntity(e) {+ if (e.attrs?.kind) return e.attrs.kind === 'video';+ const ext = e.attrs?.path?.split('.').pop()?.toLowerCase();+ return !!ext && VIDEO_EXTS.has(ext);+}++export const entityIcon = (e) =>+ e.type === 'media' && isVideoEntity(e) ? 'video' : ENTITY_ICONS[e.type] ?? 'note';diff --git a/frontend/src/lib/entityIcon.test.js b/frontend/src/lib/entityIcon.test.jsnew file mode 100644index 0000000..a83073a--- /dev/null+++ b/frontend/src/lib/entityIcon.test.js@@ -0,0 +1,27 @@+import { describe, expect, it } from 'vitest';+import { entityIcon, isVideoEntity } from './entityIcon.js';++describe('entityIcon', () => {+ it('maps a type to its icon and falls back to the note glyph', () => {+ expect(entityIcon({ type: 'place', attrs: {} })).toBe('pin');+ expect(entityIcon({ type: 'capture', attrs: {} })).toBe('satellite');+ expect(entityIcon({ type: 'whatever-new', attrs: {} })).toBe('note');+ });++ it('tells video media from images', () => {+ expect(entityIcon({ type: 'media', attrs: { kind: 'video' } })).toBe('video');+ expect(entityIcon({ type: 'media', attrs: { kind: 'image' } })).toBe('image');+ });+});++describe('isVideoEntity', () => {+ it('falls back to the extension for media filed before `kind` existed', () => {+ expect(isVideoEntity({ attrs: { path: 'raw/clip_04.MP4' } })).toBe(true);+ expect(isVideoEntity({ attrs: { path: 'raw/frame.png' } })).toBe(false);+ expect(isVideoEntity({ attrs: {} })).toBe(false);+ });++ it('trusts `kind` over the extension', () => {+ expect(isVideoEntity({ attrs: { kind: 'image', path: 'weird.mp4' } })).toBe(false);+ });+});diff --git a/frontend/src/lib/fileSort.js b/frontend/src/lib/fileSort.jsnew file mode 100644index 0000000..c78c027--- /dev/null+++ b/frontend/src/lib/fileSort.js@@ -0,0 +1,66 @@+/** Stable sorting helpers for the Files details view. */++function textOf(value) {+ return String(value ?? '');+}++function compareText(a, b) {+ return textOf(a).localeCompare(textOf(b), undefined, {+ numeric: true,+ sensitivity: 'base',+ });+}++function compareNullable(a, b, compare) {+ const aMissing = a == null;+ const bMissing = b == null;+ if (aMissing || bMissing) {+ if (aMissing && bMissing) return 0;+ return aMissing ? 1 : -1;+ }+ return compare(a, b);+}++/**+ * Return a sorted copy of entity rows. Missing Size/Added values stay at the+ * end in either direction, like a desktop file manager.+ */+export function sortFileEntities(+ items,+ { sort = 'name', direction = 'asc', sizeOf = () => null } = {}+) {+ const sign = direction === 'desc' ? -1 : 1;+ const out = [...items];+ const name = (item) => item.label ?? '';+ const primary = (a, b) => {+ if (sort === 'type') return compareText(a.type, b.type);+ if (sort === 'size') return compareNullable(sizeOf(a), sizeOf(b), (x, y) => x - y);+ if (sort === 'recent') {+ return compareNullable(+ a.provenance?.at,+ b.provenance?.at,+ (x, y) => compareText(x, y)+ );+ }+ return compareText(name(a), name(b));+ };++ out.sort((a, b) => {+ const valueOf = (item) => {+ if (sort === 'size') return sizeOf(item);+ if (sort === 'recent') return item.provenance?.at;+ return null;+ };+ const aValue = valueOf(a);+ const bValue = valueOf(b);+ if ((sort === 'size' || sort === 'recent') && (aValue == null || bValue == null)) {+ if (aValue == null && bValue == null) return 0;+ return aValue == null ? 1 : -1;+ }+ const result = primary(a, b);+ if (result) return result * sign;+ if (sort !== 'name') return compareText(name(a), name(b));+ return 0;+ });+ return out;+}diff --git a/frontend/src/lib/fileSort.test.js b/frontend/src/lib/fileSort.test.jsnew file mode 100644index 0000000..0cc41be--- /dev/null+++ b/frontend/src/lib/fileSort.test.js@@ -0,0 +1,42 @@+import { describe, expect, it } from 'vitest';+import { sortFileEntities } from './fileSort.js';++const entity = (id, label, extra = {}) => ({+ id,+ label,+ type: 'media',+ provenance: { at: '2026-01-01T00:00:00Z' },+ ...extra,+});++describe('sortFileEntities', () => {+ const rows = [+ entity('1', 'file 10', { type: 'note', provenance: { at: '2026-01-03T00:00:00Z' } }),+ entity('2', 'file 2', { type: 'media', provenance: { at: '2026-01-01T00:00:00Z' } }),+ entity('3', 'file 1', { type: 'proof', provenance: { at: '2026-01-02T00:00:00Z' } }),+ ];++ it('sorts names naturally in both directions', () => {+ expect(sortFileEntities(rows).map((e) => e.label)).toEqual(['file 1', 'file 2', 'file 10']);+ expect(sortFileEntities(rows, { direction: 'desc' }).map((e) => e.label)).toEqual([+ 'file 10', 'file 2', 'file 1',+ ]);+ });++ it('sorts type, size and added values across the complete input', () => {+ expect(sortFileEntities(rows, { sort: 'type' }).map((e) => e.id)).toEqual(['2', '1', '3']);+ const sizes = { 1: 100, 2: 10, 3: 50 };+ expect(sortFileEntities(rows, { sort: 'size', sizeOf: (e) => sizes[e.id] }).map((e) => e.id)).toEqual([+ '2', '3', '1',+ ]);+ expect(sortFileEntities(rows, { sort: 'recent', direction: 'desc' }).map((e) => e.id)).toEqual([+ '1', '3', '2',+ ]);+ });++ it('keeps missing values last in either direction', () => {+ const withMissing = [...rows, entity('4', 'missing', { provenance: {} })];+ expect(sortFileEntities(withMissing, { sort: 'recent' }).at(-1).id).toBe('4');+ expect(sortFileEntities(withMissing, { sort: 'recent', direction: 'desc' }).at(-1).id).toBe('4');+ });+});diff --git a/frontend/src/lib/folderBrowse.js b/frontend/src/lib/folderBrowse.jsnew file mode 100644index 0000000..c4a7734--- /dev/null+++ b/frontend/src/lib/folderBrowse.js@@ -0,0 +1,45 @@+/**+ * The read-only folder browser behind the modal pickers (Inspect sources and+ * sessions, Reverse Search media, Proof panels and saved proofs). A picker+ * lists a flat, searchable set by default and drops into this view when the+ * analyst presses "…": crumbs, folder rows, then the entries filed there.+ *+ * `buildTree` (folderTree.js) turns the folder strings into the node tree;+ * these helpers walk it. Entries carry their folder on `attrs.folder`, matching+ * the catalog entity shape.+ */++/** Sentinel path for entries with no folder. Not a real folder name — the empty+ * string already means "browser root". */+export const UNFILED = '\u0000unfiled';++/** The node to render for `path`: its child folders and the entries filed in+ * it. The root lists Unfiled first, then the tree; an unknown path is empty. */+export function browserView(tree, entries, path) {+ if (path === UNFILED) return { children: [], entities: entries.filter((entry) => !entry.attrs?.folder) };+ if (!path) return { children: [{ name: 'Unfiled', path: UNFILED, children: [], entities: [] }, ...tree], entities: [] };+ let children = tree;+ let node = null;+ for (const segment of path.split('/')) {+ node = children.find((child) => child.name === segment) ?? null;+ if (!node) return { children: [], entities: [] };+ children = node.children;+ }+ return node;+}++/** The crumb trail for `path`, root excluded (the pickers label the root). */+export function browseCrumbs(path) {+ if (!path) return [];+ if (path === UNFILED) return [{ name: 'Unfiled', path: UNFILED }];+ return path.split('/').map((name, i, parts) => ({ name, path: parts.slice(0, i + 1).join('/') }));+}++/** Every whitespace-separated term of `query` appears in `text`. An empty+ * query matches everything. */+export function matchesTerms(text, query) {+ const q = String(query ?? '').trim().toLowerCase();+ if (!q) return true;+ const haystack = String(text ?? '').toLowerCase();+ return q.split(/\s+/).every((term) => haystack.includes(term));+}diff --git a/frontend/src/lib/folderBrowse.test.js b/frontend/src/lib/folderBrowse.test.jsnew file mode 100644index 0000000..30b6c03--- /dev/null+++ b/frontend/src/lib/folderBrowse.test.js@@ -0,0 +1,70 @@+import { describe, expect, it } from 'vitest';+import { buildTree } from './folderTree.js';+import { UNFILED, browseCrumbs, browserView, matchesTerms } from './folderBrowse.js';++const entries = [+ { id: 'a', attrs: { folder: '' } },+ { id: 'b', attrs: { folder: 'field' } },+ { id: 'c', attrs: { folder: 'field/day-1' } },+];+const tree = () => buildTree(['field', 'field/day-1'], entries);++describe('browserView', () => {+ it('lists Unfiled first at the root, and no entries there', () => {+ const view = browserView(tree(), entries, '');++ expect(view.children[0]).toMatchObject({ name: 'Unfiled', path: UNFILED });+ expect(view.children.map((c) => c.name)).toContain('field');+ expect(view.entities).toEqual([]);+ });++ it('collects the folderless entries under Unfiled', () => {+ const view = browserView(tree(), entries, UNFILED);++ expect(view.entities.map((e) => e.id)).toEqual(['a']);+ expect(view.children).toEqual([]);+ });++ it('walks a nested path down to the entries filed there', () => {+ const view = browserView(tree(), entries, 'field/day-1');++ expect(view.entities.map((e) => e.id)).toEqual(['c']);+ });++ it('returns an empty view for a folder that does not exist', () => {+ expect(browserView(tree(), entries, 'field/day-9')).toEqual({ children: [], entities: [] });+ });+});++describe('browseCrumbs', () => {+ it('has no crumbs at the root', () => {+ expect(browseCrumbs('')).toEqual([]);+ });++ it('names the Unfiled bucket', () => {+ expect(browseCrumbs(UNFILED)).toEqual([{ name: 'Unfiled', path: UNFILED }]);+ });++ it('builds one crumb per segment, each with its own path', () => {+ expect(browseCrumbs('field/day-1')).toEqual([+ { name: 'field', path: 'field' },+ { name: 'day-1', path: 'field/day-1' },+ ]);+ });+});++describe('matchesTerms', () => {+ it('matches everything on an empty query', () => {+ expect(matchesTerms('anything', ' ')).toBe(true);+ expect(matchesTerms('', '')).toBe(true);+ });++ it('requires every term, in any order and any case', () => {+ expect(matchesTerms('Bridge north bank', 'north BRIDGE')).toBe(true);+ expect(matchesTerms('Bridge north bank', 'north river')).toBe(false);+ });++ it('tolerates missing text', () => {+ expect(matchesTerms(undefined, 'north')).toBe(false);+ });+});diff --git a/frontend/src/lib/folderView.js b/frontend/src/lib/folderView.jsnew file mode 100644index 0000000..a89b92c--- /dev/null+++ b/frontend/src/lib/folderView.js@@ -0,0 +1,79 @@+/**+ * The Saved panel's other tree: My-work folders instead of geography.+ *+ * Same index, same filters, same node shape as `buildGeoTree` — the panel+ * renders whichever tree it is handed through one snippet. Structure comes from+ * `folderTree.js`, which the case sidebar and Files already build on, so a+ * folder means the same thing everywhere in the app.+ *+ * Pure and synchronous: the index and the case's folder list are both already+ * in memory.+ */++import { buildTree } from './folderTree.js';+import { filterSaved } from './geoTree.js';++/** Where an item that was never filed goes, and what that bucket is called. */+export const UNFILED = 'Unfiled';++const newestFirst = (rows) =>+ [...rows].sort((a, b) => String(b.fetched_at ?? '').localeCompare(String(a.fetched_at ?? '')));++/** Turn one `folderTree.js` node into the shape the panel renders. A folder can+ * hold subfolders *and* items, which a geography node never does. */+function toNode(node) {+ const children = node.children.map(toNode);+ const items = newestFirst(node.entities);+ return {+ level: 'folder',+ name: node.name,+ label: node.name,+ key: node.path,+ // what is filed below, not only what is filed directly here — a collapsed+ // folder must still say how much work is inside it+ count: items.length + children.reduce((sum, child) => sum + child.count, 0),+ children,+ items,+ };+}++/**+ * The folder tree for one kind + query.+ *+ * `folders` is the case's own folder list: passing it is what makes an empty+ * folder — or one holding only media — appear, and therefore reachable as a+ * drop target. Folders named only by the rows are merged in, so an item filed+ * into a path that was never an explicit folder still has a node.+ *+ * Returns `{ nodes, unfiled }`. `unfiled` is a node like any other and always+ * renders last; its count is 0 when everything is filed.+ */+export function buildFolderTree(rows, folders = [], { kind = 'all', query = '' } = {}) {+ const shown = filterSaved(rows, { kind, query });+ const filed = [];+ const stray = [];+ for (const row of shown) (row.folder ? filed : stray).push(row);++ const paths = [...new Set([...(folders ?? []).filter(Boolean), ...filed.map((row) => row.folder)])];+ // folderTree.js reads the folder off `attrs`, the catalog entity shape+ const entities = filed.map((row) => ({ ...row, attrs: { folder: row.folder } }));++ return {+ nodes: buildTree(paths, entities).map(toNode),+ unfiled: {+ level: 'unfiled',+ name: UNFILED,+ label: UNFILED,+ key: UNFILED,+ count: stray.length,+ children: [],+ items: newestFirst(stray),+ },+ };+}++/** The node key holding `row` — the address the panel expands to when something+ * elsewhere asks to reveal one saved item. */+export function keyForFolder(row) {+ return row?.folder || UNFILED;+}diff --git a/frontend/src/lib/folderView.test.js b/frontend/src/lib/folderView.test.jsnew file mode 100644index 0000000..a1631f8--- /dev/null+++ b/frontend/src/lib/folderView.test.js@@ -0,0 +1,85 @@+import { describe, expect, it } from 'vitest';+import { buildFolderTree, keyForFolder, UNFILED } from './folderView.js';++const row = (id, folder, extra = {}) => ({+ id,+ kind: 'place',+ title: id,+ folder,+ fetched_at: '2026-07-20T09:00:00Z',+ geo: { state: 'ok', country: 'Ukraine', country_code: 'ua', region: 'Kyiv' },+ ...extra,+});++const rows = [+ row('a', 'Recon'),+ row('b', 'Recon/North'),+ row('c', ''),+ row('d', 'Recon/North', { kind: 'capture', title: 'crop', fetched_at: '2026-07-21T09:00:00Z' }),+];++const find = (nodes, name) => nodes.find((node) => node.name === name);++describe('buildFolderTree', () => {+ it('nests folders and attaches items to the exact folder they are filed in', () => {+ const { nodes } = buildFolderTree(rows, []);+ const recon = find(nodes, 'Recon');+ expect(recon.items.map((i) => i.id)).toEqual(['a']);+ expect(find(recon.children, 'North').items.map((i) => i.id)).toEqual(['d', 'b']); // newest first+ });++ it('counts the whole subtree, not only what is filed directly in the node', () => {+ const { nodes } = buildFolderTree(rows, []);+ expect(find(nodes, 'Recon').count).toBe(3);+ expect(find(find(nodes, 'Recon').children, 'North').count).toBe(2);+ });++ it('collects unfiled items in their own trailing node', () => {+ const { nodes, unfiled } = buildFolderTree(rows, []);+ expect(unfiled.key).toBe(UNFILED);+ expect(unfiled.count).toBe(1);+ expect(unfiled.items.map((i) => i.id)).toEqual(['c']);+ expect(nodes.some((node) => node.name === UNFILED)).toBe(false);+ });++ it("shows the case's own folders, so an empty or media-only one can be dropped into", () => {+ const { nodes } = buildFolderTree(rows, ['Recon', 'Recon/North', 'Imagery', 'Imagery/Raw']);+ expect(nodes.map((n) => n.name)).toEqual(['Imagery', 'Recon']);+ const imagery = find(nodes, 'Imagery');+ expect(imagery.count).toBe(0);+ expect(imagery.children.map((c) => c.name)).toEqual(['Raw']);+ });++ it('keeps a folder named only by a row, even when the case never declared it', () => {+ const { nodes } = buildFolderTree([row('x', 'Stray/Deep')], []);+ expect(find(find(nodes, 'Stray').children, 'Deep').items.map((i) => i.id)).toEqual(['x']);+ });++ it('filters by kind and by query before grouping, so the counts match the screen', () => {+ const captures = buildFolderTree(rows, [], { kind: 'captures' });+ expect(find(captures.nodes, 'Recon').count).toBe(1);+ expect(captures.unfiled.count).toBe(0);++ const searched = buildFolderTree(rows, [], { query: 'crop' });+ expect(find(searched.nodes, 'Recon').count).toBe(1);+ });++ it('gives every node its folder path as key, so a branch can be expanded', () => {+ const { nodes } = buildFolderTree(rows, []);+ expect(find(nodes, 'Recon').key).toBe('Recon');+ expect(find(find(nodes, 'Recon').children, 'North').key).toBe('Recon/North');+ });++ it('reads no folders at all as one Unfiled bucket', () => {+ const { nodes, unfiled } = buildFolderTree([row('a', ''), row('b', '')], []);+ expect(nodes).toEqual([]);+ expect(unfiled.count).toBe(2);+ });+});++describe('keyForFolder', () => {+ it('addresses a filed row by its folder and an unfiled one by the bucket', () => {+ expect(keyForFolder(row('a', 'Recon/North'))).toBe('Recon/North');+ expect(keyForFolder(row('a', ''))).toBe(UNFILED);+ });+});diff --git a/frontend/src/lib/geoTree.js b/frontend/src/lib/geoTree.jsnew file mode 100644index 0000000..2986b9c--- /dev/null+++ b/frontend/src/lib/geoTree.js@@ -0,0 +1,236 @@+/**+ * The Saved panel's geography tree: continent › country › region › items.+ *+ * Saved work is browsed by *where it is*, not by how far you have scrolled, so+ * this turns the flat saved index (GET /satellite/index) into the tree the+ * panel renders. Pure and synchronous — the whole index is already in memory,+ * so filtering and grouping never touch the network.+ *+ * Continent is derived server-side from the country code; nothing here talks to+ * a geocoder.+ */++import { matchesTerms } from './folderBrowse.js';+import { haversine } from './measure.js';++/** The switch's four positions. The first three filter the saved rows — a+ * screenshot is a capture with a different origin, not a thing to choose+ * between. The fourth is a *mode*: a proof carries no point of its own and+ * borrows its capture's, so drawing both at once would stack two marks on one+ * place. It swaps the rows the panel reads instead. */+export const KINDS = [+ { id: 'all', label: 'All' },+ { id: 'places', label: 'Places' },+ { id: 'captures', label: 'Captures' },+ { id: 'proofs', label: 'Proofs', mode: true },+];++/** True when this position swaps the row source rather than filtering it. */+export function isMode(kind) {+ return KINDS.some((k) => k.id === kind && k.mode);+}++/** Where an item with no country goes, and what that bucket is called. */+export const UNLOCATED = 'Unlocated';++/** A located country whose code isn't in the continent table still groups by+ * country — the country is the useful part, the continent is the shelf. */+const OTHER_CONTINENT = 'Other';++function matchesKind(row, kind) {+ if (kind === 'places') return row.kind === 'place';+ if (kind === 'captures') return row.kind === 'capture' || row.kind === 'screenshot';+ return true;+}++/** Everything a search over saved work reads: what it is called, what was+ * written about it, where it is, and who it came from. */+function savedText(row) {+ const geo = row.geo ?? {};+ // both spellings a pair of coordinates gets pasted in: the stored precision+ // and the rounded one the panel prints+ const coords =+ row.lat == null || row.lon == null+ ? ''+ : `${row.lat}, ${row.lon}\n${Number(row.lat).toFixed(4)}, ${Number(row.lon).toFixed(4)}`;+ return [+ row.title,+ row.notes,+ row.provider,+ row.site,+ geo.country,+ geo.region,+ // both spellings of the place, so "Russia" finds a case filed as Россия+ row.country_en,+ geo.region_en,+ row.continent,+ coords,+ ]+ .filter(Boolean)+ .join('\n');+}++/** One row per entity, keeping the first. A proof that composes captures in two+ * cities is two marks on the map — the map is about places — but one line in a+ * flat list, which is about things. */+export function oneEach(rows) {+ const seen = new Set();+ return (rows ?? []).filter((row) => !seen.has(row.id) && seen.add(row.id));+}++/** The rows a kind + query select, in the index's own newest-first order. */+export function filterSaved(rows, { kind = 'all', query = '' } = {}) {+ return (rows ?? []).filter((row) => matchesKind(row, kind) && matchesTerms(savedText(row), query));+}++/** How the search modal can order results. The tree has no sort control: its+ * order *is* the geography, and inside a leaf newest-first is the only one+ * that makes sense. */+export const SORTS = [+ { id: 'newest', label: 'Newest' },+ { id: 'title', label: 'Title' },+ { id: 'distance', label: 'Distance from map centre' },+];++/** Order a flat result list. `origin` is the map centre, and rows with no+ * coordinates sort to the end rather than pretending to be at 0°,0°. */+export function sortSaved(rows, sort = 'newest', origin = null) {+ const out = [...(rows ?? [])];+ if (sort === 'title') {+ return out.sort((a, b) => String(a.title ?? '').localeCompare(String(b.title ?? '')));+ }+ if (sort === 'distance' && origin) {+ const far = Number.POSITIVE_INFINITY;+ const away = (row) =>+ row.lat == null || row.lon == null+ ? far+ : haversine(origin, { lat: Number(row.lat), lon: Number(row.lon) });+ return out.sort((a, b) => away(a) - away(b));+ }+ return out.sort((a, b) => String(b.fetched_at ?? '').localeCompare(String(a.fetched_at ?? '')));+}++/** True once a country is known — the only state the tree can place. */+export function isLocated(row) {+ return row.geo?.state === 'ok' && !!row.geo?.country;+}++/** How many items a Locate pass would still have something to do about:+ * never attempted, or attempted and failed. Open sea and coordinate-less+ * items are settled, and asking again would only waste a lookup. */+export function pendingLocate(rows) {+ return (rows ?? []).filter((row) => !row.geo || row.geo.state === 'failed').length;+}++const newestFirst = (rows) =>+ [...rows].sort((a, b) => String(b.fetched_at ?? '').localeCompare(String(a.fetched_at ?? '')));++function labelAt(row, level) {+ if (level === 'continent') return row.continent || OTHER_CONTINENT;+ if (level === 'country') return row.geo.country;+ // Nominatim has no region for every point (city-states, small islands). The+ // country is then the finest honest name, and using it keeps the tree one+ // shape deep rather than letting some branches end a level early.+ return row.geo.region || row.geo.country;+}++/** How a place reads in the tree: `English (native)`, or one name when that is+ * all there is to say. Nominatim answers in the local language, which is right+ * for a proof or a post and hard to scan in a panel. */+export function bilingual(english, native) {+ const en = String(english ?? '').trim();+ const local = String(native ?? '').trim();+ if (!en) return local;+ if (!local || en === local) return en || local;+ return `${en} (${local})`;+}++/** The bilingual label for a node. The native name stays the identity (see+ * `group`); this is only what the analyst reads. */+function displayAt(row, level) {+ if (level === 'continent') return labelAt(row, level); // already English+ if (level === 'country') return bilingual(row.country_en, row.geo.country);+ if (row.geo.region) return bilingual(row.geo.region_en, row.geo.region);+ return bilingual(row.country_en, row.geo.country);+}++function group(rows, levels, prefix) {+ const [level, ...rest] = levels;+ const buckets = new Map();+ for (const row of rows) {+ // Grouped and keyed on the native name, never on the label: rows that+ // carry an English name and rows that don't belong in the same bucket,+ // and an expanded branch must survive a name gaining its translation.+ const name = labelAt(row, level);+ if (!buckets.has(name)) buckets.set(name, { rows: [], label: displayAt(row, level) });+ buckets.get(name).rows.push(row);+ }+ return [...buckets.entries()]+ .sort(([, a], [, b]) => a.label.localeCompare(b.label))+ .map(([name, bucket]) => {+ const key = prefix ? `${prefix}/${name}` : name;+ return {+ level,+ name,+ label: bucket.label,+ key,+ count: bucket.rows.length,+ children: rest.length ? group(bucket.rows, rest, key) : [],+ items: rest.length ? [] : newestFirst(bucket.rows),+ };+ });+}++/**+ * The tree for one kind + query.+ *+ * Levels are decided **globally**, over the whole filtered set, never per+ * branch: a case that sits in one continent doesn't show that continent, and+ * one that also sits in a single country opens straight on its regions. So the+ * tree has one depth at a time instead of a ragged mix, and the counts always+ * describe what the filter is showing.+ *+ * Returns `{ levels, nodes, unlocated }`. `unlocated` is a node like any other+ * and always renders last; its count is 0 when there is nothing in it.+ */+export function buildGeoTree(rows, { kind = 'all', query = '' } = {}) {+ const shown = filterSaved(rows, { kind, query });+ const placed = [];+ const stray = [];+ for (const row of shown) (isLocated(row) ? placed : stray).push(row);++ const continents = new Set(placed.map((row) => labelAt(row, 'continent')));+ const countries = new Set(placed.map((row) => row.geo.country));+ const levels = [];+ if (continents.size > 1) levels.push('continent');+ if (levels.length || countries.size > 1) levels.push('country');+ levels.push('region');++ return {+ levels,+ nodes: placed.length ? group(placed, levels, '') : [],+ unlocated: {+ level: 'unlocated',+ name: UNLOCATED,+ label: UNLOCATED,+ key: UNLOCATED,+ count: stray.length,+ children: [],+ items: newestFirst(stray),+ },+ };+}++/** Every node key on the path down to `key`, so opening a search result can+ * expand exactly the branch it lives in and nothing else. */+export function branchKeys(key) {+ const parts = String(key ?? '').split('/');+ return parts.map((_, i) => parts.slice(0, i + 1).join('/'));+}++/** The leaf key holding `row` in a tree of `levels` — the address the panel+ * expands to when something elsewhere asks to reveal one saved item. */+export function keyFor(row, levels) {+ if (!isLocated(row)) return UNLOCATED;+ return levels.map((level) => labelAt(row, level)).join('/');+}diff --git a/frontend/src/lib/geoTree.test.js b/frontend/src/lib/geoTree.test.jsnew file mode 100644index 0000000..8a00ff6--- /dev/null+++ b/frontend/src/lib/geoTree.test.js@@ -0,0 +1,303 @@+import { describe, expect, it } from 'vitest';+import {+ bilingual,+ branchKeys,+ buildGeoTree,+ filterSaved,+ isMode,+ keyFor,+ KINDS,+ oneEach,+ pendingLocate,+} from './geoTree.js';++const ok = (country, code, region, extra = {}) => ({+ geo: { state: 'ok', country, country_code: code, ...(region ? { region } : {}) },+ ...extra,+});++const row = (id, opts = {}) => ({+ id,+ kind: 'place',+ title: id,+ lat: 48,+ lon: 37,+ notes: '',+ fetched_at: `2026-07-2${id.length}T10:00:00Z`,+ continent: null,+ ...opts,+});++const UA = (id, region, extra = {}) =>+ row(id, { continent: 'Europe', ...ok('Ukraine', 'ua', region), ...extra });+const PL = (id, extra = {}) =>+ row(id, { continent: 'Europe', ...ok('Poland', 'pl', 'Mazovia'), ...extra });+const KE = (id, extra = {}) =>+ row(id, { continent: 'Africa', ...ok('Kenya', 'ke', 'Nairobi'), ...extra });++const names = (nodes) => nodes.map((n) => n.name);++describe('buildGeoTree levels', () => {+ it('groups by continent, country and region when the case spans several', () => {+ const tree = buildGeoTree([UA('a', 'Donetsk Oblast'), PL('b'), KE('c')]);++ expect(tree.levels).toEqual(['continent', 'country', 'region']);+ expect(names(tree.nodes)).toEqual(['Africa', 'Europe']);+ expect(names(tree.nodes[1].children)).toEqual(['Poland', 'Ukraine']);+ expect(names(tree.nodes[1].children[1].children)).toEqual(['Donetsk Oblast']);+ });++ it('drops the continent level when everything sits in one continent', () => {+ const tree = buildGeoTree([UA('a', 'Donetsk Oblast'), PL('b')]);++ expect(tree.levels).toEqual(['country', 'region']);+ expect(names(tree.nodes)).toEqual(['Poland', 'Ukraine']);+ });++ it('opens straight on regions when everything sits in one country', () => {+ const tree = buildGeoTree([UA('a', 'Donetsk Oblast'), UA('bb', 'Kyiv Oblast')]);++ expect(tree.levels).toEqual(['region']);+ expect(names(tree.nodes)).toEqual(['Donetsk Oblast', 'Kyiv Oblast']);+ });++ it('decides the depth over the whole set, not per branch', () => {+ // Kenya has one country in its continent; the tree must not end a level+ // early there just because that branch could+ const tree = buildGeoTree([UA('a', 'Donetsk Oblast'), KE('c')]);++ expect(tree.levels).toEqual(['continent', 'country', 'region']);+ expect(tree.nodes[0].children[0].children[0].name).toBe('Nairobi');+ });++ it('names a region-less country after itself rather than ending short', () => {+ const tree = buildGeoTree([UA('a', 'Donetsk Oblast'), row('bb', { continent: 'Europe', ...ok('Monaco', 'mc') })]);++ expect(tree.levels).toEqual(['country', 'region']);+ const monaco = tree.nodes.find((n) => n.name === 'Monaco');+ expect(names(monaco.children)).toEqual(['Monaco']);+ expect(monaco.children[0].items).toHaveLength(1);+ });++ it('shelves a country with no known continent instead of losing it', () => {+ const tree = buildGeoTree([UA('a', 'Donetsk Oblast'), row('bb', { continent: null, ...ok('Atlantis', 'zz', 'North') })]);++ expect(names(tree.nodes)).toEqual(['Europe', 'Other']);+ });+});++describe('buildGeoTree counts and order', () => {+ it('counts what is beneath each node', () => {+ const tree = buildGeoTree([UA('a', 'Donetsk Oblast'), UA('bb', 'Donetsk Oblast'), PL('ccc')]);++ expect(tree.nodes.map((n) => [n.name, n.count])).toEqual([+ ['Poland', 1],+ ['Ukraine', 2],+ ]);+ });++ it('sorts alphabetically at every level and newest first inside a leaf', () => {+ const older = UA('a', 'Donetsk Oblast', { fetched_at: '2026-01-01T00:00:00Z' });+ const newer = UA('bb', 'Donetsk Oblast', { fetched_at: '2026-07-01T00:00:00Z' });+ const tree = buildGeoTree([older, newer]);++ expect(tree.nodes[0].items.map((i) => i.id)).toEqual(['bb', 'a']);+ });+});++describe('buildGeoTree unlocated bucket', () => {+ it('collects everything with no country, whatever the reason', () => {+ const tree = buildGeoTree([+ UA('a', 'Donetsk Oblast'),+ row('bb', { geo: null }),+ row('ccc', { geo: { state: 'failed' } }),+ row('dddd', { geo: { state: 'nocoords' }, lat: null, lon: null }),+ row('eeeee', { geo: { state: 'nocountry' } }),+ ]);++ expect(tree.unlocated.count).toBe(4);+ expect(tree.nodes).toHaveLength(1);+ });++ it('is present but empty when everything is located', () => {+ expect(buildGeoTree([UA('a', 'Donetsk Oblast')]).unlocated.count).toBe(0);+ });++ it('does not let unplaced items decide the depth', () => {+ const tree = buildGeoTree([UA('a', 'Donetsk Oblast'), row('bb', { geo: null })]);++ expect(tree.levels).toEqual(['region']);+ });+});++describe('buildGeoTree filtering', () => {+ const rows = [+ UA('a', 'Donetsk Oblast', { kind: 'place', title: 'checkpoint north' }),+ UA('bb', 'Kyiv Oblast', { kind: 'capture', provider: 'Esri World Imagery' }),+ UA('ccc', 'Kyiv Oblast', { kind: 'screenshot', site: 'yandex-maps' }),+ ];++ it('treats a screenshot as a capture in the kind filter', () => {+ expect(filterSaved(rows, { kind: 'captures' }).map((r) => r.id)).toEqual(['bb', 'ccc']);+ expect(filterSaved(rows, { kind: 'places' }).map((r) => r.id)).toEqual(['a']);+ expect(filterSaved(rows, { kind: 'all' })).toHaveLength(3);+ });++ it('switches to proofs rather than mixing them into the saved rows', () => {+ // A proof sits on the capture it composes, so drawing both at once would+ // stack two marks on one point. The fourth position swaps the source+ // instead: `isMode` tells the panel to fetch, not to filter.+ expect(KINDS.map((k) => k.id)).toEqual(['all', 'places', 'captures', 'proofs']);+ expect(isMode('proofs')).toBe(true);+ expect(isMode('all')).toBe(false);++ // and the filter itself never has to know about proofs+ expect(filterSaved(rows, { kind: 'proofs' })).toHaveLength(3);+ });++ it('lists a two-place proof once, however many marks it draws', () => {+ // the map is about places, a flat list is about things+ const twice = [+ { ...rows[0], id: 'pr1', key: 'pr1@50,30', kind: 'proof', title: 'Two cities' },+ { ...rows[0], id: 'pr1', key: 'pr1@48,2', kind: 'proof', title: 'Two cities' },+ { ...rows[1] },+ ];++ expect(oneEach(twice).map((r) => r.key ?? r.id)).toEqual(['pr1@50,30', 'bb']);+ });++ it('searches title, notes, provider, site and geography', () => {+ const noted = UA('dddd', 'Kyiv Oblast', { notes: 'two vehicles at the gate' });+ const all = [...rows, noted];++ expect(filterSaved(all, { query: 'checkpoint' }).map((r) => r.id)).toEqual(['a']);+ expect(filterSaved(all, { query: 'vehicles' }).map((r) => r.id)).toEqual(['dddd']);+ expect(filterSaved(all, { query: 'esri' }).map((r) => r.id)).toEqual(['bb']);+ expect(filterSaved(all, { query: 'yandex' }).map((r) => r.id)).toEqual(['ccc']);+ expect(filterSaved(all, { query: 'ukraine' })).toHaveLength(4);+ expect(filterSaved(all, { query: 'donetsk' }).map((r) => r.id)).toEqual(['a']);+ });++ it('matches coordinates as they are read off a row', () => {+ expect(filterSaved(rows, { query: '48.0000, 37.0000' })).toHaveLength(3);+ });++ it('filters before grouping, so counts describe what is shown', () => {+ const tree = buildGeoTree(rows, { kind: 'captures' });++ expect(tree.levels).toEqual(['region']);+ expect(tree.nodes.map((n) => [n.name, n.count])).toEqual([['Kyiv Oblast', 2]]);+ });++ it('re-decides the depth on the filtered set', () => {+ const tree = buildGeoTree([UA('a', 'Donetsk Oblast'), KE('c')], { query: 'kenya' });++ expect(tree.levels).toEqual(['region']);+ expect(names(tree.nodes)).toEqual(['Nairobi']);+ });+});++describe('bilingual labels', () => {+ // a Russian case as the index hands it over: native geo, English country+ // derived server-side, English region only where a lookup answered+ const RU = (id, region, region_en, extra = {}) =>+ row(id, {+ continent: 'Europe',+ country_en: 'Russia',+ geo: {+ state: 'ok',+ country: 'Россия',+ country_code: 'ru',+ region,+ ...(region_en ? { region_en } : {}),+ },+ ...extra,+ });++ it('reads English first and the native name in brackets', () => {+ expect(bilingual('Russia', 'Россия')).toBe('Russia (Россия)');+ });++ it('says a name once when both languages agree, or when only one is known', () => {+ expect(bilingual('France', 'France')).toBe('France');+ expect(bilingual('', 'Московская область')).toBe('Московская область');+ expect(bilingual('Moscow Oblast', '')).toBe('Moscow Oblast');+ expect(bilingual(null, null)).toBe('');+ });++ it('labels country and region branches in both languages', () => {+ const tree = buildGeoTree([+ RU('a', 'Московская область', 'Moscow Oblast'),+ KE('bb'),+ ]);++ expect(tree.levels).toEqual(['continent', 'country', 'region']);+ const europe = tree.nodes.find((n) => n.name === 'Europe');+ expect(europe.children.map((n) => n.label)).toEqual(['Russia (Россия)']);+ expect(europe.children[0].children.map((n) => n.label)).toEqual([+ 'Moscow Oblast (Московская область)',+ ]);+ });++ it('keeps one bucket when only some of its rows carry an English region', () => {+ // rows saved before the tree spoke English sit in the same region as new+ // ones; grouping on the label would split the branch in two+ const tree = buildGeoTree([+ RU('a', 'Московская область', 'Moscow Oblast'),+ RU('bb', 'Московская область'),+ ]);++ expect(tree.nodes.map((n) => [n.name, n.label, n.count])).toEqual([+ ['Московская область', 'Moscow Oblast (Московская область)', 2],+ ]);+ // the key is the native name, so reveal-from-elsewhere still finds it+ expect(keyFor(RU('bb', 'Московская область'), tree.levels)).toBe(tree.nodes[0].key);+ });++ it('orders branches by what is on screen', () => {+ const tree = buildGeoTree([RU('a', 'Московская область', 'Moscow Oblast'), KE('bb')]);+ // Russia sorts under R, not under Р — the tree reads in English+ expect(tree.nodes.map((n) => n.label)).toEqual(['Africa', 'Europe']);+ });++ it('finds a natively-filed row from either language', () => {+ const rows = [RU('a', 'Московская область', 'Moscow Oblast')];++ expect(filterSaved(rows, { query: 'russia' })).toHaveLength(1);+ expect(filterSaved(rows, { query: 'Россия' })).toHaveLength(1);+ expect(filterSaved(rows, { query: 'moscow' })).toHaveLength(1);+ expect(filterSaved(rows, { query: 'московская' })).toHaveLength(1);+ });+});++describe('pendingLocate', () => {+ it('counts only what another pass could still resolve', () => {+ expect(+ pendingLocate([+ UA('a', 'Donetsk Oblast'),+ row('bb', { geo: null }),+ row('ccc', { geo: { state: 'failed' } }),+ row('dddd', { geo: { state: 'nocoords' } }),+ row('eeeee', { geo: { state: 'nocountry' } }),+ ])+ ).toBe(2);+ });+});++describe('addressing a row in the tree', () => {+ it('gives the leaf key for the levels in play', () => {+ expect(keyFor(UA('a', 'Donetsk Oblast'), ['continent', 'country', 'region'])).toBe(+ 'Europe/Ukraine/Donetsk Oblast'+ );+ expect(keyFor(UA('a', 'Donetsk Oblast'), ['region'])).toBe('Donetsk Oblast');+ expect(keyFor(row('bb', { geo: null }), ['region'])).toBe('Unlocated');+ });++ it('expands exactly the branch a key lives in', () => {+ expect(branchKeys('Europe/Ukraine/Donetsk Oblast')).toEqual([+ 'Europe',+ 'Europe/Ukraine',+ 'Europe/Ukraine/Donetsk Oblast',+ ]);+ });+});diff --git a/frontend/src/lib/inspect.js b/frontend/src/lib/inspect.jsindex a3c0564..35ac0e8 100644--- a/frontend/src/lib/inspect.js+++ b/frontend/src/lib/inspect.js@@ -15,6 +15,44 @@ export const ADJUST_ORDER = [let _seq = 0;export const uid = (prefix = 'id') => `${prefix}_${Date.now().toString(36)}_${_seq++}`;+// -- Save-tab naming ---------------------------------------------------------+// What the user types at the Save gate becomes the media title *and* the stem of+// the file on disk, so these defaults have to read as names, not placeholders.++export function sourceStem(source) {+ const raw = source?.label || source?.filename || source?.path || '';+ const base = String(raw).split(/[\\/]/).pop() ?? '';+ return base.replace(/\.[^.]+$/, '') || 'Capture';+}++/** Seconds → `hh-mm-ss`, safe in a filename and readable in a list. */+export function timecode(seconds) {+ const t = Math.max(0, Math.round(Number(seconds) || 0));+ const pad = (n) => String(n).padStart(2, '0');+ return `${pad(Math.floor(t / 3600))}-${pad(Math.floor((t % 3600) / 60))}-${pad(t % 60)}`;+}++/**+ * The name every savable starts out holding, before anyone edits it.+ *+ * A base name numbers the gallery (`Roof 01`, `Roof 02`); numbering runs over the+ * whole gallery, not the ticked subset, so a name never renumbers under you as+ * you tick boxes. A lone savable takes the base name bare — a `01` with nothing+ * to follow it just adds noise. With no base name, each item's default stands.+ */+export function autoSaveNames(savables, baseName = '') {+ const base = String(baseName ?? '').trim();+ return savables.map((it, i) => {+ if (!base) return it.defaultName;+ return savables.length > 1 ? `${base} ${String(i + 1).padStart(2, '0')}` : base;+ });+}++/** The name an item is filed under: what stands in its field, else its default. */+export function saveNameOf(item, value) {+ return String(value ?? '').trim() || item.defaultName;+}+export function adjustDefaults(filters) {const out = {};for (const f of filters) out[f.id] = f.params[0]?.default ?? 0;diff --git a/frontend/src/lib/inspect.test.js b/frontend/src/lib/inspect.test.jsindex 2b2f641..d09b284 100644--- a/frontend/src/lib/inspect.test.js+++ b/frontend/src/lib/inspect.test.js@@ -4,6 +4,7 @@ import {QUAD_SIDES, quadEdgeMidpoints, moveQuadEdge, quadCentroid,quadsBounds, translateQuad, moveQuads, rotateQuads, scaleQuads, pinholeOps,buildFrameOps, hasVideoEdits, normalizeRightAngleRotation, rotationOps,+ sourceStem, timecode, autoSaveNames, saveNameOf,} from './inspect.js';const near = (a, b, eps = 1e-6) => Math.abs(a - b) < eps;@@ -303,3 +304,85 @@ describe('scaleQuads — the block grows as one', () => {expect(scaleQuads([], 2)).toEqual([]);});});+++describe('sourceStem', () => {+ it('prefers the title, then the filename, then the path', () => {+ expect(sourceStem({ label: 'Hangar clip', filename: 'dsc_1.mp4' })).toBe('Hangar clip');+ expect(sourceStem({ filename: 'dsc_1.mp4', path: 'media/dsc_1.mp4' })).toBe('dsc_1');+ expect(sourceStem({ path: 'media/sub/roof.png' })).toBe('roof');+ });++ it('strips only the extension, keeping dots inside the name', () => {+ expect(sourceStem({ filename: 'v1.2 roof.png' })).toBe('v1.2 roof');+ });++ it('falls back to Capture when there is nothing to read', () => {+ expect(sourceStem(null)).toBe('Capture');+ expect(sourceStem({})).toBe('Capture');+ });++ it('reads Windows paths too', () => {+ expect(sourceStem({ path: 'media\\sub\\roof.png' })).toBe('roof');+ });+});++describe('timecode', () => {+ it('formats seconds as hh-mm-ss', () => {+ expect(timecode(0)).toBe('00-00-00');+ expect(timecode(750)).toBe('00-12-30');+ expect(timecode(3725)).toBe('01-02-05');+ });++ it('rounds and floors at zero rather than producing a negative name', () => {+ expect(timecode(12.6)).toBe('00-00-13');+ expect(timecode(-5)).toBe('00-00-00');+ expect(timecode(undefined)).toBe('00-00-00');+ });+});++describe('autoSaveNames', () => {+ const items = [+ { key: 'a', defaultName: 'roof 00-01-00' },+ { key: 'b', defaultName: 'roof 00-02-00' },+ ];++ it('starts every field on the item default', () => {+ expect(autoSaveNames(items)).toEqual(['roof 00-01-00', 'roof 00-02-00']);+ });++ it('numbers the gallery under a base name', () => {+ expect(autoSaveNames(items, 'Roof')).toEqual(['Roof 01', 'Roof 02']);+ });++ it('numbers over the whole gallery, so ticking a box never renumbers a field', () => {+ const three = [...items, { key: 'c', defaultName: 'collage' }];+ expect(autoSaveNames(three, 'Roof')).toEqual(['Roof 01', 'Roof 02', 'Roof 03']);+ });++ it('leaves a lone item unnumbered', () => {+ expect(autoSaveNames([items[0]], 'Roof')).toEqual(['Roof']);+ });++ it('ignores a whitespace-only base name', () => {+ expect(autoSaveNames(items, ' ')).toEqual(['roof 00-01-00', 'roof 00-02-00']);+ });+});++describe('saveNameOf', () => {+ const item = { key: 'a', defaultName: 'roof 00-01-00' };++ it('files under what stands in the field', () => {+ expect(saveNameOf(item, 'Front door')).toBe('Front door');+ });++ it('trims what the user typed', () => {+ expect(saveNameOf(item, ' Front door ')).toBe('Front door');+ });++ it('falls back to the default rather than filing something nameless', () => {+ expect(saveNameOf(item, ' ')).toBe('roof 00-01-00');+ expect(saveNameOf(item, '')).toBe('roof 00-01-00');+ expect(saveNameOf(item)).toBe('roof 00-01-00');+ });+});diff --git a/frontend/src/lib/maplinks.js b/frontend/src/lib/maplinks.jsindex c410b05..dd9d289 100644--- a/frontend/src/lib/maplinks.js+++ b/frontend/src/lib/maplinks.js@@ -19,8 +19,8 @@ export function mapLinks(lat, lon, zoom = 17) {{id: 'apple',label: 'Apple Maps',- // t=k selects the satellite/hybrid basemap- url: `https://maps.apple.com/?ll=${lat},${lon}&z=${z}&t=k`,+ // map=satellite selects the satellite basemap in Apple's current web URL+ url: `https://maps.apple.com/?ll=${lat},${lon}&z=${z}&map=satellite`,},{ id: 'bing', label: 'Bing Maps', url: `https://www.bing.com/maps?cp=${lat}~${lon}&lvl=${z}&style=h` },{diff --git a/frontend/src/lib/maplinks.test.js b/frontend/src/lib/maplinks.test.jsindex 639f1ed..0335de9 100644--- a/frontend/src/lib/maplinks.test.js+++ b/frontend/src/lib/maplinks.test.js@@ -36,6 +36,7 @@ describe('mapLinks', () => {it('rounds zoom and uses lon,lat order for Yandex', () => {expect(byId.google.url).toContain(',16z');expect(byId.yandex.url).toContain('ll=2.2945,48.8584');+ expect(byId.apple.url).toContain('map=satellite');});it('every entry has a label and an https url', () => {diff --git a/frontend/src/lib/mediaFilter.js b/frontend/src/lib/mediaFilter.jsindex 2015c9f..e3ebffe 100644--- a/frontend/src/lib/mediaFilter.js+++ b/frontend/src/lib/mediaFilter.js@@ -23,6 +23,24 @@ export function matchesQuery(item, query) {return q.split(/\s+/).every((term) => haystack.includes(term));}+/** True for native satellite captures and extension screenshots whose URL+ * explicitly identified satellite imagery. */+export function isSatelliteMedia(item) {+ const source = item?.source ?? {};+ return source.type === 'satellite' ||+ (source.type === 'screenshot' && source.imagery_mode === 'satellite');+}++/** Images that are not already classified as satellite captures. */+export function isGenericImage(item) {+ return item?.kind === 'image' && !isSatelliteMedia(item);+}++/** User-facing kind label for the Media Library card. */+export function mediaDisplayKind(item) {+ return isSatelliteMedia(item) ? 'satellite' : item?.kind;+}+export const SORTS = [{ id: 'newest', label: 'Newest first' },{ id: 'oldest', label: 'Oldest first' },@@ -41,7 +59,7 @@ export const SORTS = [*/export function visibleMedia(items,- { hasCase = true, catMatch = null, folderFilter = null, query = '', sort = 'newest' } = {}+ { hasCase = true, catMatch = null, folderFilter = null, query = '', sort = 'newest', direction } = {}) {if (!hasCase) return [];return sortItems(@@ -51,7 +69,18 @@ export function visibleMedia((!folderFilter || i.folder === folderFilter) &&matchesQuery(i, query)),- sort+ sort,+ direction+ );+}++/** Whether a folder and category can produce at least one media item.+ * Deliberately ignores the text query: choosing a compatible folder/type+ * combination should not reset either filter just because a search is active.+ */+export function hasMediaForFilters(items, { catMatch = null, folderFilter = null } = {}) {+ return items.some(+ (i) => (!catMatch || catMatch(i)) && (!folderFilter || i.folder === folderFilter));}@@ -59,8 +88,9 @@ const displayName = (i) => (i.title ?? i.filename ?? '').toLowerCase();/** Stable-sorted copy of `items` (the API's order is newest-first on disk scan,* but sorting explicitly keeps the toggle honest whatever the backend does). */-export function sortItems(items, sort) {+export function sortItems(items, sort, direction) {const out = [...items];+ let descending = false;switch (sort) {case 'oldest':out.sort((a, b) => (a.added_at ?? '').localeCompare(b.added_at ?? ''));@@ -68,13 +98,24 @@ export function sortItems(items, sort) {case 'name':out.sort((a, b) => displayName(a).localeCompare(displayName(b)));break;+ case 'type':+ out.sort((a, b) => (mediaDisplayKind(a) ?? '').localeCompare(mediaDisplayKind(b) ?? ''));+ break;+ case 'folder':+ out.sort((a, b) => (a.folder ?? '').localeCompare(b.folder ?? ''));+ break;case 'size':- out.sort((a, b) => (b.size ?? 0) - (a.size ?? 0));+ out.sort((a, b) => (a.size ?? 0) - (b.size ?? 0));+ descending = true;break;case 'newest':default:- out.sort((a, b) => (b.added_at ?? '').localeCompare(a.added_at ?? ''));+ out.sort((a, b) => (a.added_at ?? '').localeCompare(b.added_at ?? ''));+ descending = true;break;}+ if (direction === 'asc') descending = false;+ if (direction === 'desc') descending = true;+ if (descending) out.reverse();return out;}diff --git a/frontend/src/lib/mediaFilter.test.js b/frontend/src/lib/mediaFilter.test.jsindex 7ba6931..f15ed95 100644--- a/frontend/src/lib/mediaFilter.test.js+++ b/frontend/src/lib/mediaFilter.test.js@@ -1,5 +1,13 @@import { describe, it, expect } from 'vitest';-import { matchesQuery, sortItems, visibleMedia } from './mediaFilter.js';+import {+ hasMediaForFilters,+ isGenericImage,+ isSatelliteMedia,+ mediaDisplayKind,+ matchesQuery,+ sortItems,+ visibleMedia,+} from './mediaFilter.js';const item = (extra = {}) => ({filename: 'strike_video.mp4',@@ -46,6 +54,37 @@ describe('matchesQuery', () => {});});+describe('media categories', () => {+ it('classifies native satellite captures as Satellite', () => {+ const capture = { kind: 'image', source: { type: 'satellite' } };+ expect(isSatelliteMedia(capture)).toBe(true);+ expect(isGenericImage(capture)).toBe(false);+ });++ it('classifies explicit satellite screenshots as Satellite', () => {+ const capture = {+ kind: 'image',+ source: { type: 'screenshot', imagery_mode: 'satellite' },+ };+ expect(isSatelliteMedia(capture)).toBe(true);+ expect(isGenericImage(capture)).toBe(false);+ });++ it('keeps ordinary extension screenshots under Images', () => {+ const capture = { kind: 'image', source: { type: 'screenshot' } };+ expect(isSatelliteMedia(capture)).toBe(false);+ expect(isGenericImage(capture)).toBe(true);+ expect(mediaDisplayKind(capture)).toBe('image');+ });++ it('uses the Satellite label for satellite captures while keeping image data', () => {+ expect(mediaDisplayKind({ kind: 'image', source: { type: 'satellite' } })).toBe('satellite');+ expect(+ mediaDisplayKind({ kind: 'image', source: { type: 'screenshot', imagery_mode: 'satellite' } })+ ).toBe('satellite');+ });+});+describe('sortItems', () => {const a = item({ filename: 'b.mp4', title: 'Bravo', size: 10, added_at: '2026-07-01T00:00:00Z' });const b = item({ filename: 'a.jpg', title: null, size: 30, added_at: '2026-07-03T00:00:00Z' });@@ -67,6 +106,18 @@ describe('sortItems', () => {expect(sortItems([a, b, c], 'size').map((i) => i.filename)).toEqual(['a.jpg', 'c.png', 'b.mp4']);});+ it('reverses a column when requested', () => {+ expect(sortItems([a, b, c], 'name', 'desc').map((i) => i.filename)).toEqual(['b.mp4', 'c.png', 'a.jpg']);+ expect(sortItems([a, b, c], 'size', 'asc').map((i) => i.filename)).toEqual(['b.mp4', 'c.png', 'a.jpg']);+ });++ it('sorts the details-list type and folder columns', () => {+ const image = item({ filename: 'image.png', kind: 'image', folder: 'evidence' });+ const video = item({ filename: 'video.mp4', kind: 'video', folder: 'archive' });+ expect(sortItems([image, video], 'type').map((i) => i.filename)).toEqual(['image.png', 'video.mp4']);+ expect(sortItems([image, video], 'folder').map((i) => i.filename)).toEqual(['video.mp4', 'image.png']);+ });+it('does not mutate the input', () => {const input = [a, b, c];sortItems(input, 'name');@@ -118,3 +169,20 @@ describe('visibleMedia — case gating', () => {expect(items.map((i) => i.filename)).toEqual(snapshot);});});++describe('hasMediaForFilters', () => {+ const items = [+ { kind: 'image', folder: 'sources' },+ { kind: 'video', folder: 'sources' },+ { kind: 'image', folder: 'evidence' },+ ];++ it('finds whether a folder and category intersection exists', () => {+ expect(hasMediaForFilters(items, { folderFilter: 'sources', catMatch: (i) => i.kind === 'image' })).toBe(true);+ expect(hasMediaForFilters(items, { folderFilter: 'evidence', catMatch: (i) => i.kind === 'video' })).toBe(false);+ });++ it('ignores the text query because it only validates the two filter facets', () => {+ expect(hasMediaForFilters(items, { folderFilter: 'sources' })).toBe(true);+ });+});diff --git a/frontend/src/lib/mediaQuery.js b/frontend/src/lib/mediaQuery.jsnew file mode 100644index 0000000..ac93892--- /dev/null+++ b/frontend/src/lib/mediaQuery.js@@ -0,0 +1,19 @@+/** Build the bounded media-page request path. Only the filters that are set+ * appear; an empty `folder` string is kept (it means "the unfiled bucket"),+ * distinct from an unset folder. Mirrors `buildCatalogQuery` in catalog.js. */+export function buildMediaQuery(+ caseId,+ { q, kind, category, folder, sort, direction, limit, cursor } = {}+) {+ const params = new URLSearchParams();+ if (q) params.set('q', q);+ if (kind) params.set('kind', kind);+ if (category) params.set('category', category);+ if (folder != null) params.set('folder', folder);+ if (sort) params.set('sort', sort);+ if (direction) params.set('direction', direction);+ if (limit != null) params.set('limit', String(limit));+ if (cursor) params.set('cursor', cursor);+ const qs = params.toString();+ return `/api/cases/${caseId}/media/page${qs ? `?${qs}` : ''}`;+}diff --git a/frontend/src/lib/mediaQuery.test.js b/frontend/src/lib/mediaQuery.test.jsnew file mode 100644index 0000000..58bf313--- /dev/null+++ b/frontend/src/lib/mediaQuery.test.js@@ -0,0 +1,29 @@+import { describe, expect, it } from 'vitest';+import { buildMediaQuery } from './mediaQuery.js';++describe('buildMediaQuery', () => {+ it('omits unset filters', () => {+ expect(buildMediaQuery('c1', {})).toBe('/api/cases/c1/media/page');+ });++ it('carries only the params that are set', () => {+ expect(+ buildMediaQuery('c1', {+ q: 'bridge kyiv',+ kind: 'image',+ category: 'satellite',+ folder: 'Sources/Telegram',+ sort: 'name',+ direction: 'desc',+ limit: 50,+ cursor: '2',+ })+ ).toBe(+ '/api/cases/c1/media/page?q=bridge+kyiv&kind=image&category=satellite&folder=Sources%2FTelegram&sort=name&direction=desc&limit=50&cursor=2'+ );+ });++ it('keeps an empty folder distinct from an unset one', () => {+ expect(buildMediaQuery('c1', { folder: '' })).toBe('/api/cases/c1/media/page?folder=');+ });+});diff --git a/frontend/src/lib/naming.js b/frontend/src/lib/naming.jsnew file mode 100644index 0000000..d5a2cbe--- /dev/null+++ b/frontend/src/lib/naming.js@@ -0,0 +1,94 @@+/**+ * Naming rules shared by everything the analyst saves under a name: inspect+ * sessions, proofs and post drafts.+ *+ * The rule is one line: **the name is the filename**. What the header shows is+ * slugified into the file that holds it, so renaming moves the file (the+ * backend does the move — see `api/naming.py`, which mirrors `slugify` exactly).+ * That is why the collision checks here matter: the frontend can tell before it+ * posts whether a name is free.+ */++// Long enough to stay readable, short enough that the path survives Windows'+// 260-character limit under a deep workspace root. Mirrors api/naming.py.+export const MAX_SLUG = 80;++/** What a fresh item of each kind is called until the analyst renames it. */+export const NAME_PREFIX = { session: 'Inspect', proof: 'Proof', draft: 'Post' };++/** URL- and filesystem-safe stem from free text — mirror of the backend `slugify`. */+export function slugify(text, fallback) {+ const slug = (text ?? '')+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '');+ return slug.slice(0, MAX_SLUG) || fallback;+}++/**+ * A name that doesn't collide with `taken`: `base` when free, else `base 2`,+ * `base 3`, … `taken` is a Set or array of names already in the case.+ */+export function uniqueName(base, taken) {+ const set = taken instanceof Set ? taken : new Set(taken);+ if (!set.has(base)) return base;+ let n = 2;+ while (set.has(`${base} ${n}`)) n += 1;+ return `${base} ${n}`;+}++/**+ * Name for a fresh item of `kind`: "Inspect 1", "Proof 1", … taking the lowest+ * free number so the case doesn't count past the gaps deletions leave behind.+ */+export function nextName(kind, taken) {+ const set = taken instanceof Set ? taken : new Set(taken);+ const prefix = NAME_PREFIX[kind];+ let n = 1;+ while (set.has(`${prefix} ${n}`)) n += 1;+ return `${prefix} ${n}`;+}++/**+ * Whether `name` is one this app assigned rather than one the analyst typed.+ * A default name says nothing about the work, so it must not be carried into+ * places that want a description (the Post Composer pulls a proof's title into+ * its text, and "Proof 3" is not text worth posting).+ */+export function isDefaultName(name, kind) {+ return new RegExp(`^${NAME_PREFIX[kind]} \\d+$`).test((name ?? '').trim());+}++// Where each kind's spec lives, and the entity attribute that points at it.+const SPEC_ATTR = {+ session: { dir: 'inspect/', attr: 'spec' },+ proof: { dir: 'proofs/', attr: 'spec' },+ draft: { dir: 'exports/', attr: 'draft' },+};++/** The filed entities of `kind`, read off a case's entity list. */+export function savedEntities(entities, kind) {+ const { dir, attr } = SPEC_ATTR[kind];+ return (entities ?? []).filter((e) => {+ const spec = e.attrs?.[attr];+ return typeof spec === 'string' && spec.startsWith(dir) && spec.endsWith('.json');+ });+}++/** Slugs of everything of `kind` already saved — the collision set. */+export function savedSlugs(entities, kind) {+ const { dir, attr } = SPEC_ATTR[kind];+ return new Set(savedEntities(entities, kind).map((e) => e.attrs[attr].slice(dir.length, -5)));+}++/** Names of everything of `kind` already saved, so a fresh one reads apart. */+export function savedTitles(entities, kind) {+ return new Set(savedEntities(entities, kind).map((e) => e.label ?? ''));+}++/** Name of the saved item of `kind` with slug `slug`, for the overwrite prompt. */+export function savedTitle(entities, kind, slug) {+ const { dir, attr } = SPEC_ATTR[kind];+ const found = savedEntities(entities, kind).find((e) => e.attrs[attr] === `${dir}${slug}.json`);+ return found?.label ?? slug;+}diff --git a/frontend/src/lib/naming.test.js b/frontend/src/lib/naming.test.jsnew file mode 100644index 0000000..05f672d--- /dev/null+++ b/frontend/src/lib/naming.test.js@@ -0,0 +1,118 @@+import { describe, it, expect } from 'vitest';+import {+ MAX_SLUG, NAME_PREFIX, slugify, uniqueName, nextName, isDefaultName,+ savedEntities, savedSlugs, savedTitles, savedTitle,+} from './naming.js';++describe('slugify — mirrors the backend api/naming.slugify', () => {+ it('lowercases, hyphenates runs of non-alphanumerics, trims edges', () => {+ expect(slugify('Inspect 1', 'session')).toBe('inspect-1');+ expect(slugify(' Rooftop! @ 12:30 ', 'proof')).toBe('rooftop-12-30');+ expect(slugify('Café déjà', 'proof')).toBe('caf-d-j');+ });++ it('falls back to the caller word when nothing survives, and caps the length', () => {+ expect(slugify('', 'proof')).toBe('proof');+ expect(slugify('!!!', 'session')).toBe('session');+ expect(slugify(null, 'draft')).toBe('draft');+ expect(slugify('a'.repeat(200), 'proof')).toHaveLength(MAX_SLUG);+ });+});++describe('nextName — the default name of a fresh item', () => {+ it('starts at 1 for each kind', () => {+ expect(nextName('session', [])).toBe('Inspect 1');+ expect(nextName('proof', new Set())).toBe('Proof 1');+ expect(nextName('draft', [])).toBe('Post 1');+ });++ it('takes the lowest free number, so deletions leave no gap to count past', () => {+ expect(nextName('proof', ['Proof 1', 'Proof 2'])).toBe('Proof 3');+ expect(nextName('proof', ['Proof 1', 'Proof 3'])).toBe('Proof 2');+ });++ it('ignores names the analyst typed', () => {+ expect(nextName('session', ['Rooftop angle', 'Bridge'])).toBe('Inspect 1');+ });++ it('numbers a name that still slugs to a distinct filename', () => {+ expect(slugify(nextName('proof', ['Proof 1']), 'proof')).toBe('proof-2');+ });+});++describe('uniqueName — a typed name that has to read apart', () => {+ it('returns the base when it is free', () => {+ expect(uniqueName('Rooftop', new Set())).toBe('Rooftop');+ expect(uniqueName('Rooftop', ['Bridge'])).toBe('Rooftop');+ });++ it('numbers past the base and any run already taken', () => {+ expect(uniqueName('Rooftop', new Set(['Rooftop']))).toBe('Rooftop 2');+ expect(uniqueName('Rooftop', ['Rooftop', 'Rooftop 2', 'Rooftop 3'])).toBe('Rooftop 4');+ });+});++describe('isDefaultName — an assigned name is not a description', () => {+ it('recognizes the names this app assigns', () => {+ expect(isDefaultName('Proof 1', 'proof')).toBe(true);+ expect(isDefaultName(' Proof 12 ', 'proof')).toBe(true);+ expect(isDefaultName('Inspect 3', 'session')).toBe(true);+ expect(isDefaultName('Post 2', 'draft')).toBe(true);+ });++ it('leaves anything the analyst typed alone', () => {+ expect(isDefaultName('Rooftop angle', 'proof')).toBe(false);+ expect(isDefaultName('Proof', 'proof')).toBe(false);+ expect(isDefaultName('Proof 1 rooftop', 'proof')).toBe(false);+ expect(isDefaultName('Inspect 1', 'proof')).toBe(false); // right shape, wrong kind+ expect(isDefaultName(null, 'proof')).toBe(false);+ });+});++describe('saved-item case queries', () => {+ const entities = [+ { label: 'Rooftop', attrs: { spec: 'proofs/rooftop.json' } },+ { label: 'Bridge', attrs: { spec: 'proofs/bridge.json' } },+ { label: 'Angle', attrs: { spec: 'inspect/angle.json' } },+ { label: 'Thread', attrs: { draft: 'exports/thread.json' } },+ { label: 'A place', attrs: { spec: 'places/x.json' } }, // filed, but not one of ours+ { label: 'No spec' },+ ];++ it('picks only the entities of the asked-for kind', () => {+ expect(savedEntities(entities, 'proof').map((e) => e.label)).toEqual(['Rooftop', 'Bridge']);+ expect(savedEntities(entities, 'session').map((e) => e.label)).toEqual(['Angle']);+ expect(savedEntities(entities, 'draft').map((e) => e.label)).toEqual(['Thread']);+ expect(savedEntities(undefined, 'proof')).toEqual([]);+ });++ it('lists the slugs (filename without its folder and .json)', () => {+ expect(savedSlugs(entities, 'proof')).toEqual(new Set(['rooftop', 'bridge']));+ expect(savedSlugs(entities, 'session')).toEqual(new Set(['angle']));+ expect(savedSlugs(entities, 'draft')).toEqual(new Set(['thread']));+ });++ it('lists the names', () => {+ expect(savedTitles(entities, 'proof')).toEqual(new Set(['Rooftop', 'Bridge']));+ });++ it('resolves a name by slug, falling back to the slug itself', () => {+ expect(savedTitle(entities, 'proof', 'bridge')).toBe('Bridge');+ expect(savedTitle(entities, 'draft', 'thread')).toBe('Thread');+ expect(savedTitle(entities, 'proof', 'unknown')).toBe('unknown');+ });++ it('numbers a fresh name past what the case already holds', () => {+ const saved = [+ { label: 'Proof 1', attrs: { spec: 'proofs/proof-1.json' } },+ { label: 'Rooftop', attrs: { spec: 'proofs/rooftop.json' } },+ ];+ expect(nextName('proof', savedTitles(saved, 'proof'))).toBe('Proof 2');+ });+});++describe('every kind names its work the same way', () => {+ it('has one prefix per kind and no other', () => {+ expect(Object.keys(NAME_PREFIX).sort()).toEqual(['draft', 'proof', 'session']);+ });+});diff --git a/frontend/src/lib/pagedList.svelte.js b/frontend/src/lib/pagedList.svelte.jsnew file mode 100644index 0000000..b625ccc--- /dev/null+++ b/frontend/src/lib/pagedList.svelte.js@@ -0,0 +1,97 @@+/**+ * The hybrid client/server list behind the search surfaces (Media Library,+ * Files, the case switcher). It loads one bounded first page. If that page is+ * the whole dataset (no `next_cursor`), the surface filters/sorts in memory —+ * instant, no network on keystroke, exactly what a 3–4 item case wants. If+ * there is more, it switches to debounced server search and a "Show more".+ *+ * `fetchPage({ query, cursor })` returns `{ items, next_cursor, total, facets }`+ * (facets optional). `serverMode` is sticky once true within a case, so a query+ * that happens to fit one page doesn't strand later, broader queries on a+ * client-only subset — only `reload()` re-establishes the baseline.+ */+export function createPagedList({ fetchPage, debounceMs = 250 }) {+ let items = $state([]);+ let total = $state(0);+ let facets = $state(null);+ let query = $state('');+ let loading = $state(false);+ let nextCursor = $state(null);+ let serverMode = $state(false);+ let timer = null;+ let runId = 0;++ async function load({ query: q, append }) {+ const myRun = ++runId;+ loading = true;+ const cursor = append ? nextCursor : null;+ try {+ const page = await fetchPage({ query: q, cursor });+ if (myRun !== runId) return; // a newer load superseded this one+ const rows = page.items ?? [];+ items = append ? [...items, ...rows] : rows;+ nextCursor = page.next_cursor ?? null;+ total = page.total ?? items.length;+ facets = page.facets ?? null;+ if (!append && nextCursor != null) serverMode = true; // sticky-true+ } finally {+ if (myRun === runId) loading = false;+ }+ }++ return {+ get items() {+ return items;+ },+ get total() {+ return total;+ },+ get facets() {+ return facets;+ },+ get loading() {+ return loading;+ },+ get hasMore() {+ return nextCursor != null;+ },+ get serverMode() {+ return serverMode;+ },+ get query() {+ return query;+ },+ /** Drop everything synchronously — call before switching cases so a stale+ * list can't render for a beat against the new case's file URLs. */+ clear() {+ clearTimeout(timer);+ runId++; // abandon any in-flight load+ items = [];+ total = 0;+ facets = null;+ nextCursor = null;+ serverMode = false;+ loading = false;+ },+ /** Re-establish the baseline (first page, mode reset). Call on case open. */+ reload() {+ clearTimeout(timer);+ serverMode = false;+ return load({ query, append: false });+ },+ /** In client mode just record the term (the surface filters in memory); in+ * server mode debounce a fresh first-page fetch carrying the query. */+ setQuery(q) {+ query = q;+ if (!serverMode) return;+ clearTimeout(timer);+ timer = setTimeout(() => load({ query: q, append: false }), debounceMs);+ },+ /** Append the next server page. No-op when there is nothing more or a load+ * is already in flight. */+ loadMore() {+ if (nextCursor == null || loading) return undefined;+ return load({ query, append: true });+ },+ };+}diff --git a/frontend/src/lib/pagedList.test.js b/frontend/src/lib/pagedList.test.jsnew file mode 100644index 0000000..3339018--- /dev/null+++ b/frontend/src/lib/pagedList.test.js@@ -0,0 +1,107 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { createPagedList } from './pagedList.svelte.js';++/** A fake backend paging a fixed id list, recording the queries it received. */+function backend(ids, { pageSize = 100 } = {}) {+ const calls = [];+ const fetchPage = async ({ query, cursor }) => {+ calls.push({ query, cursor });+ const all = query ? ids.filter((id) => id.includes(query)) : ids;+ const start = cursor ? Number(cursor) : 0;+ const slice = all.slice(start, start + pageSize).map((id) => ({ id }));+ const next = start + pageSize < all.length ? String(start + pageSize) : null;+ return { items: slice, next_cursor: next, total: all.length, facets: { kind_counts: {} } };+ };+ return { fetchPage, calls };+}++describe('createPagedList — small case (single page)', () => {+ it('filters client-side with no extra fetch', async () => {+ const { fetchPage, calls } = backend(['alpha', 'beta', 'gamma']);+ const list = createPagedList({ fetchPage });+ await list.reload();+ expect(list.items.map((i) => i.id)).toEqual(['alpha', 'beta', 'gamma']);+ expect(list.serverMode).toBe(false);+ expect(list.hasMore).toBe(false);++ list.setQuery('bet'); // small case → consumer filters in memory+ expect(calls).toHaveLength(1); // no second network call+ });+});++describe('createPagedList — large case (multi page)', () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => vi.useRealTimers());++ it('goes server-side and debounces the query', async () => {+ const ids = Array.from({ length: 250 }, (_, i) => `item${i}`);+ const { fetchPage, calls } = backend(ids, { pageSize: 100 });+ const list = createPagedList({ fetchPage, debounceMs: 250 });+ await list.reload();+ expect(list.serverMode).toBe(true);+ expect(list.hasMore).toBe(true);+ expect(list.total).toBe(250);++ list.setQuery('item1');+ expect(calls).toHaveLength(1); // not yet — debounced+ await vi.advanceTimersByTimeAsync(250);+ expect(calls.at(-1).query).toBe('item1');+ });++ it('loadMore appends the next page and clears hasMore at the end', async () => {+ const ids = Array.from({ length: 150 }, (_, i) => `item${i}`);+ const { fetchPage } = backend(ids, { pageSize: 100 });+ const list = createPagedList({ fetchPage });+ await list.reload();+ expect(list.items).toHaveLength(100);+ await list.loadMore();+ expect(list.items).toHaveLength(150);+ expect(list.hasMore).toBe(false);+ });++ it('stays server-side even when a narrow query fits one page', async () => {+ const ids = Array.from({ length: 250 }, (_, i) => `item${i}`);+ const { fetchPage } = backend(ids, { pageSize: 100 });+ const list = createPagedList({ fetchPage, debounceMs: 0 });+ await list.reload();+ list.setQuery('item42'); // one match → single page+ await vi.advanceTimersByTimeAsync(0);+ expect(list.hasMore).toBe(false);+ expect(list.serverMode).toBe(true); // sticky: a broader query must re-hit the server+ });+});++describe('createPagedList — clear', () => {+ it('drops items synchronously and abandons an in-flight load', async () => {+ let resolveSlow;+ const fetchPage = () => new Promise((r) => (resolveSlow = r));+ const list = createPagedList({ fetchPage });+ const p = list.reload();+ list.clear();+ expect(list.items).toEqual([]);+ resolveSlow({ items: [{ id: 'stale' }], next_cursor: null, total: 1 });+ await p;+ expect(list.items).toEqual([]); // the abandoned load never lands+ });+});++describe('createPagedList — superseded loads', () => {+ it('a slow earlier load does not clobber a newer one', async () => {+ let resolveFirst;+ const seq = [+ new Promise((r) => (resolveFirst = r)),+ Promise.resolve({ items: [{ id: 'new' }], next_cursor: null, total: 1 }),+ ];+ let n = 0;+ const fetchPage = () => seq[n++];+ const list = createPagedList({ fetchPage });++ const p1 = list.reload();+ const p2 = list.reload(); // supersedes p1+ await p2;+ expect(list.items.map((i) => i.id)).toEqual(['new']);+ resolveFirst({ items: [{ id: 'old' }], next_cursor: null, total: 1 });+ await p1;+ expect(list.items.map((i) => i.id)).toEqual(['new']); // not clobbered+ });+});diff --git a/frontend/src/lib/panelWidth.js b/frontend/src/lib/panelWidth.jsnew file mode 100644index 0000000..1605357--- /dev/null+++ b/frontend/src/lib/panelWidth.js@@ -0,0 +1,52 @@+/**+ * Drag-resizable side panels. A panel's edge is a drag handle and the width it+ * lands on survives reloads; the pointer glue lives in the components.+ *+ * The width is clamped both ways: narrow enough and the content turns into+ * ellipses, wide enough and it eats the canvas it exists to annotate. The+ * viewport-relative cap is what stops a wide window's setting from swallowing a+ * laptop screen when the app is reopened there.+ */++/**+ * Build the pure width helpers for one panel.+ *+ * @param {object} opts+ * @param {string} opts.key localStorage key holding the remembered width+ * @param {number} opts.min narrowest usable width, px+ * @param {number} opts.max hard cap, px+ * @param {number} opts.def width before the user ever drags, px+ * @param {number} [opts.fraction] share of the window the panel may take+ */+export function panelWidth({ key, min, max, def, fraction = 0.5 }) {+ /** The widest the panel may get in a `viewportW`-wide window. */+ function maxWidth(viewportW) {+ const cap = Math.min(max, Math.round(viewportW * fraction));+ return Math.max(min, cap); // a tiny window still gets a usable panel+ }++ /** Snap any width — dragged, restored, or garbage — into the allowed range. */+ function clampWidth(w, viewportW = Infinity) {+ if (!Number.isFinite(w)) return def;+ return Math.min(maxWidth(viewportW), Math.max(min, Math.round(w)));+ }++ function loadWidth() {+ try {+ const stored = localStorage.getItem(key);+ return stored === null ? def : clampWidth(Number(stored));+ } catch {+ return def; // localStorage unavailable (private mode) — non-fatal+ }+ }++ function saveWidth(w) {+ try {+ localStorage.setItem(key, String(w));+ } catch {+ /* ignore */+ }+ }++ return { MIN_W: min, MAX_W: max, DEFAULT_W: def, maxWidth, clampWidth, loadWidth, saveWidth };+}diff --git a/frontend/src/lib/panelWidth.test.js b/frontend/src/lib/panelWidth.test.jsnew file mode 100644index 0000000..4152923--- /dev/null+++ b/frontend/src/lib/panelWidth.test.js@@ -0,0 +1,76 @@+import { describe, it, expect, vi, afterEach } from 'vitest';+import { panelWidth } from './panelWidth.js';++/** A localStorage stand-in — the test env has no DOM. */+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,+ };+}++const panel = panelWidth({ key: 'azimut:testW', min: 100, max: 400, def: 200, fraction: 0.25 });++afterEach(() => vi.unstubAllGlobals());++describe('panelWidth', () => {+ it('caps at the configured fraction of the viewport, then at the hard max', () => {+ expect(panel.maxWidth(1200)).toBe(300); // a quarter of the window+ expect(panel.maxWidth(4000)).toBe(400); // a quarter would be 1000 — the cap wins+ });++ it('never drops below the minimum, however small the window', () => {+ expect(panel.maxWidth(200)).toBe(100);+ });++ it('clamps both ends and rounds to whole pixels', () => {+ expect(panel.clampWidth(40, 1600)).toBe(100);+ expect(panel.clampWidth(5000, 1600)).toBe(400);+ expect(panel.clampWidth(220.6, 1600)).toBe(221);+ });++ it('falls back to the default for garbage', () => {+ expect(panel.clampWidth(NaN)).toBe(200);+ expect(panel.clampWidth(Infinity)).toBe(200);+ });++ it('round-trips a stored width under its own key', () => {+ const store = fakeStorage();+ vi.stubGlobal('localStorage', store);+ panel.saveWidth(320);+ expect(store.data['azimut:testW']).toBe('320');+ expect(panel.loadWidth()).toBe(320);+ });++ it('returns the default when nothing was ever stored', () => {+ vi.stubGlobal('localStorage', fakeStorage());+ expect(panel.loadWidth()).toBe(200);+ });++ it('re-clamps a stored width instead of trusting it', () => {+ vi.stubGlobal('localStorage', fakeStorage({ 'azimut:testW': '9000' }));+ expect(panel.loadWidth()).toBe(400);+ });++ it('survives a hostile or absent localStorage (private mode)', () => {+ vi.stubGlobal('localStorage', {+ getItem: () => {+ throw new Error('denied');+ },+ setItem: () => {+ throw new Error('denied');+ },+ });+ expect(panel.loadWidth()).toBe(200);+ expect(() => panel.saveWidth(300)).not.toThrow();+ });++ it('keeps two panels independent', () => {+ vi.stubGlobal('localStorage', fakeStorage());+ const other = panelWidth({ key: 'azimut:otherW', min: 100, max: 400, def: 150 });+ panel.saveWidth(300);+ expect(other.loadWidth()).toBe(150);+ });+});diff --git a/frontend/src/lib/pasteAsset.js b/frontend/src/lib/pasteAsset.jsnew file mode 100644index 0000000..a4d3cdd--- /dev/null+++ b/frontend/src/lib/pasteAsset.js@@ -0,0 +1,35 @@+/**+ * Naming and encoding for images pasted into a proof.+ *+ * An asset is named after its own bytes. That is what lets the composer hand an+ * image to the server exactly once: the API refuses a name that does not match+ * its content, two pastes of the same screenshot collapse into one file, and a+ * paste the case already holds needs no resend on the next save.+ */++export const PASTE_TYPES = ['image/png', 'image/jpeg', 'image/webp'];+export const MAX_PASTE_BYTES = 20 * 1024 * 1024; // mirrors the API's own cap+export const MAX_PASTES = 12;++/** File extension for a pasted image's type; anything unexpected reads as PNG. */+export function assetExtension(type) {+ if (type === 'image/jpeg') return 'jpg';+ if (type === 'image/webp') return 'webp';+ return 'png';+}++/** First 16 hex digits of the bytes' sha256, plus the extension. */+export async function assetName(bytes, type) {+ const digest = await crypto.subtle.digest('SHA-256', bytes);+ const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');+ return `${hex.slice(0, 16)}.${assetExtension(type)}`;+}++/** base64 of the bytes, chunked so a large image cannot blow the call stack. */+export function base64Of(bytes) {+ let out = '';+ for (let i = 0; i < bytes.length; i += 0x8000) {+ out += String.fromCharCode(...bytes.subarray(i, i + 0x8000));+ }+ return btoa(out);+}diff --git a/frontend/src/lib/pasteAsset.test.js b/frontend/src/lib/pasteAsset.test.jsnew file mode 100644index 0000000..e69f2a6--- /dev/null+++ b/frontend/src/lib/pasteAsset.test.js@@ -0,0 +1,50 @@+import { describe, it, expect } from 'vitest';+import { createHash } from 'node:crypto';+import {+ assetName, assetExtension, base64Of, PASTE_TYPES, MAX_PASTE_BYTES, MAX_PASTES,+} from './pasteAsset.js';++const bytes = (...values) => new Uint8Array(values);++describe('pasted asset naming', () => {+ it('names an image after its own content', async () => {+ const data = bytes(1, 2, 3, 4, 5);+ const expected = createHash('sha256').update(data).digest('hex').slice(0, 16);++ expect(await assetName(data, 'image/png')).toBe(`${expected}.png`);+ });++ it('gives the same paste the same name twice, and different pixels a new one', async () => {+ const a = await assetName(bytes(9, 9, 9), 'image/png');+ const b = await assetName(bytes(9, 9, 9), 'image/png');+ const c = await assetName(bytes(9, 9, 8), 'image/png');++ expect(a).toBe(b); // pasting a screenshot twice writes one file+ expect(a).not.toBe(c);+ });++ it('keeps the image type in the extension', async () => {+ expect(assetExtension('image/jpeg')).toBe('jpg');+ expect(assetExtension('image/webp')).toBe('webp');+ expect(assetExtension('image/png')).toBe('png');+ expect(assetExtension('image/gif')).toBe('png'); // never a type we did not accept+ expect(await assetName(bytes(1), 'image/jpeg')).toMatch(/^[0-9a-f]{16}\.jpg$/);+ });++ it('produces a name the API will accept', async () => {+ // the server checks this exact shape before writing anything+ expect(await assetName(bytes(7, 7), 'image/webp')).toMatch(/^[0-9a-f]{16}\.(png|jpe?g|webp)$/);+ });++ it('encodes bytes past one chunk correctly', () => {+ const big = new Uint8Array(0x8000 * 2 + 17).map((_, i) => i % 256);++ expect(base64Of(big)).toBe(Buffer.from(big).toString('base64'));+ });++ it('agrees with the caps the API enforces', () => {+ expect(MAX_PASTES).toBe(12);+ expect(MAX_PASTE_BYTES).toBe(20 * 1024 * 1024);+ expect(PASTE_TYPES).toEqual(['image/png', 'image/jpeg', 'image/webp']);+ });+});diff --git a/frontend/src/lib/poll.js b/frontend/src/lib/poll.jsnew file mode 100644index 0000000..dac0c7a--- /dev/null+++ b/frontend/src/lib/poll.js@@ -0,0 +1,24 @@+/**+ * Call `tick` every `ms` while `active()` holds, then stop; returns a stop fn.+ *+ * Why not a `setTimeout` scheduled inside an `$effect`: an `$effect` re-runs+ * only when a value it reads changes. A poll keyed on a `$derived` boolean+ * (e.g. "thumbnails still pending") that stays `true` across a refresh never+ * re-triggers the effect, so a one-shot timer there fires exactly once and the+ * thumbnail stays stuck until a full page reload. A self-repeating interval+ * keeps polling on its own until the condition clears. Timers are injectable so+ * the loop is unit-testable with fake timers.+ */+export function pollWhile(+ active,+ tick,+ ms,+ { setInterval: si = setInterval, clearInterval: ci = clearInterval } = {}+) {+ if (!active()) return () => {};+ const handle = si(() => {+ if (active()) tick();+ else ci(handle);+ }, ms);+ return () => ci(handle);+}diff --git a/frontend/src/lib/poll.test.js b/frontend/src/lib/poll.test.jsnew file mode 100644index 0000000..8382ccf--- /dev/null+++ b/frontend/src/lib/poll.test.js@@ -0,0 +1,32 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { pollWhile } from './poll.js';++describe('pollWhile', () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => vi.useRealTimers());++ it('keeps ticking while the condition holds (the poll a one-shot timer misses)', () => {+ let ticks = 0;+ pollWhile(() => true, () => (ticks += 1), 1500);+ vi.advanceTimersByTime(1500 * 3);+ expect(ticks).toBe(3); // repeats — not stuck at 1+ });++ it('stops on its own once the condition clears', () => {+ let pending = true;+ let ticks = 0;+ pollWhile(() => pending, () => (ticks += 1), 1000);+ vi.advanceTimersByTime(1000); // tick 1 (pending)+ pending = false;+ vi.advanceTimersByTime(1000 * 5); // sees !pending, clears itself+ expect(ticks).toBe(1);+ });++ it('never starts when the condition is already false, and stop is safe', () => {+ let ticks = 0;+ const stop = pollWhile(() => false, () => (ticks += 1), 1000);+ vi.advanceTimersByTime(5000);+ expect(ticks).toBe(0);+ expect(() => stop()).not.toThrow();+ });+});diff --git a/frontend/src/lib/rowSelect.js b/frontend/src/lib/rowSelect.jsnew file mode 100644index 0000000..eade3f6--- /dev/null+++ b/frontend/src/lib/rowSelect.js@@ -0,0 +1,29 @@+/**+ * Multi-select for the sidebar's entity rows: ctrl/cmd-click toggles one row,+ * shift-click extends from the anchor, and a drag carries whatever is selected.+ * Folders are never part of it — a folder is a drop target, not cargo.+ */++/** Ctrl/cmd-click: add or remove one row. */+export function toggleSelected(selected, id) {+ const next = new Set(selected);+ if (!next.delete(id)) next.add(id);+ return next;+}++/** Shift-click: every row between the anchor and the clicked one, in the order+ * they are displayed. An anchor that scrolled out of the list selects alone. */+export function rangeSelected(ids, anchorId, targetId) {+ const a = ids.indexOf(anchorId);+ const b = ids.indexOf(targetId);+ if (a === -1 || b === -1) return new Set(targetId == null ? [] : [targetId]);+ const [lo, hi] = a <= b ? [a, b] : [b, a];+ return new Set(ids.slice(lo, hi + 1));+}++/** What a drag actually moves: the whole selection when the dragged row belongs+ * to it, otherwise that row alone (dragging elsewhere doesn't take it along). */+export function dragPayload(rows, selected, entity) {+ if (!selected.has(entity.id)) return [entity];+ return rows.filter((r) => selected.has(r.id));+}diff --git a/frontend/src/lib/rowSelect.test.js b/frontend/src/lib/rowSelect.test.jsnew file mode 100644index 0000000..5d71876--- /dev/null+++ b/frontend/src/lib/rowSelect.test.js@@ -0,0 +1,45 @@+import { describe, expect, it } from 'vitest';+import { dragPayload, rangeSelected, toggleSelected } from './rowSelect.js';++const rows = ['a', 'b', 'c', 'd'].map((id) => ({ id }));+const ids = rows.map((r) => r.id);++describe('toggleSelected', () => {+ it('adds then removes, without touching the previous set', () => {+ const first = toggleSelected(new Set(), 'b');+ expect([...first]).toEqual(['b']);+ const second = toggleSelected(first, 'c');+ expect([...second]).toEqual(['b', 'c']);+ expect([...toggleSelected(second, 'b')]).toEqual(['c']);+ expect([...first]).toEqual(['b']); // untouched+ });+});++describe('rangeSelected', () => {+ it('takes the run between the anchor and the clicked row, either way round', () => {+ expect([...rangeSelected(ids, 'b', 'd')]).toEqual(['b', 'c', 'd']);+ expect([...rangeSelected(ids, 'd', 'b')]).toEqual(['b', 'c', 'd']);+ expect([...rangeSelected(ids, 'c', 'c')]).toEqual(['c']);+ });++ it('selects the clicked row alone when the anchor is no longer displayed', () => {+ expect([...rangeSelected(ids, 'gone', 'c')]).toEqual(['c']);+ });+});++describe('dragPayload', () => {+ it('carries the whole selection when the dragged row belongs to it', () => {+ const selected = new Set(['a', 'c']);+ expect(dragPayload(rows, selected, { id: 'c' }).map((r) => r.id)).toEqual(['a', 'c']);+ });++ it('carries the dragged row alone when it is outside the selection', () => {+ const selected = new Set(['a', 'c']);+ expect(dragPayload(rows, selected, { id: 'd' }).map((r) => r.id)).toEqual(['d']);+ });++ it('keeps display order, not click order', () => {+ const selected = new Set(['d', 'a']);+ expect(dragPayload(rows, selected, { id: 'a' }).map((r) => r.id)).toEqual(['a', 'd']);+ });+});diff --git a/frontend/src/lib/savedMarkers.js b/frontend/src/lib/savedMarkers.jsnew file mode 100644index 0000000..97ed019--- /dev/null+++ b/frontend/src/lib/savedMarkers.js@@ -0,0 +1,74 @@+/**+ * Saved work as map markers.+ *+ * Two items saved at the same spot must read as one mark on the map, not as a+ * pin stacked invisibly on another — the question the overlay answers is "what+ * do I already have here?", and the answer is a list, not a pile. Grouping by+ * rounded coordinates does both jobs: at full precision it collapses re-visits+ * of the same point, and at a coarser one it is the clustering that keeps a+ * zoomed-out world map readable.+ */++/** Decimal places to key on at a given map zoom.+ *+ * 5 decimals is about a metre: at street zoom only items at genuinely the same+ * spot merge. Zoom out and the key coarsens, so a country's worth of pins+ * becomes a handful of counted marks instead of a smear. */+export function markerPrecision(zoom) {+ const z = Number(zoom);+ if (!Number.isFinite(z)) return 5;+ if (z < 5) return 0; // whole degrees — continents+ if (z < 8) return 1;+ if (z < 11) return 2;+ if (z < 14) return 3;+ if (z < 16) return 4;+ return 5; // ~1 m — same spot only+}++/**+ * Group rows into marks. Rows with no coordinates are left out — a point with+ * no position has nowhere to be drawn — and each mark reports which kinds it+ * holds so the icon can say whether it is a place, a capture, or a mix.+ *+ * Marks come back in the order their first item appears (the index's newest+ * first), and each mark's items keep that order.+ */+export function groupSavedMarkers(rows, precision = 5) {+ const marks = new Map();+ for (const row of rows ?? []) {+ if (row.lat == null || row.lon == null) continue;+ const lat = Number(row.lat);+ const lon = Number(row.lon);+ if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue;+ const key = `${lat.toFixed(precision)},${lon.toFixed(precision)}`;+ const mark = marks.get(key);+ if (mark) {+ mark.items.push(row);+ mark.kinds.add(row.kind);+ } else {+ marks.set(key, { key, lat, lon, items: [row], kinds: new Set([row.kind]) });+ }+ }+ return [...marks.values()].map((mark) => ({+ key: mark.key,+ // the mark sits on its first item, not on the rounded key: a lone pin must+ // land exactly where it was saved, however coarse the grouping was+ lat: mark.lat,+ lon: mark.lon,+ items: mark.items,+ kinds: [...mark.kinds],+ }));+}++/** A stack's items ordered for the popup: by imagery date, newest first, so+ * "what do I already have here?" reads as a timeline of the ground. Items+ * with no imagery date fall to the end, ordered by when they were saved. */+export function stackOrder(items) {+ return [...(items ?? [])].sort((a, b) => {+ const left = a.imagery_date ?? '';+ const right = b.imagery_date ?? '';+ if (!left !== !right) return left ? -1 : 1; // dated imagery first+ if (left !== right) return right.localeCompare(left);+ return String(b.fetched_at ?? '').localeCompare(String(a.fetched_at ?? ''));+ });+}diff --git a/frontend/src/lib/savedMarkers.test.js b/frontend/src/lib/savedMarkers.test.jsnew file mode 100644index 0000000..da11326--- /dev/null+++ b/frontend/src/lib/savedMarkers.test.js@@ -0,0 +1,98 @@+import { describe, expect, it } from 'vitest';+import { groupSavedMarkers, markerPrecision, stackOrder } from './savedMarkers.js';++const at = (id, lat, lon, extra = {}) => ({ id, kind: 'capture', lat, lon, ...extra });++describe('groupSavedMarkers', () => {+ it('collapses items saved at the same spot into one mark', () => {+ const marks = groupSavedMarkers([+ at('a', 48.015912, 37.802901),+ at('b', 48.015913, 37.802899), // same metre+ ]);++ expect(marks).toHaveLength(1);+ expect(marks[0].items.map((i) => i.id)).toEqual(['a', 'b']);+ });++ it('keeps distinct spots apart', () => {+ expect(groupSavedMarkers([at('a', 48.0159, 37.8029), at('b', 48.02, 37.81)])).toHaveLength(2);+ });++ it('places a mark on its first item, not on the rounded key', () => {+ const [mark] = groupSavedMarkers([at('a', 48.015912, 37.802901)], 2);++ expect(mark.lat).toBe(48.015912);+ expect(mark.lon).toBe(37.802901);+ });++ it('leaves out rows with no coordinates', () => {+ const marks = groupSavedMarkers([+ at('a', 48.0159, 37.8029),+ at('b', null, null),+ at('c', undefined, undefined),+ ]);++ expect(marks).toHaveLength(1);+ expect(marks[0].items.map((i) => i.id)).toEqual(['a']);+ });++ it('reports every kind stacked on one mark', () => {+ const marks = groupSavedMarkers([+ at('a', 48.0159, 37.8029, { kind: 'place' }),+ at('b', 48.0159, 37.8029, { kind: 'capture' }),+ at('c', 48.0159, 37.8029, { kind: 'capture' }),+ ]);++ expect(marks[0].kinds).toEqual(['place', 'capture']);+ expect(marks[0].items).toHaveLength(3);+ });++ it('merges more coarsely at a lower precision', () => {+ const rows = [at('a', 48.0159, 37.8029), at('b', 48.4, 37.9)];++ expect(groupSavedMarkers(rows, 5)).toHaveLength(2);+ expect(groupSavedMarkers(rows, 0)).toHaveLength(1);+ });++ it('handles an empty or missing list', () => {+ expect(groupSavedMarkers([])).toEqual([]);+ expect(groupSavedMarkers()).toEqual([]);+ });+});++describe('markerPrecision', () => {+ it('merges only the same spot at street zoom, and whole regions at world zoom', () => {+ expect(markerPrecision(18)).toBe(5);+ expect(markerPrecision(16)).toBe(5);+ expect(markerPrecision(12)).toBe(3);+ expect(markerPrecision(6)).toBe(1);+ expect(markerPrecision(3)).toBe(0);+ });++ it('falls back to same-spot grouping when the zoom is unknown', () => {+ expect(markerPrecision(undefined)).toBe(5);+ expect(markerPrecision(NaN)).toBe(5);+ });+});++describe('stackOrder', () => {+ it('reads as a timeline of the ground, newest imagery first', () => {+ const ordered = stackOrder([+ { id: 'a', imagery_date: '2021-06' },+ { id: 'b', imagery_date: '2024-03' },+ { id: 'c', imagery_date: '2023-01' },+ ]);++ expect(ordered.map((i) => i.id)).toEqual(['b', 'c', 'a']);+ });++ it('sends undated items to the end, newest save first', () => {+ const ordered = stackOrder([+ { id: 'a', fetched_at: '2026-01-01T00:00:00Z' },+ { id: 'b', imagery_date: '2024-03' },+ { id: 'c', fetched_at: '2026-05-01T00:00:00Z' },+ ]);++ expect(ordered.map((i) => i.id)).toEqual(['b', 'c', 'a']);+ });+});diff --git a/frontend/src/lib/sidebar.js b/frontend/src/lib/sidebar.jsindex f275547..8e96ef1 100644--- a/frontend/src/lib/sidebar.js+++ b/frontend/src/lib/sidebar.js@@ -1,46 +1,16 @@/**- * Case sidebar width. The sidebar's left edge is a drag handle, and the width- * it lands on survives reloads. Pure helpers here — the pointer glue lives in- * CaseSidebar.svelte.- *- * The width is clamped both ways: narrow enough and the entity tree turns into- * ellipses, wide enough and it eats the tool canvas it exists to annotate. The- * viewport-relative cap is what stops a wide window's setting from swallowing a- * laptop screen when the case is reopened there.+ * Case sidebar width — the shared panel helpers (lib/panelWidth.js) bound to+ * the sidebar's own key and range. The pointer glue lives in CaseSidebar.svelte.*/+import { panelWidth } from './panelWidth.js';export const MIN_W = 240;export const MAX_W = 640;export const DEFAULT_W = 320;-const MAX_VIEWPORT_FRACTION = 0.5;-const KEY = 'azimut:sidebarW';--/** The widest the sidebar may get in a `viewportW`-wide window. */-export function maxWidth(viewportW) {- const cap = Math.min(MAX_W, Math.round(viewportW * MAX_VIEWPORT_FRACTION));- return Math.max(MIN_W, cap); // a tiny window still gets a usable sidebar-}--/** Snap any width — dragged, restored, or garbage — into the allowed range. */-export function clampWidth(w, viewportW = Infinity) {- if (!Number.isFinite(w)) return DEFAULT_W;- return Math.min(maxWidth(viewportW), Math.max(MIN_W, Math.round(w)));-}--export function loadWidth() {- try {- const stored = localStorage.getItem(KEY);- return stored === null ? DEFAULT_W : clampWidth(Number(stored));- } catch {- return DEFAULT_W; // localStorage unavailable (private mode) — non-fatal- }-}--export function saveWidth(w) {- try {- localStorage.setItem(KEY, String(w));- } catch {- /* ignore */- }-}+export const { maxWidth, clampWidth, loadWidth, saveWidth } = panelWidth({+ key: 'azimut:sidebarW',+ min: MIN_W,+ max: MAX_W,+ def: DEFAULT_W,+});diff --git a/frontend/src/lib/sidebarSearch.js b/frontend/src/lib/sidebarSearch.jsnew file mode 100644index 0000000..674a430--- /dev/null+++ b/frontend/src/lib/sidebarSearch.js@@ -0,0 +1,42 @@+/**+ * Case sidebar browse-vs-results rule (docs/UI.md §Case sidebar).+ *+ * The sidebar shows its folder tree while nothing is filtered, and a flat+ * result list as soon as a text query or a type chip is active. A filtered tree+ * would have to badge each folder with a per-type count the catalog summary+ * cannot give, so the two modes are exclusive rather than combined.+ */++/** True when the body should show results instead of the tree. */+export const isFiltering = ({ query = '', type = null } = {}) => !!query.trim() || !!type;++/** Header chips: one per type present in the case, biggest first, ties by name.+ * Counts come from the already-loaded catalog summary — no extra request. */+export function typeChips(summary) {+ return Object.entries(summary?.by_type ?? {})+ .filter(([, count]) => count > 0)+ .map(([type, count]) => ({ type, count }))+ .sort((a, b) => b.count - a.count || a.type.localeCompare(b.type));+}++/**+ * Client-side filter for a case that fits one page (`createPagedList` client+ * mode). It matches folder and type as well as the label, so typing a folder+ * name reveals its contents; the server `q` behind a large case matches the+ * label alone.+ */+export function filterEntities(items, { query = '', type = null } = {}) {+ const q = query.trim().toLowerCase();+ return items.filter((e) => {+ if (type && e.type !== type) return false;+ if (!q) return true;+ return [e.label, e.type, e.attrs?.folder]+ .filter(Boolean)+ .join(' ')+ .toLowerCase()+ .includes(q);+ });+}++/** Row meta in the result list: the type, plus where the row is filed. */+export const resultMeta = (e) => (e.attrs?.folder ? `${e.type} · ${e.attrs.folder}` : e.type);diff --git a/frontend/src/lib/sidebarSearch.test.js b/frontend/src/lib/sidebarSearch.test.jsnew file mode 100644index 0000000..fb38ead--- /dev/null+++ b/frontend/src/lib/sidebarSearch.test.js@@ -0,0 +1,60 @@+import { describe, expect, it } from 'vitest';+import { filterEntities, isFiltering, resultMeta, typeChips } from './sidebarSearch.js';++describe('isFiltering', () => {+ it('is false for nothing typed and no chip, true for either', () => {+ expect(isFiltering()).toBe(false);+ expect(isFiltering({ query: ' ' })).toBe(false);+ expect(isFiltering({ query: 'kh' })).toBe(true);+ expect(isFiltering({ type: 'media' })).toBe(true);+ });+});++describe('typeChips', () => {+ it('lists the types present, biggest first, ties by name', () => {+ const chips = typeChips({ by_type: { media: 64, place: 22, capture: 22, proof: 0 } });+ expect(chips).toEqual([+ { type: 'media', count: 64 },+ { type: 'capture', count: 22 },+ { type: 'place', count: 22 },+ ]);+ });++ it('survives a summary that has not landed yet', () => {+ expect(typeChips(null)).toEqual([]);+ });+});++describe('filterEntities', () => {+ const items = [+ { id: '1', label: 'clip_04.mp4', type: 'media', attrs: { folder: 'Terrain/Videos' } },+ { id: '2', label: 'Bridge north', type: 'place', attrs: { folder: 'Terrain' } },+ { id: '3', label: 'Account @relay', type: 'account', attrs: {} },+ ];++ it('matches the label case-insensitively', () => {+ expect(filterEntities(items, { query: 'CLIP' }).map((e) => e.id)).toEqual(['1']);+ });++ it('matches the folder too, so typing a folder name reveals its contents', () => {+ expect(filterEntities(items, { query: 'terrain' }).map((e) => e.id)).toEqual(['1', '2']);+ });++ it('combines the type chip with the text', () => {+ expect(filterEntities(items, { query: 'terrain', type: 'place' }).map((e) => e.id)).toEqual(['2']);+ expect(filterEntities(items, { type: 'account' }).map((e) => e.id)).toEqual(['3']);+ });++ it('returns everything when nothing is filtered', () => {+ expect(filterEntities(items, {})).toHaveLength(3);+ });+});++describe('resultMeta', () => {+ it('shows where a row is filed, and the type alone when it is not', () => {+ expect(resultMeta({ type: 'media', attrs: { folder: 'Terrain/Videos' } })).toBe(+ 'media · Terrain/Videos'+ );+ expect(resultMeta({ type: 'media', attrs: {} })).toBe('media');+ });+});diff --git a/frontend/src/lib/state.svelte.js b/frontend/src/lib/state.svelte.jsindex 154eb9e..f73d4b4 100644--- a/frontend/src/lib/state.svelte.js+++ b/frontend/src/lib/state.svelte.js@@ -207,8 +207,9 @@ export function toast(message, kind = 'info', timeout = 3800, action = null) {}, timeout);}-export async function refreshCaseList() {- caseState.list = await api.get('/api/cases');+export async function refreshCaseList({ q } = {}) {+ const query = q?.trim();+ caseState.list = await api.get(`/api/cases${query ? `?q=${encodeURIComponent(query)}` : ''}`);}// Remember the last open case across page reloads so work is never "lost".@@ -287,7 +288,7 @@ export async function ensureCase() {const scratch = await api.post('/api/cases/scratch');await refreshCaseList();await openCase(scratch.id);- toast('Scratch session started — “Keep as case…” to save it for good', 'info');+ toast('Scratch session started. Use “Keep as case…” to save it', 'info');return caseState.current;}diff --git a/frontend/src/tools/Files.svelte b/frontend/src/tools/Files.svelteindex cfe9f00..f1776d0 100644--- a/frontend/src/tools/Files.svelte+++ b/frontend/src/tools/Files.svelte@@ -16,8 +16,11 @@import { openNotebook } from '../lib/navigate.js';import { createBookmark } from '../lib/bookmarks.js';import { marqueeRect, marqueeHits, toggleSelection } from '../lib/gridSelect.js';- import { fetchAllEntities } from '../lib/catalog.js';+ import { buildCatalogQuery, fetchAllEntities } from '../lib/catalog.js';+ import { sortFileEntities } from '../lib/fileSort.js';+ import { createPagedList } from '../lib/pagedList.svelte.js';import Icon from '../components/Icon.svelte';+ import SearchInput from '../components/SearchInput.svelte';import Modal from '../components/Modal.svelte';import ConfirmDialog from '../components/ConfirmDialog.svelte';import EntityDetails from '../components/EntityDetails.svelte';@@ -32,64 +35,71 @@const FILE_BACKED = new Set(['media', 'capture', 'proof', 'post', 'inspect-session', 'note']);// ── case data ──────────────────────────────────────────────────────────────- // 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([]);+ // Bounded loading: a first page (200) off the catalog, not the whole graph on+ // open. A small case (incl. a 3–4 file one) fits one page, so the tree, search+ // and counts below are the full picture and everything filters in memory. A+ // large case loads more under the analyst's control ("Show more"); `summary`+ // gives the honest total. Re-read on case change or a save/delete elsewhere.+ const PAGE = 200;+ const pl = createPagedList({+ fetchPage: ({ query: serverQuery, cursor }) =>+ api.get(+ buildCatalogQuery(caseState.current?.id, {+ status: 'confirmed',+ query: serverQuery,+ folder: serverQuery && cwd ? cwd : undefined,+ unfiled: Boolean(serverQuery && showUnfiled),+ recursive: Boolean(serverQuery && cwd),+ limit: PAGE,+ cursor,+ })+ ),+ });+ const confirmed = $derived(pl.items);+ let summary = $state(null); // { total, by_type, by_status, by_folder }+ let loadedFor = null; // non-reactive: only the load effect reads/writes it$effect(() => {const id = caseState.current?.id;caseState.rev;if (!id) {- confirmed = [];+ pl.clear();+ summary = null;return;}- let live = true;- fetchAllEntities(id, { status: 'confirmed' })- .then((list) => { if (live) confirmed = list; })- .catch(() => { if (live) confirmed = []; });- return () => { live = false; };+ if (id !== loadedFor) {+ loadedFor = id;+ pl.clear();+ }+ pl.reload();+ api+ .get(`/api/cases/${id}/catalog/summary`)+ .then((s) => (summary = s))+ .catch(() => (summary = null));+ });+ $effect(() => {+ pl.setQuery(query);});const tree = $derived(buildTree(caseState.current?.folders ?? [], confirmed));const allFolders = $derived(flattenPaths(tree));const unfiled = $derived(confirmed.filter((e) => !folderOf(e)));- // Thumbnails: the media + satellite shelves, indexed by path. Same lists the- // Media Library reads — a local call to our own backend, nothing external.- let pathInfo = $state(new Map());- $effect(() => {- const id = caseState.current?.id;- caseState.rev; // refetch after a save/move elsewhere- if (!id) {- pathInfo = new Map();- return;- }- loadThumbs(id);- });- async function loadThumbs(id) {- try {- const [media, sat] = await Promise.all([- api.get(`/api/cases/${id}/media`),- api.get(`/api/cases/${id}/satellite`),- ]);- const m = new Map();- for (const it of [...media, ...sat]) m.set(it.path, { thumbnail: it.thumbnail, kind: it.kind });- pathInfo = m;- } catch {- pathInfo = new Map();- }- }-function tileIcon(e) {if (e.type === 'media') {- const kind = pathInfo.get(e.attrs?.path)?.kind;+ const kind = pathInfo.get(e.attrs?.path)?.kind ?? e.attrs?.kind;if (kind === 'video') return 'video';const ext = e.attrs?.path?.split('.').pop()?.toLowerCase();if (ext && VIDEO_EXTS.has(ext)) return 'video';}return TYPE_ICON[e.type] ?? 'file';}- const tileThumb = (e) => pathInfo.get(e.attrs?.path)?.thumbnail ?? null;+ // Proofs keep their rendered PNG directly at attrs.path rather than in the+ // media thumbnail index. Use it as their preview, while spec-only proofs+ // continue to show the proof icon.+ const tileThumb = (e) => {+ const path = e.attrs?.path;+ if (e.type === 'proof' && typeof path === 'string' && /\.png$/i.test(path)) return path;+ return pathInfo.get(path)?.thumbnail ?? null;+ };// ── navigation ──────────────────────────────────────────────────────────────let cwd = $state(''); // '' = root ("All")@@ -111,21 +121,131 @@// one intentional exception: it represents all of My work.let query = $state('');const searching = $derived(!!query.trim());+ const total = $derived(+ searching && pl.serverMode ? pl.total : (summary?.total ?? confirmed.length)+ );function matches(e) {const q = query.trim().toLowerCase();return ((e.label ?? '').toLowerCase().includes(q) ||e.type.toLowerCase().includes(q) ||- (folderOf(e) ?? '').toLowerCase().includes(q)+ (folderOf(e) ?? '').toLowerCase().includes(q) ||+ (e.attrs?.notes ?? '').toLowerCase().includes(q));}+ // Sort the current view. The list headers use the same state as the grid+ // selector, so changing view does not silently change the order.+ let sort = $state('name');+ let sortDirection = $state('asc');+ let headerSort = $state(null);+ const SORTS = [+ { id: 'name', label: 'Name A–Z' },+ { id: 'type', label: 'Type' },+ { id: 'recent', label: 'Recent' },+ ];+ const LIST_SORTS = [+ { id: 'name', label: 'Name' },+ { id: 'type', label: 'Type' },+ { id: 'size', label: 'Size' },+ { id: 'recent', label: 'Added' },+ ];+ function onSortSelect(event) {+ sort = event.currentTarget.value;+ sortDirection = sort === 'recent' ? 'desc' : 'asc';+ headerSort = null;+ }+ function setHeaderSort(next) {+ if (headerSort === next) {+ sortDirection = sortDirection === 'asc' ? 'desc' : 'asc';+ return;+ }+ headerSort = next;+ sort = next;+ // Recent is useful in newest-first order; the other columns start low to+ // high, matching the first Name click requested for the list view.+ sortDirection = next === 'recent' ? 'desc' : 'asc';+ }+ function sortFolders(list) {+ if (sort !== 'name') return list;+ const out = [...list].sort((a, b) =>+ a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: 'base' })+ );+ return sortDirection === 'desc' ? out.reverse() : out;+ }+ function sortEntities(list) {+ return sortFileEntities(list, {+ sort,+ direction: sortDirection,+ sizeOf: (e) => pathInfo.get(e.attrs?.path)?.size ?? null,+ });+ }++ function sortOptionLabel(option) {+ if (option.id === 'name') return `Name ${sort === 'name' && sortDirection === 'desc' ? 'Z–A' : 'A–Z'}`;+ if (option.id === 'recent') return sort === 'recent' && sortDirection === 'asc' ? 'Oldest' : 'Recent';+ return option.label;+ }++ let completeFolderEntities = $state(null);+ let completeFolderLoading = $state(false);+ let completeFolderError = $state(false);+ let completeFolderRun = 0;++ // Query metadata only for rows this view can render. The backend reads the+ // SQLite media index, so opening Files never scans every media sidecar.+ let pathInfo = $state(new Map());+ $effect(() => {+ const id = caseState.current?.id;+ caseState.rev;+ const rows = completeFolderEntities ?? confirmed;+ const paths = rows+ .filter((entity) => entity.type === 'media' || entity.type === 'capture')+ .map((entity) => entity.attrs?.path)+ .filter(Boolean);+ if (!id) {+ pathInfo = new Map();+ return;+ }+ loadThumbs(id, paths);+ });+ async function loadThumbs(id, paths) {+ try {+ const unique = [...new Set(paths)];+ const batches = [];+ for (let i = 0; i < unique.length; i += 500) {+ batches.push(+ api.post(`/api/cases/${id}/media/metadata`, { paths: unique.slice(i, i + 500) })+ );+ }+ const pages = await Promise.all(batches);+ if (caseState.current?.id !== id) return;+ const next = new Map();+ for (const item of pages.flat()) {+ next.set(item.path, {+ thumbnail: item.thumbnail,+ kind: item.kind,+ size: item.size,+ });+ }+ pathInfo = next;+ } catch {+ if (caseState.current?.id === id) pathInfo = new Map();+ }+ }+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 ? searchScope.filter(matches) : current.entities);+ const visibleEntities = $derived(searching ? searchScope.filter(matches) : current.entities);+ const completeVisibleEntities = $derived(+ completeFolderEntities === null+ ? visibleEntities+ : (searching ? completeFolderEntities.filter(matches) : completeFolderEntities)+ );+ const curFolders = $derived(searching ? [] : sortFolders(current.children));+ const curEntities = $derived(sortEntities(completeVisibleEntities));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@@ -136,9 +256,11 @@function openFolder(path) {showUnfiled = false;cwd = path;+ if (searching && pl.serverMode) pl.reload();}function openUnfiled() {showUnfiled = true;+ if (searching && pl.serverMode) pl.reload();}// ── selection ────────────────────────────────────────────────────────────────@@ -164,7 +286,16 @@let marquee = $state(null); // {left, top, width, height} in the grid's content spacefunction onGridPointerDown(e) {- if (e.button !== 0 || e.target.closest('.tile')) return;+ if (e.button !== 0) return;+ // List view has no rubber-band; a click on empty space just clears.+ if (view === 'list') {+ if (!e.target.closest('.lrow')) {+ selected = [];+ anchor = null;+ }+ return;+ }+ if (e.target.closest('.tile')) return;const rect = gridEl.getBoundingClientRect();const additive = e.shiftKey || e.metaKey || e.ctrlKey;const base = additive ? [...selected] : [];@@ -324,8 +455,8 @@? `${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.',+ ? 'Deletes the underlying files from disk and cannot be undone.'+ : `${multi ? 'Removes them' : 'Removes it'} from the case and cannot be undone.`,consequences,confirmLabel: multi ? 'Delete all' : 'Delete everywhere',tone: 'danger',@@ -466,7 +597,85 @@// ── details ────────────────────────────────────────────────────────────────let infoEntityId = $state(null);- let dense = $state(true); // small thumbnails by default — this view's whole point++ // View mode: small/large icon grids, plus a details list with columns.+ let view = $state('small');+ const dense = $derived(view === 'small');+ const VIEWS = [+ { id: 'small', label: 'Small', icon: 'grid' },+ { id: 'large', label: 'Large', icon: 'image' },+ { id: 'list', label: 'List', icon: 'note' },+ ];++ const tileSize = (e) => pathInfo.get(e.attrs?.path)?.size ?? null;+ function fmtSize(bytes) {+ if (bytes == null) return '—';+ if (bytes >= 1 << 30) return (bytes / (1 << 30)).toFixed(1) + ' GB';+ if (bytes >= 1 << 20) return (bytes / (1 << 20)).toFixed(1) + ' MB';+ if (bytes >= 1 << 10) return (bytes / (1 << 10)).toFixed(0) + ' KB';+ return bytes + ' B';+ }+ // Compact local timestamp (MM-DD HH:mm) from an entity's provenance.+ function fmtAdded(e) {+ const iso = e.provenance?.at;+ if (!iso) return '—';+ const d = new Date(iso);+ if (Number.isNaN(d.getTime())) return '—';+ const p = (n) => String(n).padStart(2, '0');+ return `${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;+ }++ // List view must not sort only the first catalog page. Fetch the exact open+ // folder, or every descendant folder while searching, through the bounded+ // endpoint and merge the pages before applying the local column sort.+ $effect(() => {+ const id = caseState.current?.id;+ const folders = caseState.current?.folders ?? [];+ caseState.rev;+ const needsCompleteList = view === 'list' && (Boolean(cwd) || showUnfiled || searching);+ if (!id || !needsCompleteList) {+ completeFolderRun += 1;+ completeFolderEntities = null;+ completeFolderLoading = false;+ completeFolderError = false;+ return;+ }++ const folderPaths = cwd && searching+ ? [cwd, ...folders.filter((path) => path.startsWith(`${cwd}/`))]+ : cwd+ ? [cwd]+ : [];+ const scopes = showUnfiled+ ? [{ unfiled: true }]+ : folderPaths.length+ ? folderPaths.map((folder) => ({ folder }))+ : [{}];+ const run = ++completeFolderRun;+ completeFolderEntities = null;+ completeFolderLoading = true;+ completeFolderError = false;++ Promise.all(+ scopes.map((scope) => fetchAllEntities(id, { status: 'confirmed', ...scope }))+ )+ .then((pages) => {+ if (run !== completeFolderRun) return;+ const seen = new Set();+ completeFolderEntities = pages.flat().filter((entity) => {+ if (seen.has(entity.id)) return false;+ seen.add(entity.id);+ return true;+ });+ })+ .catch(() => {+ if (run !== completeFolderRun) return;+ completeFolderError = true;+ })+ .finally(() => {+ if (run === completeFolderRun) completeFolderLoading = false;+ });+ });</script><div class="tool">@@ -474,22 +683,32 @@<h2>Files</h2><span class="sub">Organize My work</span><div class="spacer"></div>- <div class="search-box">- <Icon name="search" size={13} />- <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} />+ <SearchInput+ bind:value={query}+ placeholder={cwd ? 'Search this folder…' : 'Search My work…'}+ width="160px"+ />+ {#if view !== 'list'}+ <select class="select sort-select" value={sort} onchange={onSortSelect} title="Sort order">+ {#each SORTS as s (s.id)}+ <option value={s.id}>{sortOptionLabel(s)}</option>+ {/each}+ </select>+ {/if}+ <div class="view-switch" role="group" aria-label="View">+ {#each VIEWS as v (v.id)}+ <button+ class="view-btn"+ class:active={view === v.id}+ title={`${v.label} view`}+ aria-pressed={view === v.id}+ onclick={() => (view = v.id)}+ >+ <Icon name={v.icon} size={14} /> {v.label}</button>- {/if}+ {/each}</div>- <button- class="btn btn-ghost btn-sm"- title={dense ? 'Larger thumbnails' : 'Smaller thumbnails'}- onclick={() => (dense = !dense)}- >- <Icon name="grip" size={15} /> {dense ? 'Small' : 'Large'}- </button>+ <span class="bar-sep"></span><form class="new-folder" onsubmit={(e) => { e.preventDefault(); createFolder(); }}><input class="input" placeholder="New folder…" bind:value={newFolder} /><button class="btn" type="submit" disabled={!newFolder.trim()}>@@ -572,6 +791,119 @@{/if}</div>+ {#if view === 'list'}+ <!-- Details list: rows with columns (Name · Type · Size · Added). -->+ <!-- svelte-ignore a11y_no_static_element_interactions -->+ <div+ class="list"+ bind:this={gridEl}+ onpointerdown={onGridPointerDown}+ oncontextmenu={(e) => openCtx(e, ctxParent)}+ >+ <div class="lrow lhead" role="row">+ {#each LIST_SORTS as column (column.id)}+ <button+ class={`lhead-button lcol-${column.id === 'recent' ? 'added' : column.id}`}+ class:active={headerSort === column.id}+ type="button"+ title={`Sort by ${column.label}`}+ aria-label={`Sort by ${column.label}${headerSort === column.id ? `, ${sortDirection === 'asc' ? 'ascending' : 'descending'}` : ''}`}+ onclick={() => setHeaderSort(column.id)}+ >+ {column.label}+ {#if headerSort === column.id}+ <Icon name={sortDirection === 'asc' ? 'chevronUp' : 'chevronDown'} size={12} />+ {/if}+ </button>+ {/each}+ </div>+ {#if completeFolderLoading}+ <div class="list-status" role="status">Loading all files in this folder…</div>+ {:else if completeFolderError}+ <div class="list-status error" role="status">Could not load the complete folder. Showing loaded items.</div>+ {/if}+ {#if !showUnfiled}+ {#each curFolders as node (node.path)}+ <div+ class="lrow folder"+ class:dropping={dropTarget === node.path}+ role="button"+ tabindex="0"+ title={node.name}+ ondblclick={() => openFolder(node.path)}+ onkeydown={(e) => e.key === 'Enter' && openFolder(node.path)}+ oncontextmenu={(e) => openCtx(e, node.path, true)}+ ondragover={(e) => { e.preventDefault(); dropTarget = node.path; }}+ ondragleave={() => (dropTarget = dropTarget === node.path ? null : dropTarget)}+ ondrop={(e) => { e.preventDefault(); dropInto(node.path); }}+ >+ <span class="lcol-name"><Icon name="folder" size={15} /><span class="ltext">{node.name}</span></span>+ <span class="lcol-type">folder</span>+ <span class="lcol-size">—</span>+ <span class="lcol-added">{subtreeCount(node)} item{subtreeCount(node) === 1 ? '' : 's'}</span>+ </div>+ {/each}+ {#if showRootUnfiled}+ <div+ class="lrow folder"+ class:dropping={dropTarget === UNFILED}+ role="button"+ tabindex="0"+ title="Unfiled"+ ondblclick={openUnfiled}+ onkeydown={(e) => e.key === 'Enter' && openUnfiled()}+ ondragover={(e) => { e.preventDefault(); dropTarget = UNFILED; }}+ ondragleave={() => (dropTarget = dropTarget === UNFILED ? null : dropTarget)}+ ondrop={(e) => { e.preventDefault(); dropInto(''); }}+ >+ <span class="lcol-name"><Icon name="file" size={15} /><span class="ltext">Unfiled</span></span>+ <span class="lcol-type">—</span>+ <span class="lcol-size">—</span>+ <span class="lcol-added">{unfiled.length} item{unfiled.length === 1 ? '' : 's'}</span>+ </div>+ {/if}+ {/if}+ {#each completeFolderLoading ? [] : curEntities as e (e.id)}+ <div+ class="lrow entity"+ class:selected={selected.includes(e.id)}+ data-id={e.id}+ draggable="true"+ role="button"+ tabindex="0"+ title={e.label}+ onclick={(ev) => onTileClick(ev, 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; }}+ >+ <span class="lcol-name">+ {#if tileThumb(e)}+ <img class="lrow-thumb" src={`/files/${caseState.current.id}/${tileThumb(e)}`} alt="" loading="lazy" />+ {:else}+ <Icon name={tileIcon(e)} size={15} />+ {/if}+ <span class="ltext">{e.label}</span>+ </span>+ <span class="lcol-type">{e.type}</span>+ <span class="lcol-size">{fmtSize(tileSize(e))}</span>+ <span class="lcol-added">{fmtAdded(e)}</span>+ </div>+ {/each}+ {#if !curFolders.length && !curEntities.length && !showRootUnfiled}+ <div class="grid-empty">+ <Icon name="folder" size={34} />+ <p>+ {#if searching}No files match “{query.trim()}”.+ {:else if showUnfiled}Nothing unfiled.+ {:else}This folder is empty. Drag items here, or right-click to add a subfolder or note.{/if}+ </p>+ </div>+ {/if}+ </div>+ {:else}<!-- svelte-ignore a11y_no_static_element_interactions --><divclass="grid"@@ -674,6 +1006,15 @@></div>{/if}</div>+ {/if}+ {#if pl.hasMore}+ <div class="show-more">+ <button class="btn" onclick={() => pl.loadMore()} disabled={pl.loading}>+ {pl.loading ? 'Loading…' : 'Show more'}+ </button>+ <span>Showing {confirmed.length} of {total}</span>+ </div>+ {/if}</section></div>{/if}@@ -854,39 +1195,32 @@gap: 6px;}.new-folder .input {- width: 160px;+ width: 150px;font-size: var(--fs-sm);}- .search-box {- display: flex;- align-items: center;- gap: 6px;+ /* The global .select is width:100%; without this the sort control balloons+ across the toolbar. Keep it sized to its content, like the Media bar. */+ .sort-select {+ width: auto;+ flex-shrink: 0;+ font-size: var(--fs-xs);padding: 4px 8px;- border: 1px solid var(--border);- border-radius: var(--r-sm);- background: var(--bg-2);- color: var(--text-3);- }- .search-box:focus-within {- border-color: var(--accent);}- .search-input {- width: 160px;- border: none;- background: none;- outline: none;- color: var(--text-1);- font-size: var(--fs-xs);+ .bar-sep {+ width: 1px;+ align-self: stretch;+ margin: 4px 2px;+ background: var(--border);+ flex-shrink: 0;}- .search-clear {- display: inline-flex;+ .show-more {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 10px;+ padding: 16px 0 4px;color: var(--text-3);- padding: 1px;- border-radius: 50%;- }- .search-clear:hover {- color: var(--text-1);- background: var(--bg-3);+ font-size: var(--fs-xs);}/* right-click new-folder menu */@@ -1067,6 +1401,144 @@font-weight: 600;}+ /* segmented view switch (Small · Large · List) */+ .view-switch {+ display: flex;+ gap: 2px;+ padding: 2px;+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ background: var(--bg-2);+ flex-shrink: 0;+ }+ .view-btn {+ display: flex;+ align-items: center;+ gap: 4px;+ padding: 3px 8px;+ border-radius: var(--r-sm);+ color: var(--text-3);+ font-size: var(--fs-xs);+ white-space: nowrap;+ }+ .view-btn:hover {+ color: var(--text-1);+ }+ .view-btn.active {+ background: var(--bg-3);+ color: var(--text-1);+ }++ /* details list view */+ .list {+ flex: 1;+ min-height: 0;+ overflow: auto;+ padding: 6px 8px 14px;+ user-select: none;+ }+ .lrow {+ display: grid;+ grid-template-columns: minmax(0, 1fr) 120px 90px 110px;+ align-items: center;+ gap: 10px;+ padding: 6px 10px;+ border-radius: var(--r-sm);+ border: 1px solid transparent;+ font-size: var(--fs-sm);+ color: var(--text-2);+ cursor: pointer;+ }+ .lrow.lhead {+ position: sticky;+ top: 0;+ z-index: 1;+ background: var(--bg-1);+ color: var(--text-3);+ font-size: var(--fs-xs);+ text-transform: uppercase;+ letter-spacing: 0.06em;+ font-weight: 700;+ cursor: default;+ border-bottom: 1px solid var(--border);+ border-radius: 0;+ }+ .lhead-button {+ display: flex;+ align-items: center;+ min-width: 0;+ gap: 4px;+ padding: 0;+ border: 0;+ background: transparent;+ color: inherit;+ font: inherit;+ letter-spacing: inherit;+ text-align: left;+ text-transform: inherit;+ cursor: pointer;+ }+ .lhead-button:hover,+ .lhead-button.active {+ color: var(--text-1);+ }+ .lhead-button :global(svg) {+ flex-shrink: 0;+ }+ .list-status {+ padding: 5px 10px;+ color: var(--text-3);+ font-size: var(--fs-xs);+ }+ .list-status.error {+ color: var(--danger);+ }+ .lrow.entity:hover,+ .lrow.folder:hover {+ background: var(--bg-1);+ }+ .lrow.entity.selected {+ background: var(--accent-soft);+ border-color: var(--accent);+ }+ .lrow.dropping {+ border-color: var(--accent);+ background: var(--accent-soft);+ }+ .lcol-name {+ display: flex;+ align-items: center;+ gap: 8px;+ min-width: 0;+ color: var(--text-1);+ }+ .lcol-name > :global(svg) {+ color: var(--text-3);+ flex-shrink: 0;+ }+ .lrow-thumb {+ width: 30px;+ height: 24px;+ flex: 0 0 auto;+ border-radius: var(--r-sm);+ object-fit: cover;+ background: var(--bg-2);+ }+ .ltext {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .lcol-type,+ .lcol-size,+ .lcol-added {+ font-size: var(--fs-xs);+ color: var(--text-3);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+.grid {position: relative;flex: 1;diff --git a/frontend/src/tools/Files.test.js b/frontend/src/tools/Files.test.jsnew file mode 100644index 0000000..0d273dd--- /dev/null+++ b/frontend/src/tools/Files.test.js@@ -0,0 +1,105 @@+import { describe, expect, it } from 'vitest';+import { readFileSync } from 'node:fs';++const source = readFileSync(new URL('./Files.svelte', import.meta.url), 'utf8');++describe('Files bounded loading', () => {+ it('loads a bounded first page, not the whole catalog on open', () => {+ expect(source).toContain('createPagedList');+ expect(source).toContain("status: 'confirmed'");+ expect(source).toContain('limit: PAGE');+ // the complete-folder fetch is opt-in to List view, not part of case open+ expect(source).toContain("view === 'list'");+ });++ it('offers Show more with an honest filtered total', () => {+ expect(source).toContain('{#if pl.hasMore}');+ expect(source).toContain('pl.loadMore()');+ expect(source).toContain('Showing {confirmed.length} of {total}');+ expect(source).toContain('/catalog/summary');+ expect(source).toContain('searching && pl.serverMode ? pl.total');+ });++ it('clears the previous case before loading the next', () => {+ expect(source).toContain('pl.clear()');+ });++ it('searches every page and descendant folder through the catalog endpoint', () => {+ expect(source).toContain('pl.setQuery(query)');+ expect(source).toContain('query: serverQuery');+ expect(source).toContain('recursive: Boolean(serverQuery && cwd)');+ });++ it('loads metadata only for paths the view can render', () => {+ expect(source).toContain('/media/metadata');+ expect(source).toContain('unique.slice(i, i + 500)');+ expect(source).not.toContain(`/satellite\``);+ expect(source).not.toContain(`/media\``);+ expect(source).toContain('if (caseState.current?.id !== id) return');+ });+});++describe('Files desktop affordances', () => {+ it('uses the shared SearchInput and a sort control', () => {+ expect(source).toContain("import SearchInput from '../components/SearchInput.svelte'");+ expect(source).toContain('onSortSelect');+ expect(source).toContain('sortEntities(');+ });++ it('search also matches notes, not just label/type/folder', () => {+ expect(source).toContain('e.attrs?.notes');+ });++ it('keeps the sort control compact instead of stretching to full width', () => {+ // the global .select is width:100%; the header control must override it or+ // it balloons across the toolbar (reported "the sort bar is enormous")+ const block = source.slice(+ source.indexOf('.sort-select {'),+ source.indexOf('}', source.indexOf('.sort-select {'))+ );+ expect(block).toContain('width: auto');+ expect(block).toContain('flex-shrink: 0');+ });++ it('offers three view modes: small, large, and a details list', () => {+ expect(source).toContain("let view = $state('small')");+ expect(source).toContain("{ id: 'small', label: 'Small'");+ expect(source).toContain("{ id: 'large', label: 'Large'");+ expect(source).toContain("{ id: 'list', label: 'List'");+ expect(source).toContain('const dense = $derived(');+ });++ it('renders the list view with Name/Type/Size/Added columns', () => {+ expect(source).toContain("{#if view === 'list'}");+ expect(source).toContain("{ id: 'name', label: 'Name' }");+ expect(source).toContain("{ id: 'type', label: 'Type' }");+ expect(source).toContain("{ id: 'size', label: 'Size' }");+ expect(source).toContain("{ id: 'recent', label: 'Added' }");+ // size comes from the media shelf, added from provenance+ expect(source).toContain('fmtSize(tileSize(e))');+ expect(source).toContain('fmtAdded(e)');+ });++ it('sorts from clickable headers and loads the complete open folder', () => {+ expect(source).toContain('setHeaderSort(column.id)');+ expect(source).toContain('sortDirection');+ expect(source).toContain('fetchAllEntities(id');+ expect(source).toContain("{ folder }");+ expect(source).toContain('{ unfiled: true }');+ expect(source).toContain('Loading all files in this folder');+ });++ it('carries the same selection/drag wiring onto list rows', () => {+ // list rows must be selectable, draggable and openable like the tiles+ expect(source).toContain('class="lrow entity"');+ expect(source).toContain('onclick={(ev) => onTileClick(ev, e.id)}');+ expect(source).toContain('ondragstart={(ev) => onTileDragStart(ev, e.id)}');+ });++ it('previews rendered proof PNGs in both tiles and list rows', () => {+ expect(source).toContain("e.type === 'proof' && typeof path === 'string' && /\\.png$/i.test(path)");+ expect(source).toContain('class="lrow-thumb"');+ expect(source).toContain('src={`/files/${caseState.current.id}/${tileThumb(e)}`}');+ expect(source).toContain('{#if tileThumb(e)}');+ });+});diff --git a/frontend/src/tools/Inspector.svelte b/frontend/src/tools/Inspector.svelteindex 292334f..0ec21f1 100644--- a/frontend/src/tools/Inspector.svelte+++ b/frontend/src/tools/Inspector.svelte@@ -1,15 +1,19 @@<script>import { api } from '../lib/api.js';- import { lookupEntity } from '../lib/catalog.js';+ import { fetchAllEntities, lookupEntity } from '../lib/catalog.js';+ import { matchesTerms } from '../lib/folderBrowse.js';import { caseState, uiState, reloadCase, toast } from '../lib/state.svelte.js';import {adjustDefaults, buildFrameOps, previewStyle, uid, videoSeed, initialQuad, VIDEO_ADJUST_IDS,collageBounds, quadFromCropRect, cropImgStyle, cropAspect, styleText, hasVideoEdits,- normalizeRightAngleRotation, rotationOps,+ normalizeRightAngleRotation, rotationOps, sourceStem, timecode, autoSaveNames, saveNameOf,} from '../lib/inspect.js';+ import { isDefaultName, nextName, savedSlugs, savedTitles, savedTitle, slugify } from '../lib/naming.js';import { createHistory } from '../lib/history.js';import { IDENTITY, matrixCss, rotateAbout, isIdentity, matrixAngleDeg, pointerAngleDeg } from '../lib/frameRotate.js';import Icon from '../components/Icon.svelte';+ import SearchInput from '../components/SearchInput.svelte';+ import FolderBrowser from '../components/FolderBrowser.svelte';import ConfirmDialog from '../components/ConfirmDialog.svelte';import CropBox from './inspect/CropBox.svelte';import SelectionMenu from './inspect/SelectionMenu.svelte';@@ -21,18 +25,41 @@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- // layout all live here as plain data. Nothing becomes case media until the Save- // tab commits it — the recipes are re-derived full-res on the backend then.+ // Inspect keeps edits in session state until the Save tab renders them at full+ // resolution and commits selected outputs to the case.const TAB_META = {selection: { label: 'Selection', icon: 'video' },frame: { label: 'Frame', icon: 'image' },collage: { label: 'Collage', icon: 'layers' },save: { label: 'Save', icon: 'save' },};+ const SOURCE_FILTERS = [+ { id: 'all', label: 'All' },+ { id: 'image', label: 'Images' },+ { id: 'video', label: 'Video' },+ { id: 'capture', label: 'Captures' },+ { id: 'frame', label: 'Frames' },+ { id: 'collage', label: 'Collages' },+ ];let mediaList = $state([]);+ let sourceQuery = $state('');+ let sourceFilter = $state('all');+ let sourceModalOpen = $state(false);+ let sourceBrowserOpen = $state(false);+ let sourceBrowsePath = $state('');+ let sourceBrowseSelection = $state(null);+ let openSourceAfterDiscard = $state(false);+ const inspectableMedia = $derived(mediaList.filter((m) => m.kind === 'image' || m.kind === 'video'));+ const filteredSourceMedia = $derived(+ sourceFilter === 'all' ? inspectableMedia : inspectableMedia.filter((m) => sourceCategory(m) === sourceFilter)+ );+ const pickableMedia = $derived(+ sourceQuery.trim() ? filteredSourceMedia.filter((m) => matchesSourceName(m, sourceQuery)) : filteredSourceMedia+ );+ const sourceBrowserEntries = $derived(+ filteredSourceMedia.map((m) => ({ ...m, id: m.path, attrs: { folder: m.folder ?? '' } }))+ );let loadedFor = $state(null);let filters = $state([]);let analyses = $state([]);@@ -41,22 +68,30 @@let activeTab = $state('selection');let collageSelectedIds = $state([]);let cropPieceNode = $state(null);- // Real (backend-composited) Save-tab thumbnails, keyed by collage id:- // { sig, url } — regenerated only when a collage's layout actually changes.+ // Backend-composited Save thumbnails keyed by collage id: { sig, url }.let collagePreviews = $state({});let saving = $state(false);- const saveUi = $state({ selected: {}, folder: '' });- // the saved session this workspace came from (if any) — re-saving overwrites it- // in place instead of forking a new named session.+ // Keep names outside the derived `savables` list so slider changes preserve input.+ const saveUi = $state({ selected: {}, folder: '', names: {}, touched: {}, baseName: '', note: '' });+ // The header name controls the session filename; `openedSession` stores its slug.+ let sessionName = $state('');let openedSession = $state(null);- const sessionModal = $state({ open: false, mode: 'save', name: null, title: '', list: [], busy: false });+ const sessionModal = $state({ open: false, list: [], busy: false });+ let sessionQuery = $state('');+ let sessionBrowserOpen = $state(false);+ let sessionBrowsePath = $state('');+ let sessionBrowseSelection = $state(null);+ const visibleSessions = $derived(+ sessionQuery.trim() ? sessionModal.list.filter((s) => matchesSessionQuery(s, sessionQuery)) : sessionModal.list+ );+ const sessionBrowserEntries = $derived(+ sessionModal.list.map((s) => ({ ...s, id: s.name, attrs: { folder: s.folder ?? '' } }))+ );let discardConfirm = $state(false);- // openSession fetches the spec then re-renders every frame and collage node- // one at a time — slow enough on a heavy session that the tool needs to say so.+ // Loading can be slow because each frame and collage node is rendered in sequence.let sessionLoading = $state(false);- // A fresh, empty collage. A session can hold several — the Collage tab edits- // one at a time (session.activeCollageId) and each is saved as its own PNG.+ // A session can hold several collages and edits one at a time.function makeCollage(name) {return { id: uid('cl'), name, width: 1600, height: 800, background: '#12141c', transparent: true, nodes: [] };}@@ -202,7 +237,7 @@const videoFilters = $derived(filters.filter((f) => VIDEO_ADJUST_IDS.includes(f.id)));const tabs = $derived(- session.source?.kind === 'video' ? ['selection', 'frame', 'collage', 'save'] : ['frame', 'collage', 'save']+ session.source?.kind === 'video' ? ['selection', 'frame', 'collage', 'save'] : ['frame', 'save']);const activeFrame = $derived(session.frames.find((f) => f.id === session.activeFrameId) ?? null);const framePreview = $derived(activeFrame ? previewStyle(filters, activeFrame.adjust) : { filter: '', transform: '' });@@ -216,20 +251,21 @@const savables = $derived.by(() => {const out = [];const cid = caseState.current?.id;+ const stem = sourceStem(session.source);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,+ key: 'video', kind: 'video', defaultName: `${stem} (enhanced)`, thumb: t,filter: videoPreview.filter, transform: videoPreviewTransform,saved: !!session.saved.video,});}- let imgN = 0;for (const fr of session.frames) {- imgN += 1;+ const frameStem = sourceStem({ path: fr.path }) || stem;out.push({key: `frame:${fr.id}`, kind: 'frame', frame: fr, thumb: fr.url,- label: `Image ${imgN}`, filter: previewStyle(filters, fr.adjust).filter,+ defaultName: fr.time == null ? `${frameStem} (edited)` : `${frameStem} ${timecode(fr.time)}`,+ filter: previewStyle(filters, fr.adjust).filter,saved: !!session.saved[`frame:${fr.id}`],});}@@ -238,7 +274,7 @@colN += 1;if (!cl.nodes.length) continue;out.push({- key: `collage:${cl.id}`, kind: 'collage', label: cl.name || `Collage ${colN}`,+ key: `collage:${cl.id}`, kind: 'collage', defaultName: cl.name || `Collage ${colN}`,thumb: null, collage: cl, preview: collagePreviews[cl.id]?.url ?? null,saved: !!session.saved[`collage:${cl.id}`],});@@ -246,6 +282,30 @@return out;});+ // Every field carries real, editable text — never a placeholder to guess at.+ // Fields the user has not touched follow the base name; the ones they typed in+ // are theirs and stay put.+ //+ // A collage keeps its name in the session (session.collages[].name), not in+ // saveUi — that is the one name the Collage tab and the Save tab share, so a+ // rename in either place shows up in the other.+ const saveName = (it) => (it.kind === 'collage' ? (it.collage.name ?? '') : (saveUi.names[it.key] ?? ''));+ function setSaveName(it, value) {+ if (it.kind === 'collage') it.collage.name = value;+ else saveUi.names[it.key] = value;+ saveUi.touched[it.key] = true;+ saveUi.selected[it.key] = true;+ }++ $effect(() => {+ const auto = autoSaveNames(savables, saveUi.baseName);+ savables.forEach((it, i) => {+ if (saveUi.touched[it.key]) return;+ if (it.kind === 'collage') it.collage.name = auto[i];+ else saveUi.names[it.key] = auto[i];+ });+ });+// -- lifecycle ------------------------------------------------------------$effect(() => {const id = caseState.current?.id;@@ -338,9 +398,129 @@};});- function mediaLabel(m) {- const name = m.title || m.filename;- return name.length > 60 ? name.slice(0, 57) + '…' : name;+ // Every saved session in this case, read off the filed entities: the slugs to+ // catch a name already taken, the names so a fresh session reads apart.+ let sessionEntities = $state([]);+ $effect(() => {+ const id = caseState.current?.id;+ caseState.rev; // refresh after a save or a delete anywhere else+ if (!id) {+ sessionEntities = [];+ return;+ }+ let live = true;+ fetchAllEntities(id, { types: ['inspect-session'] })+ .then((list) => {+ if (!live) return;+ sessionEntities = list;+ // The name was assigned before the case's sessions were known. Renumber+ // it now rather than letting a fresh workspace collide on its first save.+ if (!openedSession && isDefaultName(sessionName, 'session')) {+ sessionName = nextName('session', savedTitles(sessionEntities, 'session'));+ }+ })+ .catch(() => { if (live) sessionEntities = []; });+ return () => { live = false; };+ });++ const takenSlugs = () => savedSlugs(sessionEntities, 'session');++ function openSourceDialog() {+ sourceQuery = '';+ sourceFilter = 'all';+ sourceBrowserOpen = false;+ sourceBrowsePath = '';+ sourceBrowseSelection = null;+ sourceModalOpen = true;+ }++ function matchesSourceName(item, query) {+ return matchesTerms(item.title || item.filename || '', query);+ }++ function sourceCategory(item) {+ const source = item.source ?? {};+ if (source.type === 'satellite' || source.type === 'screenshot') return 'capture';+ if (source.op === 'collage') return 'collage';+ if (source.op === 'frame' || source.op === 'adjust') return 'frame';+ return item.kind;+ }++ function matchesSessionQuery(session, query) {+ return matchesTerms([session.title, session.name, session.source].filter(Boolean).join('\n'), query);+ }++ function openSourceBrowser() {+ sourceQuery = '';+ sourceBrowsePath = '';+ sourceBrowseSelection = null;+ sourceBrowserOpen = true;+ }++ function toggleSourceBrowser() {+ if (sourceBrowserOpen) {+ sourceBrowserOpen = false;+ return;+ }+ openSourceBrowser();+ }++ function setSourceFilter(filter) {+ sourceFilter = filter;+ sourceBrowsePath = '';+ sourceBrowseSelection = null;+ }++ function openSourceFolder(path) {+ sourceBrowsePath = path;+ sourceBrowseSelection = null;+ }++ function confirmSourceBrowser() {+ const item = sourceBrowserEntries.find((m) => m.path === sourceBrowseSelection);+ if (item) selectNewSource(item);+ }++ function selectSourceBrowser(item, confirm = false) {+ sourceBrowseSelection = item.path;+ if (confirm) selectNewSource(item);+ }++ function openSessionBrowser() {+ sessionBrowsePath = '';+ sessionBrowseSelection = null;+ sessionBrowserOpen = true;+ }++ function toggleSessionBrowser() {+ if (sessionBrowserOpen) {+ sessionBrowserOpen = false;+ return;+ }+ openSessionBrowser();+ }++ function openSessionFolder(path) {+ sessionBrowsePath = path;+ sessionBrowseSelection = null;+ }++ function confirmSessionBrowser() {+ if (sessionBrowseSelection) openSession(sessionBrowseSelection);+ }++ function selectSessionBrowser(session, confirm = false) {+ sessionBrowseSelection = session.name;+ if (confirm) openSession(session.name);+ }++ function startNewSession() {+ if (session.source) {+ openSourceAfterDiscard = true;+ discardConfirm = true;+ return;+ }+ openSourceDialog();}function resetSession() {@@ -358,7 +538,13 @@session.saved = {};saveUi.selected = {};saveUi.folder = '';+ saveUi.names = {};+ saveUi.touched = {};+ saveUi.baseName = '';+ saveUi.note = '';openedSession = null;+ sessionName = nextName('session', savedTitles(sessionEntities, 'session'));+ savedSignature = null;collageSelectedIds = [];shared.currentTime = 0;shared.cropMode = false;@@ -393,6 +579,11 @@}}+ async function selectNewSource(item) {+ sourceModalOpen = false;+ await select(item);+ }+function makeFrame(path, time, url) {return {id: uid('fr'), path, time, url,@@ -745,6 +936,12 @@const folder = saveUi.folder?.trim() || null;const chosen = savables.filter((it) => saveUi.selected[it.key]);if (!chosen.length) return;+ const note = saveUi.note?.trim() || null;+ const nameOf = (item) => saveNameOf(item, saveName(item));+ // A save can land on media the case already holds (re-saving an unchanged+ // collage is the common one). The name still applies, but the toast has to+ // say no new file appeared, or the count looks wrong in the library.+ let dupes = 0;saving = true;try {const frameItems = chosen@@ -753,15 +950,22 @@path: it.frame.path,time: it.frame.time ?? null,ops: buildFrameOps(filters, it.frame),+ label: nameOf(it),}));if (frameItems.length) {- await api.post(`/api/cases/${cid}/inspect/save-frames`, { items: frameItems, folder });+ const res = await api.post(`/api/cases/${cid}/inspect/save-frames`, {+ items: frameItems, folder, notes: note,+ });+ dupes += (res?.saved ?? []).filter((r) => r.duplicate).length;for (const it of chosen) if (it.kind === 'frame') session.saved[it.key] = true;}- if (chosen.some((it) => it.kind === 'video')) {- await api.post(`/api/cases/${cid}/inspect/enhance-video`, {+ const videoItem = chosen.find((it) => it.kind === 'video');+ if (videoItem) {+ const res = await api.post(`/api/cases/${cid}/inspect/enhance-video`, {path: session.source.path, params: session.videoAdjust, rotation: videoRotation, folder,+ label: nameOf(videoItem), notes: note,});+ if (res?.duplicate) dupes += 1;session.saved.video = true;}for (const it of chosen.filter((c) => c.kind === 'collage')) {@@ -773,18 +977,25 @@src: n.save, // frozen snapshot recipe (path/time/ops)quad: n.quad.map(([x, y]) => [x - b.minX, y - b.minY]),}));- await api.post(`/api/cases/${cid}/inspect/compose`, {+ const res = await api.post(`/api/cases/${cid}/inspect/compose`, {width: b.width,height: b.height,background: null,nodes, folder,+ label: nameOf(it), notes: note,});+ if (res?.duplicate) dupes += 1;session.saved[it.key] = true;}await reloadCase();await refresh();saveUi.selected = {};- toast(`Saved ${chosen.length} item${chosen.length === 1 ? '' : 's'} to the case`, 'ok');+ saveUi.names = {};+ saveUi.touched = {};+ const dupeNote = dupes+ ? `. ${dupes} matched existing media and ${dupes === 1 ? 'was' : 'were'} renamed`+ : '';+ toast(`Saved ${chosen.length} item${chosen.length === 1 ? '' : 's'} to the case${dupeNote}`, 'ok');} catch (e) {toast(e.message, 'danger');} finally {@@ -816,19 +1027,35 @@};}- function openSaveDialog() {- sessionModal.mode = 'save';- sessionModal.name = openedSession?.name ?? null;- sessionModal.title = openedSession?.title || session.source?.label || session.source?.filename || 'Inspect session';- sessionModal.open = true;- }+ // The "unsaved" badge compares what a save would write against what the last+ // one wrote. Deriving it costs one stringify per change, which beats setting a+ // dirty flag at each of the dozens of places that mutate the workspace — and+ // it can't drift out of step with them.+ let savedSignature = $state(null);+ const signature = () => JSON.stringify([sessionName.trim(), sessionSpec()]);+ const sessionDirty = $derived(session.source ? signature() !== savedSignature : false);async function openLoadDialog() {- sessionModal.mode = 'open';sessionModal.busy = true;+ sessionQuery = '';+ sessionBrowserOpen = false;+ sessionBrowsePath = '';+ sessionBrowseSelection = null;sessionModal.open = true;try {- sessionModal.list = await api.get(`/api/cases/${caseState.current.id}/inspect/sessions`);+ const sessions = await api.get(`/api/cases/${caseState.current.id}/inspect/sessions`);+ try {+ const entities = await fetchAllEntities(caseState.current.id, { types: ['inspect-session'] });+ const folders = new Map(+ entities.map((entity) => [+ (entity.attrs?.spec ?? '').replace(/^inspect\//, '').replace(/\.json$/, ''),+ entity.attrs?.folder ?? '',+ ])+ );+ sessionModal.list = sessions.map((session) => ({ ...session, folder: folders.get(session.name) ?? '' }));+ } catch {+ sessionModal.list = sessions;+ }} catch (e) {toast(e.message, 'danger');} finally {@@ -836,22 +1063,39 @@}}- async function confirmSaveSession() {- const title = sessionModal.title.trim();- if (!title) return;- sessionModal.busy = true;+ // Saving writes under the name in the header. When that name is free the+ // backend just renames the bound session onto it; when another session holds+ // it, only an unbound workspace may take it, and only after this asks.+ let overwritePrompt = $state(null);+ let savingSession = $state(false);++ async function saveSession() {+ const title = sessionName.trim();+ if (!title || savingSession || !session.source) return;+ const slug = slugify(title, 'session');+ if (!openedSession && takenSlugs().has(slug)) {+ overwritePrompt = { slug };+ return;+ }+ return performSessionSave();+ }++ async function performSessionSave() {+ const title = sessionName.trim();+ savingSession = true;try {const res = await api.post(`/api/cases/${caseState.current.id}/inspect/sessions`, {- name: sessionModal.name, title, spec: sessionSpec(),+ rename_from: openedSession?.name ?? null, title, spec: sessionSpec(),});openedSession = { name: res.name, title };+ savedSignature = signature();await reloadCase();- sessionModal.open = false;toast('Session saved. Reopen it from the sidebar', 'ok');} catch (e) {toast(e.message, 'danger');} finally {- sessionModal.busy = false;+ savingSession = false;+ overwritePrompt = null;}}@@ -924,6 +1168,8 @@session.activeCollageId =collages.find((c) => c.id === spec.activeCollageId)?.id ?? collages[0].id;openedSession = { name, title: spec.title || name };+ sessionName = openedSession.title;+ savedSignature = signature();activeTab = src.kind === 'video' ? 'selection' : 'frame';anchorCollageHistory();} finally {@@ -934,6 +1180,15 @@function discardSession() {resetSession();discardConfirm = false;+ if (openSourceAfterDiscard) {+ openSourceAfterDiscard = false;+ openSourceDialog();+ }+ }++ function cancelDiscard() {+ discardConfirm = false;+ openSourceAfterDiscard = false;}async function deleteSession(name) {@@ -953,33 +1208,32 @@<div class="tool"><div class="tool-header"><h2>Inspect</h2>+ {#if session.source}+ <input class="input title-input" bind:value={sessionName} maxlength="200" aria-label="Session name" />+ {#if sessionDirty}<span class="badge">unsaved</span>{/if}+ {/if}<div class="spacer"></div>{#if caseState.current}<button class="btn btn-sm" onclick={openLoadDialog} title="Reopen a saved session">- <Icon name="folderOpen" size={14} /> Open+ <Icon name="folderOpen" size={14} /> Open session+ </button>+ <button class="btn btn-sm" onclick={startNewSession} title="Start from case media">+ <Icon name="plus" size={14} /> New session</button>{#if session.source}<button class="btn btn-sm" onclick={() => (discardConfirm = true)} title="Clear this workspace"><Icon name="reset" size={14} /> Discard</button>{/if}- <button class="btn btn-sm" disabled={!session.source} onclick={openSaveDialog} title="Save this workspace">- <Icon name="save" size={14} /> Save session+ <button+ class="btn btn-ok btn-sm"+ disabled={!session.source || savingSession || !sessionName.trim()}+ onclick={saveSession}+ title="Save this workspace under its name"+ >+ <Icon name="save" size={14} /> {savingSession ? 'Saving…' : 'Save session'}</button>{/if}- <select- class="input source-select"- value={session.source?.path ?? ''}- onchange={(e) => {- const m = mediaList.find((x) => x.path === e.target.value);- if (m) select(m);- }}- >- <option value="" disabled>Choose a media…</option>- {#each mediaList as m (m.path)}- <option value={m.path} title={m.title || m.filename}>{mediaLabel(m)}</option>- {/each}- </select></div>{#if !caseState.current}@@ -996,10 +1250,11 @@{:else if !session.source}<div class="empty"><Icon name="inspect" size={40} />- <p>Choose a media above to open it.</p>- {#if mediaList.length === 0}- <button class="btn" onclick={() => (uiState.tool = 'media')}>Add media first</button>- {/if}+ <h3>Start a session</h3>+ <p>Start a session to choose media.</p>+ <button class="btn" onclick={startNewSession}>+ <Icon name="plus" size={15} /> New session+ </button></div>{:else}{#if sourceGone}@@ -1132,7 +1387,7 @@{:else if activeTab === 'collage'}<CollageCanvas collage={activeCollage} bind:selectedIds={collageSelectedIds} {requestCrop} />{:else if activeTab === 'save'}- <SaveGallery {savables} {saveUi} />+ <SaveGallery {savables} {saveUi} {saveName} {setSaveName} />{/if}</div>@@ -1147,7 +1402,11 @@setActive={(id) => (session.activeFrameId = id)}/>{:else if activeTab === 'collage'}- <CollageMenu {session} {filters} bind:selectedIds={collageSelectedIds} {addToCollage} {requestCrop} {renderPiece} />+ <CollageMenu+ {session} {filters} bind:selectedIds={collageSelectedIds}+ {addToCollage} {requestCrop} {renderPiece}+ onRename={(cl) => (saveUi.touched[`collage:${cl.id}`] = true)}+ />{:else if activeTab === 'save'}<SaveMenu {savables} {saveUi} {saving} save={saveSelected} />{/if}@@ -1172,10 +1431,111 @@tone="danger"icon="reset"onconfirm={discardSession}- oncancel={() => (discardConfirm = false)}+ oncancel={cancelDiscard}/>{/if}+ {#if overwritePrompt}+ <ConfirmDialog+ title="Overwrite this session?"+ message={`“${savedTitle(sessionEntities, 'session', overwritePrompt.slug)}” is already saved in this case.`}+ detail="Saving replaces its workspace. Rename this session to keep both."+ confirmLabel="Overwrite"+ tone="danger"+ icon="check"+ onconfirm={performSessionSave}+ oncancel={() => (overwritePrompt = null)}+ />+ {/if}++ {#if sourceModalOpen}+ <!-- svelte-ignore a11y_click_events_have_key_events -->+ <!-- svelte-ignore a11y_no_static_element_interactions -->+ <div class="modal-back" onclick={() => (sourceModalOpen = false)} role="presentation">+ <!-- svelte-ignore a11y_click_events_have_key_events -->+ <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->+ <div class="modal source-modal" onclick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" aria-labelledby="new-session-title" tabindex="-1">+ <div class="modal-head">+ <h3 id="new-session-title">New session</h3>+ <button class="btn btn-ghost btn-xs" onclick={() => (sourceModalOpen = false)} aria-label="Close">+ <Icon name="x" size={15} />+ </button>+ </div>++ <div class="picker-search">+ <SearchInput bind:value={sourceQuery} placeholder="Search names…" width="100%" />+ <button class="btn btn-ghost btn-sm browse-btn" title="Browse folders" onclick={toggleSourceBrowser}>…</button>+ </div>++ {#if inspectableMedia.length === 0}+ <p class="modal-hint">Add an image or video to start an Inspect session.</p>+ <div class="modal-actions">+ <button class="btn btn-sm" onclick={() => (sourceModalOpen = false)}>Cancel</button>+ <button class="btn btn-primary btn-sm" onclick={() => { sourceModalOpen = false; uiState.tool = 'media'; }}>+ Go to Media Library+ </button>+ </div>+ {:else}+ <div class="source-filters" aria-label="Media type">+ {#each SOURCE_FILTERS as filter (filter.id)}+ <button+ class="btn btn-ghost btn-sm"+ class:active={sourceFilter === filter.id}+ aria-pressed={sourceFilter === filter.id}+ onclick={() => setSourceFilter(filter.id)}+ >+ {filter.label}+ </button>+ {/each}+ </div>++ {#if sourceBrowserOpen}+ <FolderBrowser+ entries={sourceBrowserEntries}+ path={sourceBrowsePath}+ rootLabel="Case media"+ selectedId={sourceBrowseSelection}+ matches={(m) => matchesSourceName(m, sourceQuery)}+ emptyText="This folder has no matching media."+ icon={(m) => (m.kind === 'video' ? 'video' : 'image')}+ label={(m) => m.title || m.filename}+ onnavigate={openSourceFolder}+ onselect={(m) => selectSourceBrowser(m)}+ onconfirm={(m) => selectSourceBrowser(m, true)}+ />+ <div class="modal-actions">+ <button class="btn btn-primary btn-sm" disabled={!sourceBrowseSelection} onclick={confirmSourceBrowser}>Open selected</button>+ </div>+ {:else}+ {#if pickableMedia.length === 0}+ <p class="modal-hint">No media matches this filter.</p>+ {:else}+ <div class="source-list">+ {#each pickableMedia as m (m.path)}+ <button class="source-open" onclick={() => selectNewSource(m)}>+ <div class="source-thumb">+ {#if m.thumbnail}+ <img src={`/files/${caseState.current.id}/${m.thumbnail}`} alt="" loading="lazy" />+ {:else}+ <Icon name={m.kind === 'video' ? 'video' : 'image'} size={22} />+ {/if}+ </div>+ <span class="source-copy">+ <span class="source-title">{m.title || m.filename}</span>+ <span class="source-meta">+ {sourceCategory(m)}{m.folder ? ` · ${m.folder}` : ''}{m.title && m.filename !== m.title ? ` · ${m.filename}` : ''}+ </span>+ </span>+ </button>+ {/each}+ </div>+ {/if}+ {/if}+ {/if}+ </div>+ </div>+ {/if}+{#if sessionModal.open}<!-- svelte-ignore a11y_click_events_have_key_events --><!-- svelte-ignore a11y_no_static_element_interactions -->@@ -1184,45 +1544,62 @@<!-- svelte-ignore a11y_no_noninteractive_element_interactions --><div class="modal" onclick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" tabindex="-1"><div class="modal-head">- <h3>{sessionModal.mode === 'save' ? 'Save session' : 'Open session'}</h3>+ <h3>Open session</h3><button class="btn btn-ghost btn-xs" onclick={() => (sessionModal.open = false)} aria-label="Close"><Icon name="x" size={15} /></button></div>- {#if sessionModal.mode === 'save'}- <p class="modal-hint">Saves the workspace to reopen later; no media is filed.</p>- <input- class="input"- placeholder="Session name"- bind:value={sessionModal.title}- onkeydown={(e) => e.key === 'Enter' && confirmSaveSession()}+ {#if sessionBrowserOpen}+ <div class="picker-search">+ <SearchInput bind:value={sessionQuery} placeholder="Search sessions…" width="100%" />+ <button class="btn btn-ghost btn-sm browse-btn" title="Show session list" onclick={toggleSessionBrowser}>…</button>+ </div>+ <FolderBrowser+ entries={sessionBrowserEntries}+ path={sessionBrowsePath}+ rootLabel="Sessions"+ selectedId={sessionBrowseSelection}+ matches={(s) => matchesSessionQuery(s, sessionQuery)}+ emptyText="This folder has no matching sessions."+ icon={() => 'inspect'}+ label={(s) => s.title}+ onnavigate={openSessionFolder}+ onselect={(s) => selectSessionBrowser(s)}+ onconfirm={(s) => selectSessionBrowser(s, true)}/><div class="modal-actions">- <button class="btn btn-sm" onclick={() => (sessionModal.open = false)}>Cancel</button>- <button class="btn btn-primary btn-sm" disabled={sessionModal.busy || !sessionModal.title.trim()} onclick={confirmSaveSession}>- <Icon name="save" size={14} /> Save- </button>+ <button class="btn btn-primary btn-sm" disabled={!sessionBrowseSelection} onclick={confirmSessionBrowser}>Open selected</button></div>{:else}{#if sessionModal.busy}<p class="modal-hint">Loading…</p>- {:else if sessionModal.list.length === 0}- <p class="modal-hint">No saved sessions yet.</p>{:else}- <div class="session-list">- {#each sessionModal.list as s (s.name)}- <div class="session-row">- <button class="session-open" disabled={sessionLoading} onclick={() => openSession(s.name)}>- <span class="session-title">{s.title}</span>- <span class="session-meta">{s.frames} frame{s.frames === 1 ? '' : 's'} · {s.collage} collage piece{s.collage === 1 ? '' : 's'}</span>- </button>- <button class="btn btn-ghost btn-xs" disabled={sessionLoading} onclick={() => deleteSession(s.name)} aria-label="Delete session">- <Icon name="trash" size={14} />- </button>- </div>- {/each}- </div>+ {#if sessionModal.list.length > 6}+ <div class="picker-search">+ <SearchInput bind:value={sessionQuery} placeholder="Search sessions…" width="100%" />+ <button class="btn btn-ghost btn-sm browse-btn" title="Browse folders" onclick={toggleSessionBrowser}>…</button>+ </div>+ {/if}+ {#if sessionModal.list.length === 0}+ <p class="modal-hint">No saved sessions yet.</p>+ {:else if visibleSessions.length === 0}+ <p class="modal-hint">No sessions match this search.</p>+ {:else}+ <div class="session-list">+ {#each visibleSessions as s (s.name)}+ <div class="session-row">+ <button class="session-open" disabled={sessionLoading} onclick={() => openSession(s.name)}>+ <span class="session-title">{s.title}</span>+ <span class="session-meta">{s.frames} frame{s.frames === 1 ? '' : 's'} · {s.collage} collage piece{s.collage === 1 ? '' : 's'}</span>+ </button>+ <button class="btn btn-ghost btn-xs" disabled={sessionLoading} onclick={() => deleteSession(s.name)} aria-label="Delete session">+ <Icon name="trash" size={14} />+ </button>+ </div>+ {/each}+ </div>+ {/if}{/if}{/if}</div>@@ -1251,9 +1628,6 @@.spacer {flex: 1;}- .source-select {- max-width: 280px;- }.empty,.hint-mid {flex: 1;@@ -1467,6 +1841,9 @@flex-direction: column;gap: 12px;}+ .source-modal {+ width: 560px;+ }.modal-head {display: flex;align-items: center;@@ -1486,6 +1863,88 @@justify-content: flex-end;gap: 8px;}+ .source-list {+ display: flex;+ flex-direction: column;+ gap: 6px;+ max-height: min(52vh, 480px);+ overflow: auto;+ }+ .source-filters {+ display: flex;+ gap: 4px;+ overflow-x: auto;+ padding-bottom: 2px;+ }+ .picker-search {+ display: flex;+ align-items: center;+ gap: 6px;+ }+ .picker-search :global(.search-box) {+ flex: 1;+ }+ .browse-btn {+ min-width: 30px;+ font-size: var(--fs-lg);+ line-height: 1;+ }+ .source-filters .active {+ color: var(--text-1);+ background: var(--bg-3);+ }+ .source-open {+ display: flex;+ align-items: center;+ gap: 10px;+ width: 100%;+ padding: 7px;+ text-align: left;+ border: 1px solid var(--border);+ border-radius: var(--r-md);+ background: var(--bg-2);+ }+ .source-open:hover {+ border-color: var(--accent);+ background: var(--bg-3);+ }+ .source-thumb {+ display: grid;+ place-items: center;+ width: 48px;+ height: 40px;+ flex-shrink: 0;+ overflow: hidden;+ border-radius: var(--r-sm);+ background: var(--bg-0);+ color: var(--text-3);+ }+ .source-thumb img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ }+ .source-copy {+ display: flex;+ flex-direction: column;+ min-width: 0;+ gap: 2px;+ }+ .source-title,+ .source-meta {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .source-title {+ color: var(--text-1);+ font-size: var(--fs-sm);+ font-weight: 600;+ }+ .source-meta {+ color: var(--text-3);+ font-size: var(--fs-xs);+ }.session-list {display: flex;flex-direction: column;diff --git a/frontend/src/tools/Inspector.test.js b/frontend/src/tools/Inspector.test.jsnew file mode 100644index 0000000..36dcd7d--- /dev/null+++ b/frontend/src/tools/Inspector.test.js@@ -0,0 +1,172 @@+import { describe, expect, it } from 'vitest';+import { readFileSync } from 'node:fs';++const source = readFileSync(new URL('./Inspector.svelte', import.meta.url), 'utf8');++describe('Inspect sessions', () => {+ it('opens saved workspaces under an explicit label', () => {+ expect(source).toContain('<Icon name="folderOpen" size={14} /> Open session');+ expect(source).toContain('title="Reopen a saved session"');+ });++ it('uses the same non-gold colored save action as Proof', () => {+ expect(source).toContain('class="btn btn-ok btn-sm"');+ expect(source).toContain('onclick={saveSession}');+ expect(source).not.toContain('class="btn btn-primary btn-sm"\n disabled={!session.source}');+ });++ it('names the session in the header, and saves under that name', () => {+ // Same affordance as the Proof Composer: the name is edited at the top of+ // the tool, and Save writes under it — there is no "name this" dialog.+ expect(source).toContain('<input class="input title-input" bind:value={sessionName}');+ expect(source).toContain('aria-label="Session name"');+ expect(source).toContain('rename_from: openedSession?.name ?? null, title, spec: sessionSpec()');+ expect(source).not.toContain("sessionModal.mode = 'save'");+ expect(source).not.toContain('placeholder="Session name"');+ });++ it('numbers a fresh session past the ones already in the case', () => {+ expect(source).toContain("nextName('session', savedTitles(sessionEntities, 'session'))");+ });++ it('flags unsaved work against the last save rather than a hand-set flag', () => {+ expect(source).toContain('{#if sessionDirty}<span class="badge">unsaved</span>{/if}');+ expect(source).toContain("const signature = () => JSON.stringify([sessionName.trim(), sessionSpec()]);");+ });++ it('asks before an unbound workspace takes a name another session holds', () => {+ expect(source).toContain('if (!openedSession && takenSlugs().has(slug))');+ expect(source).toContain('title="Overwrite this session?"');+ });++ it('starts new workspaces from a searchable image/video picker', () => {+ expect(source).toContain("import SearchInput from '../components/SearchInput.svelte'");+ expect(source).toContain("m.kind === 'image' || m.kind === 'video'");+ expect(source).toContain('<Icon name="plus" size={14} /> New session');+ expect(source).toContain('<h3 id="new-session-title">New session</h3>');+ expect(source).toContain('bind:value={sourceQuery}');+ expect(source).toContain('filteredSourceMedia.filter((m) => matchesSourceName(m, sourceQuery))');+ expect(source).toContain('{#each pickableMedia as m (m.path)}');+ expect(source).toContain('placeholder="Search names…"');+ expect(source).toContain('function matchesSourceName(item, query)');+ expect(source).toContain("matchesTerms(item.title || item.filename || '', query)");+ expect(source).toContain('label={(m) => m.title || m.filename}');+ expect(source).not.toContain('class="input source-select"');+ expect(source).not.toContain('Choose a media…');+ });++ it('offers New session from the centered empty state', () => {+ expect(source).toContain('<h3>Start a session</h3>');+ expect(source).toContain(` <p>Start a session to choose media.</p>+ <button class="btn" onclick={startNewSession}>+ <Icon name="plus" size={15} /> New session+ </button>`);+ });++ it('separates images, videos, captures, frames, and collages in the new-session picker', () => {+ expect(source).toContain("{ id: 'all', label: 'All' }");+ expect(source).toContain("{ id: 'capture', label: 'Captures' }");+ expect(source).toContain("{ id: 'frame', label: 'Frames' }");+ expect(source).toContain("{ id: 'collage', label: 'Collages' }");+ expect(source).toContain("source.type === 'satellite' || source.type === 'screenshot'");+ expect(source).toContain("source.op === 'frame' || source.op === 'adjust'");+ expect(source).toContain("source.op === 'collage'");+ });++ it('adds session search only once the saved-session list has more than six entries', () => {+ expect(source).toContain('{#if sessionModal.list.length > 6}');+ expect(source).toContain('bind:value={sessionQuery}');+ expect(source).toContain('{#each visibleSessions as s (s.name)}');+ });++ it('offers a read-only folder browser with single selection and double-click confirmation', () => {+ expect(source).toContain('title="Browse folders"');+ expect(source).toContain('onconfirm={(m) => selectSourceBrowser(m, true)}');+ expect(source).toContain('onconfirm={(s) => selectSessionBrowser(s, true)}');+ expect(source).toContain('disabled={!sourceBrowseSelection} onclick={confirmSourceBrowser}');+ expect(source).toContain('disabled={!sessionBrowseSelection} onclick={confirmSessionBrowser}');+ expect(source).toContain("fetchAllEntities(caseState.current.id, { types: ['inspect-session'] })");+ expect(source).toContain('function toggleSourceBrowser()');+ expect(source).toContain('function toggleSessionBrowser()');+ expect(source).not.toContain('>Back</button>');+ });++ it('shares one folder-browser helper with the other pickers', () => {+ expect(source).toContain("import FolderBrowser from '../components/FolderBrowser.svelte'");+ expect(source).not.toContain('function browserView(');+ expect(source).not.toContain('class="browser-row"');+ expect(source).toContain('white-space: nowrap;');+ });++ it('requires an active workspace to be discarded before starting another', () => {+ expect(source).toContain('openSourceAfterDiscard = true;');+ expect(source).toContain('if (openSourceAfterDiscard) {');+ expect(source).toContain('openSourceDialog();');+ });++ it('keeps the Collage tab for video sessions but hides it for a still image', () => {+ expect(source).toContain(+ "session.source?.kind === 'video' ? ['selection', 'frame', 'collage', 'save'] : ['frame', 'save']"+ );+ expect(source).not.toContain(+ "session.source?.kind === 'video' ? ['selection', 'frame', 'collage', 'save'] : ['frame', 'collage', 'save']"+ );+ });++ it('names each savable after its source instead of Image 1', () => {+ expect(source).toContain('defaultName: `${stem} (enhanced)`');+ expect(source).toContain(+ "defaultName: fr.time == null ? `${frameStem} (edited)` : `${frameStem} ${timecode(fr.time)}`"+ );+ expect(source).not.toContain('label: `Image ${imgN}`');+ expect(source).not.toContain("label: 'Video 1'");+ });++ it('keeps typed names outside the derived list so a slider move cannot wipe them', () => {+ expect(source).toContain(+ "const saveUi = $state({ selected: {}, folder: '', names: {}, touched: {}, baseName: '', note: '' });"+ );+ });++ it('seeds every field with real text and lets the base name refill the untouched ones', () => {+ expect(source).toContain(` const auto = autoSaveNames(savables, saveUi.baseName);+ savables.forEach((it, i) => {+ if (saveUi.touched[it.key]) return;+ if (it.kind === 'collage') it.collage.name = auto[i];+ else saveUi.names[it.key] = auto[i];+ });`);+ });++ it('gives a collage one name, shared by the Collage tab and the Save tab', () => {+ expect(source).toContain(+ "const saveName = (it) => (it.kind === 'collage' ? (it.collage.name ?? '') : (saveUi.names[it.key] ?? ''));"+ );+ expect(source).toContain(` if (it.kind === 'collage') it.collage.name = value;+ else saveUi.names[it.key] = value;`);+ expect(source).toContain('<SaveGallery {savables} {saveUi} {saveName} {setSaveName} />');+ });++ it('protects a hand-renamed collage from being refilled by a base name', () => {+ expect(source).toContain('onRename={(cl) => (saveUi.touched[`collage:${cl.id}`] = true)}');+ });++ it('files every kind under its resolved name, with the batch note', () => {+ expect(source).toContain('const nameOf = (item) => saveNameOf(item, saveName(item));');+ expect(source).toContain('items: frameItems, folder, notes: note,');+ expect(source).toContain('label: nameOf(videoItem), notes: note,');+ expect(source).toContain('label: nameOf(it), notes: note,');+ expect(source).toContain('ops: buildFrameOps(filters, it.frame),\n label: nameOf(it),');+ });++ it('says when a save landed on media the case already held', () => {+ expect(source).toContain("dupes += (res?.saved ?? []).filter((r) => r.duplicate).length;");+ expect(source).toContain("matched existing media and ${dupes === 1 ? 'was' : 'were'} renamed");+ });++ it('clears the naming fields when the workspace resets', () => {+ expect(source).toContain(` saveUi.names = {};+ saveUi.touched = {};+ saveUi.baseName = '';+ saveUi.note = '';`);+ });+});diff --git a/frontend/src/tools/MediaLibrary.svelte b/frontend/src/tools/MediaLibrary.svelteindex 26644d9..988f08b 100644--- a/frontend/src/tools/MediaLibrary.svelte+++ b/frontend/src/tools/MediaLibrary.svelte@@ -1,17 +1,47 @@<script>import { api } from '../lib/api.js';import { lookupEntity } from '../lib/catalog.js';+ import { buildMediaQuery } from '../lib/mediaQuery.js';+ import { createPagedList } from '../lib/pagedList.svelte.js';+ import { pollWhile } from '../lib/poll.js';import { caseState, uiState, ensureCase, reloadCase, toast } from '../lib/state.svelte.js';- import { visibleMedia, SORTS } from '../lib/mediaFilter.js';+ import {+ hasMediaForFilters,+ isGenericImage,+ isSatelliteMedia,+ mediaDisplayKind,+ visibleMedia,+ SORTS,+ } from '../lib/mediaFilter.js';import Icon from '../components/Icon.svelte';+ import SearchInput from '../components/SearchInput.svelte';import Modal from '../components/Modal.svelte';import ConfirmDialog from '../components/ConfirmDialog.svelte';import EntityDetails from '../components/EntityDetails.svelte';- const KIND_ICONS = { image: 'image', video: 'video', audio: 'audio', file: 'file' };+ const KIND_ICONS = { image: 'image', satellite: 'satellite', video: 'video', audio: 'audio', file: 'file' };- let items = $state([]);- let loadedFor = $state(null);+ // Bounded loading: a case that fits one page (the common case, incl. a 3–4+ // file case) is filtered/sorted entirely client-side below; a large case+ // pages in and searches server-side. The unbounded `/media` list still backs+ // the pickers/derivation elsewhere — this browse view uses `/media/page`.+ const PAGE = 200;+ const pl = createPagedList({+ fetchPage: ({ query, cursor }) =>+ api.get(+ buildMediaQuery(caseState.current?.id, {+ q: query,+ category: catFilter,+ folder: folderFilter,+ sort,+ direction: sortDirection,+ limit: PAGE,+ cursor,+ })+ ),+ });+ const items = $derived(pl.items);+ let loadedFor = null; // non-reactive: only the load effect reads/writes itlet url = $state('');let picker = $state(null); // multi-item picker: {url, items: [{index, title, thumbnail, kind, selected}]}let dragOver = $state(false);@@ -40,10 +70,10 @@// Overlapping filters (a downloaded video matches both Videos and Downloads);// clicking one narrows the grid to that facet. Order matches the sidebar bar.const CATEGORIES = [- { key: 'image', label: 'Images', icon: 'image', match: (i) => i.kind === 'image' },+ { key: 'image', label: 'Images', icon: 'image', match: isGenericImage },{ key: 'video', label: 'Videos', icon: 'video', match: (i) => i.kind === 'video' },{ key: 'collage', label: 'Collages', icon: 'layers', match: (i) => i.source?.op === 'collage' },- { key: 'satellite', label: 'Satellite', icon: 'satellite', match: (i) => i.source?.type === 'satellite' },+ { key: 'satellite', label: 'Satellite', icon: 'satellite', match: isSatelliteMedia },{ key: 'upload', label: 'Imports', icon: 'upload', match: (i) => i.source?.type === 'upload' },{ key: 'download', label: 'Downloads', icon: 'download', match: (i) => i.source?.type === 'download' },{ key: 'other', label: 'Other files', icon: 'file', match: (i) => i.kind !== 'image' && i.kind !== 'video' },@@ -52,9 +82,10 @@let catFilter = $state(null); // null = All typesconst activeCats = $derived(- CATEGORIES.map((c) => ({ ...c, count: items.filter(c.match).length })).filter(- (c) => c.count > 0- )+ CATEGORIES.map((c) => ({+ ...c,+ count: pl.facets?.category_counts?.[c.key] ?? items.filter(c.match).length,+ })).filter((c) => c.count > 0));const catMatch = $derived(CATEGORIES.find((c) => c.key === catFilter)?.match ?? null);@@ -63,10 +94,32 @@// --- free-text search + sort ---let query = $state('');- let sort = $state('newest');+ let sort = $state('name');+ let sortDirection = $state('asc');+ let headerSort = $state(null);+ const LIST_SORTS = [+ { id: 'name', label: 'Name' },+ { id: 'type', label: 'Type' },+ { id: 'size', label: 'Size' },+ { id: 'folder', label: 'Folder' },+ { id: 'added', label: 'Added' },+ ];+ const browseFiltersActive = $derived(+ query.length > 0 || catFilter !== null || folderFilter !== null+ );+ const filtersActive = $derived(+ query.length > 0 || catFilter !== null || folderFilter !== null || sort !== 'name' || sortDirection !== 'asc'+ );+ const showBrowseBar = $derived(items.length > 0 || browseFiltersActive);const folders = $derived(- [...new Set(items.filter((i) => i.folder).map((i) => i.folder))].sort()+ [+ ...new Set([+ ...Object.keys(pl.facets?.folder_counts ?? {}).filter(Boolean),+ ...items.filter((i) => i.folder).map((i) => i.folder),+ ...(folderFilter ? [folderFilter] : []),+ ]),+ ].sort());// Empty when no case is open — the grid cards build file URLs from// `caseState.current.id`, so a stale render during case-close (current is@@ -78,9 +131,77 @@folderFilter,query,sort,+ direction: sortDirection,}));+ function reloadIfServerBacked() {+ if (pl.serverMode || pl.loading) pl.reload();+ }++ function onSortSelect(event) {+ sort = event.currentTarget.value;+ sortDirection = sort === 'newest' || sort === 'size' ? 'desc' : 'asc';+ headerSort = null;+ reloadIfServerBacked();+ }++ function setHeaderSort(next) {+ if (headerSort === next) {+ sortDirection = sortDirection === 'asc' ? 'desc' : 'asc';+ } else {+ headerSort = next;+ sort = next === 'added' ? 'newest' : next;+ sortDirection = next === 'added' ? 'desc' : 'asc';+ }+ reloadIfServerBacked();+ }++ function onFolderSelect(event) {+ const nextFolder = event.currentTarget.value || null;+ const category = CATEGORIES.find((c) => c.key === catFilter);+ const resetCategory =+ nextFolder &&+ catFilter &&+ !hasMediaForFilters(items, { catMatch: category?.match, folderFilter: nextFolder });+ folderFilter = nextFolder;+ if (resetCategory) catFilter = null;+ reloadIfServerBacked();+ }++ function onCategorySelect(event) {+ const nextCategory = event.currentTarget.value || null;+ const category = CATEGORIES.find((c) => c.key === nextCategory);+ const resetFolder =+ nextCategory &&+ folderFilter &&+ !hasMediaForFilters(items, { catMatch: category?.match, folderFilter });+ catFilter = nextCategory;+ if (resetFolder) {+ folderFilter = null;+ }+ reloadIfServerBacked();+ }++ function resetFilters() {+ query = '';+ catFilter = null;+ folderFilter = null;+ sort = 'name';+ sortDirection = 'asc';+ headerSort = null;+ reloadIfServerBacked();+ }++ // The current card layout is the large view. Small is a denser grid and List+ // uses the Files-style details table while the grids keep their cards.+ let view = $state('large');+ const VIEWS = [+ { id: 'small', label: 'Small', icon: 'grid' },+ { id: 'large', label: 'Large', icon: 'image' },+ { id: 'list', label: 'List', icon: 'note' },+ ];+// --- details modal (shared EntityDetails, keyed by the file's entity id) ---let infoEntityId = $state(null);@@ -121,9 +242,21 @@caseState.rev; // also refetch when the case is reloaded elsewhere (e.g. sidebar edit)if (id !== loadedFor) {loadedFor = id;- items = [];+ pl.clear(); // drop the old case's page before the new one loads+ // Drop broken-thumb flags too: the switch briefly renders the new case+ // id against the old case's items, 404-ing each <img> and marking its+ // path broken. Left to accumulate, those flags hide the *other* case's+ // ready thumbnails until a page reload (the reported "must refresh" bug).+ brokenThumbs = new Set();}- if (id) refresh(id);+ if (id) pl.reload();+ });++ // Drive the paged list from the search box: in a small (single-page) case+ // this just records the term and `visibleMedia` filters in memory with no+ // network; in a large case it debounces a server search.+ $effect(() => {+ pl.setQuery(query);});// Pick up a "focus this media" handoff from the sidebar: clear filters that@@ -155,17 +288,19 @@});});- async function refresh(id = caseState.current?.id) {- if (id) items = await api.get(`/api/cases/${id}/media`);+ async function refresh() {+ if (caseState.current?.id) await pl.reload();}// 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.+ // and the poll stops on its own once nothing is pending. Uses a repeating+ // poll, not a one-shot timer: this effect only re-runs when `thumbsPending`+ // flips, so a `setTimeout` here would fire once and leave a slow thumbnail+ // stuck until a page reload (e.g. after a case switch reloads pending items).$effect(() => {if (!thumbsPending || uiState.tool !== 'media' || !caseState.current) return;- const t = setTimeout(() => refresh(), 1500);- return () => clearTimeout(t);+ return pollWhile(() => thumbsPending, () => refresh(), 1500);});// Queue (re)generation: a single failed thumbnail (path given) or every@@ -361,12 +496,20 @@}function fmtSize(bytes) {+ if (bytes == null) return '—';if (bytes >= 1 << 30) return (bytes / (1 << 30)).toFixed(1) + ' GB';if (bytes >= 1 << 20) return (bytes / (1 << 20)).toFixed(1) + ' MB';if (bytes >= 1 << 10) return (bytes / (1 << 10)).toFixed(0) + ' KB';return bytes + ' B';}+ function fmtAdded(item) {+ const date = new Date(item.added_at);+ if (Number.isNaN(date.getTime())) return '—';+ const part = (value) => String(value).padStart(2, '0');+ return `${date.getFullYear()}-${part(date.getMonth() + 1)}-${part(date.getDate())} ${part(date.getHours())}:${part(date.getMinutes())}`;+ }+function onDrop(e) {e.preventDefault();dragOver = false;@@ -438,61 +581,68 @@</div><!-- search + sort + category + folder filter bar -->- {#if items.length > 0}+ {#if showBrowseBar}<div class="folder-bar">- <div class="search-box">- <Icon name="search" size={13} />- <input- class="search-input"- placeholder="Search name, notes, source…"- bind:value={query}- />- {#if query}- <button class="search-clear" onclick={() => (query = '')} aria-label="Clear search">- <Icon name="x" size={12} />- </button>- {/if}- </div>- <select class="select sort-select" bind:value={sort} title="Sort order">+ <SearchInput+ bind:value={query}+ placeholder="Search name, source…"+ count={query ? `${filteredItems.length} shown` : null}+ />+ <select class="select sort-select" value={sort} onchange={onSortSelect} title="Sort order">{#each SORTS as s (s.id)}<option value={s.id}>{s.label}</option>{/each}</select>+ <div class="view-switch" role="group" aria-label="View">+ {#each VIEWS as v (v.id)}+ <button+ class="view-btn"+ class:active={view === v.id}+ title={`${v.label} view`}+ aria-pressed={view === v.id}+ onclick={() => (view = v.id)}+ >+ <Icon name={v.icon} size={14} /> {v.label}+ </button>+ {/each}+ </div><span class="bar-sep"></span>- <!-- type / source facets -->- <button- class="folder-chip"- class:active={catFilter === null}- onclick={() => (catFilter = null)}+ <select+ class="select category-select"+ value={catFilter ?? ''}+ onchange={onCategorySelect}+ title="Filter by type or source">- <Icon name="media" size={13} /> All- <span class="chip-count">{items.length}</span>- </button>- {#each activeCats as c (c.key)}- <button- class="folder-chip"- class:active={catFilter === c.key}- onclick={() => (catFilter = catFilter === c.key ? null : c.key)}- >- <Icon name={c.icon} size={13} />{c.label}- <span class="chip-count">{c.count}</span>- </button>- {/each}+ <option value="">All types</option>+ {#each activeCats as c (c.key)}+ <option value={c.key}>{c.label} ({c.count})</option>+ {/each}+ </select><!-- user-defined folders (independent facet) -->{#if folders.length}<span class="bar-sep"></span>- {#each folders as f (f)}- <button- class="folder-chip"- class:active={folderFilter === f}- onclick={() => (folderFilter = folderFilter === f ? null : f)}- >- <Icon name="folder" size={13} />{f}- <span class="chip-count">{items.filter((i) => i.folder === f).length}</span>- </button>- {/each}+ <select+ class="select folder-select"+ value={folderFilter ?? ''}+ onchange={onFolderSelect}+ title="Filter by folder"+ >+ <option value="">All folders</option>+ {#each folders as f (f)}+ <option value={f}>{f}</option>+ {/each}+ </select>{/if}+ <button+ class="btn btn-ghost btn-sm reset-filters"+ type="button"+ title="Reset filters"+ disabled={!filtersActive}+ onclick={resetFilters}+ >+ <Icon name="reset" size={13} /> Reset filters+ </button></div>{/if}@@ -515,7 +665,7 @@</div>{/each}- {#if !items.length && !jobs.length}+ {#if !items.length && !jobs.length && !browseFiltersActive}<div class="empty" style="height: 100%"><div class="empty-icon"><Icon name="media" size={42} /></div><h3>No media yet</h3>@@ -528,7 +678,104 @@<p>No media matches this filter.</p></div>{:else}- <div class="grid">+ {#if view === 'list'}+ <div class="media-list" role="table" aria-label="Media files">+ <div class="media-row media-head" role="row">+ <span aria-hidden="true"></span>+ {#each LIST_SORTS as column (column.id)}+ <button+ class={`media-head-button media-col-${column.id}`}+ class:active={headerSort === column.id}+ type="button"+ title={`Sort by ${column.label}`}+ aria-label={`Sort by ${column.label}${headerSort === column.id ? `, ${sortDirection === 'asc' ? 'ascending' : 'descending'}` : ''}`}+ onclick={() => setHeaderSort(column.id)}+ >+ {column.label}+ {#if headerSort === column.id}+ <Icon name={sortDirection === 'asc' ? 'chevronUp' : 'chevronDown'} size={12} />+ {/if}+ </button>+ {/each}+ <span class="media-col-actions" aria-label="Actions"></span>+ </div>+ {#each filteredItems as item (item.path)}+ <div class="media-row" class:focused={item.path === focusedPath} data-path={item.path} role="row">+ <!-- The preview remains an image-only control; the row itself is not a card. -->+ <!-- svelte-ignore a11y_no_noninteractive_tabindex -->+ <div+ class="list-preview"+ class:clickable={item.kind === 'image'}+ onclick={() => item.kind === 'image' && (lightboxItem = item)}+ role={item.kind === 'image' ? 'button' : undefined}+ tabindex={item.kind === 'image' ? 0 : undefined}+ onkeydown={(e) => e.key === 'Enter' && item.kind === 'image' && (lightboxItem = item)}+ aria-label={item.kind === 'image' ? `Preview ${item.filename}` : undefined}+ >+ {#if item.thumbnail && item.thumb_state === 'ready' && !brokenThumbs.has(item.path)}+ <img+ src={`/files/${caseState.current.id}/${item.thumbnail}`}+ alt=""+ loading="lazy"+ decoding="async"+ onerror={() => (brokenThumbs = new Set(brokenThumbs).add(item.path))}+ />+ {:else if item.thumb_state === 'failed'}+ <button+ class="thumb-status thumb-retry"+ title="Retry thumbnail"+ onclick={() => regenerateThumbs(item.path)}+ >+ <Icon name="reset" size={16} />+ </button>+ {:else if item.thumb_state === 'queued' || item.thumb_state === 'running'}+ <Icon name="clock" size={16} />+ {:else}+ <Icon name={KIND_ICONS[mediaDisplayKind(item)] ?? 'file'} size={18} />+ {/if}+ </div>+ <span class="media-col-name" title={item.filename}>+ <span class="list-name">{item.title ?? item.filename}</span>+ {#if item.title}+ <span class="list-filename">{item.filename}</span>+ {/if}+ </span>+ <span class="media-col-type">{mediaDisplayKind(item)}</span>+ <span class="media-col-size">{fmtSize(item.size)}</span>+ <span class="media-col-folder" title={item.folder ?? ''}>{item.folder || '—'}</span>+ <span class="media-col-added">{fmtAdded(item)}</span>+ <div class="media-col-actions actions" aria-label={`Actions for ${item.title ?? item.filename}`}>+ <button class="btn btn-ghost btn-sm" title="Info / Edit notes" onclick={() => openInfo(item)}>+ <Icon name="note" size={14} />+ </button>+ <a+ class="btn btn-ghost btn-sm"+ href={`/files/${caseState.current.id}/${item.path}`}+ target="_blank"+ rel="noreferrer"+ title="Open file"+ >+ <Icon name="external" size={14} />+ </a>+ {#if item.kind === 'image' || item.kind === 'video'}+ <button class="btn btn-ghost btn-sm" title="Open in Inspect" onclick={() => inspect(item)}>+ <Icon name="inspect" size={14} />+ </button>+ {/if}+ {#if item.kind === 'image'}+ <button class="btn btn-ghost btn-sm" title="Send to Geo Proof" onclick={() => sendToComposer(item)}>+ <Icon name="proof" size={14} />+ </button>+ {/if}+ <button class="btn btn-ghost btn-sm del" title="Delete" onclick={() => (deleteTarget = item)}>+ <Icon name="trash" size={14} />+ </button>+ </div>+ </div>+ {/each}+ </div>+ {:else}+ <div class="grid" class:compact={view === 'small'}>{#each filteredItems as item (item.path)}<divclass="media-card card"@@ -573,9 +820,9 @@<span>Retry</span></button>{:else}- <Icon name={KIND_ICONS[item.kind] ?? 'file'} size={34} />+ <Icon name={KIND_ICONS[mediaDisplayKind(item)] ?? 'file'} size={34} />{/if}- <span class="kind badge">{item.kind}</span>+ <span class="kind badge">{mediaDisplayKind(item)}</span>{#if item.folder}<span class="folder-badge badge"><Icon name="folder" size={10} />{item.folder}@@ -637,6 +884,14 @@</div>{/each}</div>+ {/if}+ {#if pl.hasMore}+ <div class="show-more">+ <button class="btn" onclick={() => pl.loadMore()} disabled={pl.loading}>+ {pl.loading ? 'Loading…' : 'Show more'}+ </button>+ </div>+ {/if}{/if}</div>@@ -806,7 +1061,7 @@<ConfirmDialogtitle="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="Deletes the file from disk and cannot be undone."confirmLabel="Delete"tone="danger"busy={deleteBusy}@@ -830,42 +1085,18 @@/* folder filter bar */.folder-bar {+ position: sticky;+ top: 0;+ z-index: 2;display: flex;align-items: center;gap: 6px;padding: 8px 20px;border-bottom: 1px solid var(--border);+ background: var(--bg-1);overflow-x: auto;flex-shrink: 0;}- .folder-chip {- display: flex;- align-items: center;- gap: 5px;- padding: 4px 10px;- 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;- }- .folder-chip:hover {- border-color: var(--border-strong);- color: var(--text-1);- }- .folder-chip.active {- border-color: var(--border-strong);- background: var(--bg-3);- color: var(--text-1);- }- .chip-count {- font-size: var(--fs-xs);- color: var(--text-3);- margin-left: 2px;- }.bar-sep {width: 1px;align-self: stretch;@@ -873,43 +1104,61 @@background: var(--border);flex-shrink: 0;}- .search-box {+ .show-more {display: flex;- align-items: center;- gap: 6px;+ justify-content: center;+ padding: 16px 0 4px;+ }+ .sort-select {+ width: auto;+ font-size: var(--fs-xs);padding: 4px 8px;- border: 1px solid var(--border);- border-radius: var(--r-sm);- background: var(--bg-2);- color: var(--text-3);flex-shrink: 0;}- .search-box:focus-within {- border-color: var(--accent);+ .folder-select {+ width: auto;+ min-width: 150px;+ font-size: var(--fs-xs);+ padding: 4px 8px;+ flex-shrink: 0;}- .search-input {- width: 180px;- border: none;- background: none;- outline: none;- color: var(--text-1);+ .category-select {+ width: auto;+ min-width: 130px;font-size: var(--fs-xs);+ padding: 4px 8px;+ flex-shrink: 0;}- .search-clear {- display: inline-flex;+ .reset-filters {+ margin-left: auto;+ white-space: nowrap;+ flex-shrink: 0;+ }+ .view-switch {+ display: flex;+ gap: 2px;+ padding: 2px;+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ background: var(--bg-2);+ flex-shrink: 0;+ }+ .view-btn {+ display: flex;+ align-items: center;+ gap: 4px;+ padding: 3px 8px;+ border-radius: var(--r-sm);color: var(--text-3);- padding: 1px;- border-radius: 50%;+ font-size: var(--fs-xs);+ white-space: nowrap;}- .search-clear:hover {+ .view-btn:hover {color: var(--text-1);- background: var(--bg-3);}- .sort-select {- width: auto;- font-size: var(--fs-xs);- padding: 4px 8px;- flex-shrink: 0;+ .view-btn.active {+ background: var(--bg-3);+ color: var(--text-1);}.job {@@ -959,6 +1208,10 @@gap: 14px;padding: 18px 20px;}+ .grid.compact {+ grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));+ gap: 10px;+ }.media-card {overflow: hidden;display: flex;@@ -1087,6 +1340,123 @@.del {margin-left: auto;}+ /* Details list: deliberately plain rows, not card-shaped mini tiles. */+ .media-list {+ /* Every row, including the header, must share this exact grid. An `auto`+ actions column is empty in the header but wide in a data row, which+ shifts every sortable heading out of alignment. */+ --media-columns: 54px minmax(180px, 1fr) 90px 82px minmax(100px, 0.45fr) 132px 168px;+ padding: 6px 20px 18px;+ }+ .media-row {+ display: grid;+ grid-template-columns: var(--media-columns);+ align-items: center;+ min-width: 790px;+ min-height: 54px;+ gap: 10px;+ padding: 5px 8px;+ border-bottom: 1px solid var(--border);+ color: var(--text-2);+ font-size: var(--fs-sm);+ }+ .media-row:not(.media-head):hover {+ background: var(--bg-2);+ }+ .media-row.focused {+ outline: 2px solid var(--accent);+ outline-offset: -2px;+ animation: focus-flash 0.9s var(--ease) 2;+ }+ .media-head {+ position: sticky;+ top: 0;+ z-index: 1;+ min-height: 32px;+ background: var(--bg-1);+ color: var(--text-3);+ font-size: var(--fs-xs);+ font-weight: 700;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ }+ .media-head-button {+ display: flex;+ align-items: center;+ min-width: 0;+ gap: 4px;+ padding: 0;+ border: 0;+ background: transparent;+ color: inherit;+ font: inherit;+ letter-spacing: inherit;+ text-align: left;+ text-transform: inherit;+ cursor: pointer;+ }+ .media-head-button:hover,+ .media-head-button.active {+ color: var(--text-1);+ }+ .media-col-name {+ min-width: 0;+ }+ .media-col-type,+ .media-col-size,+ .media-col-folder,+ .media-col-added {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .list-preview {+ width: 46px;+ height: 34px;+ border-radius: var(--r-sm);+ background: var(--bg-2);+ color: var(--text-3);+ display: flex;+ align-items: center;+ justify-content: center;+ overflow: hidden;+ }+ .list-preview img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ }+ .list-preview.clickable {+ cursor: zoom-in;+ }+ .list-name,+ .list-filename {+ display: block;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .list-name {+ color: var(--text-1);+ font-weight: 600;+ }+ .list-filename {+ color: var(--text-3);+ font-size: var(--fs-xs);+ }+ .media-col-actions {+ display: flex;+ align-items: center;+ min-width: 0;+ gap: 2px;+ }+ .media-row:not(.media-head) .media-col-actions {+ opacity: 0.72;+ }+ .media-row:not(.media-head):hover .media-col-actions,+ .media-row.focused .media-col-actions {+ opacity: 1;+ }.drop-overlay {position: absolute;inset: 0;diff --git a/frontend/src/tools/MediaLibrary.test.js b/frontend/src/tools/MediaLibrary.test.jsindex f9f1362..722cc97 100644--- a/frontend/src/tools/MediaLibrary.test.js+++ b/frontend/src/tools/MediaLibrary.test.js@@ -56,6 +56,137 @@ describe('Media Library thumbnail states', () => {expect(source).toContain("if (!thumbsPending || uiState.tool !== 'media' || !caseState.current) return;");expect(source).toContain('/media/thumbnails/regenerate');});++ it('repeats the poll (not a one-shot timer that leaves a slow thumbnail stuck)', () => {+ // a self-repeating poll, so a thumbnail slower than one tick still resolves+ // without a page reload; the effect alone would not re-arm while pending+ expect(source).toContain('pollWhile(() => thumbsPending, () => refresh(), 1500)');+ expect(source).not.toContain('setTimeout(() => refresh()');+ });+});++describe('Media Library bounded loading', () => {+ it('browses via the bounded /media/page endpoint, not the unbounded list', () => {+ expect(source).toContain('createPagedList');+ expect(source).toContain('buildMediaQuery(caseState.current?.id');+ // the browse view must not fetch the whole media list on mount+ expect(source).not.toMatch(/api\.get\(`\/api\/cases\/\$\{[^}]+\}\/media`\)/);+ expect(source).toContain('category: catFilter');+ });++ it('shares the SearchInput and pages the rest in with Show more', () => {+ expect(source).toContain("import SearchInput from '../components/SearchInput.svelte'");+ expect(source).toContain('pl.setQuery(query)');+ expect(source).toContain('{#if pl.hasMore}');+ expect(source).toContain('pl.loadMore()');+ });++ it('clears the previous case before loading the next', () => {+ expect(source).toContain('pl.clear()');+ });++ it('resets broken-thumbnail flags on case change so they never leak across cases', () => {+ // During a case switch there is one render where the new case id is paired+ // with the old case's items, so each <img> 404s and reports into+ // brokenThumbs. Those flags must not survive into the next case or they hide+ // that case's ready thumbnails until a page reload.+ const effect = source.slice(+ source.indexOf('const id = caseState.current?.id;'),+ source.indexOf('if (id) pl.reload();')+ );+ expect(effect).toContain('pl.clear()');+ expect(effect).toContain('brokenThumbs = new Set()');+ });+});++describe('Media Library search empty state', () => {+ it('keeps the search bar available when a search has no matches', () => {+ expect(source).toContain('const browseFiltersActive = $derived(');+ expect(source).toContain('query.length > 0 || catFilter !== null || folderFilter !== null');+ expect(source).toContain('const showBrowseBar = $derived(items.length > 0 || browseFiltersActive)');+ expect(source).toContain('{#if showBrowseBar}');+ expect(source).toContain('{#if !items.length && !jobs.length && !browseFiltersActive}');+ });++ it('describes media fields without mentioning notes', () => {+ expect(source).toContain('placeholder="Search name, source…"');+ expect(source).not.toContain('placeholder="Search name, notes, source…"');+ });+});++describe('Media Library browse controls', () => {+ it('separates satellite captures from generic Images', () => {+ expect(source).toContain("match: isGenericImage");+ expect(source).toContain("match: isSatelliteMedia");+ expect(source).toContain('mediaDisplayKind(item)');+ });++ it('offers grids plus a plain, sortable details list', () => {+ expect(source).toContain("let sort = $state('name')");+ expect(source).toContain("let view = $state('large')");+ expect(source).toContain("{ id: 'small', label: 'Small'");+ expect(source).toContain("{ id: 'large', label: 'Large'");+ expect(source).toContain("{ id: 'list', label: 'List'");+ expect(source).toContain('onSortSelect');+ expect(source).toContain('class:compact={view === \'small\'}');+ expect(source).toContain("{#if view === 'list'}");+ expect(source).toContain('class="media-list"');+ expect(source).toContain('const LIST_SORTS = [');+ expect(source).toContain('function setHeaderSort(next)');+ expect(source).toContain('class="media-row media-head"');+ expect(source).toContain('class="media-row" class:focused={item.path === focusedPath}');+ expect(source).not.toContain('.list-view .media-card');+ });++ it('keeps the browse bar and list headers visible while the results scroll', () => {+ expect(source).toContain('.folder-bar {\n position: sticky;\n top: 0;');+ expect(source).toContain('.media-head {\n position: sticky;\n top: 0;');+ // The outer tool body owns vertical scrolling, so the header must not be+ // trapped in a nested scrolling container.+ expect(source).not.toContain('.media-list {\n overflow-x: auto;');+ });++ it('uses one fixed grid definition for the header and each media row', () => {+ expect(source).toContain('--media-columns: 54px minmax(180px, 1fr) 90px 82px minmax(100px, 0.45fr) 132px 168px;');+ expect(source).toContain('grid-template-columns: var(--media-columns);');+ expect(source).not.toContain('132px auto;');+ });++ it('uses one folder dropdown and keeps its default unfiltered', () => {+ expect(source).toContain('class="select folder-select"');+ expect(source).toContain("value={folderFilter ?? ''}");+ expect(source).toContain('<option value="">All folders</option>');+ expect(source).toContain('onFolderSelect');+ expect(source).toContain('folder: folderFilter');+ expect(source).toContain('pl.facets?.folder_counts');+ });++ it('uses one dropdown for type and source filters', () => {+ expect(source).toContain('class="select category-select"');+ expect(source).toContain("value={catFilter ?? ''}");+ expect(source).toContain('<option value="">All types</option>');+ expect(source).toContain('onCategorySelect');+ expect(source).toContain('{c.label} ({c.count})');+ expect(source).toContain('pl.facets?.category_counts?.[c.key]');+ expect(source).toContain('reloadIfServerBacked();');+ expect(source).not.toContain('class="folder-chip"');+ });++ it('resets the other facet when a folder/type combination is empty', () => {+ expect(source).toContain('hasMediaForFilters(items');+ expect(source).toContain('if (resetCategory) catFilter = null');+ expect(source).toContain('if (resetFolder) {');+ expect(source).toContain('folderFilter = null;');+ });++ it('offers a right-side reset button for all browse filters', () => {+ expect(source).toContain('function resetFilters()');+ expect(source).toContain("query = '';\n catFilter = null;\n folderFilter = null;\n sort = 'name';\n sortDirection = 'asc';");+ expect(source).toContain('class="btn btn-ghost btn-sm reset-filters"');+ expect(source).toContain('Reset filters');+ expect(source).toContain('<Icon name="reset" size={13} /> Reset filters');+ expect(source).toContain('disabled={!filtersActive}');+ });});describe('Media Library gated-download cookie affordance', () => {diff --git a/frontend/src/tools/Notebook.svelte b/frontend/src/tools/Notebook.svelteindex 66618fd..87651be 100644--- a/frontend/src/tools/Notebook.svelte+++ b/frontend/src/tools/Notebook.svelte@@ -12,7 +12,10 @@import { insertNotebookText, notebookImageMarkdown, notebookMediaMarkdown } from '../lib/notebookContent.js';import { caseTab, closeNotebookTab, openNotebookTab } from '../lib/notebookTabs.js';import { openEntity } from '../lib/navigate.js';+ import { matchesTerms } from '../lib/folderBrowse.js';import Icon from '../components/Icon.svelte';+ import SearchInput from '../components/SearchInput.svelte';+ import FolderBrowser from '../components/FolderBrowser.svelte';import ConfirmDialog from '../components/ConfirmDialog.svelte';import Modal from '../components/Modal.svelte';import FolderSelect from '../components/FolderSelect.svelte';@@ -22,6 +25,12 @@let tabsCaseId = $state(null);let menuOpen = $state(false);let query = $state('');+ // Past a handful of notes the flat list stops being a way to find one: the+ // menu then offers a search box and a "…" that browses the note folders, the+ // same pair the media and proof pickers use.+ const NOTE_SEARCH_MIN = 6;+ let notesBrowserOpen = $state(false);+ let notesBrowsePath = $state('');let previewOnly = $state(false);let split = $state(loadNotebookSplit());let panesEl = $state(null);@@ -71,10 +80,7 @@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 filteredNotes = $derived(noteEntities.filter((entity) => matchesNote(entity, query)));const referenceEntities = $derived(graphEntities.filter((entity) => entity.provenance?.status !== 'suggested').filter((entity) => `${entity.label} ${entity.type}`.toLowerCase().includes(referenceQuery.trim().toLowerCase()))@@ -104,6 +110,8 @@activeId = 'case';previewOnly = false;menuOpen = false;+ notesBrowserOpen = false;+ notesBrowsePath = '';query = '';referenceOpen = false;referenceQuery = '';@@ -172,16 +180,41 @@return () => window.removeEventListener('resize', clampToPanes);});+ function onWindowKeydown(event) {+ if (event.key === 'Escape' && menuOpen) closeNotesMenu();+ }++ function matchesNote(entity, search) {+ return matchesTerms(`${entity.label} ${entity.attrs?.folder ?? ''}`, search);+ }++ function toggleNotesMenu() {+ menuOpen = !menuOpen;+ if (menuOpen) return;+ closeNotesMenu();+ }++ function closeNotesMenu() {+ menuOpen = false;+ notesBrowserOpen = false;+ notesBrowsePath = '';+ }++ function toggleNotesBrowser() {+ notesBrowserOpen = !notesBrowserOpen;+ notesBrowsePath = '';+ }+function selectTab(tab) {activeId = tab.id;uiState.openNotebook = { noteId: tab.noteId };- menuOpen = false;+ closeNotesMenu();}function selectNote(noteId = null) {openRequestedNote(noteId);uiState.openNotebook = { noteId };- menuOpen = false;+ closeNotesMenu();}function openNewNote() {@@ -465,29 +498,56 @@}</script>+<svelte:window onkeydown={onWindowKeydown} />+{#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}>+ <button class="menu-toggle" class:active={menuOpen} onclick={toggleNotesMenu} aria-expanded={menuOpen}><Icon name="note" size={15} /> Notes <Icon name="chevronDown" size={13} /></button>{#if menuOpen}+ <button class="menu-backdrop" onclick={closeNotesMenu} aria-label="Close the notes menu"></button><div class="notes-menu">- <input class="input note-search" bind:value={query} placeholder="Find a note…" />+ {#if notesBrowserOpen || noteEntities.length > NOTE_SEARCH_MIN}+ <div class="note-search">+ <SearchInput bind:value={query} placeholder="Find a note…" width="100%" />+ <button+ class="btn btn-ghost btn-sm browse-btn"+ title={notesBrowserOpen ? 'Show every note' : 'Browse folders'}+ onclick={toggleNotesBrowser}+ >…</button>+ </div>+ {/if}<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}+ {#if notesBrowserOpen}+ <FolderBrowser+ entries={noteEntities}+ path={notesBrowsePath}+ rootLabel="Notes"+ selectedId={activeId}+ matches={(note) => matchesNote(note, query)}+ emptyText="This folder has no matching notes."+ icon={() => 'note'}+ label={(note) => note.label}+ onnavigate={(path) => (notesBrowsePath = path)}+ onselect={(note) => selectNote(note.id)}+ />+ {:else}+ {#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}+ {/if}</div>{/if}</div>@@ -670,7 +730,7 @@ console.log(status);</code></pre></div>? `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.'+ ? 'Removes the note and its contents and cannot be undone.': 'The case note will remain, but its content will be cleared.'}confirmLabel={noteAction.kind === 'delete' ? 'Delete' : 'Reset'}tone={noteAction.kind === 'delete' ? 'danger' : 'default'}@@ -689,7 +749,10 @@ console.log(status);</code></pre></div>.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-backdrop { position: fixed; inset: 0; z-index: 7; cursor: default; }+ .note-search { display: flex; align-items: center; gap: 6px; margin-bottom: 5px; }+ .note-search :global(.search-box) { flex: 1; }+ .browse-btn { min-width: 30px; font-size: var(--fs-lg); line-height: 1; }.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; }diff --git a/frontend/src/tools/Notebook.test.js b/frontend/src/tools/Notebook.test.jsindex 5a49d51..00cbe79 100644--- a/frontend/src/tools/Notebook.test.js+++ b/frontend/src/tools/Notebook.test.js@@ -1,5 +1,6 @@import { describe, expect, it, afterEach } from 'vitest';import { render } from 'svelte/server';+import { readFileSync } from 'node:fs';import { caseState, uiState } from '../lib/state.svelte.js';import Notebook from './Notebook.svelte';@@ -8,6 +9,33 @@ afterEach(() => {uiState.openNotebook = null;});+const source = readFileSync(new URL('./Notebook.svelte', import.meta.url), 'utf8');++describe('Notebook notes menu', () => {+ it('closes on a click outside and on Escape', () => {+ expect(source).toContain('class="menu-backdrop" onclick={closeNotesMenu}');+ expect(source).toContain("if (event.key === 'Escape' && menuOpen) closeNotesMenu();");+ expect(source).toContain('<svelte:window onkeydown={onWindowKeydown} />');+ });++ it('searches and browses note folders once the case has more than six notes', () => {+ expect(source).toContain('const NOTE_SEARCH_MIN = 6;');+ expect(source).toContain('{#if notesBrowserOpen || noteEntities.length > NOTE_SEARCH_MIN}');+ expect(source).toContain("import FolderBrowser from '../components/FolderBrowser.svelte'");+ expect(source).toContain('rootLabel="Notes"');+ expect(source).toContain('onselect={(note) => selectNote(note.id)}');+ expect(source).toContain('matches={(note) => matchesNote(note, query)}');+ });++ it('leaves the browser and the search behind when the menu closes', () => {+ expect(source).toContain(` function closeNotesMenu() {+ menuOpen = false;+ notesBrowserOpen = false;+ notesBrowsePath = '';+ }`);+ });+});+describe('Notebook note creation', () => {it('shows a new-note button beside the open note tabs', () => {caseState.current = { id: 'case-1', entities: [] };diff --git a/frontend/src/tools/PostComposer.svelte b/frontend/src/tools/PostComposer.svelteindex a0d7658..ae2a537 100644--- a/frontend/src/tools/PostComposer.svelte+++ b/frontend/src/tools/PostComposer.svelte@@ -1,11 +1,12 @@<script>import { api } from '../lib/api.js';- import { lookupEntity, fetchDerivation } from '../lib/catalog.js';+ import { fetchAllEntities, 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 { proofCoordsText, proofSource } from '../lib/composer.js';+ import { isDefaultName, nextName, savedSlugs, savedTitles, savedTitle, slugify } from '../lib/naming.js';import {buildTweet1 as buildTweet1Lines, DEFAULT_TWEET_BODY,extraPostTweetText, groupPostMedia, MAX_POST_MEDIA, mediaTweetText,@@ -15,7 +16,9 @@postTarget, templateUsesPostField, togglePostMedia,} from '../lib/post.js';import { bidiSafe } from '../lib/bidi.js';+ import { matchesQuery } from '../lib/mediaFilter.js';import Icon from '../components/Icon.svelte';+ import SearchInput from '../components/SearchInput.svelte';import Modal from '../components/Modal.svelte';import ConfirmDialog from '../components/ConfirmDialog.svelte';import FolderSelect from '../components/FolderSelect.svelte';@@ -49,8 +52,39 @@let extraSeq = 0;let extraTweets = $state([]); // [{ id, text, mediaPaths, mediaType }]- // Draft persistence- let draftName = $state(null); // slug of the saved draft (null until first save)+ // Draft persistence. The name in the header is the draft's filename: saving+ // writes under it, and renaming a saved draft moves its file (the backend+ // does the move). `draftName` is the slug it is currently bound to, or null+ // before the first save.+ let postName = $state('');+ let draftName = $state(null);++ // Every draft already saved in this case: the slugs to catch a name already+ // taken, the names so a fresh draft reads apart from them.+ let draftEntities = $state([]);+ $effect(() => {+ const id = caseState.current?.id;+ caseState.rev;+ if (!id) {+ draftEntities = [];+ return;+ }+ let live = true;+ fetchAllEntities(id, { types: ['post'] })+ .then((list) => {+ if (!live) return;+ draftEntities = list;+ // The name was assigned before the case's drafts were known. Renumber it+ // now rather than letting a fresh thread collide on its first save.+ if (!draftName && isDefaultName(postName, 'draft')) postName = freshPostName();+ })+ .catch(() => { if (live) draftEntities = []; });+ return () => { live = false; };+ });++ // Numbered past the drafts already in the case, so two never-renamed threads+ // read apart. Assigned on mount and on discard.+ const freshPostName = () => nextName('draft', savedTitles(draftEntities, 'draft'));// Kept in step with deletes made anywhere else in the app: a draft deleted// from the sidebar must not be resurrected by the next Save under its old@@ -93,6 +127,7 @@let pickerOpen = $state(false);let mediaLibrary = $state([]);let mediaPickerTarget = $state(null); // null = tweet 2; an id = a later media tweet+ let pickerQuery = $state(''); // search box, shown once the picker holds >6 items// 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.@@ -134,7 +169,7 @@const p = uiState.postProof;if (!p) return;uiState.postProof = null;- description = p.title === DEFAULT_PROOF_TITLE ? '' : (p.title ?? '');+ description = isDefaultName(p.title, 'proof') ? '' : (p.title ?? '');const proofSourceUrl = p.source ?? p.sources?.[0] ?? '';source = proofSourceUrl;setProof(p.png ?? null);@@ -353,6 +388,7 @@try {mediaLibrary = await api.get(`/api/cases/${caseState.current.id}/media`);mediaPickerTarget = normalizePostMediaPickerTarget(target);+ pickerQuery = '';pickerOpen = true;} catch (e) {toast(e.message, 'danger');@@ -369,6 +405,14 @@return postMediaForType(mediaLibrary, pickerTweet()?.mediaType);}+ // The picker narrows by a search box once the list grows past six. Reuses the+ // Media Library matcher (filename/title/notes/source).+ function visiblePickerItems() {+ const items = pickerItems();+ const q = pickerQuery.trim();+ return q ? items.filter((m) => matchesQuery(m, q)) : items;+ }+function pickerTitle() {const tweet = pickerTweet();const kind = tweet?.mediaType === 'video' ? 'videos' : 'images';@@ -491,7 +535,7 @@async function pickProof(item) {setProof(item.png);proofPickerOpen = false;- if (!description.trim() && item.title && item.title !== DEFAULT_PROOF_TITLE) {+ if (!description.trim() && item.title && !isDefaultName(item.title, 'proof')) {description = item.title;}// Pull the proof's coordinates + source into the post so the fields fill in.@@ -614,20 +658,38 @@};}- function draftTitle() {- return (place.trim() || description.trim() || 'Untitled post').slice(0, 120);- }+ // The saved report is titled after the thread it documents, so the two read as+ // one piece of work. The report dialog leaves it editable.+ const draftTitle = () => postName.trim() || 'Untitled post';++ // Saving writes under the name in the header. A bound draft writes back over+ // itself, and renaming it moves the file — the backend refuses a rename onto a+ // name another draft holds. An unbound draft landing on a saved name is the+ // one case that can go either way, so it asks first.+ let overwritePrompt = $state(null);async function saveDraft() {if (!caseState.current) {toast('Open a case to save a draft', 'warn');return;}+ const title = postName.trim();+ if (!title || saving) return;+ if (!draftName && savedSlugs(draftEntities, 'draft').has(slugify(title, 'draft'))) {+ overwritePrompt = { slug: slugify(title, 'draft') };+ return;+ }+ return performDraftSave();+ }++ async function performDraftSave() {saving = true;try {- const body = { title: draftTitle(), state: snapshot() };- if (draftName) body.name = draftName;- const r = await api.post(`/api/cases/${caseState.current.id}/drafts`, body);+ const r = await api.post(`/api/cases/${caseState.current.id}/drafts`, {+ rename_from: draftName,+ title: postName.trim(),+ state: snapshot(),+ });draftName = r.name;await reloadCase(); // surface the post entity in the sidebartoast('Draft saved', 'ok', 1600);@@ -635,6 +697,7 @@toast(`Draft not saved: ${e.message}`, 'danger');} finally {saving = false;+ overwritePrompt = null;}}@@ -700,6 +763,7 @@};});draftName = name;+ postName = doc.title || name;appliedPostTemplate = null;// restore geo facts from the coordinates, then honor any manual tweet editsif (s.coordsText?.trim()) {@@ -739,6 +803,7 @@body = DEFAULT_TWEET_BODY;extraTweets = [];draftName = null;+ postName = freshPostName();appliedPostTemplate = null;discardConfirm = false;}@@ -851,6 +916,9 @@<div class="head-text"><h2>Geo Report</h2></div>+ {#if caseState.current}+ <input class="input title-input" bind:value={postName} maxlength="200" aria-label="Post name" />+ {/if}<div class="head-actions">{#if caseState.current}<button class="btn btn-ghost btn-sm" onclick={openDraftList} title="Reopen a saved draft">@@ -862,7 +930,7 @@<Icon name="reset" size={14} /> Discard</button>{/if}- <button class="btn btn-ghost btn-sm" onclick={saveDraft} disabled={saving}>+ <button class="btn btn-ghost btn-sm" onclick={saveDraft} disabled={saving || !postName.trim()}><Icon name="save" size={14} /> {draftName ? 'Save draft' : 'Save as draft'}</button><button class="btn btn-ghost btn-sm" onclick={openSaveReport} disabled={!hasContent || reportSaving}>@@ -1307,7 +1375,7 @@<ConfirmDialogtitle="Delete this draft?"message={`“${deleteEntry.title}” will be removed from the case.`}- detail="This permanently deletes the saved draft. It cannot be undone."+ detail="Deletes the saved draft and cannot be undone."confirmLabel="Delete"tone="danger"icon="trash"@@ -1329,13 +1397,39 @@/>{/if}+{#if overwritePrompt}+ <ConfirmDialog+ title="Overwrite this draft?"+ message={`“${savedTitle(draftEntities, 'draft', overwritePrompt.slug)}” is already saved in this case.`}+ detail="Saving replaces its thread. Rename this draft to keep both."+ confirmLabel="Overwrite"+ tone="danger"+ icon="check"+ onconfirm={performDraftSave}+ oncancel={() => (overwritePrompt = null)}+ />+{/if}+{#if pickerOpen}<Modal title={pickerTitle()} width="640px" onclose={() => (pickerOpen = false)}>{#if pickerItems().length === 0}<p class="picker-empty">No {pickerTweet()?.mediaType === 'video' ? 'videos' : 'images'} in this case.</p>{:else}+ {#if pickerItems().length > 6}+ <div class="picker-search">+ <SearchInput+ bind:value={pickerQuery}+ placeholder="Search media…"+ width="100%"+ count={pickerQuery.trim() ? `${visiblePickerItems().length} shown` : null}+ />+ </div>+ {/if}+ {#if visiblePickerItems().length === 0}+ <p class="picker-empty">No media matches “{pickerQuery.trim()}”.</p>+ {/if}<div class="picker-grid">- {#each (caseState.current ? pickerItems() : []) as item (item.path)}+ {#each (caseState.current ? visiblePickerItems() : []) as item (item.path)}{@const targetTweet = mediaPickerTarget === null? null: extraTweets.find((tweet) => tweet.id === mediaPickerTarget)}@@ -1642,6 +1736,9 @@font-size: var(--fs-sm);padding: 8px 0;}+ .picker-search {+ margin-bottom: 12px;+ }.picker-grid {display: grid;grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));diff --git a/frontend/src/tools/PostComposer.test.js b/frontend/src/tools/PostComposer.test.jsindex 1605982..b80f2c8 100644--- a/frontend/src/tools/PostComposer.test.js+++ b/frontend/src/tools/PostComposer.test.js@@ -1,8 +1,26 @@import { afterEach, describe, expect, it } from 'vitest';import { render } from 'svelte/server';+import { readFileSync } from 'node:fs';import { caseState, uiState } from '../lib/state.svelte.js';import PostComposer from './PostComposer.svelte';+const source = readFileSync(new URL('./PostComposer.svelte', import.meta.url), 'utf8');++describe('Post media picker search', () => {+ it('shows a search box only once the picker holds more than six items', () => {+ expect(source).toContain("import SearchInput from '../components/SearchInput.svelte'");+ expect(source).toContain('{#if pickerItems().length > 6}');+ expect(source).toContain('bind:value={pickerQuery}');+ });++ it('renders the filtered items and resets the query when the picker opens', () => {+ expect(source).toContain("import { matchesQuery } from '../lib/mediaFilter.js'");+ expect(source).toContain('items.filter((m) => matchesQuery(m, q))');+ expect(source).toContain('{#each (caseState.current ? visiblePickerItems() : []) as item (item.path)}');+ expect(source).toContain('pickerQuery = \'\';');+ });+});+afterEach(() => {caseState.current = null;uiState.postProof = null;@@ -19,3 +37,30 @@ describe('Geo Report actions', () => {expect(body).not.toContain('Copy report');});});++describe('Post naming', () => {+ it('names the draft in the header, like Inspect and the Proof Composer', () => {+ expect(source).toContain('<input class="input title-input" bind:value={postName}');+ expect(source).toContain('aria-label="Post name"');+ });++ it('names a fresh draft "Post N" instead of deriving it from the place field', () => {+ expect(source).toContain("const freshPostName = () => nextName('draft', savedTitles(draftEntities, 'draft'));");+ expect(source).not.toContain("place.trim() || description.trim() || 'Untitled post'");+ });++ it('renames in place: saving sends the bound slug so the backend moves the file', () => {+ expect(source).toContain('rename_from: draftName,');+ expect(source).toContain('title: postName.trim(),');+ });++ it('asks before an unbound draft takes a name another draft holds', () => {+ expect(source).toContain("if (!draftName && savedSlugs(draftEntities, 'draft').has(slugify(title, 'draft')))");+ expect(source).toContain('title="Overwrite this draft?"');+ });++ it('does not carry an auto-assigned proof name into the post text', () => {+ expect(source).toContain("isDefaultName(p.title, 'proof') ? '' : (p.title ?? '')");+ expect(source).toContain("!isDefaultName(item.title, 'proof')");+ });+});diff --git a/frontend/src/tools/ProofComposer.svelte b/frontend/src/tools/ProofComposer.svelteindex 65b4a47..d4e84ba 100644--- a/frontend/src/tools/ProofComposer.svelte+++ b/frontend/src/tools/ProofComposer.svelte@@ -3,15 +3,20 @@import Konva from 'konva';import { api } from '../lib/api.js';import { lookupEntity, fetchAllEntities } from '../lib/catalog.js';+ import { matchesTerms } from '../lib/folderBrowse.js';+ import { isSatelliteMedia } from '../lib/mediaFilter.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 SearchInput from '../components/SearchInput.svelte';+ import FolderBrowser from '../components/FolderBrowser.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 PanelCategories from './proof/PanelCategories.svelte';import { bindPanelPointerLifecycle, createCanvasRenderGate } from './proof/canvasLifecycle.js';import {ANNO_COLORS, PAD, GAP, ROW_GAP, PANEL_H, TWEET_GUIDES,@@ -23,16 +28,22 @@toSpec, newId, loadImage, orderedFeatureColors, notesFromShapes,templateFromProof, applyProofStyle, normalizeProofStyle, newSignatureText,anchoredPos, anchoredOffset, SIG_TEXT_SIZE,- copyShapeSpec, dedupeBySrc, isSatelliteCapture, satPanelInput, mediaPanelInput,+ copyShapeSpec, dedupeBySrc, satPanelInput, mediaPanelInput,SIG_ANCHORS, SIG_SCALE, newSignature, signatureBox, signatureOffset, signaturePairPositions,- remapPanelXY, panelHitTest, groupNeighborIndex, hasGroupNeighbor,+ remapPanelXY, groupNeighborIndex, hasGroupNeighbor,denseRowValues, clampPanelScale, trimClosingDuplicate, freehandShape,canReassignLegendNote,- savedProofSlugs, savedProofTitles as libSavedProofTitles, savedProofTitle as libSavedProofTitle,- DEFAULT_PROOF_TITLE, proofSlug, uniqueProofTitle, proofTitleFromCase,- filterProofPanelItems, hasProofCanvasContent, proofExportOptions,+ surfaces, surfaceHitTest, pasteBoxes, clampPaste, clampPasteScale,+ pasteInsertScale, newPaste, newFrame, normalizeFrame, FRAME_WIDTH_MAX, FRAME_COLOR,+ PASTE_SCALE_MIN, PASTE_SCALE_MAX,+ filterProofPanelItems, hasProofCanvasContent, proofExportOptions, panelPreview,} from '../lib/composer.js';+ import {+ assetName, base64Of, PASTE_TYPES, MAX_PASTES, MAX_PASTE_BYTES,+ } from '../lib/pasteAsset.js';+ import { nextName, savedSlugs, savedTitles, savedTitle, slugify } from '../lib/naming.js';import { createHistory } from '../lib/history.js';+ import { pollWhile } from '../lib/poll.js';const SCALE_MIN = 0.25;const SCALE_MAX = 2.5;@@ -49,11 +60,10 @@{ id: 'text', icon: 'text', label: 'Text', shortcut: 't' },];- // ---- document state -------------------------------------------------------- // `notes` holds the legend text per color (annotations are written by color,- // not per element); `shapes` are the drawn geometry bound to a panel.+ // Document state. Notes are keyed by color, shapes bind to surfaces and pasted+ // images remain local to this proof.const proof = $state({- title: DEFAULT_PROOF_TITLE, panels: [], shapes: [], notes: {}, legendOrder: [],+ title: '', panels: [], pastes: [], shapes: [], notes: {}, legendOrder: [],templateId: null, // selected saved house style; its values remain copied belowcoordsText: '', source: '', // '' → auto-derived from panels; non-empty → manual overridecaptionSize: CAPTION_SIZE, legendSize: LEGEND_SIZE, footerSize: FOOTER_SIZE, footer: '',@@ -70,34 +80,27 @@palette: [...ANNO_COLORS], // ordered drawing colours, most preferred first});- // The analyst's logo (Settings → Signature): one app-wide PNG, loaded once per- // session and shared by every proof. `null` = none saved, which is what keeps- // the signature control disabled rather than stamping a broken image.+ // Load the app-wide signature once per session; null disables the control.let sigImg = $state(null);async function loadSignature() {try {sigImg = await loadImage('/api/settings/signature.png');} catch {- sigImg = null; // none saved — the control stays disabled+ sigImg = null; // No saved logo.}}let advancedOpen = $state(false);- let collapsed = $state({ panels: false, annotations: false, elements: false });+ let collapsed = $state({ panels: false, overlays: false, annotations: false, elements: false });+ // Saved proof slug, or null before the first save.let savedName = $state(null);- // Whether the analyst edited the title on this document (vs the auto-assigned- // default). An untouched default renumbers on a name clash; a title they typed- // asks before overwriting an existing proof. Reset on open/discard.- let titleTouched = $state(false);let dirty = $state(false);// A named proof can exist before it has content. This distinguishes the// initial composer shell from a template-only proof the user just created.let proofStarted = $state(false);- // Kept in step with deletes made anywhere else in the app. If the saved proof- // this canvas came from is gone, the binding has to go with it — otherwise the- // 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.+ // Drop the saved binding when another surface deletes the proof.+ // Keep the canvas so a later Save creates a new proof.$effect(() => {const id = caseState.current?.id;caseState.rev;@@ -151,11 +154,11 @@let guide = $state(null); // null | '16:9' | '4:5' — tweet centre-crop overlaylet selectedId = $state(null);let selectedPanelId = $state(null); // free-layout only: panel picked for move/resize+ let selectedPasteId = $state(null); // pasted image picked for move/resize/framelet selectedSig = $state(null); // null | 'logo' | 'text' — signature picked for resizelet picker = $state(false);let pickerItems = $state([]);let newProofOpen = $state(false);- let newProofName = $state('');let newProofTemplateId = $state('');let newProofPanelPaths = $state([]);let newProofQuery = $state('');@@ -167,7 +170,31 @@filterProofPanelItems(pickerItems, newProofQuery, newProofCategory));const proofHasContent = $derived(hasProofCanvasContent(proof));+ // Both pickers below follow the Inspect rule: a flat list until it passes six+ // entries, then a search box and a "…" that swaps in the read-only folder+ // browser (crumbs, folders, then what is filed there).+ const PICKER_SEARCH_MIN = 6;+ let panelQuery = $state('');+ let panelCategory = $state('all');+ let panelBrowserOpen = $state(false);+ let panelBrowsePath = $state('');+ let panelBrowseSelection = $state(null);+ // The chips narrow the set (and the folders); the search box then narrows what+ // is shown inside it, in the grid and in the browser alike.+ const panelCategoryItems = $derived(filterProofPanelItems(pickerItems, '', panelCategory));+ const visiblePanelItems = $derived(filterProofPanelItems(panelCategoryItems, panelQuery, 'all'));+ const panelBrowserEntries = $derived(+ panelCategoryItems.map((item) => ({ ...item, id: item.src, attrs: { folder: item.folder ?? '' } }))+ );let openList = $state(null); // list of saved proofs, null = closed+ let proofQuery = $state('');+ let proofBrowserOpen = $state(false);+ let proofBrowsePath = $state('');+ let proofBrowseSelection = $state(null);+ const visibleProofs = $derived((openList ?? []).filter((entry) => matchesProofQuery(entry, proofQuery)));+ const proofBrowserEntries = $derived(+ (openList ?? []).map((entry) => ({ ...entry, id: entry.name, attrs: { folder: entry.folder ?? '' } }))+ );let saving = $state(false);let proofFor = $state(undefined);let discardConfirm = $state(false);@@ -178,6 +205,10 @@// entry; panel images are re-attached from a cache on restore.const history = createHistory();const imgCache = new Map(); // src → HTMLImageElement, survives undo/redo+ // asset name → { img, data, pending }. `data` is the base64 body a paste that+ // has never been saved still has to hand to the server; `pending` clears once+ // the case holds the file. Survives undo/redo like imgCache does.+ const pasteAssets = new Map();let canUndo = $state(false);let canRedo = $state(false);let histBusy = false; // plain (untracked): suppresses capture while restoring@@ -212,7 +243,7 @@histBusy = true;proofStarted = true;if (pathDraft) finishPath(false);- proof.title = spec.title ?? DEFAULT_PROOF_TITLE;+ proof.title = spec.title ?? freshTitle();proof.coordsText = spec.coordsText ?? '';proof.source = spec.source ?? '';proof.captionSize = style.captionSize;@@ -235,6 +266,10 @@proof.legendOrder = spec.legendOrder ?? [];proof.templateId = typeof spec.templateId === 'string' ? spec.templateId : null;proof.panels = spec.panels.map((p) => ({ ...p, img: imgCache.get(p.src) ?? null }));+ proof.pastes = (spec.pastes ?? []).map((p) => ({+ ...p,+ img: pasteAssets.get(p.asset)?.img ?? null,+ }));proof.shapes = spec.shapes ?? [];// a panel image missing from the cache (shouldn't happen) reloads asyncfor (const p of proof.panels.filter((x) => !x.img)) {@@ -247,6 +282,7 @@}selectedId = null;selectedPanelId = null;+ selectedPasteId = null;selectedSig = null;const template = templatesState.proof.find((t) => t.id === proof.templateId);appliedTemplate = template@@ -386,7 +422,8 @@// and gets a lightweight refresh below, without recreating every image node.$effect(() => {JSON.stringify([- proof.panels.map((p) => [p.src, p.caption, p.row, p.scale, p.x, p.y]),+ proof.panels.map((p) => [p.src, p.caption, p.row, p.scale, p.x, p.y, p.frame]),+ proof.pastes.map((p) => [p.asset, p.x, p.y, p.scale, p.frame, !!p.img]),proof.shapes,proof.notes,proof.legendOrder,@@ -407,6 +444,7 @@$effect(() => {selectedId;selectedPanelId;+ selectedPasteId;selectedSig;guide;tool;@@ -421,14 +459,18 @@footerEnabled: proof.footerEnabled !== false,});- // Layout boxes + document measure for the active layout mode.+ // Layout boxes + document measure for the active layout mode. Pasted images+ // are deliberately absent from the measure: the panels alone size the+ // document, so moving a paste can never change the export.const boxesOf = () => layoutPanels(proof.panels, proof.captionSize, proof.layout, proof.space);+ const surfacesOf = () => surfaces(proof);const measureDoc = () =>docSize(proof.panels, proof.shapes, proof.notes, textOpts(), proof.legendOrder, proof.layout, proof.space);function resetDoc() {proof.title = freshTitle();proof.panels = [];+ proof.pastes = [];proof.shapes = [];proof.notes = {};proof.legendOrder = [];@@ -452,14 +494,15 @@proof.palette = [...ANNO_COLORS];color = proof.palette[0];savedName = null;- titleTouched = false;proofStarted = false;selectedId = null;selectedPanelId = null;+ selectedPasteId = null;selectedSig = null;appliedTemplate = null;dirty = false;imgCache.clear();+ pasteAssets.clear();anchorHistory();}@@ -525,11 +568,21 @@selectedSig = which;selectedId = null;selectedPanelId = null;+ selectedPasteId = null;+ }++ function selectPaste(id) {+ if (tool !== 'select') return;+ selectedPasteId = id;+ selectedId = null;+ selectedPanelId = null;+ selectedSig = null;}function selectPanel(id) {if (tool !== 'select') return;selectedPanelId = id;+ selectedPasteId = null;selectedId = null;selectedSig = null;}@@ -542,30 +595,37 @@api.get(`/api/cases/${caseState.current.id}/media`),api.get(`/api/cases/${caseState.current.id}/satellite`),]);- // A satellite capture *is* a media image, so it shows up in both lists. List- // it once, via its richer satellite entry (coordinates/attribution), and drop- // it from the media half. dedupeBySrc is a belt-and-braces guard so a stray- // overlap can never throw the keyed picker's `each_key_duplicate`.+ // A capture *is* a media image, so it shows up in both lists. List it once,+ // via its richer capture entry (coordinates/attribution), and drop it from+ // the media half. dedupeBySrc is a belt-and-braces guard so a stray overlap+ // can never throw the keyed picker's `each_key_duplicate`.+ //+ // The capture listing also carries map screenshots the extension filed, and+ // only some of those are satellite imagery. The chips call an item satellite+ // exactly when the Media Library does (isSatelliteMedia), so a Street View+ // grab reads the same on both screens.+ const captured = new Set(sats.map((s) => s.path));return dedupeBySrc([...sats.map((s) => ({...satPanelInput(s, prefs.coordFormat),label: `${fmtCoords(s.lat, s.lon)} · z${s.zoom}`,- thumb: s.path,- kind: 'satellite',+ ...panelPreview(s),+ kind: isSatelliteMedia(s) ? 'satellite' : 'media',+ folder: s.folder ?? '',})),...media- .filter((m) => m.kind === 'image' && !isSatelliteCapture(m))+ .filter((m) => m.kind === 'image' && !captured.has(m.path)).map((m) => ({...mediaPanelInput(m, media),- label: m.filename,- thumb: m.thumbnail ?? m.path,+ label: m.title || m.filename,+ ...panelPreview(m),kind: 'media',+ folder: m.folder ?? '',})),]);}async function openNewProofDialog() {- newProofName = proofTitleFromCase(caseState.current?.name, savedProofTitles());newProofTemplateId = '';newProofPanelPaths = [];newProofQuery = '';@@ -589,7 +649,7 @@}function requestNewProofCreation() {- if (!newProofName.trim() || creatingProof) return;+ if (creatingProof) return;if (proofStarted && dirty) {replaceWithNewConfirm = true;return;@@ -598,9 +658,8 @@}async function createNewProof() {- if (!newProofName.trim() || creatingProof) return;+ if (creatingProof) return;creatingProof = true;- const title = newProofName.trim();const template = templatesState.proof.find((t) => t.id === newProofTemplateId);const selectedItems = newProofPanelPaths.map((path) => pickerItems.find((item) => item.src === path))@@ -608,8 +667,6 @@try {resetDoc();proofStarted = true;- proof.title = title;- titleTouched = true;if (template) applyTemplate(template, { notify: false });for (const item of selectedItems) await addPanel(item);dirty = true;@@ -628,10 +685,66 @@uiState.tool = 'media';return;}+ panelQuery = '';+ panelCategory = 'all';+ panelBrowserOpen = false;+ panelBrowsePath = '';+ panelBrowseSelection = null;pickerItems = await fetchPanelItems();picker = true;}+ // Items whose thumbnail the worker has not produced yet show a placeholder.+ // Re-list while a picker is open so they fill in on their own, and stop as+ // soon as nothing is pending (or the dialog closes).+ const pickerThumbsPending = $derived(pickerItems.some((i) => i.thumbPending));++ async function refreshPickerItems() {+ if (caseState.current) pickerItems = await fetchPanelItems();+ }++ $effect(() => {+ if (!pickerThumbsPending || !(picker || newProofOpen)) return;+ return pollWhile(() => pickerThumbsPending, () => refreshPickerItems(), 1500);+ });++ function setPanelCategory(category) {+ panelCategory = category;+ panelBrowsePath = '';+ panelBrowseSelection = null;+ }++ function togglePanelBrowser() {+ if (panelBrowserOpen) {+ panelBrowserOpen = false;+ return;+ }+ panelQuery = '';+ panelBrowsePath = '';+ panelBrowseSelection = null;+ panelBrowserOpen = true;+ }++ function openPanelFolder(path) {+ panelBrowsePath = path;+ panelBrowseSelection = null;+ }++ function selectPanelBrowser(item, confirm = false) {+ panelBrowseSelection = item.src;+ if (confirm) addPanelFromPicker(item);+ }++ function confirmPanelBrowser() {+ const item = panelBrowserEntries.find((entry) => entry.src === panelBrowseSelection);+ if (item) addPanelFromPicker(item);+ }++ function addPanelFromPicker(item) {+ addPanel(item);+ picker = false;+ }+async function addPanel(item) {try {proofStarted = true;@@ -815,6 +928,149 @@requestAnimationFrame(fit);}+ // ---- overlays ----------------------------------------------------------------+ // An image dropped straight into the composition: a screenshot, a chart, a+ // crop from somewhere else. It never becomes a panel, so it is never filed as+ // media and the save records no source for it — it is decoration the analyst+ // moves, sizes and frames. Called a paste in the code and in the spec, after+ // how it gets there; the UI calls it an overlay, after what it is. The caps+ // mirror the ones the API enforces.++ let imageInputEl = $state();++ /** Doc-space centre of what the analyst is looking at. */+ function viewCentre() {+ if (!stage || !containerEl) return { x: 0, y: 0 };+ return {+ x: (containerEl.clientWidth / 2 - stage.x()) / stage.scaleX(),+ y: (containerEl.clientHeight / 2 - stage.y()) / stage.scaleY(),+ };+ }++ async function addPastedImage(file) {+ // A paste sits on top of a proof; the panels are what give the document its+ // size, so there has to be one before an image has anywhere to land.+ if (!proof.panels.length) {+ toast('Add a panel before adding an overlay', 'warn', 5000);+ return;+ }+ if (!file || !PASTE_TYPES.includes(file.type)) {+ toast('Paste a PNG, JPEG or WebP image', 'warn');+ return;+ }+ if (proof.pastes.length >= MAX_PASTES) {+ toast(`A proof holds ${MAX_PASTES} overlays at most`, 'warn');+ return;+ }+ try {+ const bytes = new Uint8Array(await file.arrayBuffer());+ if (bytes.length > MAX_PASTE_BYTES) {+ toast('That image is too large to paste (20 MB max)', 'warn');+ return;+ }+ const name = await assetName(bytes, file.type);+ const data = base64Of(bytes);+ const img = await loadImage(`data:${file.type};base64,${data}`);+ // an image already in the case keeps its saved state: no re-upload+ pasteAssets.set(name, { img, data, pending: pasteAssets.get(name)?.pending ?? true });+ const { width, height } = measureDoc();+ const natural = [img.naturalWidth, img.naturalHeight];+ const scale = pasteInsertScale(natural, width);+ const centre = viewCentre();+ const paste = newPaste(name, natural, {+ x: centre.x - (natural[0] * scale) / 2,+ y: centre.y - (natural[1] * scale) / 2,+ scale,+ });+ Object.assign(paste, clampPaste(paste, width, height));+ paste.img = img;+ proof.pastes.unshift(paste); // newest lands in front+ tool = 'select';+ selectPaste(paste.id);+ dirty = true;+ } catch (e) {+ toast(`Could not add that image (${e.message})`, 'danger');+ }+ }++ const isTextTarget = (el) =>+ !!el && (['INPUT', 'TEXTAREA', 'SELECT'].includes(el.tagName) || el.isContentEditable);++ /**+ * One place decides what Ctrl+V means: an image in the system clipboard is+ * what the analyst just copied, so it wins; otherwise the copied annotation is+ * pasted, which is what this shortcut did before images could be pasted.+ */+ function onPaste(e) {+ if (uiState.tool !== 'proof' || isTextTarget(e.target)) return;+ const item = [...(e.clipboardData?.items ?? [])].find((i) => i.type.startsWith('image/'));+ if (item) {+ e.preventDefault();+ addPastedImage(item.getAsFile());+ } else if (clipboard) {+ e.preventDefault();+ pasteShape();+ }+ }++ function pickImageFile() {+ imageInputEl?.click();+ }++ function onImageFile(e) {+ const file = e.currentTarget.files?.[0];+ e.currentTarget.value = ''; // so picking the same file twice still fires+ if (file) addPastedImage(file);+ }++ function onCanvasDrop(e) {+ const file = [...(e.dataTransfer?.files ?? [])].find((f) => f.type.startsWith('image/'));+ if (!file) return;+ e.preventDefault();+ addPastedImage(file);+ }++ // Dropping an image on the canvas pastes it. Wired here rather than in the+ // markup so the canvas needs no interactive ARIA role to be a drop target.+ $effect(() => {+ if (!containerEl) return;+ const allow = (e) => e.preventDefault();+ containerEl.addEventListener('dragover', allow);+ containerEl.addEventListener('drop', onCanvasDrop);+ return () => {+ containerEl.removeEventListener('dragover', allow);+ containerEl.removeEventListener('drop', onCanvasDrop);+ };+ });++ function removePaste(index) {+ const paste = proof.pastes[index];+ if (!paste) return;+ proof.shapes = proof.shapes.filter((s) => s.panel !== paste.id);+ proof.pastes.splice(index, 1);+ selectedId = null;+ if (selectedPasteId === paste.id) selectedPasteId = null;+ dirty = true;+ }++ function movePasteZ(index, delta) {+ const target = index + delta;+ if (target < 0 || target >= proof.pastes.length) return;+ const [paste] = proof.pastes.splice(index, 1);+ proof.pastes.splice(target, 0, paste);+ dirty = true;+ }++ /**+ * The decorative border of a panel or a pasted image. `patch` of null removes+ * it, `{}` adds it at the default colour and thickness, and a width of 0+ * removes it too — which is how the thickness input turns one off.+ */+ function setFrame(item, patch) {+ item.frame = patch === null ? null : normalizeFrame({ ...(item.frame ?? newFrame()), ...patch });+ dirty = true;+ }+// ---- view (zoom / pan / fit) ----------------------------------------------------function fit() {@@ -859,8 +1115,10 @@return { x: (p.x - stage.x()) / stage.scaleX(), y: (p.y - stage.y()) / stage.scaleY() };}- function panelAt(doc) {- return panelHitTest(boxesOf(), doc);+ // Annotations are drawn on whatever surface is under the pointer — a panel or+ // a pasted image. Pasted images are in front, so they claim the point first.+ function surfaceAt(doc) {+ return surfaceHitTest(surfacesOf(), doc);}function onPointerDown(e) {@@ -877,14 +1135,17 @@if (onEmpty) {selectedId = null;selectedPanelId = null;+ selectedPasteId = null;selectedSig = null;}return;}stage.draggable(false);- const hit = panelAt(docPoint());+ const hit = surfaceAt(docPoint());if (!hit) return;- const panel = proof.panels[hit.index];+ // `panel` here is the surface the annotation binds to: the shape's `panel`+ // field holds a panel id or a pasted image's id.+ const panel = hit.item;const group = docLayer.findOne(`#pg-${panel.id}`);if (!group) return;// text is placed with a single click (no drag) then edited in the side list@@ -1053,6 +1314,34 @@}}+ // Fold a drag or a corner-resize of a pasted image back into its stored+ // position and scale, then hold it inside the document.+ function commitPasteNode(paste, node, { resized = false } = {}) {+ if (resized) paste.scale = clampPasteScale(node.scaleX());+ paste.x = node.x();+ paste.y = node.y();+ const { width, height } = measureDoc();+ Object.assign(paste, clampPaste(paste, width, height));+ node.scale({ x: paste.scale, y: paste.scale });+ node.position({ x: paste.x, y: paste.y });+ dirty = true;+ }++ /**+ * The decorative border of a panel or a pasted image, drawn inset so it never+ * spills past the image: the document is measured from the panels, and a frame+ * must not change what that measure sees. Width is in the surface's own pixels,+ * so it grows with the surface exactly as an annotation does.+ */+ function frameNode(frame, natural) {+ const w = frame.width;+ return new Konva.Rect({+ x: w / 2, y: w / 2,+ width: Math.max(0, natural[0] - w), height: Math.max(0, natural[1] - w),+ stroke: frame.color, strokeWidth: w, listening: false,+ });+ }+// ---- rebuild canvas from state ------------------------------------------------------function rebuild() {@@ -1070,6 +1359,7 @@}const { width, height, legend, cols } = measureDoc();const boxes = boxesOf();+ const pasteBox = pasteBoxes(proof.pastes);const capSize = proof.captionSize ?? CAPTION_SIZE;const free = proof.layout === 'free';const { pad } = normSpace(proof.space);@@ -1130,6 +1420,7 @@}));group.add(imgClip);}+ if (panel.frame) group.add(frameNode(panel.frame, panel.natural));for (const s of proof.shapes.filter((x) => x.panel === panel.id)) {group.add(makeShapeNode(s, box));}@@ -1179,6 +1470,42 @@}));}+ // Pasted images, over the panels and the legend: pixels laid on top of the+ // proof rather than part of its composition. Back→front like the panels, so+ // the first one in the list is the one in front.+ for (let i = proof.pastes.length - 1; i >= 0; i--) {+ const paste = proof.pastes[i];+ const box = pasteBox[i];+ const group = new Konva.Group({+ id: `pg-${paste.id}`,+ x: box.x, y: box.y,+ scaleX: box.scale, scaleY: box.scale,+ draggable: false,+ });+ // same invisible hit target as a panel: the image never listens, so a+ // drawing tool passes through to the stage, but a click still selects.+ group.add(new Konva.Rect({+ x: 0, y: 0, width: paste.natural[0], height: paste.natural[1],+ fill: 'transparent', listening: true, name: 'panel-hit',+ }));+ bindPanelPointerLifecycle(group, {+ onPress: () => group.draggable(tool === 'select' && !spacePan),+ onSelect: () => selectPaste(paste.id),+ onDragEnd: () => commitPasteNode(paste, group),+ });+ group.on('transformend', () => commitPasteNode(paste, group, { resized: true }));+ if (paste.img) {+ group.add(new Konva.Image({+ image: paste.img, width: paste.natural[0], height: paste.natural[1], listening: false,+ }));+ }+ if (paste.frame) group.add(frameNode(paste.frame, paste.natural));+ for (const s of proof.shapes.filter((x) => x.panel === paste.id)) {+ group.add(makeShapeNode(s, box));+ }+ docLayer.add(group);+ }+const st = proof.signatureText && prefs.signatureHandle?.trim() ? proof.signatureText : null;const pendingHandleNode = st ? new Konva.Text({id: 'sig-text',@@ -1293,30 +1620,42 @@// the drag overshot the 25–250% range (worst at the bounds, where a resize// in the blocked direction just reverted). Shapes stay unconstrained.// the logo or the @handle, picked for a corner-resize (aspect locked).- const sigNode = !selectedNode && !panelNode && selectedSig+ // a pasted image resizes from its corners with its aspect locked, within the+ // same kind of scale bounds a panel has+ const pasteNode = !selectedNode && !panelNode && selectedPasteId+ ? docLayer.findOne(`#pg-${selectedPasteId}`)+ : null;+ const sigNode = !selectedNode && !panelNode && !pasteNode && selectedSig? docLayer.findOne(selectedSig === 'logo' ? '#sig-logo' : '#sig-text'): null;const boundPanel = panelNode ? proof.panels.find((p) => p.id === selectedPanelId) : null;+ const boundPaste = pasteNode ? proof.pastes.find((p) => p.id === selectedPasteId) : null;transformer.boundBoxFunc((oldBox, newBox) => {+ if (boundPaste) {+ const implied = newBox.width / stage.scaleX() / boundPaste.natural[0];+ return implied < PASTE_SCALE_MIN || implied > PASTE_SCALE_MAX ? oldBox : newBox;+ }if (!boundPanel) return newBox;const impliedScale =(newBox.width / stage.scaleX()) * (boundPanel.natural[1] / (boundPanel.natural[0] * PANEL_H));return impliedScale < SCALE_MIN || impliedScale > SCALE_MAX ? oldBox : newBox;});- transformer.keepRatio(!!sigNode);+ transformer.keepRatio(!!sigNode || !!pasteNode);transformer.nodes(- selectedNode ? [selectedNode] : panelNode ? [panelNode] : sigNode ? [sigNode] : []+ selectedNode+ ? [selectedNode]+ : panelNode ? [panelNode] : pasteNode ? [pasteNode] : sigNode ? [sigNode] : []);const selKind = selectedShape?.kind;transformer.rotateEnabled(selKind === 'text' || selKind === 'rect' || selKind === 'ellipse');transformer.enabledAnchors(selKind === 'rect' || selKind === 'ellipse'? ['top-left', 'top-right', 'bottom-left', 'bottom-right', 'middle-left', 'middle-right', 'top-center', 'bottom-center']- : selKind === 'text' || panelNode || sigNode+ : selKind === 'text' || panelNode || pasteNode || sigNode? ['top-left', 'top-right', 'bottom-left', 'bottom-right']: []);- drawEndHandles(boxes);+ drawEndHandles(surfacesOf());drawPanelMoveControls(boxes);drawGuide(width, height);uiLayer.batchDraw();@@ -1363,14 +1702,14 @@// Freehand strokes stay draggable as a whole; showing every sampled point// would cover the stroke in handles.const POINT_KINDS = new Set(['line', 'arrow', 'curve']);- function drawEndHandles(boxes) {+ function drawEndHandles(list) {endHandles.destroyChildren();const s = selectedShape;if (tool !== 'select' || !s || !POINT_KINDS.has(s.kind)) return;- const idx = proof.panels.findIndex((p) => p.id === s.panel);- if (idx < 0) return;- const box = boxes[idx];- const panel = proof.panels[idx];+ const surface = list.find((x) => x.id === s.panel);+ if (!surface) return;+ const box = surface.box;+ const panel = surface.item;const node = docLayer.findOne(`#${s.id}`);const r = 7 / stage.scaleX();for (let vi = 0; vi < s.points.length; vi += 2) {@@ -1451,14 +1790,15 @@}}- // On drop, re-bind a shape to whichever panel its anchor now sits over and- // convert its coordinates into that panel's natural pixel space. Returns the- // source/destination layout boxes so the caller can remap x/y or points.+ // On drop, re-bind a shape to whichever surface its anchor now sits over — a+ // panel or a pasted image — and convert its coordinates into that surface's+ // natural pixel space. Returns the source/destination layout boxes so the+ // caller can remap x/y or points.function rebindOnDrop(s, node) {- const boxes = boxesOf();- const fromIdx = proof.panels.findIndex((p) => p.id === s.panel);- if (fromIdx < 0) return { fromBox: null, toBox: null };- const fromBox = boxes[fromIdx];+ const list = surfacesOf();+ const from = list.find((x) => x.id === s.panel);+ if (!from) return { fromBox: null, toBox: null };+ const fromBox = from.box;let anchor;if (s.kind === 'rect') {anchor = { x: node.x() + (s.w ?? 0) / 2, y: node.y() + (s.h ?? 0) / 2 };@@ -1472,14 +1812,10 @@}const dx = fromBox.x + anchor.x * fromBox.scale;const dy = fromBox.y + anchor.y * fromBox.scale;- let toIdx = fromIdx;- // array order is front→back — the topmost panel claims the drop- for (let i = 0; i < boxes.length; i++) {- const b = boxes[i];- if (dx >= b.x && dx <= b.x + b.w && dy >= b.y && dy <= b.y + b.h) { toIdx = i; break; }- }- s.panel = proof.panels[toIdx].id;- return { fromBox, toBox: boxes[toIdx] };+ // the list is front→back, so the topmost surface claims the drop+ const to = surfaceHitTest(list, { x: dx, y: dy }) ?? from;+ s.panel = to.id;+ return { fromBox, toBox: to.box };}// Doc→panel remap of a single x/y origin between two layout boxes.@@ -1532,6 +1868,7 @@e.cancelBubble = true;selectedId = s.id;selectedPanelId = null;+ selectedPasteId = null;selectedSig = null;}});@@ -1587,6 +1924,7 @@e.cancelBubble = true;selectedId = s.id;selectedPanelId = null;+ selectedPasteId = null;selectedSig = null;}});@@ -1632,9 +1970,7 @@// ---- inline text editing (double-click a label on the canvas) ---------------function startTextEdit(s, node) {- const boxes = boxesOf();- const idx = proof.panels.findIndex((p) => p.id === s.panel);- const panelScale = idx >= 0 ? boxes[idx].scale : 1;+ const panelScale = surfacesOf().find((x) => x.id === s.panel)?.box.scale ?? 1;const abs = node.getAbsolutePosition(); // container px, stage transform includedselectedId = s.id;textEdit = {@@ -1782,8 +2118,9 @@// clipboard / undo / save chordsif (e.ctrlKey || e.metaKey) {const k = e.key.toLowerCase();+ // Ctrl+V is deliberately absent: the paste event decides between an image+ // in the system clipboard and a copied annotation (see onPaste).if (k === 'c' && selectedId) { e.preventDefault(); copyShape(); }- else if (k === 'v' && clipboard) { e.preventDefault(); pasteShape(); }else if (k === 'd' && selectedId) { e.preventDefault(); duplicateShape(); }else if (k === 'z') { e.preventDefault(); e.shiftKey ? redo() : undo(); }else if (k === 'y') { e.preventDefault(); redo(); }@@ -1809,9 +2146,12 @@} else if ((e.key === 'Delete' || e.key === 'Backspace') && selectedPanelId) {const idx = proof.panels.findIndex((p) => p.id === selectedPanelId);if (idx >= 0) removePanel(idx);+ } else if ((e.key === 'Delete' || e.key === 'Backspace') && selectedPasteId) {+ removePaste(proof.pastes.findIndex((p) => p.id === selectedPasteId));} else if (e.key === 'Escape') {selectedId = null;selectedPanelId = null;+ selectedPasteId = null;selectedSig = null;tool = 'select';} else if (e.key === 'v') tool = 'select';@@ -1877,51 +2217,52 @@// 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(proofEntities);- const savedProofTitles = () => libSavedProofTitles(proofEntities);+ // the names so a fresh proof can take one that reads apart from them.+ const savedProofNames = () => savedSlugs(proofEntities, 'proof');+ const savedProofTitles = () => savedTitles(proofEntities, 'proof');- // Title of a saved proof by its slug, for the overwrite prompt.- function savedProofTitle(name) {- return libSavedProofTitle(proofEntities, name);- }-- // Default title for a fresh proof, numbered past any already in the case so- // the top-of-screen name reads apart ("Untitled proof 2"). Called on reset.- const freshTitle = () => uniqueProofTitle(DEFAULT_PROOF_TITLE, savedProofTitles());+ // Default name for a fresh proof, numbered past those already in the case so+ // the top-of-screen name reads apart ("Proof 2"). Called on reset.+ const freshTitle = () => nextName('proof', savedProofTitles());- let overwritePrompt = $state(null); // { name, andPost } when a first save hits a named proof+ let overwritePrompt = $state(null); // { slug, andPost } when a save hits a named proofasync function save({ andPost = false } = {}) {if (!proof.panels.length || saving) return;- // A proof already bound to a saved name (opened, or saved once) writes back- // over itself — no collision to resolve. On a first save the title is the- // name: an untouched default title keeps itself unique/numbered (no prompt),- // a title the analyst typed that lands on an existing proof asks before it- // overwrites the one already under that name.- if (!savedName) {- if (!titleTouched) {- proof.title = freshTitle();- } else if (savedProofNames().has(proofSlug(proof.title))) {- overwritePrompt = { name: proofSlug(proof.title), andPost };- return;- }+ // The name in the header is the filename. A bound proof writes back over+ // itself, and renaming it moves the file — the backend refuses a rename onto+ // a name another proof holds. An unbound proof landing on a saved name is+ // the one case that can go either way, so it asks first.+ if (!savedName && savedProofNames().has(slugify(proof.title, 'proof'))) {+ overwritePrompt = { slug: slugify(proof.title, 'proof'), andPost };+ return;}- return performSave(savedName, andPost);+ return performSave(andPost);}- async function performSave(name, andPost = false) {+ async function performSave(andPost = false) {if (!proof.panels.length || saving) return;saving = true;try {const c = await ensureCase();const dataUrl = exportPng();+ // Pasted images the case does not hold yet ride along with the spec; the+ // ones already written are named by their content, so they need no resend.+ const assets = [...new Set(proof.pastes.map((p) => p.asset))]+ .map((name) => ({ name, entry: pasteAssets.get(name) }))+ .filter(({ entry }) => entry?.pending && entry.data)+ .map(({ name, entry }) => ({ name, data: entry.data }));const result = await api.post(`/api/cases/${c.id}/proofs`, {- name,+ rename_from: savedName,title: proof.title,spec: toSpec(proof),png_base64: dataUrl.split(',')[1],+ assets,});+ for (const { name } of assets) {+ const entry = pasteAssets.get(name);+ if (entry) entry.pending = false;+ }savedName = result.name;dirty = false;await reloadCase();@@ -1943,8 +2284,59 @@}}+ /** Open the list fresh: search and folder view reset. Deleting from the list+ * refreshes through openProofList instead, which keeps them. */+ function openProofDialog() {+ proofQuery = '';+ proofBrowserOpen = false;+ proofBrowsePath = '';+ proofBrowseSelection = null;+ return openProofList();+ }+async function openProofList() {- openList = await api.get(`/api/cases/${caseState.current.id}/proofs`);+ const proofs = await api.get(`/api/cases/${caseState.current.id}/proofs`);+ // A saved proof is filed like any other entity, so its folder lives on the+ // catalog side; the proofs route only knows the files.+ try {+ const entities = await fetchAllEntities(caseState.current.id, { types: ['proof'] });+ const folders = new Map(+ entities.map((entity) => [entity.attrs?.spec ?? '', entity.attrs?.folder ?? ''])+ );+ openList = proofs.map((entry) => ({ ...entry, folder: folders.get(entry.spec_path) ?? '' }));+ } catch {+ openList = proofs;+ }+ }++ function matchesProofQuery(entry, query) {+ return matchesTerms([entry.title, entry.name, entry.folder].filter(Boolean).join('\n'), query);+ }++ function toggleProofBrowser() {+ if (proofBrowserOpen) {+ proofBrowserOpen = false;+ return;+ }+ proofQuery = '';+ proofBrowsePath = '';+ proofBrowseSelection = null;+ proofBrowserOpen = true;+ }++ function openProofFolder(path) {+ proofBrowsePath = path;+ proofBrowseSelection = null;+ }++ function selectProofBrowser(entry, confirm = false) {+ proofBrowseSelection = entry.name;+ if (confirm) openProof(entry);+ }++ function confirmProofBrowser() {+ const entry = proofBrowserEntries.find((item) => item.name === proofBrowseSelection);+ if (entry) openProof(entry);}let deleteEntry = $state(null); // open-list entry pending deletion@@ -1997,8 +2389,21 @@toast(`Missing panel image: ${p.src}`, 'warn');}}- const validPanels = new Set(proof.panels.map((p) => p.id));- proof.shapes = (spec.shapes ?? []).filter((s) => validPanels.has(s.panel));+ // Pasted images come from the proof's own assets folder — nothing in the+ // case points at them, so they are read by the name the spec carries.+ for (const p of spec.pastes ?? []) {+ try {+ const img = await loadImage(+ `/files/${caseState.current.id}/proofs/${entry.name}.assets/${p.asset}`+ );+ pasteAssets.set(p.asset, { img, data: null, pending: false });+ proof.pastes.push({ ...p, id: p.id ?? newId('x'), img });+ } catch {+ toast('An overlay of this proof is missing', 'warn');+ }+ }+ const validSurfaces = new Set([...proof.panels, ...proof.pastes].map((s) => s.id));+ proof.shapes = (spec.shapes ?? []).filter((s) => validSurfaces.has(s.panel));// legend text lives in `notes` (per color); migrate old per-shape commentsproof.notes = spec.notes ?? notesFromShapes(proof.shapes);proof.legendOrder = spec.legendOrder ?? [];@@ -2040,7 +2445,7 @@const displayedSource = $derived(proof.source.trim() || autoSource(proof.panels));</script>-<svelte:window onkeydown={onKeydown} onkeyup={onKeyup} />+<svelte:window onkeydown={onKeydown} onkeyup={onKeyup} onpaste={onPaste} /><div class="tool"><div class="tool-header">@@ -2049,37 +2454,40 @@<inputclass="input title-input"bind:value={proof.title}- oninput={() => { dirty = true; titleTouched = true; }}+ oninput={() => (dirty = true)}/>{#if dirty}<span class="badge">unsaved</span>{/if}{/if}<div class="spacer"></div>{#if caseState.current}- <button class="btn" onclick={openProofList}><Icon name="folderOpen" size={15} /> Open</button>+ <button class="btn btn-sm" onclick={openProofDialog}><Icon name="folderOpen" size={14} /> Open proof</button>{/if}{#if proofStarted}- <button class="btn" onclick={() => (discardConfirm = true)} title="Clear this proof">- <Icon name="reset" size={15} /> Discard+ <button class="btn btn-sm" onclick={() => (discardConfirm = true)} title="Clear this proof">+ <Icon name="reset" size={14} /> Discard</button>{/if}- <button class="btn" onclick={openNewProofDialog}><Icon name="plus" size={15} /> New proof</button>+ <button class="btn btn-sm" onclick={openNewProofDialog}><Icon name="plus" size={14} /> New proof</button><button- class="btn"+ class="btn btn-sm"onclick={copyPng}disabled={!proofHasContent || copying}title="Copy the composed PNG to the clipboard">- <Icon name="copy" size={15} /> {copying ? 'Copying…' : 'Copy PNG'}+ <Icon name="copy" size={14} /> {copying ? 'Copying…' : 'Copy PNG'}</button>- <button class="btn btn-primary" onclick={() => save()} disabled={!proofHasContent || saving}>- <Icon name="check" size={15} /> {saving ? 'Saving…' : 'Save'}+ <button class="btn btn-ok btn-sm" onclick={() => save()} disabled={!proofHasContent || saving}>+ <Icon name="save" size={14} /> {saving ? 'Saving…' : 'Save proof'}</button>- <button class="btn" onclick={() => save({ andPost: true })} disabled={!proofHasContent || saving}>- <Icon name="post" size={15} /> To Post+ <button class="btn btn-info btn-sm" onclick={() => save({ andPost: true })} disabled={!proofHasContent || saving}>+ <Icon name="post" size={14} /> To Post</button></div><div class="body">+ <!-- The drawing tools act on a proof; until one is open or created there is+ nothing to draw on, so the rail stays out of the way. -->+ {#if proofStarted}<ProofToolbar{canUndo}{canRedo}@@ -2101,6 +2509,7 @@panelCount={proof.panels.length}{applyMagic}/>+ {/if}<ProofCanvasbind:containerEl@@ -2114,6 +2523,16 @@{openNewProofDialog}/>+ <!-- Image picked off the disk for a paste: it goes into the proof, never+ into the case, so it does not travel through the media ingest. -->+ <input+ type="file"+ hidden+ accept="image/png,image/jpeg,image/webp"+ bind:this={imageInputEl}+ onchange={onImageFile}+ />+<!-- right: proof settings, panels & annotations -->{#if proofStarted}<aside class="side">@@ -2216,16 +2635,23 @@{collapsed}{gonePanels}bind:selectedPanelId+ bind:selectedPasteIdbind:selectedId{activeColor}caseId={caseState.current?.id}scaleMin={SCALE_MIN}scaleMax={SCALE_MAX}scaleStep={SCALE_STEP}+ frameWidthMax={FRAME_WIDTH_MAX}+ frameColor={FRAME_COLOR}{openPicker}{movePanelZ}{scalePanel}{removePanel}+ {movePasteZ}+ {removePaste}+ {setFrame}+ {pickImageFile}{featureList}{moveLegendColor}{setColor}@@ -2397,7 +2823,6 @@{#if newProofOpen}<NewProofDialog- bind:name={newProofName}bind:templateId={newProofTemplateId}bind:panelPaths={newProofPanelPaths}bind:query={newProofQuery}@@ -2443,7 +2868,7 @@{#if overwritePrompt}<ConfirmDialogtitle="Overwrite this proof?"- message={`“${savedProofTitle(overwritePrompt.name)}” is already saved in this case.`}+ message={`“${savedTitle(proofEntities, 'proof', overwritePrompt.slug)}” is already saved in this case.`}detail="Saving replaces its PNG and editable spec. Rename this proof to keep both."confirmLabel="Overwrite"tone="danger"@@ -2451,7 +2876,7 @@onconfirm={() => {const p = overwritePrompt;overwritePrompt = null;- performSave(p.name, p.andPost);+ performSave(p.andPost);}}oncancel={() => (overwritePrompt = null)}/>@@ -2461,7 +2886,7 @@<ConfirmDialogtitle="Delete this proof?"message={`“${deleteEntry.title}” will be removed from the case.`}- detail="This permanently deletes the exported PNG and its editable spec. It cannot be undone."+ detail="Deletes the PNG and editable proof and cannot be undone."confirmLabel="Delete"tone="danger"icon="trash"@@ -2477,22 +2902,57 @@<p>No images in this case yet. Import media or capture satellite imagery first.</p></div>{:else}- <div class="pick-grid">- {#each pickerItems as item (item.src)}- <button- class="pick card"- onclick={() => {- addPanel(item);- picker = false;- }}- >- <img src={`/files/${caseState.current.id}/${item.thumb}`} alt="" loading="lazy" />- <span class="pick-label">- <Icon name={item.kind === 'satellite' ? 'satellite' : 'image'} size={12} />- {item.label}- </span>- </button>- {/each}+ <div class="picker-stack">+ {#if panelBrowserOpen || pickerItems.length > PICKER_SEARCH_MIN}+ <div class="picker-search">+ <SearchInput bind:value={panelQuery} placeholder="Search titles…" width="100%" />+ <button+ class="btn btn-ghost btn-sm browse-btn"+ title={panelBrowserOpen ? 'Show every image' : 'Browse folders'}+ onclick={togglePanelBrowser}+ >…</button>+ </div>+ {/if}+ <PanelCategories items={pickerItems} category={panelCategory} onpick={setPanelCategory} />+ {#if panelBrowserOpen}+ <FolderBrowser+ entries={panelBrowserEntries}+ path={panelBrowsePath}+ rootLabel="Case images"+ selectedId={panelBrowseSelection}+ matches={(item) => filterProofPanelItems([item], panelQuery, 'all').length > 0}+ emptyText="This folder has no matching images."+ icon={(item) => (item.kind === 'satellite' ? 'satellite' : 'image')}+ onnavigate={openPanelFolder}+ onselect={(item) => selectPanelBrowser(item)}+ onconfirm={(item) => selectPanelBrowser(item, true)}+ />+ <div class="picker-actions">+ <button class="btn btn-primary btn-sm" disabled={!panelBrowseSelection} onclick={confirmPanelBrowser}>Add selected</button>+ </div>+ {:else if !visiblePanelItems.length}+ <p class="picker-hint">No image matches this search.</p>+ {:else}+ <div class="pick-grid">+ {#each visiblePanelItems as item (item.src)}+ <button class="pick card" onclick={() => addPanelFromPicker(item)}>+ {#if item.thumb}+ <img src={`/files/${caseState.current.id}/${item.thumb}`} alt="" loading="lazy" decoding="async" />+ {:else if item.thumbPending}+ <span class="pick-placeholder"><Icon name="clock" size={20} /></span>+ {:else}+ <span class="pick-placeholder">+ <Icon name={item.kind === 'satellite' ? 'satellite' : 'image'} size={20} />+ </span>+ {/if}+ <span class="pick-label">+ <Icon name={item.kind === 'satellite' ? 'satellite' : 'image'} size={12} />+ {item.label}+ </span>+ </button>+ {/each}+ </div>+ {/if}</div>{/if}</Modal>@@ -2503,34 +2963,74 @@{#if !openList.length}<div class="empty"><p>No saved proofs in this case yet.</p></div>{:else}- <div class="open-list">- {#each openList as entry (entry.name)}- <div class="open-row-wrap">- <button class="open-row" onclick={() => openProof(entry)}>- {#if entry.png}- <img src={`/files/${caseState.current.id}/${entry.png}`} alt="" loading="lazy" />- {/if}- <div class="open-meta">- <span class="open-title">{entry.title}</span>- <span class="open-sub">{entry.panels} panels · {entry.shapes} annotations · {entry.updated_at?.slice(0, 10)}</span>+ <div class="picker-stack">+ {#if proofBrowserOpen || openList.length > PICKER_SEARCH_MIN}+ <div class="picker-search">+ <SearchInput bind:value={proofQuery} placeholder="Search proofs…" width="100%" />+ <button+ class="btn btn-ghost btn-sm browse-btn"+ title={proofBrowserOpen ? 'Show every proof' : 'Browse folders'}+ onclick={toggleProofBrowser}+ >…</button>+ </div>+ {/if}+ {#if proofBrowserOpen}+ <FolderBrowser+ entries={proofBrowserEntries}+ path={proofBrowsePath}+ rootLabel="Proofs"+ selectedId={proofBrowseSelection}+ matches={(entry) => matchesProofQuery(entry, proofQuery)}+ emptyText="This folder has no matching proofs."+ icon={() => 'proof'}+ label={(entry) => entry.title}+ onnavigate={openProofFolder}+ onselect={(entry) => selectProofBrowser(entry)}+ onconfirm={(entry) => selectProofBrowser(entry, true)}+ />+ <div class="picker-actions">+ <button class="btn btn-primary btn-sm" disabled={!proofBrowseSelection} onclick={confirmProofBrowser}>Open selected</button>+ </div>+ {:else if !visibleProofs.length}+ <p class="picker-hint">No proof matches this search.</p>+ {:else}+ <div class="open-list">+ {#each visibleProofs as entry (entry.name)}+ <div class="open-row-wrap">+ <button class="open-row" onclick={() => openProof(entry)}>+ {#if entry.thumb || entry.png}+ <!-- the thumbnail of the export, or the export itself when+ it could not be rendered; decoded off the main thread -->+ <img src={`/files/${caseState.current.id}/${entry.thumb ?? entry.png}`} alt="" loading="lazy" decoding="async" />+ {/if}+ <div class="open-meta">+ <span class="open-title">{entry.title}</span>+ <span class="open-sub">{entry.panels} panels · {entry.shapes} annotations · {entry.updated_at?.slice(0, 10)}</span>+ </div>+ </button>+ <button class="btn btn-ghost btn-sm open-del" title="Delete this saved proof" onclick={() => (deleteEntry = entry)}>+ <Icon name="trash" size={13} />+ </button></div>- </button>- <button class="btn btn-ghost btn-sm open-del" title="Delete this saved proof" onclick={() => (deleteEntry = entry)}>- <Icon name="trash" size={13} />- </button>+ {/each}</div>- {/each}+ {/if}</div>{/if}</Modal>{/if}<style>- .spacer { flex: 1; }- .title-input {- width: min(320px, 26vw);- font-weight: 600;+ .tool-header {+ align-items: baseline;+ gap: 10px;+ padding: 14px 16px 12px;+ flex-shrink: 0;+ }+ .tool-header h2 {+ font-weight: 700;}+ .spacer { flex: 1; }.tpl-none {margin: 0 0 6px;font-size: var(--fs-xs);@@ -2668,6 +3168,33 @@color: var(--accent);border-color: var(--accent);}+ .picker-stack {+ display: flex;+ flex-direction: column;+ gap: 10px;+ }+ .picker-search {+ display: flex;+ align-items: center;+ gap: 6px;+ }+ .picker-search :global(.search-box) {+ flex: 1;+ }+ .browse-btn {+ min-width: 30px;+ font-size: var(--fs-lg);+ line-height: 1;+ }+ .picker-hint {+ color: var(--text-3);+ font-size: var(--fs-sm);+ padding: 8px 2px;+ }+ .picker-actions {+ display: flex;+ justify-content: flex-end;+ }.pick-grid {display: grid;grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));@@ -2685,6 +3212,15 @@object-fit: cover;background: var(--bg-2);}+ .pick-placeholder {+ width: 100%;+ aspect-ratio: 16 / 11;+ display: flex;+ align-items: center;+ justify-content: center;+ background: var(--bg-2);+ color: var(--text-3);+ }.pick-label {display: flex;align-items: center;diff --git a/frontend/src/tools/ProofComposer.test.js b/frontend/src/tools/ProofComposer.test.jsindex 075f283..17f3b16 100644--- a/frontend/src/tools/ProofComposer.test.js+++ b/frontend/src/tools/ProofComposer.test.js@@ -1,4 +1,5 @@import { describe, expect, it, vi } from 'vitest';+import { readFileSync } from 'node:fs';import { render } from 'svelte/server';vi.mock('konva', () => ({ default: {} }));@@ -9,12 +10,14 @@ import {createCanvasRenderGate,} from './proof/canvasLifecycle.js';+const source = readFileSync(new URL('./ProofComposer.svelte', import.meta.url), 'utf8');+describe('Proof Composer empty state', () => {it('hides proof-specific chrome until a proof is started', () => {const { body } = render(ProofComposer);expect(body).toContain('Compose a proof');- expect(body).toContain('Freehand (d)');+ expect(body).not.toContain('Freehand (d)');expect(body).not.toContain('title-input');expect(body).not.toContain('<aside');expect(body).not.toContain('House style');@@ -23,6 +26,85 @@ describe('Proof Composer empty state', () => {});});+describe('Proof Composer header', () => {+ it('uses the same compact controls as Inspect', () => {+ const header = source.slice(source.indexOf('<div class="tool-header">'), source.indexOf('</div>\n\n <div class="body">'));++ expect(header).not.toContain('class="btn"');+ expect(header).not.toContain('btn-primary');+ expect(header).toContain('btn-ok');+ expect(header).not.toContain('size={15}');+ expect(header).toContain('Open proof');+ expect(header).toContain("saving ? 'Saving…' : 'Save proof'");+ expect(header).toContain('<Icon name="save" size={14} /> {saving');+ expect(header).not.toContain('<Icon name="check" size={14} /> {saving');+ expect(header).toContain('btn-info');+ expect(source).toContain('align-items: baseline;');+ expect(source).toContain('font-weight: 700;');+ });+});++describe('Proof Composer pickers', () => {+ it('searches the panel picker and the saved-proof list only past six entries', () => {+ expect(source).toContain("import SearchInput from '../components/SearchInput.svelte'");+ expect(source).toContain('const PICKER_SEARCH_MIN = 6;');+ expect(source).toContain('{#if panelBrowserOpen || pickerItems.length > PICKER_SEARCH_MIN}');+ expect(source).toContain('{#if proofBrowserOpen || openList.length > PICKER_SEARCH_MIN}');+ expect(source).toContain('bind:value={panelQuery}');+ expect(source).toContain('bind:value={proofQuery}');+ expect(source).toContain('{#each visiblePanelItems as item (item.src)}');+ expect(source).toContain('{#each visibleProofs as entry (entry.name)}');+ });++ it('offers the Inspect folder browser behind the "…" in both pickers', () => {+ expect(source).toContain("import FolderBrowser from '../components/FolderBrowser.svelte'");+ expect(source).toContain('function togglePanelBrowser()');+ expect(source).toContain('function toggleProofBrowser()');+ expect(source).toContain('onconfirm={(item) => selectPanelBrowser(item, true)}');+ expect(source).toContain('onconfirm={(entry) => selectProofBrowser(entry, true)}');+ expect(source).toContain('disabled={!panelBrowseSelection} onclick={confirmPanelBrowser}');+ expect(source).toContain('disabled={!proofBrowseSelection} onclick={confirmProofBrowser}');+ expect(source).not.toContain('>Back</button>');+ });++ it('filters panels by satellite / other images, like the Create proof dialog', () => {+ expect(source).toContain("import PanelCategories from './proof/PanelCategories.svelte'");+ expect(source).toContain('<PanelCategories items={pickerItems} category={panelCategory} onpick={setPanelCategory} />');+ expect(source).toContain("filterProofPanelItems(pickerItems, '', panelCategory)");+ });++ it('calls a capture satellite exactly when the Media Library does', () => {+ expect(source).toContain("import { isSatelliteMedia } from '../lib/mediaFilter.js'");+ expect(source).toContain("kind: isSatelliteMedia(s) ? 'satellite' : 'media'");+ // captures are dropped from the media half by path, so a Street View grab+ // is listed once, under Other images, instead of twice+ expect(source).toContain('const captured = new Set(sats.map((s) => s.path));');+ expect(source).toContain('!captured.has(m.path)');+ expect(source).not.toContain('isSatelliteCapture');+ });++ it('searches panels by their title, not by the file name', () => {+ expect(source).toContain('label: m.title || m.filename');+ expect(source).toContain('placeholder="Search titles…"');+ });++ it('files panels and saved proofs by their case folder', () => {+ expect(source).toContain("folder: m.folder ?? ''");+ expect(source).toContain("folder: s.folder ?? ''");+ expect(source).toContain("fetchAllEntities(caseState.current.id, { types: ['proof'] })");+ expect(source).toContain('folders.get(entry.spec_path)');+ });+});++describe('Proof Composer empty canvas', () => {+ it('keeps the drawing rail out until a proof is open', () => {+ const rail = source.slice(source.indexOf('<div class="body">'), source.indexOf('<ProofCanvas'));++ expect(rail).toContain('{#if proofStarted}');+ expect(rail).toContain('<ProofToolbar');+ });+});+describe('Proof Composer panel pointer lifecycle', () => {function fakeGroup() {const handlers = new Map();@@ -173,3 +255,175 @@ describe('Proof Composer canvas render gate', () => {expect(rebuild).not.toHaveBeenCalled();});});++describe('Proof Composer panel previews', () => {+ it('builds picker cells from the cached thumbnail, never the full-size image', () => {+ // a satellite capture is a multi-megabyte PNG: rendering it in a 150px cell+ // is what made "Add panel" and "New proof" crawl+ expect(source).toContain("import { pollWhile } from '../lib/poll.js'");+ expect(source).toContain('...panelPreview(s)');+ expect(source).toContain('...panelPreview(m)');+ expect(source).not.toContain('thumb: s.path');+ expect(source).not.toContain('thumb: m.thumbnail ?? m.path');+ });++ it('renders a placeholder instead of an <img> while a thumbnail is missing', () => {+ expect(source).toContain('{#if item.thumb}');+ expect(source).toContain('{:else if item.thumbPending}');+ });++ it('re-lists the picker while the worker is still generating thumbnails', () => {+ expect(source).toContain(+ "const pickerThumbsPending = $derived(pickerItems.some((i) => i.thumbPending));"+ );+ expect(source).toContain(+ 'pollWhile(() => pickerThumbsPending, () => refreshPickerItems(), 1500)'+ );+ });+});++describe('Proof Composer saved-proof list', () => {+ it('never blocks the list on the full-resolution export', () => {+ // the saved PNG is the export itself; it is decoded lazily and off the+ // main thread so opening the list stays instant+ const row = source.slice(source.indexOf('<div class="open-list">'), source.indexOf('open-del'));+ expect(row).toContain('loading="lazy"');+ expect(row).toContain('decoding="async"');+ });++ it('shows the export thumbnail, falling back to the export itself', () => {+ // a proof saved before thumbnails existed has none until the listing+ // backfills it, and one that could not be rendered never gets one+ const row = source.slice(source.indexOf('<div class="open-list">'), source.indexOf('open-del'));+ expect(row).toContain('{#if entry.thumb || entry.png}');+ expect(row).toContain('${entry.thumb ?? entry.png}');+ });+});++describe('Proof naming', () => {+ it('names a fresh proof "Proof N", numbered past the case', () => {+ expect(source).toContain("const freshTitle = () => nextName('proof', savedProofTitles());");+ expect(source).toContain("savedTitles(proofEntities, 'proof')");+ expect(source).not.toContain('Untitled proof');+ });++ it('names the proof in the header and nowhere else', () => {+ expect(source).toContain('<input\n class="input title-input"\n bind:value={proof.title}');+ expect(source).not.toContain('newProofName');+ });++ it('renames in place: saving sends the bound slug so the backend moves the file', () => {+ expect(source).toContain('rename_from: savedName,');+ expect(source).toContain('title: proof.title,');+ });++ it('asks before an unbound proof takes a name another proof holds', () => {+ expect(source).toContain("if (!savedName && savedProofNames().has(slugify(proof.title, 'proof')))");+ expect(source).toContain('title="Overwrite this proof?"');+ });+});++describe('Proof Composer pasted images', () => {+ it('keeps a pasted image out of the case: no panel, no source, no media', () => {+ // it goes into its own array, so nothing that walks `panels` can mistake it+ // for evidence — the save files derived-from edges from panels alone+ expect(source).toContain("title: '', panels: [], pastes: []");+ expect(source).not.toContain('proof.panels.push(paste');+ expect(source).toContain('proof.pastes.unshift(paste)');+ // the picker and the ingest are never involved+ expect(source).toContain('accept="image/png,image/jpeg,image/webp"');+ expect(source).not.toContain('/api/cases/${c.id}/media');+ });++ it('needs a panel before an image has anywhere to land', () => {+ expect(source).toContain('if (!proof.panels.length) {');+ expect(source).toContain('Add a panel before adding an overlay');+ });++ it('lets one paste handler decide between an image and a copied annotation', () => {+ expect(source).toContain('onpaste={onPaste}');+ expect(source).toContain("i.type.startsWith('image/')");+ expect(source).toContain('} else if (clipboard) {');+ // the old Ctrl+V keydown branch would have swallowed the paste event+ expect(source).not.toContain("k === 'v' && clipboard");+ // and a paste into the title or a caption stays text+ expect(source).toContain('isTextTarget(e.target)');+ });++ it('offers the file picker and the drop as well as Ctrl+V', () => {+ expect(source).toContain('{pickImageFile}');+ expect(source).toContain("containerEl.addEventListener('drop', onCanvasDrop)");+ // the drawing rail stays about drawing: adding an overlay lives in its own+ // side section, and pasting is the shortcut+ const rail = source.slice(source.indexOf('<ProofToolbar'), source.indexOf('<ProofCanvas'));+ expect(rail).not.toContain('pickImageFile');+ expect(source).not.toContain('navigator.clipboard.read');+ });++ it('sends a pasted image once, with the save that references it', () => {+ expect(source).toContain('.filter(({ entry }) => entry?.pending && entry.data)');+ expect(source).toContain('assets,');+ expect(source).toContain('if (entry) entry.pending = false;');+ // no upload endpoint of its own: an unsaved proof leaves nothing behind+ expect(source).not.toContain('/assets/upload');+ });++ it('reads pasted images back from the proof folder on open', () => {+ expect(source).toContain('proofs/${entry.name}.assets/${p.asset}');+ expect(source).toContain("pasteAssets.set(p.asset, { img, data: null, pending: false })");+ // annotations bound to a paste survive the reload with it+ expect(source).toContain('const validSurfaces = new Set([...proof.panels, ...proof.pastes]');+ });++ it('never lets a pasted image change the size of the document', () => {+ // docSize is measured from panels and shapes only, and a drag is clamped+ expect(source).toContain('docSize(proof.panels, proof.shapes');+ expect(source).toContain('Object.assign(paste, clampPaste(paste, width, height))');+ });++ it('draws pasted images over the panels and the legend', () => {+ const rebuild = source.slice(source.indexOf('function rebuild()'), source.indexOf("const st = proof.signatureText"));+ expect(rebuild.indexOf('for (let i = proof.panels.length - 1')).toBeLessThan(+ rebuild.indexOf('for (let i = proof.pastes.length - 1')+ );+ // and each one hosts its own annotations, like a panel does+ expect(rebuild).toContain('for (const s of proof.shapes.filter((x) => x.panel === paste.id))');+ });++ it('resizes a pasted image from its corners with the aspect locked', () => {+ expect(source).toContain('transformer.keepRatio(!!sigNode || !!pasteNode)');+ expect(source).toContain('implied < PASTE_SCALE_MIN || implied > PASTE_SCALE_MAX');+ expect(source).toContain('|| pasteNode || sigNode');+ });++ it('drops a pasted image with its annotations, and only one thing is selected', () => {+ expect(source).toContain('proof.shapes.filter((s) => s.panel !== paste.id)');+ expect(source).toContain('selectedPasteId = null');+ expect(source).toContain('removePaste(proof.pastes.findIndex((p) => p.id === selectedPasteId))');+ });+});++describe('Proof Composer frames', () => {+ const layers = readFileSync(new URL('./proof/ProofLayersPanel.svelte', import.meta.url), 'utf8');++ it('offers the same colour and thickness control on a panel and on a pasted image', () => {+ expect(layers).toContain('{#snippet frameControl(item)}');+ expect(layers.match(/\{@render frameControl\(/g)).toHaveLength(2);+ expect(layers).toContain('aria-label="border thickness"');+ expect(layers).toContain('setFrame(item, null)');+ });++ it('is decoration: a frame never reaches the legend', () => {+ // the legend is built from shape colours; frames are not shapes+ expect(source).toContain('orderedFeatureColors(proof.shapes');+ expect(source).not.toContain('orderedFeatureColors([...proof.shapes');+ expect(source).toContain('if (panel.frame) group.add(frameNode(panel.frame, panel.natural))');+ expect(source).toContain('if (paste.frame) group.add(frameNode(paste.frame, paste.natural))');+ });++ it('draws the border inset so it cannot move the layout', () => {+ const fn = source.slice(source.indexOf('function frameNode('), source.indexOf('// ---- rebuild canvas'));+ expect(fn).toContain('x: w / 2, y: w / 2');+ expect(fn).toContain('natural[0] - w');+ });+});diff --git a/frontend/src/tools/ReverseSearch.svelte b/frontend/src/tools/ReverseSearch.svelteindex 6552145..1907c12 100644--- a/frontend/src/tools/ReverseSearch.svelte+++ b/frontend/src/tools/ReverseSearch.svelte@@ -9,19 +9,48 @@// image via a same-origin canvas — nothing leaves the machine until an// engine tab is opened by the analyst.import { api } from '../lib/api.js';+ import { matchesTerms } from '../lib/folderBrowse.js';import { caseState, uiState, toast } from '../lib/state.svelte.js';import { UPLOAD_PAGES } from '../lib/reverseSearch.js';import Modal from '../components/Modal.svelte';import Icon from '../components/Icon.svelte';+ import SearchInput from '../components/SearchInput.svelte';+ import FolderBrowser from '../components/FolderBrowser.svelte';const PASTE = UPLOAD_PAGES.filter((e) => e.paste);const DRAG = UPLOAD_PAGES.filter((e) => !e.paste);+ const MEDIA_FILTERS = [+ { id: 'all', label: 'All' },+ { id: 'image', label: 'Images' },+ { id: 'video', label: 'Video' },+ { id: 'capture', label: 'Captures' },+ { id: 'frame', label: 'Frames' },+ { id: 'collage', label: 'Collages' },+ ];let pickerOpen = $state(false);let mediaLibrary = $state([]);+ let mediaQuery = $state('');+ let mediaFilter = $state('all');+ let pickerBrowserOpen = $state(false);+ let pickerBrowsePath = $state('');+ let pickerBrowseSelection = $state(null);let selected = $state(null); // the chosen media item, or nulllet videoEl = $state(null); // the <video> element, when a video is selected+ const searchableMedia = $derived(mediaLibrary.filter((m) => m.kind === 'image' || m.kind === 'video'));+ const filteredPickerMedia = $derived(+ mediaFilter === 'all' ? searchableMedia : searchableMedia.filter((m) => mediaCategory(m) === mediaFilter)+ );+ const pickableMedia = $derived(+ mediaQuery.trim()+ ? filteredPickerMedia.filter((m) => matchesMediaName(m, mediaQuery))+ : filteredPickerMedia+ );+ const pickerBrowserEntries = $derived(+ filteredPickerMedia.map((m) => ({ ...m, id: m.path, attrs: { folder: m.folder ?? '' } }))+ );+// -- adjustments (client-side CSS filters, baked into the export) -----------const NEUTRAL = { brightness: 100, contrast: 100, saturate: 100, grayscale: 0 };let adjust = $state({ ...NEUTRAL });@@ -48,6 +77,11 @@toast('Open a case to search its media', 'warn');return;}+ mediaQuery = '';+ mediaFilter = 'all';+ pickerBrowserOpen = false;+ pickerBrowsePath = '';+ pickerBrowseSelection = null;try {mediaLibrary = await api.get(`/api/cases/${caseState.current.id}/media`);pickerOpen = true;@@ -62,6 +96,54 @@pickerOpen = false;}+ function matchesMediaName(item, query) {+ return matchesTerms(item.title || item.filename || '', query);+ }++ function mediaCategory(item) {+ const source = item.source ?? {};+ if (source.type === 'satellite' || source.type === 'screenshot') return 'capture';+ if (source.op === 'collage') return 'collage';+ if (source.op === 'frame' || source.op === 'adjust') return 'frame';+ return item.kind;+ }++ function openPickerBrowser() {+ mediaQuery = '';+ pickerBrowsePath = '';+ pickerBrowseSelection = null;+ pickerBrowserOpen = true;+ }++ function togglePickerBrowser() {+ if (pickerBrowserOpen) {+ pickerBrowserOpen = false;+ return;+ }+ openPickerBrowser();+ }++ function setMediaFilter(filter) {+ mediaFilter = filter;+ pickerBrowsePath = '';+ pickerBrowseSelection = null;+ }++ function openPickerFolder(path) {+ pickerBrowsePath = path;+ pickerBrowseSelection = null;+ }++ function confirmPickerBrowser() {+ const item = pickerBrowserEntries.find((m) => m.path === pickerBrowseSelection);+ if (item) pickMedia(item);+ }++ function selectPickerBrowser(item, confirm = false) {+ pickerBrowseSelection = item.path;+ if (confirm) pickMedia(item);+ }+function discard() {selected = null;resetAdjust();@@ -158,7 +240,7 @@<div class="empty-icon"><Icon name="search" size={42} /></div><h3>Reverse image search</h3><p>Pick a case photo, or a video to grab a frame from, then send it to the engines.</p>- <button class="btn btn-primary" onclick={openPicker}>+ <button class="btn btn-sm" onclick={openPicker}><Icon name="image" size={15} /> Pick from case</button><div class="fallback">@@ -270,25 +352,70 @@{#if pickerOpen}<Modal title="Pick a case image or video" width="640px" onclose={() => (pickerOpen = false)}>- {#if mediaLibrary.length === 0}- <p class="picker-empty">No media in this case yet. Import or download some in the Media tab.</p>- {:else}- <div class="picker-grid">- {#each mediaLibrary as item (item.path)}- <button class="picker-item" onclick={() => pickMedia(item)} title={item.path}>- <div class="picker-thumb">- {#if item.thumbnail}- <img src={`/files/${caseState.current.id}/${item.thumbnail}`} alt={item.path} />- {:else}- <Icon name={item.kind === 'video' ? 'video' : 'image'} size={24} />- {/if}- {#if item.kind === 'video'}<span class="kind-badge"><Icon name="video" size={11} /></span>{/if}- </div>- <span class="picker-name">{nameOf(item)}</span>- </button>- {/each}+ <div class="picker-content">+ <div class="picker-search">+ <SearchInput bind:value={mediaQuery} placeholder="Search names…" width="100%" />+ <button class="btn btn-ghost btn-sm browse-btn" title="Browse folders" onclick={togglePickerBrowser}>…</button></div>- {/if}++ {#if searchableMedia.length === 0}+ <p class="picker-empty">No images or videos in this case yet. Import or download some in the Media tab.</p>+ {:else}+ <div class="picker-filters" aria-label="Media type">+ {#each MEDIA_FILTERS as filter (filter.id)}+ <button+ class="btn btn-ghost btn-sm"+ class:active={mediaFilter === filter.id}+ aria-pressed={mediaFilter === filter.id}+ onclick={() => setMediaFilter(filter.id)}+ >+ {filter.label}+ </button>+ {/each}+ </div>++ {#if pickerBrowserOpen}+ <FolderBrowser+ entries={pickerBrowserEntries}+ path={pickerBrowsePath}+ rootLabel="Case media"+ selectedId={pickerBrowseSelection}+ matches={(m) => matchesMediaName(m, mediaQuery)}+ emptyText="This folder has no matching media."+ icon={(m) => (m.kind === 'video' ? 'video' : 'image')}+ label={(m) => m.title || m.filename}+ onnavigate={openPickerFolder}+ onselect={(m) => selectPickerBrowser(m)}+ onconfirm={(m) => selectPickerBrowser(m, true)}+ />+ <div class="modal-actions">+ <button class="btn btn-primary btn-sm" disabled={!pickerBrowseSelection} onclick={confirmPickerBrowser}>Use selected</button>+ </div>+ {:else if pickableMedia.length === 0}+ <p class="modal-hint">No media matches this filter.</p>+ {:else}+ <div class="picker-list">+ {#each pickableMedia as item (item.path)}+ <button class="picker-open" onclick={() => pickMedia(item)} title={item.path}>+ <div class="picker-thumb">+ {#if item.thumbnail}+ <img src={`/files/${caseState.current.id}/${item.thumbnail}`} alt="" loading="lazy" />+ {:else}+ <Icon name={item.kind === 'video' ? 'video' : 'image'} size={22} />+ {/if}+ </div>+ <span class="picker-copy">+ <span class="picker-title">{item.title || item.filename}</span>+ <span class="picker-meta">+ {mediaCategory(item)}{item.folder ? ` · ${item.folder}` : ''}{item.title && item.filename !== item.title ? ` · ${item.filename}` : ''}+ </span>+ </span>+ </button>+ {/each}+ </div>+ {/if}+ {/if}+ </div></Modal>{/if}@@ -492,39 +619,80 @@}/* picker modal */+ .picker-content {+ display: flex;+ flex-direction: column;+ gap: 12px;+ }.picker-empty {color: var(--text-3);font-size: var(--fs-sm);padding: 8px;}- .picker-grid {- display: grid;- grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));+ .modal-hint {+ color: var(--text-3);+ font-size: var(--fs-sm);+ margin: 0;+ }+ .modal-actions {+ display: flex;+ justify-content: flex-end;gap: 8px;}- .picker-item {+ .picker-search {+ display: flex;+ align-items: center;+ gap: 6px;+ }+ .picker-search :global(.search-box) {+ flex: 1;+ }+ .browse-btn {+ min-width: 30px;+ font-size: var(--fs-lg);+ line-height: 1;+ }+ .picker-filters {+ display: flex;+ gap: 4px;+ overflow-x: auto;+ padding-bottom: 2px;+ }+ .picker-filters .active {+ color: var(--text-1);+ background: var(--bg-3);+ }+ .picker-list {display: flex;flex-direction: column;- gap: 5px;- padding: 6px;- background: var(--bg-2);- border: 1px solid var(--border);- border-radius: 4px;- cursor: pointer;+ gap: 6px;+ max-height: min(52vh, 480px);+ overflow: auto;+ }+ .picker-open {+ display: flex;+ align-items: center;+ gap: 10px;+ width: 100%;+ padding: 7px;text-align: left;+ border: 1px solid var(--border);+ border-radius: var(--r-md);+ background: var(--bg-2);}- .picker-item:hover {- border-color: var(--border-strong);+ .picker-open:hover {+ border-color: var(--accent);+ background: var(--bg-3);}.picker-thumb {- position: relative;- aspect-ratio: 4 / 3;- display: flex;- align-items: center;- justify-content: center;- background: var(--bg-0);- border-radius: 3px;+ display: grid;+ place-items: center;+ width: 48px;+ height: 40px;+ flex-shrink: 0;overflow: hidden;+ border-radius: var(--r-sm);+ background: var(--bg-0);color: var(--text-3);}.picker-thumb img {@@ -532,19 +700,25 @@height: 100%;object-fit: cover;}- .kind-badge {- position: absolute;- bottom: 3px;- right: 3px;- display: inline-flex;- padding: 2px;- background: rgba(0, 0, 0, 0.6);- border-radius: 3px;+ .picker-copy {+ display: flex;+ flex-direction: column;+ min-width: 0;+ gap: 2px;}- .picker-name {- font-size: var(--fs-xs);+ .picker-title,+ .picker-meta {overflow: hidden;text-overflow: ellipsis;white-space: nowrap;}+ .picker-title {+ color: var(--text-1);+ font-size: var(--fs-sm);+ font-weight: 600;+ }+ .picker-meta {+ color: var(--text-3);+ font-size: var(--fs-xs);+ }</style>diff --git a/frontend/src/tools/ReverseSearch.test.js b/frontend/src/tools/ReverseSearch.test.jsnew file mode 100644index 0000000..d55a8ae--- /dev/null+++ b/frontend/src/tools/ReverseSearch.test.js@@ -0,0 +1,37 @@+import { describe, expect, it } from 'vitest';+import { readFileSync } from 'node:fs';++const source = readFileSync(new URL('./ReverseSearch.svelte', import.meta.url), 'utf8');++describe('Reverse Search case picker', () => {+ it('starts from a searchable image/video media list', () => {+ expect(source).toContain("import SearchInput from '../components/SearchInput.svelte'");+ expect(source).toContain("m.kind === 'image' || m.kind === 'video'");+ expect(source).toContain('bind:value={mediaQuery}');+ expect(source).toContain('filteredPickerMedia.filter((m) => matchesMediaName(m, mediaQuery))');+ expect(source).toContain('{#each pickableMedia as item (item.path)}');+ expect(source).toContain('placeholder="Search names…"');+ expect(source).toContain('function matchesMediaName(item, query)');+ expect(source).toContain("matchesTerms(item.title || item.filename || '', query)");+ });++ it('separates reverse-search sources by media type and provenance', () => {+ expect(source).toContain("{ id: 'all', label: 'All' }");+ expect(source).toContain("{ id: 'capture', label: 'Captures' }");+ expect(source).toContain("{ id: 'frame', label: 'Frames' }");+ expect(source).toContain("{ id: 'collage', label: 'Collages' }");+ expect(source).toContain("source.type === 'satellite' || source.type === 'screenshot'");+ expect(source).toContain("source.op === 'frame' || source.op === 'adjust'");+ expect(source).toContain("source.op === 'collage'");+ });++ it('offers the same read-only folder browser as Inspect', () => {+ expect(source).toContain("import FolderBrowser from '../components/FolderBrowser.svelte'");+ expect(source).toContain('title="Browse folders"');+ expect(source).toContain('onconfirm={(m) => selectPickerBrowser(m, true)}');+ expect(source).toContain('disabled={!pickerBrowseSelection} onclick={confirmPickerBrowser}');+ expect(source).toContain('function togglePickerBrowser()');+ expect(source).toContain('Use selected');+ });++});diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelteindex e74d5a9..c3c663c 100644--- a/frontend/src/tools/Satellite.svelte+++ b/frontend/src/tools/Satellite.svelte@@ -3,7 +3,7 @@import L from 'leaflet';import 'leaflet/dist/leaflet.css';import { api } from '../lib/api.js';- import { fetchAllEntities } from '../lib/catalog.js';+ import { filterSaved, isMode, pendingLocate } from '../lib/geoTree.js';import {caseState, uiState, ensureCase, reloadCase, toast, prefs, fmtCoords, prefsReady,} from '../lib/state.svelte.js';@@ -12,6 +12,8 @@import * as gridSearch from '../lib/gridSearch.js';import { dragBearing, pivotPanOffset } from '../lib/satRotate.js';import { clampSize, scaledCapture } from '../lib/captureSize.js';+ import { panelWidth } from '../lib/panelWidth.js';+ import { assignFolder } from '../lib/filing.js';import { isRegistered, sourceRect, frameFitsView } from '../lib/screenCrop.js';import { extensionVersion, captureTab, onActivated } from '../lib/extBridge.js';import {@@ -40,44 +42,73 @@} from '../lib/sentinel.js';import { createViewer, nextZ, restack } from '../lib/refViewers.js';import { loadGoogleMaps, createSatelliteMutant } from '../lib/gmaps.js';+ import { matchesQuery } from '../lib/mediaFilter.js';import Icon from '../components/Icon.svelte';import Modal from '../components/Modal.svelte';+ import SearchInput from '../components/SearchInput.svelte';+ import FolderBrowser from '../components/FolderBrowser.svelte';import ConfirmDialog from '../components/ConfirmDialog.svelte';+ import FolderSelect from '../components/FolderSelect.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';+ import SavedTree from './satellite/SavedTree.svelte';+ import SavedSearch from './satellite/SavedSearch.svelte';+ import SavedOverlay from './satellite/SavedOverlay.svelte';let mapEl;- let toolEl; // tool root — target of the real (browser) fullscreen (item 5)- let map;+ let toolEl; // Browser fullscreen target.+ let map = $state.raw(null);let tileLayer;let providers = $state([]);let providerId = $state('esri-world-imagery');let coordsText = $state('');- // opens on the user's home view (Settings → Preferences) until a case- // artifact or a "go to coords" handoff points the map somewhere else.- // Seeded from the defaults, then re-read under `prefsReady` in onMount —- // a deep link to #satellite mounts this before the settings fetch lands.+ // Start at the saved home view unless case navigation supplies a position.+ // Re-read after preferences load because deep links can mount first.let center = $state({ ...prefs.homeView });- let markerStyle = $state('none'); // 'crosshair' | 'pin' | 'none' — clean view by default (item 4)+ let markerStyle = $state('none'); // 'crosshair' | 'pin' | 'none'let moveMode = $state(false); // pin decoupled from center, draggablelet marker = null; // Leaflet marker instance while in move modelet markerLatLng = $state(null); // {lat, lon} of the moved pinlet bearing = $state(0);- // Middle-drag rotation: a sober "target" marks the grabbed point and the map- // turns around it (Google-Earth style, mirrors the Frame viewer).+ // Middle-drag rotates the map around the grabbed point.let rotating = $state(false);let rotatePivot = $state({ x: 0, y: 0 }); // grabbed point, map-wrap-local pxlet capturing = $state(false);let captureHover = $state(false); // previewing the crop frame (capture group hover)let hideOverlays = $state(false); // frame/marquee outlines must not land in a screen crop- let captures = $state([]);- let capturesFor = $state(null);+ // One compact Saved index for places, captures and filed screenshots.+ let saved = $state([]);+ let savedKind = $state('all');+ let savedQuery = $state('');+ let savedSearchOpen = $state(false);+ let savedOverlay = $state(false); // map layer: off by default, session only+ // Persist geography or My-work folder grouping across reloads.+ const GROUP_KEY = 'azimut:satelliteSavedGroup';+ let savedGroup = $state(loadSavedGroup());+ let hoveredSavedId = $state(null); // shared by the tree, the modal and the map+ // Proofs use a separate mode because they can borrow capture coordinates.+ // Fetch them only when that mode opens.+ let savedProofs = $state([]);+ let savedFor = null; // case id held by both Saved indexes+ let proofsFor = null; // the case id savedProofs was loaded for+ const savedRows = $derived(isMode(savedKind) ? savedProofs : saved);+ // The map layer follows the Saved panel filter.+ const savedShown = $derived(filterSaved(savedRows, { kind: savedKind, query: savedQuery }));+ let revealSavedId = $state(null);let capturesCollapsed = $state(false);- let capturesSubCollapsed = $state(false);- let focusedCapturePath = $state(null);+ // the Saved panel's left edge is a drag handle; the width sticks across reloads+ const savedPanel = panelWidth({+ key: 'azimut:satelliteSavedW',+ min: 260,+ max: 560,+ def: 300,+ fraction: 0.4,+ });+ let savedW = $state(savedPanel.loadWidth());+ let savedResizing = $state(false);let mapReady = $state(false);// OSM labels overlay: a transparent labels-only layer laid over the imagery so@@ -280,10 +311,27 @@let refPicker = $state(false); // the "pick an image" modallet refMedia = $state([]); // case images available to referencelet refLoading = $state(false);+ let refQuery = $state('');+ let refBrowserOpen = $state(false); // "…" swaps the grid for the folder browser+ let refBrowsePath = $state('');+ let refBrowseSelection = $state(null);let refSeq = 0; // id source for spawned windows+ const REF_SEARCH_MIN = 6; // below that, the grid is easier to scan than to search++ // Same free-text match as the Media Library (filename, title, notes, folder,+ // download source), so what works there works here.+ const visibleRefMedia = $derived(+ caseState.current ? refMedia.filter((m) => matchesQuery(m, refQuery)) : []+ );+ const refBrowserEntries = $derived(+ refMedia.map((m) => ({ ...m, id: m.path, attrs: { folder: m.folder ?? '' } }))+ );async function openRefPicker() {refPicker = true;+ refQuery = '';+ resetRefBrowser();+ refBrowserOpen = false;refLoading = true;try {const id = caseState.current?.id;@@ -297,6 +345,31 @@}}+ function resetRefBrowser() {+ refBrowsePath = '';+ refBrowseSelection = null;+ }++ function toggleRefBrowser() {+ if (refBrowserOpen) {+ refBrowserOpen = false;+ return;+ }+ refQuery = '';+ resetRefBrowser();+ refBrowserOpen = true;+ }++ function openRefFolder(path) {+ refBrowsePath = path;+ refBrowseSelection = null;+ }++ function confirmRefBrowser() {+ const item = refBrowserEntries.find((entry) => entry.path === refBrowseSelection);+ if (item) addRef(item);+ }+function addRef(item) {const vs = uiState.refViewers;const n = vs.length;@@ -881,11 +954,16 @@const externalLinks = $derived(mapLinks(displayCoords.lat, displayCoords.lon, center.zoom));// fly the map to a capture's recorded point (item 7)- function flyToCapture(item) {- // ingest captures can arrive without coordinates (nothing in the URL)- if (!map || item.lat == null || item.lon == null) return;- map.setView([item.lat, item.lon], item.zoom || map.getZoom());- setBearing(item.bearing || 0);+ /** Open one saved item: fly the map to it, or — for a screenshot of a site we+ * cannot embed, filed without coordinates — reopen the page it came from. */+ function openSaved(row) {+ if (row.lat == null || row.lon == null) {+ if (row.source_url && !fullscreen) window.open(row.source_url, '_blank', 'noopener,noreferrer');+ return;+ }+ if (!map) return;+ map.setView([row.lat, row.lon], Number(row.zoom) || map.getZoom());+ setBearing(Number(row.bearing) || 0);}// --- tile seam fix ---@@ -1054,23 +1132,60 @@$effect(() => {const id = caseState.current?.id;caseState.rev; // re-fetch when the case is reloaded elsewhere (e.g. sidebar delete)+ if (savedFor !== id) {+ savedFor = id;+ saved = [];+ savedProofs = [];+ proofsFor = null;+ savedSearchOpen = false;+ hoveredSavedId = null;+ revealSavedId = null;+ deleteTarget = null;+ notesItem = null;+ placeModal = null;+ locateStopped = true;+ locateGeneration += 1;+ locating = null;+ }if (!id) {- capturesFor = null;- captures = [];return;}- capturesFor = id;- api.get(`/api/cases/${id}/satellite`).then((r) => (captures = r));+ let live = true;+ api+ .get(`/api/cases/${id}/satellite/index`)+ .then((rows) => { if (live) saved = rows; })+ .catch(() => { if (live) saved = []; });+ return () => { live = false; };+ });++ // The proofs index, read the first time the Proofs position is opened. Keyed+ // on the case *and its revision*: filing or saving a proof reloads the case,+ // and a stale list would still show the folder the proof just left.+ $effect(() => {+ const id = caseState.current?.id;+ const stamp = `${id}:${caseState.rev}`;+ if (!id || !isMode(savedKind) || proofsFor === stamp) return;+ proofsFor = stamp;+ let live = true;+ api+ .get(`/api/cases/${id}/proofs/index`)+ .then((rows) => { if (live) savedProofs = rows; })+ .catch(() => { if (live) { savedProofs = []; proofsFor = null; } });+ return () => { live = false; };});+ // another workspace asked to show one capture: clear whatever filter is on so+ // it can't be hidden, then let the tree open its branch and scroll to it$effect(() => {const path = uiState.focusCapture;- if (!path || !captures.some((capture) => capture.path === path)) return;+ if (!path) return;+ const row = saved.find((item) => item.path === path);+ if (!row) return;uiState.focusCapture = null;capturesCollapsed = false;- capturesSubCollapsed = false;- focusedCapturePath = path;- requestAnimationFrame(() => document.querySelector(`[data-capture-path="${CSS.escape(path)}"]`)?.scrollIntoView({ behavior: 'smooth', block: 'nearest' }));+ savedKind = 'all';+ savedQuery = '';+ revealSavedId = row.id;});// the map container resizes when the sidebar toggles or is dragged wider, and@@ -1297,7 +1412,6 @@// other provider's is Esri's best-effort estimate or nothingimagery_date: s2PinnedDate ?? imageryDate?.date ?? null,});- captures = [result, ...captures];await reloadCase();toast(result.tiles_missing@@ -1461,7 +1575,6 @@form.append('provider', currentProvider.id);form.append('framed', String(!!framed));const result = await api.post(`/api/cases/${c.id}/satellite/screenshot`, form);- captures = [result, ...captures];await reloadCase();toast(framed@@ -2212,27 +2325,25 @@}}- // Deletions drop a file / an entity — always behind a confirm.- // { kind: 'capture', item } | { kind: 'place', item }+ // Deletions drop a file / an entity — always behind a confirm. The target is+ // a saved-index row; its kind says which of the two it is.let deleteTarget = $state(null);let deleteBusy = $state(false);- async function removeCapture(item) {- await api.del(- `/api/cases/${caseState.current.id}/satellite?path=${encodeURIComponent(item.path)}`- );- captures = captures.filter((c) => c.path !== item.path);- // the capture's place entity may have gone with it — refresh the sidebar- await reloadCase();- }-async function confirmDelete() {if (!deleteTarget || deleteBusy) return;deleteBusy = true;+ const row = deleteTarget;try {- if (deleteTarget.kind === 'capture') await removeCapture(deleteTarget.item);- else await removePlace(deleteTarget.item);+ if (row.kind === 'place') {+ await api.del(`/api/cases/${caseState.current.id}/entities/${row.id}`);+ } else {+ await api.del(+ `/api/cases/${caseState.current.id}/satellite?path=${encodeURIComponent(row.path)}`+ );+ }deleteTarget = null;+ await reloadCase(); // re-reads the saved index and the case sidebar} catch (e) {toast(e.message, 'danger');} finally {@@ -2240,28 +2351,34 @@}}+ /** The edit action, for whichever kind of row it was pressed on. */+ function editSaved(row) {+ if (row.kind === 'place') openEditPlace(row);+ else openNotes(row);+ }+// --- details modal (title + notes) ---let notesItem = $state(null);let notesText = $state('');let notesTitle = $state('');+ let notesFolder = $state('');let notesSaving = $state(false);- function openNotes(item) {- notesItem = item;- notesText = item.notes ?? '';- notesTitle = item.title ?? coordsLabel(item);+ function openNotes(row) {+ notesItem = row;+ notesText = row.notes ?? '';+ notesTitle = row.title ?? coordsLabel(row);+ notesFolder = row.folder ?? '';}async function saveNotes() {if (!notesItem) return;notesSaving = true;try {- const updated = await api.patch(+ await api.patch(`/api/cases/${caseState.current.id}/satellite`,- { path: notesItem.path, notes: notesText, title: notesTitle }+ { path: notesItem.path, notes: notesText, title: notesTitle, folder: notesFolder });- const idx = captures.findIndex((c) => c.path === notesItem.path);- if (idx !== -1) captures[idx] = updated;notesItem = null;// the mirrored place entity was retitled too — refresh the sidebarawait reloadCase();@@ -2277,11 +2394,23 @@return fmtCoords(item.lat, item.lon);}+ // One action, two directions: a capture goes *into* a new proof, a proof row+ // opens the proof it already is.function sendToComposer(item) {- if (!uiState.composeQueue.includes(item.path)) uiState.composeQueue.push(item.path);+ if (item.kind === 'proof') {+ uiState.openProof = item.name;+ } else if (!uiState.composeQueue.includes(item.path)) {+ uiState.composeQueue.push(item.path);+ }uiState.tool = 'proof';}+ function openLinkedPost(post) {+ if (!post.name) return;+ uiState.openDraft = post.name;+ uiState.tool = 'post';+ }+// the HUD readout and everything copied out of it follow the user's// coordinate format (Settings → Preferences); captures keep decimal degreesconst readout = $derived(fmtCoords(displayCoords.lat, displayCoords.lon));@@ -2298,41 +2427,164 @@map?.invalidateSize();}- // 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([]);+ function loadSavedGroup() {+ try {+ return localStorage.getItem(GROUP_KEY) === 'folders' ? 'folders' : 'geo';+ } catch {+ return 'geo'; // localStorage unavailable (private mode) — non-fatal+ }+ }+$effect(() => {- const id = caseState.current?.id;- caseState.rev; // re-read after a place is added/removed here or elsewhere- if (!id) {- places = [];- return;+ try {+ localStorage.setItem(GROUP_KEY, savedGroup);+ } catch {+ /* ignore */}- 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);- const lon = Number(p.attrs?.lon);- if (!map || !Number.isFinite(lat) || !Number.isFinite(lon)) return;- map.setView([lat, lon], Number(p.attrs?.zoom) || map.getZoom());- setBearing(Number(p.attrs?.bearing) || 0);+ // File a saved item into a My-work folder, dropped onto a folder in the+ // panel. One PATCH through the shared filing route (a capture's sidecar is+ // the authority, a place carries the folder itself), then the case reload+ // every other edit here does: the index, the sidebar and the map overlay all+ // read the new filing from it.+ async function moveSaved(row, folder) {+ // the row's kind *is* its entity type, bar the screenshot that rides the+ // capture type. Filing a proof as a capture would route it to PATCH /media,+ // the sidecar of an image it is not.+ const entity = {+ id: row.id,+ type: row.kind === 'place' ? 'place' : row.kind === 'proof' ? 'proof' : 'capture',+ attrs: { path: row.path },+ };+ try {+ await assignFolder(caseState.current.id, entity, folder);+ await reloadCase();+ toast(folder ? `Filed in ${folder}` : 'Removed from My work', 'ok', 1600);+ } catch (e) {+ toast(e.message, 'danger');+ }+ }++ // --- resize: the Saved panel's left edge is a drag handle ---+ const SAVED_KEY_STEP = 16;++ function setSavedWidth(w) {+ savedW = savedPanel.clampWidth(w, window.innerWidth);}- async function removePlace(p) {- await api.del(`/api/cases/${caseState.current.id}/entities/${p.id}`);- await reloadCase();+ function startSavedResize(e) {+ if (e.button !== 0) return;+ e.preventDefault(); // don't start a text selection under the cursor+ const startX = e.clientX;+ const startW = savedW;+ savedResizing = true;+ let frame = 0;+ // dragging left (a smaller clientX) widens the panel — it grows into the map+ const move = (ev) => {+ setSavedWidth(startW + startX - ev.clientX);+ // the map container shrank with it; one redraw per frame, not per event+ if (!frame) {+ frame = requestAnimationFrame(() => {+ frame = 0;+ map?.invalidateSize({ animate: false });+ });+ }+ };+ const up = () => {+ savedResizing = false;+ if (frame) cancelAnimationFrame(frame);+ map?.invalidateSize({ animate: false });+ savedPanel.saveWidth(savedW); // one write per drag, not one per frame+ window.removeEventListener('pointermove', move);+ window.removeEventListener('pointerup', up);+ };+ window.addEventListener('pointermove', move);+ window.addEventListener('pointerup', up);+ }++ async function onSavedResizeKey(e) {+ const step = { ArrowLeft: SAVED_KEY_STEP, ArrowRight: -SAVED_KEY_STEP }[e.key];+ if (step === undefined) return;+ e.preventDefault();+ setSavedWidth(savedW + step);+ savedPanel.saveWidth(savedW);+ await tick();+ map?.invalidateSize({ animate: false });}- // collapse state for the two saved-work sections- let placesCollapsed = $state(false);+ async function resetSavedWidth() {+ setSavedWidth(savedPanel.DEFAULT_W);+ savedPanel.saveWidth(savedW);+ await tick();+ map?.invalidateSize({ animate: false });+ }++ // A width dragged out on a wide screen would eat a narrower window whole, so+ // re-clamp against the viewport as it changes. The clamped-down value is not+ // written back — what the user actually chose is what a later session restores.+ $effect(() => {+ const onWindowResize = () => setSavedWidth(savedW);+ window.addEventListener('resize', onWindowResize);+ return () => window.removeEventListener('resize', onWindowResize);+ });++ // --- Locate: fill in the country of everything that still has none ---------+ // One batch per request (Nominatim is one lookup a second), looped until the+ // backlog is empty. Progress is the stored geography itself, so cancelling+ // keeps whatever was already resolved and a later pass picks up where this+ // one stopped.+ const LOCATE_BATCH = 10;+ let locating = $state(null); // { done, total } while a pass runs+ let locateStopped = false;+ let locateGeneration = 0;++ async function runLocate() {+ if (locating || !caseState.current) return;+ const id = caseState.current.id;+ const generation = ++locateGeneration;+ locateStopped = false;+ const total = pendingLocate(saved);+ locating = { done: 0, total };+ let located = 0;+ let failed = 0;+ try {+ let remaining = total;+ while (remaining > 0 && !locateStopped && generation === locateGeneration) {+ const batch = await api.post(+ `/api/cases/${id}/satellite/locate?limit=${LOCATE_BATCH}`+ );+ if (generation !== locateGeneration) return;+ located += batch.located;+ failed += batch.failed;+ // A batch that resolved nothing means the network is down, not that the+ // next one will do better: stop instead of hammering Nominatim forever.+ const stalled = batch.remaining >= remaining;+ remaining = batch.remaining;+ locating = { done: total - remaining, total };+ if (stalled) break;+ }+ if (generation !== locateGeneration) return;+ const rows = await api.get(`/api/cases/${id}/satellite/index`);+ if (generation !== locateGeneration) return;+ saved = rows;+ toast(+ failed+ ? `Located ${located} of ${total}. ${failed} lookup(s) failed; run Locate again to retry`+ : `Located ${located} of ${total}`,+ failed ? 'warn' : 'ok'+ );+ } catch (e) {+ if (generation === locateGeneration) {+ toast(`Locate stopped: ${e.message}`, 'danger', 6000);+ }+ } finally {+ if (generation === locateGeneration) locating = null;+ }+ }// --- place edit modal (title + notes), used for both save & later edits ---- // { id: string|null, title, notes, lat, lon, zoom, bearing }; id null = new+ // { id: string|null, title, notes, folder, lat, lon, zoom, bearing }; id null = newlet placeModal = $state(null);let placeSaving = $state(false);@@ -2341,6 +2593,7 @@id: null,title: '',notes: '',+ folder: '',lat: displayCoords.lat,lon: displayCoords.lon,zoom: center.zoom,@@ -2348,15 +2601,16 @@};}- function openEditPlace(p) {+ function openEditPlace(row) {placeModal = {- id: p.id,- title: p.label ?? '',- notes: p.attrs?.notes ?? '',- lat: Number(p.attrs?.lat),- lon: Number(p.attrs?.lon),- zoom: p.attrs?.zoom,- bearing: p.attrs?.bearing,+ id: row.id,+ title: row.title ?? '',+ notes: row.notes ?? '',+ folder: row.folder ?? '',+ lat: Number(row.lat),+ lon: Number(row.lon),+ zoom: row.zoom,+ bearing: row.bearing,};}@@ -2374,7 +2628,7 @@const title = m.title.trim() || placeCoordsLabel(m);await api.patch(`/api/cases/${caseState.current.id}/entities/${m.id}`, {label: title,- attrs: { notes: m.notes.trim() },+ attrs: { notes: m.notes.trim(), folder: m.folder ?? '' },});} else {const c = await ensureCase();@@ -2385,6 +2639,7 @@bearing: m.bearing,title: m.title,notes: m.notes,+ folder: m.folder,});}placeModal = null;@@ -2431,6 +2686,24 @@><div class="map" bind:this={mapEl}></div>+ <!-- saved work on the map: navigation only, off by default, session-only.+ It draws the panel's current selection, not the whole index. -->+ {#if savedOverlay}+ <SavedOverlay+ map={mapReady ? map : null}+ items={savedShown}+ caseId={caseState.current?.id}+ coords={coordsLabel}+ {fullscreen}+ bind:hoveredId={hoveredSavedId}+ onopen={openSaved}+ onedit={editSaved}+ onproof={sendToComposer}+ onpost={openLinkedPost}+ onshowproofs={() => (savedKind = 'proofs')}+ />+ {/if}+<!-- top-left control cluster: fullscreen, OSM labels overlay, measure tools --><div class="map-tools"><MapToolCluster@@ -2443,6 +2716,8 @@{toggleTools}{gridMode}{toggleGridMode}+ bind:savedOverlay+ savedCount={saved.length}referenceCount={uiState.refViewers.length}{openRefPicker}{setMeasureMode}@@ -2755,16 +3030,34 @@{/each}</div>- <aside class="captures" class:collapsed={capturesCollapsed}>+ <aside+ class="captures"+ class:collapsed={capturesCollapsed}+ class:resizing={savedResizing}+ style={capturesCollapsed ? undefined : `width: ${savedW}px`}+ >+ {#if !capturesCollapsed}+ <!-- a <button> rather than a bare div: the handle must be focusable and+ keyboard-driven (arrows resize), and the element carries that for free -->+ <button+ type="button"+ class="resizer"+ aria-label="Resize the saved panel"+ title="Drag to resize · double-click to reset"+ onpointerdown={startSavedResize}+ ondblclick={resetSavedWidth}+ onkeydown={onSavedResizeKey}+ ></button>+ {/if}<buttontype="button"class="cap-head"onclick={toggleCaptures}- title={capturesCollapsed ? 'Show captures' : 'Hide captures'}+ title={capturesCollapsed ? 'Show saved work' : 'Hide saved work'}><Icon name={capturesCollapsed ? 'chevronLeft' : 'chevronRight'} size={15} /><span class="label" style="margin:0">Saved</span>- <span class="count">{places.length + captures.length}</span>+ <span class="count">{saved.length}</span></button>{#if capturesCollapsed}<!-- collapsed: header acts as the toggle back to the list -->@@ -2809,177 +3102,27 @@</button>{/if}- <!-- Places: navigable points (no image) -->- <button- type="button"- class="sub-head"- onclick={() => (placesCollapsed = !placesCollapsed)}- >- <Icon name={placesCollapsed ? 'chevronRight' : 'chevronDown'} size={12} />- <Icon name="pin" size={13} />- <span>Places</span>- <span class="count">{places.length}</span>- </button>- {#if !placesCollapsed}- {#if !places.length}- <div class="none">Use “Save place” to drop a point you can fly back to.</div>- {:else}- <div class="place-list">- {#each places as p (p.id)}- <div class="place-row card">- <div class="place-main">- <button- type="button"- class="place-goto"- title="Fly the map to this point"- onclick={() => flyToPlace(p)}- >- <Icon name="pin" size={15} />- <div class="place-meta">- <span class="title">{p.label}</span>- <span class="prov">- z{p.attrs?.zoom}{p.attrs?.bearing ? ` · ${Math.round(p.attrs.bearing)}°` : ''}- </span>- </div>- </button>- <button- class="btn btn-ghost btn-sm"- title="Edit title & note"- onclick={() => openEditPlace(p)}- >- <Icon name="note" size={14} />- </button>- <button- class="btn btn-ghost btn-sm"- title="Delete place"- onclick={() => (deleteTarget = { kind: 'place', item: p })}- >- <Icon name="trash" size={14} />- </button>- </div>- {#if p.attrs?.notes}- <div class="place-notes">{p.attrs.notes}</div>- {/if}- </div>- {/each}- </div>- {/if}- {/if}-- <!-- Captures: sourced imagery crops (images) -->- <button- type="button"- class="sub-head"- onclick={() => (capturesSubCollapsed = !capturesSubCollapsed)}- >- <Icon name={capturesSubCollapsed ? 'chevronRight' : 'chevronDown'} size={12} />- <Icon name="satellite" size={13} />- <span>Captures</span>- <span class="count">{captures.length}</span>- </button>- {#if !capturesSubCollapsed}- {#if !captures.length}- <div class="none">- Captured crops land in the case with full provenance: provider, zoom, date,- attribution.- </div>- {:else}- <div class="cap-list">- {#each (caseState.current ? captures : []) as item (item.path)}- <div class="cap card" class:focused={focusedCapturePath === item.path} data-capture-path={item.path}>- <a- class="cap-goto"- class:disabled={fullscreen}- href={fullscreen ? undefined : `/files/${caseState.current.id}/${item.path}`}- target="_blank"- rel="noreferrer"- aria-disabled={fullscreen}- title={leavesFullscreen ?? 'Open the full image'}- >- <img- src={`/files/${caseState.current.id}/${item.path}`}- alt={item.filename}- loading="lazy"- />- <div class="cap-meta">- <span class="title">{item.title ?? coordsLabel(item)}</span>- <span class="mono coords">{coordsLabel(item)}</span>- <!-- ingest captures may have no zoom (URL carried none) -->- <span class="prov">{item.zoom != null ? `z${item.zoom}` : '—'}{item.bearing ? ` · ${Math.round(item.bearing)}°` : ''} · {item.provider_label ?? item.site}</span>- <span class="prov dates" title="Capture date · imagery acquisition date">- <Icon name="crosshair" size={10} /> {item.fetched_at?.slice(0, 10)}- {#if item.imagery_date}<span class="img-date"><Icon name="satellite" size={10} /> {item.imagery_date}</span>{/if}- </span>- </div>- </a>- <div class="cap-actions">- <button- class="btn btn-ghost btn-sm"- disabled={item.lat == null}- title={item.lat == null- ? 'No coordinates recorded for this capture'- : 'Go to these coordinates on the map'}- onclick={() => flyToCapture(item)}- >- <Icon name="crosshair" size={14} />- </button>- {#if item.source_url}- <!-- straight back to the page this was captured from — the- recorded URL itself, not a reconstruction -->- <a- class="btn btn-ghost btn-sm"- class:disabled={fullscreen}- href={fullscreen ? undefined : item.source_url}- target="_blank"- rel="noreferrer"- aria-disabled={fullscreen}- title={leavesFullscreen ?? `Open the source page (${item.site})`}- >- <Icon name="external" size={13} />- </a>- {/if}- <button- class="btn btn-ghost btn-sm"- title="Edit title & note"- onclick={() => openNotes(item)}- >- <Icon name="note" size={14} />- </button>- <button- class="btn btn-ghost btn-sm"- disabled={fullscreen}- title={leavesFullscreen ?? 'Send to Geo Proof'}- onclick={() => sendToComposer(item)}- >- <Icon name="proof" size={14} />- </button>- <a- class="btn btn-ghost btn-sm"- class:disabled={fullscreen}- href={fullscreen ? undefined : `/files/${caseState.current.id}/${item.path}`}- target="_blank"- rel="noreferrer"- aria-disabled={fullscreen}- title={leavesFullscreen ?? 'Open'}- >- <Icon name="external" size={14} />- </a>- <button- class="btn btn-ghost btn-sm"- title="Delete"- onclick={() => (deleteTarget = { kind: 'capture', item })}- >- <Icon name="trash" size={14} />- </button>- </div>- {#if item.notes}- <div class="cap-notes">{item.notes}</div>- {/if}- </div>- {/each}- </div>- {/if}- {/if}+ <SavedTree+ rows={savedRows}+ folders={caseState.current?.folders ?? []}+ caseId={caseState.current?.id}+ coords={coordsLabel}+ {fullscreen}+ bind:kind={savedKind}+ bind:query={savedQuery}+ bind:group={savedGroup}+ bind:hoveredId={hoveredSavedId}+ onmove={moveSaved}+ revealId={revealSavedId}+ {locating}+ onopen={openSaved}+ onedit={editSaved}+ ondelete={(row) => (deleteTarget = row)}+ onproof={sendToComposer}+ onbrowse={() => (savedSearchOpen = true)}+ onlocate={runLocate}+ oncancelLocate={() => (locateStopped = true)}+ /></div>{/if}</aside>@@ -2989,13 +3132,11 @@<!-- delete confirm: a capture drops its image file, a place its entity -->{#if deleteTarget}<ConfirmDialog- title={deleteTarget.kind === 'capture' ? 'Delete this capture?' : 'Delete this place?'}- message={deleteTarget.kind === 'capture'- ? `“${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.'}+ title={deleteTarget.kind === 'place' ? 'Delete this place?' : 'Delete this capture?'}+ message={`“${deleteTarget.title || coordsLabel(deleteTarget)}” will be removed from the case.`}+ detail={deleteTarget.kind === 'place'+ ? 'Removes the saved point and cannot be undone.'+ : 'Deletes the image from disk and cannot be undone.'}confirmLabel="Delete"tone="danger"busy={deleteBusy}@@ -3014,6 +3155,13 @@placeholder={coordsLabel(notesItem)}bind:value={notesTitle}/>+ <label for="capture-folder" style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin:10px 0 5px">Folder</label>+ <FolderSelect+ id="capture-folder"+ bind:value={notesFolder}+ folders={caseState.current?.folders ?? []}+ emptyLabel="My work (root)"+ /><hr style="border:none;border-top:1px solid var(--border);margin:12px 0" /><div class="sat-info-rows"><div class="sat-info-row">@@ -3022,11 +3170,11 @@</div><div class="sat-info-row"><span class="sat-info-label">Provider</span>- <span>{notesItem.provider_label}</span>+ <span>{notesItem.provider ?? notesItem.site ?? '—'}</span></div><div class="sat-info-row"><span class="sat-info-label">Zoom</span>- <span>{notesItem.zoom}</span>+ <span>{notesItem.zoom ?? '—'}</span></div><div class="sat-info-row"><span class="sat-info-label">Captured</span>@@ -3036,6 +3184,18 @@<span class="sat-info-label">Imagery date</span><span class="mono">{notesItem.imagery_date ?? '—'}</span></div>+ <div class="sat-info-row">+ <span class="sat-info-label">Image</span>+ <a+ class="link-out"+ class:disabled={fullscreen}+ href={fullscreen ? undefined : `/files/${caseState.current?.id}/${notesItem.path}`}+ target="_blank"+ rel="noreferrer"+ aria-disabled={fullscreen}+ title={leavesFullscreen ?? 'Open the full image'}+ >Open the full image <Icon name="external" size={12} /></a>+ </div></div><hr style="border:none;border-top:1px solid var(--border);margin:12px 0" /><label for="capture-notes" style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin-bottom:5px">Notes</label>@@ -3055,6 +3215,26 @@</Modal>{/if}+<!-- Search every saved item at full width: the same index the tree reads, with+ thumbnails and a sort. No fetch, no network. -->+{#if savedSearchOpen}+ <SavedSearch+ rows={savedRows}+ caseId={caseState.current?.id}+ coords={coordsLabel}+ {fullscreen}+ centre={{ lat: center.lat, lon: center.lon }}+ bind:kind={savedKind}+ bind:query={savedQuery}+ bind:hoveredId={hoveredSavedId}+ onclose={() => (savedSearchOpen = false)}+ onopen={openSaved}+ onedit={editSaved}+ ondelete={(row) => (deleteTarget = row)}+ onproof={sendToComposer}+ />+{/if}+<!-- The manual way in, for when the Capture button's extension grab can't beused or the screenshot came from somewhere else entirely. -->{#if shotOpen && !shotGrabbing}@@ -3147,6 +3327,13 @@placeholder={placeCoordsLabel(placeModal)}bind:value={placeModal.title}/>+ <label for="place-folder" style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin:10px 0 5px">Folder</label>+ <FolderSelect+ id="place-folder"+ bind:value={placeModal.folder}+ folders={caseState.current?.folders ?? []}+ emptyLabel="My work (root)"+ /><hr style="border:none;border-top:1px solid var(--border);margin:12px 0" /><div class="sat-info-rows"><div class="sat-info-row">@@ -3191,23 +3378,61 @@No images or videos in this case yet. Import one in the Media Library first.</div>{:else}- <div class="ref-grid">- {#each (caseState.current ? refMedia : []) as m (m.path)}- <button class="ref-pick" onclick={() => addRef(m)} title={m.title ?? m.filename}>- <div class="ref-thumb">- {#if m.thumbnail}- <img src={`/files/${caseState.current.id}/${m.thumbnail}`} alt={m.filename} loading="lazy" />- {:else}- <Icon name={m.kind === 'video' ? 'video' : 'image'} size={26} />- {/if}- {#if m.kind === 'video'}- <span class="ref-kind"><Icon name="video" size={11} /></span>- {/if}- </div>- <span class="ref-name">{m.title ?? m.filename}</span>+ {#if refBrowserOpen || refMedia.length > REF_SEARCH_MIN}+ <div class="ref-search">+ <SearchInput+ bind:value={refQuery}+ placeholder="Search media…"+ count={`${visibleRefMedia.length}/${refMedia.length}`}+ width="100%"+ />+ <button+ class="btn btn-ghost btn-sm browse-btn"+ title={refBrowserOpen ? 'Show every image' : 'Browse folders'}+ onclick={toggleRefBrowser}+ >…</button>+ </div>+ {/if}+ {#if refBrowserOpen}+ <FolderBrowser+ entries={refBrowserEntries}+ path={refBrowsePath}+ rootLabel="Case media"+ selectedId={refBrowseSelection}+ matches={(entry) => matchesQuery(entry, refQuery)}+ emptyText="This folder has no matching media."+ icon={(entry) => (entry.kind === 'video' ? 'video' : 'image')}+ label={(entry) => entry.title ?? entry.filename}+ onnavigate={openRefFolder}+ onselect={(entry) => (refBrowseSelection = entry.path)}+ onconfirm={(entry) => addRef(entry)}+ />+ <div class="ref-actions">+ <button class="btn btn-primary btn-sm" disabled={!refBrowseSelection} onclick={confirmRefBrowser}>+ Add selected</button>- {/each}- </div>+ </div>+ {:else if !visibleRefMedia.length}+ <div class="ref-empty">No media matches this search.</div>+ {:else}+ <div class="ref-grid">+ {#each visibleRefMedia as m (m.path)}+ <button class="ref-pick" onclick={() => addRef(m)} title={m.title ?? m.filename}>+ <div class="ref-thumb">+ {#if m.thumbnail}+ <img src={`/files/${caseState.current.id}/${m.thumbnail}`} alt={m.filename} loading="lazy" />+ {:else}+ <Icon name={m.kind === 'video' ? 'video' : 'image'} size={26} />+ {/if}+ {#if m.kind === 'video'}+ <span class="ref-kind"><Icon name="video" size={11} /></span>+ {/if}+ </div>+ <span class="ref-name">{m.title ?? m.filename}</span>+ </button>+ {/each}+ </div>+ {/if}{/if}</Modal>{/if}@@ -3618,7 +3843,8 @@}}.captures {- width: 300px;+ position: relative;+ width: 300px; /* the inline style carries the dragged width */flex-shrink: 0;border-left: 1px solid var(--border);background: var(--bg-1);@@ -3628,6 +3854,30 @@.captures.collapsed {width: 42px;}+ /* the grab strip sits just inside the left edge, over the panel's padding */+ .resizer {+ position: absolute;+ top: 0;+ left: 0;+ width: 5px;+ height: 100%;+ z-index: 2;+ cursor: col-resize;+ background: transparent;+ border: none;+ padding: 0;+ transition: background 0.12s;+ }+ .resizer:hover,+ .resizer:focus-visible,+ .captures.resizing .resizer {+ background: var(--accent);+ outline: none;+ }+ /* a drag reads as one gesture — no text selection on the way */+ .captures.resizing {+ user-select: none;+ }.cap-head {display: flex;align-items: center;@@ -3661,11 +3911,6 @@color: var(--text-3);font-weight: 600;}- .none {- padding: 8px 14px;- font-size: var(--fs-xs);- color: var(--text-3);- }.panel-scroll {flex: 1;overflow-y: auto;@@ -3759,125 +4004,6 @@.links-advert:hover {color: var(--accent);}- .place-notes {- padding: 0 10px 8px 30px;- font-size: var(--fs-xs);- color: var(--text-2);- font-style: italic;- white-space: pre-wrap;- overflow-wrap: anywhere;- word-break: break-word;- }- .place-list {- display: flex;- flex-direction: column;- gap: 6px;- }- .place-row {- display: flex;- flex-direction: column;- overflow: hidden;- }- .place-main {- display: flex;- align-items: center;- gap: 4px;- padding: 4px 6px 4px 4px;- }- .place-goto {- display: flex;- align-items: center;- gap: 9px;- flex: 1;- min-width: 0;- padding: 5px 6px;- background: none;- border: none;- color: var(--text-2);- text-align: left;- cursor: pointer;- }- .place-goto:hover,- .place-goto:hover .title {- color: var(--accent);- }- .place-meta {- display: flex;- flex-direction: column;- min-width: 0;- }- .cap-list {- display: flex;- flex-direction: column;- gap: 10px;- }- .cap {- 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%;- padding: 0;- background: none;- border: none;- color: inherit;- text-align: left;- cursor: pointer;- }- .cap img {- width: 100%;- aspect-ratio: 10 / 7;- object-fit: cover;- background: var(--bg-2);- }- .cap-goto.disabled {- cursor: not-allowed;- }- .cap-goto:hover:not(.disabled) img {- opacity: 0.9;- }- .cap-goto:hover:not(.disabled) .coords {- color: var(--accent);- }- .cap-meta {- padding: 8px 10px 2px;- display: flex;- flex-direction: column;- }- .title {- font-size: var(--fs-sm);- color: var(--text-1);- font-weight: 600;- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;- }- .coords {- font-size: var(--fs-xs);- color: var(--text-3);- }- .cap-goto:hover .title {- color: var(--accent);- }- .prov {- font-size: var(--fs-xs);- color: var(--text-3);- }- .cap-actions {- display: flex;- gap: 2px;- padding: 4px 6px 6px;- }- .cap-notes {- padding: 0 10px 8px;- font-size: var(--fs-xs);- color: var(--text-2);- font-style: italic;- white-space: pre-wrap;- word-break: break-word;- }.sat-info-rows {display: flex;@@ -3964,6 +4090,25 @@color: var(--text-2);margin: 0 0 12px;}+ .ref-search {+ display: flex;+ align-items: center;+ gap: 6px;+ margin-bottom: 10px;+ }+ .ref-search :global(.search-box) {+ flex: 1;+ }+ .browse-btn {+ min-width: 30px;+ font-size: var(--fs-lg);+ line-height: 1;+ }+ .ref-actions {+ display: flex;+ justify-content: flex-end;+ margin-top: 10px;+ }.shot-hint {font-size: var(--fs-sm);color: var(--text-2);diff --git a/frontend/src/tools/Satellite.test.js b/frontend/src/tools/Satellite.test.jsnew file mode 100644index 0000000..12dddfb--- /dev/null+++ b/frontend/src/tools/Satellite.test.js@@ -0,0 +1,255 @@+import { describe, expect, it } from 'vitest';+import { readFileSync } from 'node:fs';++const source = readFileSync(new URL('./Satellite.svelte', import.meta.url), 'utf8');+const cluster = readFileSync(+ new URL('./satellite/MapToolCluster.svelte', import.meta.url),+ 'utf8'+);++describe('Satellite saved work', () => {+ it('opens the case on one compact index, not on every capture row', () => {+ expect(source).toContain('/satellite/index');+ // the flat Places and Captures lists, and everything that served only them+ expect(source).not.toContain('fetchAllEntities');+ expect(source).not.toContain('capturesSubCollapsed');+ expect(source).not.toContain('placesCollapsed');+ expect(source).not.toContain('cap-list');+ expect(source).not.toContain('place-list');+ });++ it('hands the index to the tree, the search and the map overlay', () => {+ expect(source).toContain('<SavedTree');+ expect(source).toContain('<SavedSearch');+ expect(source).toContain('<SavedOverlay');+ expect(source).toContain('rows={savedRows}');+ expect(source).toContain('items={savedShown}');+ });++ it('draws the panel’s filtered selection on the map, not the whole index', () => {+ expect(source).toContain(+ 'const savedShown = $derived(filterSaved(savedRows, { kind: savedKind, query: savedQuery }))'+ );+ // the overlay must never be handed the unfiltered index again+ expect(source).not.toContain('items={saved}');+ });++ it('reads the proofs index only once the Proofs position is opened', () => {+ // opening a case must not pay for a view it may never show+ expect(source).toContain('const savedRows = $derived(isMode(savedKind) ? savedProofs : saved)');+ expect(source).toContain('if (!id || !isMode(savedKind) || proofsFor === stamp) return');+ expect(source).toContain('`/api/cases/${id}/proofs/index`');+ });++ it('files a dragged row through its own entity type', () => {+ // a proof filed as a capture would be routed to PATCH /media, which is the+ // sidecar of an image the proof is not+ expect(source).toContain("row.kind === 'proof' ? 'proof'");+ });++ it('re-reads the proofs index when the case is reloaded, not only when it changes', () => {+ // filing a proof reloads the case; keying only on the id would leave the+ // panel showing the folder the proof just left+ expect(source).toContain('const stamp = `${id}:${caseState.rev}`');+ });++ it('drops both saved indexes before loading a different case', () => {+ const effect = source.slice(+ source.indexOf('if (savedFor !== id)'),+ source.indexOf('return () => { live = false; };', source.indexOf('if (savedFor !== id)'))+ );+ expect(effect).toContain('saved = []');+ expect(effect).toContain('savedProofs = []');+ expect(effect).toContain('proofsFor = null');+ expect(effect).toContain('savedSearchOpen = false');+ expect(effect).toContain('deleteTarget = null');+ expect(effect).toContain('notesItem = null');+ expect(effect).toContain('placeModal = null');+ expect(effect).toContain('locateGeneration += 1');+ expect(effect.indexOf('saved = []')).toBeLessThan(effect.indexOf('/satellite/index'));+ });++ it('ignores an earlier case response after the case changes', () => {+ expect(source).toContain('.then((rows) => { if (live) saved = rows; })');+ expect(source).toContain('return () => { live = false; };');+ });++ it('opens a proof rather than queueing it as a panel of a new one', () => {+ expect(source).toContain("if (item.kind === 'proof') {");+ expect(source).toContain('uiState.openProof = item.name');+ });++ it('opens a linked post in the existing Post Composer draft flow', () => {+ expect(source).toContain('function openLinkedPost(post)');+ expect(source).toContain('uiState.openDraft = post.name');+ expect(source).toContain('onpost={openLinkedPost}');+ });++ it('shares one hovered id between the panel and the map', () => {+ expect(source).toContain('let hoveredSavedId = $state(null)');+ expect((source.match(/bind:hoveredId=\{hoveredSavedId\}/g) ?? []).length).toBe(3);+ });++ it('keeps the map overlay off by default and out of the case file', () => {+ expect(source).toContain('let savedOverlay = $state(false)');+ expect(source).toContain('{#if savedOverlay}');+ expect(cluster).toContain('savedOverlay = $bindable()');+ expect(cluster).toContain('onclick={() => (savedOverlay = !savedOverlay)}');+ // nothing about the overlay is written back to the case — session only+ expect(source).not.toContain('savedOverlay:');+ });++ it('runs Locate in bounded batches that can be stopped', () => {+ expect(source).toContain('/satellite/locate?limit=${LOCATE_BATCH}');+ expect(source).toContain(+ 'while (remaining > 0 && !locateStopped && generation === locateGeneration)'+ );+ expect(source).toContain('oncancelLocate={() => (locateStopped = true)}');+ });++ it('stops the Locate loop when a batch resolves nothing', () => {+ // offline, every batch comes back with the same backlog — looping on that+ // would hammer Nominatim forever+ expect(source).toContain('const stalled = batch.remaining >= remaining');+ expect(source).toContain('if (stalled) break;');+ });++ it('does not let a Locate pass continue in another case', () => {+ expect(source).toContain('const id = caseState.current.id');+ expect(source).toContain('const generation = ++locateGeneration');+ expect(source).toContain('generation === locateGeneration');+ expect(source).toContain('`/api/cases/${id}/satellite/locate?limit=${LOCATE_BATCH}`');+ expect(source).toContain('if (generation !== locateGeneration) return');+ });++ it('reveals a capture the case sidebar points at, whatever the filter was', () => {+ expect(source).toContain("savedKind = 'all'");+ expect(source).toContain("savedQuery = ''");+ expect(source).toContain('revealSavedId = row.id');+ });+});++describe('filing saved work from its details dialog', () => {+ it('offers the same folder picker the rest of the app uses, in both dialogs', () => {+ expect(source).toContain("import FolderSelect from '../components/FolderSelect.svelte'");+ expect(source).toContain('bind:value={notesFolder}');+ expect(source).toContain('bind:value={placeModal.folder}');+ expect((source.match(/emptyLabel="My work \(root\)"/g) ?? []).length).toBe(2);+ });++ it('opens each dialog on the folder the item is already in', () => {+ expect(source).toContain("notesFolder = row.folder ?? ''");+ expect(source).toContain("folder: row.folder ?? ''");+ });++ it('files a capture in the patch it already sends', () => {+ expect(source).toContain('title: notesTitle, folder: notesFolder');+ });++ it('files a place, whether it is being saved or edited', () => {+ expect(source).toContain("attrs: { notes: m.notes.trim(), folder: m.folder ?? '' }");+ expect(source).toMatch(/notes: m\.notes,\s*\n\s*folder: m\.folder,/);+ });+});++describe('reference picker search', () => {+ it('searches the case media instead of only listing it', () => {+ expect(source).toContain("import { matchesQuery } from '../lib/mediaFilter.js'");+ expect(source).toContain('matchesQuery(m, refQuery)');+ expect(source).toContain('{#each visibleRefMedia as m (m.path)}');+ });++ it('only shows the box once the grid is long enough to need it', () => {+ expect(source).toContain('const REF_SEARCH_MIN = 6');+ });++ it('opens the picker on a cleared query', () => {+ expect(source).toMatch(/refPicker = true;\s*\n\s*refQuery = '';/);+ });++ it('tells the user when the search matched nothing', () => {+ expect(source).toContain('No media matches this search.');+ });++ it('swaps the grid for the folder browser behind the "…" button', () => {+ expect(source).toContain('<FolderBrowser');+ expect(source).toContain('onclick={toggleRefBrowser}');+ expect(source).toContain('entries={refBrowserEntries}');+ expect(source).toContain("rootLabel=\"Case media\"");+ // the browser reads the folder off attrs, like every other picker+ expect(source).toContain("attrs: { folder: m.folder ?? '' }");+ });++ it('keeps the search box up while browsing and filters the rows with it', () => {+ expect(source).toContain('{#if refBrowserOpen || refMedia.length > REF_SEARCH_MIN}');+ expect(source).toContain('matches={(entry) => matchesQuery(entry, refQuery)}');+ });++ it('adds the browsed pick on double-click or the confirm button', () => {+ expect(source).toContain('onconfirm={(entry) => addRef(entry)}');+ expect(source).toContain('disabled={!refBrowseSelection}');+ expect(source).toContain('onclick={confirmRefBrowser}');+ });+});++describe('the saved panel is resizable', () => {+ it('drives the width from the shared panel helpers, with its own key and range', () => {+ expect(source).toContain("import { panelWidth } from '../lib/panelWidth.js'");+ expect(source).toContain("key: 'azimut:satelliteSavedW'");+ expect(source).toContain('let savedW = $state(savedPanel.loadWidth())');+ expect(source).toContain('style={capturesCollapsed ? undefined : `width: ${savedW}px`}');+ });++ it('clamps every width it sets against the live window', () => {+ expect(source).toContain('savedW = savedPanel.clampWidth(w, window.innerWidth)');+ // nothing sets the width past the clamp+ expect((source.match(/savedW = /g) ?? []).length).toBe(2); // the $state, then setSavedWidth+ });++ it('gives the handle a keyboard path and a double-click reset', () => {+ expect(source).toContain('onpointerdown={startSavedResize}');+ expect(source).toContain('ondblclick={resetSavedWidth}');+ expect(source).toContain('onkeydown={onSavedResizeKey}');+ expect(source).toContain('aria-label="Resize the saved panel"');+ });++ it('stores the width once the drag ends, not on every frame', () => {+ expect(source).toContain('savedPanel.saveWidth(savedW); // one write per drag');+ });++ it('redraws the map for the new size', () => {+ expect(source).toContain('map?.invalidateSize({ animate: false })');+ });++ it('hides the handle when the panel is collapsed to its rail', () => {+ expect(source).toContain('{#if !capturesCollapsed}');+ });+});++describe('filing saved work by dragging it in the panel', () => {+ it('hands the tree both groupings, the case folders and a move handler', () => {+ expect(source).toContain('bind:group={savedGroup}');+ expect(source).toContain('folders={caseState.current?.folders ?? []}');+ expect(source).toContain('onmove={moveSaved}');+ });++ it('remembers which grouping the panel was left on', () => {+ expect(source).toContain("const GROUP_KEY = 'azimut:satelliteSavedGroup'");+ expect(source).toContain('let savedGroup = $state(loadSavedGroup())');+ expect(source).toContain('localStorage.setItem(GROUP_KEY, savedGroup)');+ });++ it('moves through the shared filing route, then reloads the case', () => {+ expect(source).toContain("import { assignFolder } from '../lib/filing.js'");+ expect(source).toContain('await assignFolder(caseState.current.id, entity, folder)');+ expect(source).toContain(+ "type: row.kind === 'place' ? 'place' : row.kind === 'proof' ? 'proof' : 'capture'"+ );+ expect(source).toContain('await reloadCase();\n toast(');+ });++ it('leaves folder browsing out of the search modal', () => {+ expect(source).not.toContain('savedBrowsing');+ expect(source).not.toContain('bind:path=');+ });+});diff --git a/frontend/src/tools/Settings.svelte b/frontend/src/tools/Settings.svelteindex 0be1b12..8f563e4 100644--- a/frontend/src/tools/Settings.svelte+++ b/frontend/src/tools/Settings.svelte@@ -27,8 +27,7 @@import PostTemplateEditor from '../components/PostTemplateEditor.svelte';import ConfirmDialog from '../components/ConfirmDialog.svelte';- // Imagery and Usage were the same four objects seen from two rooms: the key- // here, the meter it feeds there. One tab, one card per provider.+ // Imagery keys and their usage meters share one card per provider.const TABS = [{ id: 'preferences', label: 'Preferences', icon: 'sliders' },{ id: 'imagery', label: 'Imagery', icon: 'key' },@@ -42,14 +41,9 @@const SITE_URL = 'https://osintmethat.com';// The keyed imagery providers the app knows how to light up (IMAGERY_PROVIDERS.md).- // Keys are app-wide, stored locally in settings.json, never written into a- // case folder or export bundle — they're the user's own billing identity.+ // Keys are app-wide and stored in settings.json, outside cases and exports.//- // Each provider is one collapsed row until you open it: `gives` and `cost`- // are all a closed card says, so the tab reads at a glance and only the- // provider you're actually setting up spends any text. Everything below them- // (`steps`, `warning`, `overage`) lives in the opened body — the nuance is- // still here, it just isn't charged to the other three providers.+ // Collapsed cards show `gives` and `cost`; setup details stay in the open card.const KEYED = [{id: 'mapbox',@@ -96,7 +90,7 @@placeholder: 'AIza…',help: 'https://developers.google.com/maps/documentation/javascript/get-api-key',usage: USAGE_LINKS.google_js,- // a JS key proves itself only in a browser — Test loads a real 1-tile map+ // A JavaScript key must be tested in the browser with a real map load.browserTest: true,steps: ['In the Google Cloud Console, enable the "Maps JavaScript API" on your project.',@@ -131,7 +125,7 @@},];- /** A per-provider map over KEYED — the shape every key/pref state uses. */+ /** Build the per-provider shape used by key and preference state. */const perProvider = (value) => Object.fromEntries(KEYED.map((k) => [k.id, value(k)]));const COORD_CHOICES = [@@ -146,28 +140,23 @@let keys = $state(perProvider(() => ''));let shown = $state(perProvider(() => false));- // every card starts closed: four providers' worth of setup is four walls of- // text, and you only ever set up one at a time+ // Start cards closed so setup details appear only for the selected provider.let open = $state(perProvider(() => false));let termsOpen = $state(false);let usage = $state({});let month = $state('');let testing = $state(perProvider(() => false));let testResult = $state(perProvider(() => null)); // { ok, detail } | null- // keyed-provider preferences (IMAGERY_PROVIDERS.md) — saved on toggle+ // Keyed-provider preferences are saved on toggle.let enabled = $state(perProvider(() => true));let overrides = $state(perProvider(() => false));let eco = $state(true);let ecoMaxZoom = $state(ECO_MAX_ZOOM);- // per-provider eco thresholds ('' = inherit, '0' = eco off for that basemap);- // the Maps JS widget is absent — an eco swap would re-bill a map load+ // Per-provider eco thresholds: '' inherits and '0' disables eco mode.+ // Maps JS has no threshold because reopening its widget starts a billed load.let ecoZooms = $state(perProvider(() => ''));- // The account's real monthly allowance per meter ('' = the shipped default).- // A free tier belongs to the provider's account, not to us: they hand out- // more than they document and change it silently (Copernicus documents 10k- // and provisions 30k), so the number the counter and the soft block measure- // against has to be the user's to correct. `tiers` is the resolved figure the- // helpers read; `tierEdits` is what's in the boxes.+ // The account's monthly allowance per meter; '' uses the shipped default.+ // Users can correct provider-specific allowances that differ from documentation.let tiers = $state(null);let tierEdits = $state(perProvider(() => ''));let about = $state({ version: '', workspace_root: '', extension_version: '' });@@ -175,16 +164,13 @@// The binaries bundle it; a pip install uses a system copy on PATH. Read-only.let ffmpeg = $state({ available: false, version: null, source: null, path: null });- // --- capture extension: pairing token + detection (lib/extBridge.js) ---+ // Capture extension pairing and detection.let ingestToken = $state('');let tokenShown = $state(false);- // read once per mount: the marker is stamped before the app loads, so a- // mid-session install genuinely needs a tab reload (the text says so)+ // Read once per mount because an extension installed mid-session needs a reload.const extDetected = extensionVersion();- // Is the bundled extension newer than the one loaded in this browser? The app- // can't reload an unpacked extension for the user (the browser won't let it),- // so it flags the mismatch and points at the same re-download + reload steps.+ // Flag when the bundled extension is newer than the browser's loaded copy.let extOutdated = $derived(extensionOutdated(extDetected, about.extension_version));async function copyToken() {@@ -193,14 +179,12 @@await navigator.clipboard.writeText(ingestToken);toast('Pairing token copied', 'ok');} catch {- tokenShown = true; // clipboard blocked — show it for manual copy+ tokenShown = true; // Show the token when clipboard access is blocked.toast('Could not copy. The token is shown for manual copy', 'warn');}}- // The token is no longer minted just by opening Settings (the server stopped- // doing that) — it's created the first time the user reveals or copies it to- // pair the capture extension.+ // Mint the token only when the user reveals or copies it.async function ensureToken() {if (ingestToken) return ingestToken;const r = await api.post('/api/settings/ingest-token');@@ -213,15 +197,13 @@ingestToken = r.ingest_token;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+ // Keep home-view fields as text until change so partial numbers remain editable.let home = $state({ lat: '', lon: '', zoom: '' });let mention = $state('');let postTarget = $state('x');let updateOnStart = $state(true); // pop a notice on load when a release is out- // the analyst's logo: app-wide like the API keys, and under the same rule —- // it lives beside settings.json and only ever reaches a case as pixels in a- // rendered proof PNG. `sigBust` re-fetches the <img> after a replace.+ // The app-wide logo lives beside settings.json and reaches cases only in proof PNGs.+ // `sigBust` refreshes the preview after replacement.let signature = $state(false);let signatureHandle = $state('');let sigBust = $state(0);@@ -246,9 +228,7 @@}}- // The downloaders age faster than Azimut releases: sites change, and a stale- // yt-dlp just stops finding media. They can be refreshed from PyPI in place,- // without waiting for (or reinstalling) the app — see engine/scrapers.py.+ // Downloaders can be refreshed from PyPI between Azimut releases.const SCRAPER_LABELS = { 'yt-dlp': 'yt-dlp', 'gallery-dl': 'gallery-dl' };let scrapers = $state([]);let checking = $state(false);@@ -259,8 +239,7 @@scrapers = (await api.get(path)).scrapers;}- // Opt-in, never on mount: Azimut is local-first, so opening Settings must not- // phone out. The user asks, and only then do we look at PyPI.+ // Scraper checks run only when requested and never on Settings mount.async function checkScrapers() {if (checking) return;checking = true;@@ -277,9 +256,7 @@}}- // App self-update check (engine/updates.py). The binary has no package- // manager behind it; a pip/pipx user runs `pipx upgrade azimut` instead.- // Opt-in and never on mount — local-first, like the downloader check.+ // Manual app update check. The separate startup check remains enabled by default.let appUpdate = $state(null); // { current, latest, update_available, url, error }let checkingApp = $state(false);@@ -305,7 +282,7 @@if (!r.ok) toast(`${dist}: ${r.detail}`, 'danger');else toast(`${dist} ${r.detail}`, r.restart_required ? 'warn' : 'ok');await loadScrapers();- // keep the "restart to use it" state visible — a reload would drop it+ // Preserve the restart-required state after reloading the scraper list.if (r.ok && r.restart_required) {const entry = scrapers.find((s) => s.dist === dist);if (entry) entry.restart_required = true;@@ -337,9 +314,7 @@month = s.month;enabled = perProvider((k) => s.providers_enabled[k.id] ?? true);overrides = perProvider((k) => !!s.usage_overrides[k.id]);- // a stored verdict (key test, or a live auth failure) shows up like a- // fresh test result — it's also what benches the basemap, so it must be- // visible, not buried in settings.json+ // Show stored key-test and live-auth verdicts in the provider card.testResult = perProvider((k) => s.provider_status?.[k.id] ?? null);eco = s.eco_zoom_fallback;ecoMaxZoom = s.eco_max_zoom ?? ECO_MAX_ZOOM;@@ -368,8 +343,7 @@api.get('/api/settings/ffmpeg').then((r) => (ffmpeg = r)).catch(() => {});}- // Every preference saves on change — no "Save" button to forget. The server's- // answer is the source of truth, so clamped/normalised values show up here.+ // Preferences save on change; the server returns canonical values.async function savePrefs(patch) {try {const saved = await api.put('/api/settings/prefs', patch);@@ -418,8 +392,7 @@}async function saveEcoZoom() {- // per-provider thresholds ride along: '' = inherit (server drops the- // override on null), a number (0 included — eco off) sets it+ // Empty thresholds inherit; zero disables eco mode for that provider.const perProviderZooms = {};for (const [id, v] of Object.entries(ecoZooms)) {perProviderZooms[id] = v === '' ? null : Number(v);@@ -465,7 +438,7 @@return;}const saved = await savePrefs({ home_view: view });- // echo back what the server stored — a point off the globe is refused there+ // Reflect the validated value returned by the server.if (saved) {home = {lat: String(saved.home_view.lat),@@ -553,9 +526,7 @@}}- // Keys save on change like every other preference here — no Save button to- // forget. The status chip flipping to "Untested" is the receipt, which beats- // a toast: it also says what to do next.+ // Keys save on change and reset their status to Untested.async function saveKey(id) {try {await api.put('/api/settings/keys', { [id]: keys[id] });@@ -587,12 +558,10 @@const url = `https://maps.googleapis.com/maps/api/js?key=${encodeURIComponent(keys[id].trim())}&v=weekly`;const { billed, ...verdict } = await probeKey(url);testResult[id] = verdict;- // The probe is a real map load on the user's bill, and it happens in- // this browser where no backend proxy can count it — report it, or- // testing a key silently drifts the counter under Google's number.+ // Count the billed browser probe because the backend cannot observe it.if (billed) await api.post(`/api/satellite/usage/${id}`).catch(() => {});}- // persist the browser's verdict — it's what benches/unbenches the basemap+ // Persist the browser verdict used to enable or disable the basemap.await api.post(`/api/settings/keys/${id}/status`, testResult[id]).catch(() => {});} else {testResult[id] = await api.post(`/api/settings/keys/${id}/test`);@@ -647,8 +616,7 @@</div><p class="sample mono">{coordSample}</p><p class="note">- Display only. Captures, proofs and <span class="mono">case.json</span> always- keep decimal degrees, so a case reads the same for everyone.+ Changes display only; case data stays in decimal degrees.</p></section>@@ -677,8 +645,7 @@<section class="group"><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.+ Default opening position for Satellite; case navigation still takes priority.</p><div class="grid-3"><label class="field">@@ -736,7 +703,7 @@<div class="row"><div class="row-label"><span>Your account handle</span>- <span class="row-hint">Used when a proof or template enables “Add account handle”; leave empty to hide it.</span>+ <span class="row-hint">Shown on proofs that enable “Add account handle”.</span></div><inputclass="input mention"@@ -751,9 +718,7 @@<div class="row-label"><span>Your logo</span><span class="row-hint">- 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.+ Transparent PNG, up to 2 MB, used only on signed proofs.</span></div><div class="sig-side">@@ -784,11 +749,7 @@<section class="group"><h3>Providers</h3><p class="intro">- 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- surprise.+ Add provider keys to unlock more Satellite basemaps; usage appears on each card.</p><div class="cards">@@ -951,7 +912,7 @@{#if k.browserTest}<p class="ctrl-note">- No eco mode: swapping the widget out and back would bill a fresh map load.+ Eco mode is unavailable because reopening this widget starts another billed map load.</p>{:else}<label@@ -1017,7 +978,7 @@/></label><p class="note">- Applies when zoomed out. Each provider can override this from its card.+ Applies while zoomed out; provider cards can override it.</p></section>@@ -1031,14 +992,14 @@><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">Applied automatically</span></button></div>{#if termsOpen}<ul class="rules">- <li>Google tiles are never cached to disk, and a Google capture is a flattened screenshot with the copyright line burned into its footer; both are conditions of Google's Map Tiles API terms.</li>- <li>Mapbox captures keep the © Mapbox © OpenStreetMap attribution in their provenance.</li>- <li>Keys are never bundled into a shared case or export.</li>+ <li>Google tiles are not cached; captures are screenshots with attribution.</li>+ <li>Mapbox attribution remains attached to captures.</li>+ <li>Provider keys stay outside cases and exports.</li></ul>{/if}</div>@@ -1049,9 +1010,7 @@<section class="group"><h3>Capture extension</h3><p class="note">- A browser extension (Chrome/Edge and Firefox) that captures external map- sites into Azimut and powers the Capture button on the Google (Maps JS)- basemap.+ Captures supported map sites and powers the Google basemap Capture button.</p><div class="row"><div class="row-label">@@ -1074,22 +1033,19 @@</div>{#if extOutdated}<p class="note warn">- This Azimut ships a newer capture extension (v{about.extension_version}) than the- v{extDetected} loaded here. Download it, replace the unpacked folder, then reload the- extension in your browser's extensions page. Azimut can't reload it for you.+ Bundled v{about.extension_version} is newer than installed v{extDetected}; replace+ the unpacked folder and reload the extension.</p>{/if}<p class="note">- Unzip it somewhere permanent and load it as an unpacked extension, then- reload this tab. Step-by-step instructions are in the README inside the zip.+ Unzip it, load it as an unpacked extension, then reload this tab.</p></section><section class="group"><h3>Pairing</h3><p class="note">- Paste this token once into the extension's options page. Rotating it- unpairs every extension.+ Paste this token into the extension options; rotating it unpairs existing extensions.</p><div class="row"><div class="row-label">@@ -1107,10 +1063,7 @@</div></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- extension takes one screenshot per explicit click, reads only the page- URL, and refuses non-map sites.+ The extension can file one user-requested map capture through this local app.</p></section>{/if}@@ -1133,12 +1086,11 @@{/if}</dd><dt>License</dt>- <dd>AGPL-3.0-or-later</dd>+ <dd>AGPL-3.0-only</dd></dl><p class="note">- The workspace is a plain folder you can zip, back up or put under git.- No account, no telemetry; the network is only used when a tool needs it- (tiles, geocoding, downloads), always directly to the third party.+ Case data stays in the workspace; network access is limited to requested features+ and the automatic GitHub update check.</p><div class="links"><a class="btn btn-sm" href={REPO_URL} target="_blank" rel="noreferrer">@@ -1162,7 +1114,9 @@{:else if appUpdate && !appUpdate.error}you're on the latest (<span class="mono">{about.version}</span>){:else}- looks at GitHub only when you press it+ {updateOnStart+ ? 'checks GitHub on startup and when requested'+ : 'checks GitHub when requested'}{/if}</span></div>@@ -1180,8 +1134,7 @@<div class="row-label"><span>Tell me on startup</span><span class="row-hint">- Checks GitHub when the app loads and pops a notice if a newer- release is out. The only network call Azimut makes on its own.+ Checks GitHub when the app opens and reports available releases.</span></div><input@@ -1192,17 +1145,15 @@/></div><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.+ Update with <span class="mono">pipx upgrade azimut</span>; standalone users replace+ the downloaded binary.</p></section><section class="group"><h3>Backup</h3><p class="note">- Export all settings, including your keys, to a file you can import on- another machine. Keep the file private.+ Export settings and keys for another machine; keep the file private.</p><div class="links"><a class="btn btn-sm" href="/api/settings/export" download>@@ -1224,8 +1175,7 @@<section class="group"><h3>Downloaders</h3><p class="note">- Media download leans on two projects that track sites as they change. They- age faster than Azimut does. Update these first if a link stops resolving.+ Update these tools if a media link stops resolving.</p>{#each scrapers as s (s.dist)}<div class="row">@@ -1269,8 +1219,7 @@</button></div><p class="note">- Updates are fetched from PyPI (hash-verified) only when you press the- button. Revert goes back to the bundled version.+ Updates are hash-verified from PyPI when requested; Revert restores the bundled version.</p></section>{/if}@@ -1279,9 +1228,7 @@<section class="group"><h3>Geo Proof templates</h3><p class="note">- 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.+ Reusable proof styles shared across cases.</p><div class="tpl-list">{#each templatesState.proof as t (t.id)}@@ -1310,8 +1257,7 @@<section class="group"><h3>Geo Report templates</h3><p class="note">- A thread skeleton: the mention, which lines the first tweet keeps,- whether a media tweet rides along, and boilerplate extra tweets.+ Reusable thread structures for new Geo Reports.</p><div class="tpl-list">{#each templatesState.post as t (t.id)}@@ -1401,8 +1347,7 @@font-size: var(--fs-sm);}- /* a preferences window, not a dashboard: a rail of sections on the left,- one flat scrolling pane on the right — no cards, no boxes */+ /* Preferences use a section rail and one scrolling pane. */.split {flex: 1;display: flex;@@ -1522,7 +1467,7 @@gap: 10px;}.sig-preview {- /* checkerboard: a logo is meant to be transparent — show whether it is */+ /* Checkerboard preview for transparent logos. */max-width: 88px;max-height: 44px;padding: 4px;@@ -1543,7 +1488,7 @@display: none;}- /* segmented control — one row of mutually exclusive choices */+ /* One-row segmented control. */.seg {display: flex;flex-shrink: 0;@@ -1648,10 +1593,7 @@text-decoration: none;}- /* --- provider cards: one row each until you open one --------------------- A closed card answers the only two questions you have from across the- room — what does it give me, and is it working — in one line. Setting a- provider up is the rare act; reading the tab is the common one. */+ /* Provider cards show a summary until opened for setup. */.cards {display: flex;flex-direction: column;@@ -1706,7 +1648,7 @@flex-shrink: 0;cursor: pointer;}- /* the verdict, in one word — the detail is a tooltip, and the fix is inside */+ /* One-word verdict; the tooltip carries the detail. */.chip {flex-shrink: 0;padding: 1px 7px;@@ -1764,7 +1706,7 @@font-size: var(--fs-xs);color: var(--text-3);}- /* both control rows put their box at the same x — they read as a column */+ /* Align provider control fields in one column. */.ctrl > span:first-child {min-width: 104px;color: var(--text-2);diff --git a/frontend/src/tools/inspect/CollageMenu.svelte b/frontend/src/tools/inspect/CollageMenu.svelteindex acee999..8677f50 100644--- a/frontend/src/tools/inspect/CollageMenu.svelte+++ b/frontend/src/tools/inspect/CollageMenu.svelte@@ -11,7 +11,10 @@// to the active one, and act on the selected piece. A session holds several// collages (session.collages / session.activeCollageId); each is saved as its// own PNG. Each added piece is a frozen snapshot of the frame (addToCollage).- let { session, filters, selectedIds = $bindable([]), addToCollage, requestCrop, renderPiece } = $props();+ let {+ session, filters, selectedIds = $bindable([]), addToCollage, requestCrop, renderPiece,+ onRename,+ } = $props();const active = $derived(session.collages.find((c) => c.id === session.activeCollageId) ?? session.collages[0]@@ -29,6 +32,37 @@selectedIds = [];}+ // Renaming rides on the tab itself: a click switches, a click on the tab you+ // are already in opens it for editing. The name follows the collage into the+ // Save tab, so it is worth setting here while the layout is in front of you.+ let renamingId = $state(null);+ let draftName = $state('');++ function tabClick(cl) {+ if (cl.id === session.activeCollageId) {+ renamingId = cl.id;+ draftName = cl.name ?? '';+ } else {+ switchCollage(cl.id);+ }+ }++ function commitRename(cl) {+ const next = draftName.trim();+ if (next && next !== cl.name) {+ cl.name = next;+ // The Save tab shows this same name; tell it the name is now the user's,+ // so a base name typed there stops refilling it.+ onRename?.(cl);+ }+ renamingId = null;+ }++ function renameKey(event, cl) {+ if (event.key === 'Enter') commitRename(cl);+ else if (event.key === 'Escape') renamingId = null;+ }+function addCollage() {const nums = session.collages.map((c) => parseInt((c.name?.match(/\d+/) ?? [])[0]) || 0);const next = Math.max(0, ...nums) + 1;@@ -183,9 +217,26 @@<div class="collage-tabs">{#each session.collages as cl (cl.id)}<div class="ctab" class:active={cl.id === session.activeCollageId}>- <button class="ctab-name" onclick={() => switchCollage(cl.id)} title="Switch to this collage">- {cl.name}{#if cl.nodes.length}<span class="count">{cl.nodes.length}</span>{/if}- </button>+ {#if renamingId === cl.id}+ <!-- svelte-ignore a11y_autofocus -->+ <input+ class="ctab-input"+ bind:value={draftName}+ onblur={() => commitRename(cl)}+ onkeydown={(e) => renameKey(e, cl)}+ aria-label="Collage name"+ maxlength="200"+ autofocus+ />+ {:else}+ <button+ class="ctab-name"+ onclick={() => tabClick(cl)}+ title={cl.id === session.activeCollageId ? 'Rename this collage' : 'Switch to this collage'}+ >+ {cl.name}{#if cl.nodes.length}<span class="count">{cl.nodes.length}</span>{/if}+ </button>+ {/if}{#if session.collages.length > 1}<button class="ctab-x" onclick={() => removeCollage(cl.id)} aria-label="Delete collage"><Icon name="x" size={11} /></button>{/if}@@ -360,6 +411,18 @@.ctab.active .ctab-name {color: var(--accent);}+ .ctab-input {+ width: 9em;+ font: inherit;+ font-size: var(--fs-xs);+ color: var(--text-1);+ background: var(--bg-0);+ border: none;+ padding: 4px 8px;+ }+ .ctab-input:focus {+ outline: none;+ }.ctab-name .count {font-size: 9px;padding: 0 4px;diff --git a/frontend/src/tools/inspect/CollageMenu.test.js b/frontend/src/tools/inspect/CollageMenu.test.jsnew file mode 100644index 0000000..0c324ba--- /dev/null+++ b/frontend/src/tools/inspect/CollageMenu.test.js@@ -0,0 +1,37 @@+import { describe, expect, it } from 'vitest';+import { readFileSync } from 'node:fs';++const source = readFileSync(new URL('./CollageMenu.svelte', import.meta.url), 'utf8');++describe('CollageMenu renaming', () => {+ it('opens the tab you are already in for editing, and switches to the others', () => {+ expect(source).toContain(` if (cl.id === session.activeCollageId) {+ renamingId = cl.id;+ draftName = cl.name ?? '';+ } else {+ switchCollage(cl.id);+ }`);+ expect(source).toContain(+ "title={cl.id === session.activeCollageId ? 'Rename this collage' : 'Switch to this collage'}"+ );+ });++ it('commits on Enter or blur and abandons on Escape', () => {+ expect(source).toContain("if (event.key === 'Enter') commitRename(cl);");+ expect(source).toContain("else if (event.key === 'Escape') renamingId = null;");+ expect(source).toContain('onblur={() => commitRename(cl)}');+ });++ it('refuses to blank a collage name', () => {+ expect(source).toContain(` const next = draftName.trim();+ if (next && next !== cl.name) {`);+ });++ it('tells the Save tab the name is now the user\'s', () => {+ expect(source).toContain('onRename?.(cl);');+ });++ it('caps the name at the length the Save gate accepts', () => {+ expect(source).toContain('maxlength="200"');+ });+});diff --git a/frontend/src/tools/inspect/SaveGallery.svelte b/frontend/src/tools/inspect/SaveGallery.svelteindex 6718a08..60c1ba5 100644--- a/frontend/src/tools/inspect/SaveGallery.svelte+++ b/frontend/src/tools/inspect/SaveGallery.svelte@@ -5,7 +5,10 @@// Viewer side of the Save tab: everything this session produced that can be// filed — the enhanced video, each adjusted frame, the collage. Tick the ones// to commit; the menu on the right does the actual save.- let { savables, saveUi } = $props();+ // `saveName`/`setSaveName` read and write wherever an item's name actually+ // lives — the session for a collage, saveUi for everything else — so this+ // gallery never has to know the difference.+ let { savables, saveUi, saveName, setSaveName } = $props();function toggle(key) {saveUi.selected[key] = !saveUi.selected[key];@@ -20,26 +23,34 @@</div>{:else}{#each savables as it (it.key)}- <button class="card" class:sel={saveUi.selected[it.key]} class:saved={it.saved} onclick={() => toggle(it.key)}>- <div class="thumb">- {#if it.kind === 'collage' && it.collage?.nodes.length}- {#if it.preview}- <!-- the actual composited PNG (backend warp), on a checker so alpha reads -->- <div class="collage-real checker"><img src={it.preview} alt={it.label} /></div>+ <div class="card" class:sel={saveUi.selected[it.key]} class:saved={it.saved}>+ <button class="pick" onclick={() => toggle(it.key)} aria-label={`Select ${it.defaultName}`}>+ <div class="thumb">+ {#if it.kind === 'collage' && it.collage?.nodes.length}+ {#if it.preview}+ <!-- the actual composited PNG (backend warp), on a checker so alpha reads -->+ <div class="collage-real checker"><img src={it.preview} alt={it.defaultName} /></div>+ {:else}+ <CollagePreview collage={it.collage} />+ {/if}+ {:else if it.thumb}+ <img src={it.thumb} alt={it.defaultName} style:filter={it.filter} style:transform={it.transform} />{:else}- <CollagePreview collage={it.collage} />+ <Icon name={it.kind === 'collage' ? 'layers' : it.kind === 'video' ? 'video' : 'image'} size={30} />{/if}- {:else if it.thumb}- <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}- <span class="kind"><Icon name={it.kind === 'video' ? 'video' : it.kind === 'collage' ? 'layers' : 'image'} size={12} /></span>- <span class="tick"><Icon name="check" size={14} /></span>- </div>- <span class="label">{it.label}</span>- {#if it.saved}<span class="badge">saved</span>{/if}- </button>+ <span class="kind"><Icon name={it.kind === 'video' ? 'video' : it.kind === 'collage' ? 'layers' : 'image'} size={12} /></span>+ <span class="tick"><Icon name="check" size={14} /></span>+ {#if it.saved}<span class="badge">saved</span>{/if}+ </div>+ </button>+ <input+ class="name"+ bind:value={() => saveName(it), (v) => setSaveName(it, v)}+ placeholder={it.defaultName}+ aria-label={`Name for ${it.defaultName}`}+ maxlength="200"+ />+ </div>{/each}{/if}</div>@@ -81,6 +92,13 @@text-align: left;position: relative;}+ .pick {+ display: block;+ width: 100%;+ padding: 0;+ border: 0;+ background: none;+ }.card.sel {border-color: var(--accent);}@@ -149,17 +167,27 @@border-color: var(--accent);color: var(--accent-text);}- .label {+ .name {+ width: 100%;+ font: inherit;font-size: var(--fs-sm);- color: var(--text-2);- white-space: nowrap;- overflow: hidden;- text-overflow: ellipsis;+ color: var(--text-1);+ background: var(--bg-0);+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ padding: 3px 6px;+ }+ .name:focus {+ outline: none;+ border-color: var(--accent);+ }+ .name::placeholder {+ color: var(--text-3);}.badge {position: absolute;- bottom: 8px;- right: 8px;+ bottom: 4px;+ right: 4px;font-size: 9px;text-transform: uppercase;letter-spacing: 0.04em;diff --git a/frontend/src/tools/inspect/SaveGallery.test.js b/frontend/src/tools/inspect/SaveGallery.test.jsnew file mode 100644index 0000000..7ffff00--- /dev/null+++ b/frontend/src/tools/inspect/SaveGallery.test.js@@ -0,0 +1,69 @@+import { describe, expect, it } from 'vitest';+import { render } from 'svelte/server';+import { readFileSync } from 'node:fs';+import SaveGallery from './SaveGallery.svelte';++const source = readFileSync(new URL('./SaveGallery.svelte', import.meta.url), 'utf8');++const SAVABLES = [+ { key: 'frame:1', kind: 'frame', defaultName: 'roof 00-01-00', thumb: '/files/c/a.png' },+ { key: 'frame:2', kind: 'frame', defaultName: 'roof 00-02-00', thumb: '/files/c/b.png' },+];++function body(overrides = {}) {+ const saveUi = { selected: {}, folder: '', touched: {}, baseName: '', note: '' };+ const names = { 'frame:1': 'roof 00-01-00', 'frame:2': 'roof 00-02-00', ...overrides.names };+ return render(SaveGallery, {+ props: {+ savables: SAVABLES,+ saveUi,+ saveName: (it) => names[it.key] ?? '',+ setSaveName: (it, v) => (names[it.key] = v),+ ...overrides,+ },+ }).body;+}++describe('SaveGallery naming', () => {+ it('offers a name field per card instead of a fixed label', () => {+ const html = body();+ expect(html).toContain('aria-label="Name for roof 00-01-00"');+ expect(html).toContain('aria-label="Name for roof 00-02-00"');+ expect(html).not.toContain('class="label"');+ });++ it('holds the name as editable text, not a placeholder to guess at', () => {+ const html = body();+ expect(html).toContain('value="roof 00-01-00"');+ expect(html).toContain('value="roof 00-02-00"');+ });++ it('shows the base name the gallery was refilled with', () => {+ const html = body({ names: { 'frame:1': 'Roof 01', 'frame:2': 'Roof 02' } });+ expect(html).toContain('value="Roof 01"');+ });++ it('reads and writes through the owner of the name, not a local copy', () => {+ expect(source).toContain('bind:value={() => saveName(it), (v) => setSaveName(it, v)}');+ expect(source).not.toContain('saveUi.names[it.key]');+ });++ it('caps a name at the length the API accepts', () => {+ expect(body()).toContain('maxlength="200"');+ });++++ it('keeps the thumbnail as the tick target, so typing does not toggle it', () => {+ expect(source).toContain('<button class="pick" onclick={() => toggle(it.key)}');+ expect(source).not.toContain('<button class="card"');+ });++ it('moves the saved badge onto the thumbnail, clear of the name field', () => {+ const saved = [{ ...SAVABLES[0], saved: true }];+ const html = body({ savables: saved });+ expect(html).toContain('saved');+ expect(source).toContain(`{#if it.saved}<span class="badge">saved</span>{/if}+ </div>`);+ });+});diff --git a/frontend/src/tools/inspect/SaveMenu.svelte b/frontend/src/tools/inspect/SaveMenu.svelteindex 1c0afff..4f9e327 100644--- a/frontend/src/tools/inspect/SaveMenu.svelte+++ b/frontend/src/tools/inspect/SaveMenu.svelte@@ -20,18 +20,28 @@</script><div class="module">- <p class="hint">Tick what to save; it lands in the Media Library with its provenance.</p>+ <p class="hint">Tick what to save. Names carry into the Media Library with the provenance.</p><div class="pickers"><button class="btn btn-sm" onclick={selectAll} disabled={!savables.length}>Select all</button><button class="btn btn-sm" onclick={selectNone} disabled={!count}>Clear</button></div>- <div class="folder">+ <label class="field">+ <span><Icon name="edit" size={14} /> Base name (optional)</span>+ <input class="input" bind:value={saveUi.baseName} placeholder="Names the batch" maxlength="200" />+ </label>++ <div class="field"><span><Icon name="folder" size={14} /> Folder (optional)</span><FolderSelect bind:value={saveUi.folder} {folders} emptyLabel="Unfiled" /></div>+ <label class="field">+ <span><Icon name="note" size={14} /> Note (optional)</span>+ <textarea class="input note" bind:value={saveUi.note} rows="2" placeholder="Why these matter" maxlength="2000"></textarea>+ </label>+<button class="btn btn-primary w-full" disabled={saving || !count} onclick={save}><Icon name="save" size={15} /> {saving ? 'Saving…' : `Save ${count || ''} to case`.trim()}</button>@@ -56,18 +66,21 @@display: flex;gap: 6px;}- .folder {+ .field {display: flex;flex-direction: column;gap: 5px;font-size: var(--fs-sm);color: var(--text-2);}- .folder span {+ .field span {display: flex;align-items: center;gap: 6px;}+ .note {+ resize: vertical;+ }.w-full {width: 100%;justify-content: center;diff --git a/frontend/src/tools/inspect/SaveMenu.test.js b/frontend/src/tools/inspect/SaveMenu.test.jsnew file mode 100644index 0000000..69e1cc9--- /dev/null+++ b/frontend/src/tools/inspect/SaveMenu.test.js@@ -0,0 +1,37 @@+import { describe, expect, it, vi } from 'vitest';+import { render } from 'svelte/server';+import SaveMenu from './SaveMenu.svelte';++const SAVABLES = [+ { key: 'frame:1', kind: 'frame', defaultName: 'roof 00-01-00' },+ { key: 'frame:2', kind: 'frame', defaultName: 'roof 00-02-00' },+];++function body(overrides = {}) {+ const saveUi = { selected: {}, folder: '', names: {}, baseName: '', note: '' };+ return render(SaveMenu, {+ props: { savables: SAVABLES, saveUi, saving: false, save: vi.fn(), ...overrides },+ }).body;+}++describe('SaveMenu naming', () => {+ it('offers a base name for the whole batch', () => {+ const html = body();+ expect(html).toContain('Base name (optional)');+ expect(html).toContain('placeholder="Names the batch"');+ });++ it('offers one note for the batch, capped at the length the API accepts', () => {+ const html = body();+ expect(html).toContain('Note (optional)');+ expect(html).toContain('maxlength="2000"');+ });++ it('still offers the folder, unchanged', () => {+ expect(body()).toContain('Folder (optional)');+ });++ it('says names carry into the library, in one clause', () => {+ expect(body()).toContain('Tick what to save. Names carry into the Media Library with the provenance.');+ });+});diff --git a/frontend/src/tools/proof/NewProofDialog.svelte b/frontend/src/tools/proof/NewProofDialog.svelteindex 7661e44..2f2c3ae 100644--- a/frontend/src/tools/proof/NewProofDialog.svelte+++ b/frontend/src/tools/proof/NewProofDialog.svelte@@ -1,9 +1,11 @@<script>import Icon from '../../components/Icon.svelte';import Modal from '../../components/Modal.svelte';+ import FolderBrowser from '../../components/FolderBrowser.svelte';+ import PanelCategories from './PanelCategories.svelte';+ import { filterProofPanelItems } from '../../lib/composer.js';let {- name = $bindable(),templateId = $bindable(),panelPaths = $bindable(),query = $bindable(),@@ -18,15 +20,29 @@requestCreation,close,} = $props();++ // "…" swaps the thumbnail grid for the folder view. Panels stay multi-select+ // there: a row toggles the same selection the grid does.+ let browserOpen = $state(false);+ let browsePath = $state('');+ const categoryItems = $derived(filterProofPanelItems(items, '', category));+ const browserEntries = $derived(+ categoryItems.map((item) => ({ ...item, id: item.src, attrs: { folder: item.folder ?? '' } }))+ );++ function toggleBrowser() {+ browserOpen = !browserOpen;+ browsePath = '';+ }++ function pickCategory(id) {+ category = id;+ browsePath = '';+ }</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}>@@ -56,23 +72,32 @@</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>+ <button+ type="button"+ class="btn btn-ghost btn-sm browse-btn"+ title={browserOpen ? 'Show every image' : 'Browse folders'}+ onclick={toggleBrowser}+ >…</button>+ <PanelCategories {items} {category} onpick={pickCategory} /></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 browserOpen}+ <FolderBrowser+ entries={browserEntries}+ path={browsePath}+ rootLabel="Case images"+ mark+ isSelected={(item) => panelPaths.includes(item.src)}+ matches={(item) => filterProofPanelItems([item], query, 'all').length > 0}+ emptyText="This folder has no matching images."+ icon={(item) => (item.kind === 'satellite' ? 'satellite' : 'image')}+ onnavigate={(path) => (browsePath = path)}+ onselect={(item) => togglePanel(item.src)}+ />{:else if !filteredItems.length}<div class="picker-empty">No panels match this search.</div>{:else}@@ -86,7 +111,15 @@onclick={() => togglePanel(item.src)}><span class="pick-image">- <img src={`/files/${caseId}/${item.thumb}`} alt="" loading="lazy" />+ {#if item.thumb}+ <img src={`/files/${caseId}/${item.thumb}`} alt="" loading="lazy" decoding="async" />+ {:else}+ <!-- no cached thumbnail yet: a placeholder, never the+ full-size original in a 150px cell -->+ <span class="pick-placeholder">+ <Icon name={item.thumbPending ? 'clock' : 'image'} size={20} />+ </span>+ {/if}{#if panelPaths.includes(item.src)}<span class="pick-selected"><Icon name="check" size={13} /></span>{/if}@@ -103,7 +136,7 @@<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}>+ <button type="submit" class="btn btn-primary" disabled={creating}><Icon name="plus" size={15} /> {creating ? 'Creating…' : 'Create proof'}</button></div>@@ -164,22 +197,11 @@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;+ .browse-btn {+ min-width: 30px;+ font-size: var(--fs-lg);+ line-height: 1;}- .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));@@ -200,6 +222,15 @@background: var(--bg-2);}.pick-image { position: relative; display: block; }+ .pick-placeholder {+ width: 100%;+ aspect-ratio: 16 / 11;+ display: flex;+ align-items: center;+ justify-content: center;+ background: var(--bg-2);+ color: var(--text-3);+ }.pick-selected {position: absolute;top: 6px;diff --git a/frontend/src/tools/proof/NewProofDialog.test.js b/frontend/src/tools/proof/NewProofDialog.test.jsnew file mode 100644index 0000000..7996b20--- /dev/null+++ b/frontend/src/tools/proof/NewProofDialog.test.js@@ -0,0 +1,88 @@+import { describe, expect, it, vi } from 'vitest';+import { render } from 'svelte/server';+import { readFileSync } from 'node:fs';+import NewProofDialog from './NewProofDialog.svelte';+import { filterProofPanelItems } from '../../lib/composer.js';++const source = readFileSync(new URL('./NewProofDialog.svelte', import.meta.url), 'utf8');++const ITEMS = [+ { src: 'media/sat.png', label: '48.85, 2.35 · z17', kind: 'satellite', folder: '', thumb: 'media/sat.png', meta: {} },+ { src: 'media/IMG_1.jpg', label: 'Bridge', kind: 'media', folder: 'field', thumb: 'media/IMG_1.jpg', meta: {} },+];++function props(overrides = {}) {+ const query = overrides.query ?? '';+ const category = overrides.category ?? 'all';+ return {+ templateId: '',+ panelPaths: [],+ query,+ category,+ templates: [],+ items: ITEMS,+ filteredItems: filterProofPanelItems(ITEMS, query, category),+ loading: false,+ creating: false,+ caseId: 'case-1',+ togglePanel: vi.fn(),+ requestCreation: vi.fn(),+ close: vi.fn(),+ ...overrides,+ };+}++describe('Create proof dialog', () => {+ it('offers the same category chips as the Add-a-panel picker', () => {+ const { body } = render(NewProofDialog, { props: props() });++ expect(body).toContain('Satellite captures');+ expect(body).toContain('Other images');+ expect(source).toContain("import PanelCategories from './PanelCategories.svelte'");+ });++ it('opens the shared folder browser behind the "…"', () => {+ expect(source).toContain("import FolderBrowser from '../../components/FolderBrowser.svelte'");+ expect(source).toContain('function toggleBrowser()');+ expect(source).toContain('rootLabel="Case images"');+ expect(source).toContain('onselect={(item) => togglePanel(item.src)}');+ expect(source).toContain('isSelected={(item) => panelPaths.includes(item.src)}');+ expect(source).toContain('mark');+ });++ it('does not ask for a name — the header names the proof', () => {+ const { body } = render(NewProofDialog, { props: props() });++ expect(body).not.toContain('Proof name');+ expect(source).not.toContain('bind:value={name}');+ });++ it('shows the thumbnail grid until the browser is opened', () => {+ const { body } = render(NewProofDialog, { props: props() });++ expect(body).toContain('pick-grid');+ expect(body).not.toContain('browser-list');+ });+});++describe('Create proof dialog previews', () => {+ const pending = [{ src: 'media/clip.png', label: 'Roof', kind: 'media', folder: '', thumb: null, thumbPending: true, meta: {} }];+ const ready = [{ src: 'media/roof.png', label: 'Roof', kind: 'media', folder: '', thumb: 'media/.thumbs/abc-g2.jpg', meta: {} }];++ it('renders the cached thumbnail when there is one', () => {+ const { body } = render(NewProofDialog, {+ props: props({ items: ready, filteredItems: ready }),+ });++ expect(body).toContain('/files/case-1/media/.thumbs/abc-g2.jpg');+ });++ it('shows a placeholder rather than the original while a thumbnail is generating', () => {+ const { body } = render(NewProofDialog, {+ props: props({ items: pending, filteredItems: pending }),+ });++ expect(body).not.toContain('<img');+ expect(body).not.toContain('media/clip.png');+ });+});diff --git a/frontend/src/tools/proof/PanelCategories.svelte b/frontend/src/tools/proof/PanelCategories.sveltenew file mode 100644index 0000000..d55428b--- /dev/null+++ b/frontend/src/tools/proof/PanelCategories.svelte@@ -0,0 +1,46 @@+<script>+ // The All / Satellite captures / Other images chips shared by the two panel+ // pickers (Create proof and Add a panel). Counts are of the whole set, so a+ // chip says how much it would bring back before it is pressed.+ let { items, category, onpick } = $props();++ const CATEGORIES = [+ { id: 'all', label: 'All' },+ { id: 'satellite', label: 'Satellite captures' },+ { id: 'media', label: 'Other images' },+ ];++ const count = (id) => (id === 'all' ? items.length : items.filter((item) => item.kind === id).length);+</script>++<div class="panel-categories" aria-label="Panel categories">+ {#each CATEGORIES as chip (chip.id)}+ <button+ type="button"+ class:active={category === chip.id}+ aria-pressed={category === chip.id}+ onclick={() => onpick(chip.id)}+ >+ {chip.label} <span>{count(chip.id)}</span>+ </button>+ {/each}+</div>++<style>+ .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); }+</style>diff --git a/frontend/src/tools/proof/ProofLayersPanel.svelte b/frontend/src/tools/proof/ProofLayersPanel.svelteindex af4aabb..4804754 100644--- a/frontend/src/tools/proof/ProofLayersPanel.svelte+++ b/frontend/src/tools/proof/ProofLayersPanel.svelte@@ -6,16 +6,23 @@collapsed,gonePanels,selectedPanelId = $bindable(),+ selectedPasteId = $bindable(),selectedId = $bindable(),activeColor,caseId,scaleMin,scaleMax,scaleStep,+ frameWidthMax,+ frameColor,openPicker,movePanelZ,scalePanel,removePanel,+ movePasteZ,+ removePaste,+ setFrame,+ pickImageFile,featureList,moveLegendColor,setColor,@@ -30,6 +37,45 @@} = $props();</script>+<!-- Coloured border for a panel or a pasted image. Picking a colour adds one,+ thickness 0 or the cross takes it away. -->+{#snippet frameControl(item)}+ <div class="frame-ctl">+ <label+ class="color-btn color-pick bg-pick"+ class:active={!!item.frame}+ style:background={item.frame?.color ?? 'transparent'}+ title="Border color"+ >+ <Icon name="square" size={11} />+ <input+ type="color"+ value={item.frame?.color ?? frameColor}+ oninput={(event) => setFrame(item, { color: event.target.value })}+ aria-label="border color"+ />+ </label>+ {#if item.frame}+ <input+ class="input frame-width"+ type="number"+ min="0"+ max={frameWidthMax}+ step="1"+ value={item.frame.width}+ oninput={(event) => setFrame(item, { width: +event.target.value })}+ title="Border thickness"+ aria-label="border thickness"+ />+ <button+ class="btn btn-ghost btn-sm"+ title="Remove border"+ onclick={() => setFrame(item, null)}+ ><Icon name="x" size={11} /></button>+ {/if}+ </div>+{/snippet}+<div class="side-title-row" style="margin-top: 14px"><button class="side-title collapsible" onclick={() => (collapsed.panels = !collapsed.panels)}><span>@@ -37,8 +83,8 @@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 class="btn btn-sm side-add" title="Add a panel" onclick={openPicker}>+ <Icon name="plus" size={13} /> Add panel</button></div>{#if !collapsed.panels}@@ -105,6 +151,7 @@onclick={() => scalePanel(index, scaleStep)}>+</button></div>+ {@render frameControl(panel)}<buttonclass="btn btn-ghost btn-sm remove-panel"title="Remove panel"@@ -115,6 +162,57 @@{/each}{/if}+<!-- Overlays: images this proof owns, laid over the composition. They are not+ panels, so they never join a row, claim no source, and stay out of the case. -->+<div class="side-title-row spaced">+ <button class="side-title collapsible" onclick={() => (collapsed.overlays = !collapsed.overlays)}>+ <span>+ <Icon name={collapsed.overlays ? 'chevronRight' : 'chevronDown'} size={13} />+ Overlays <span class="count">{proof.pastes.length}</span>+ </span>+ </button>+ <button class="btn btn-sm side-add" title="Add an overlay from a file" onclick={pickImageFile}>+ <Icon name="plus" size={13} /> Add overlay+ </button>+</div>+{#if !collapsed.overlays}+ {#if !proof.pastes.length}+ <div class="none">Paste a screenshot with Ctrl+V. It stays in this proof only.</div>+ {/if}+ {#each proof.pastes as paste, index (paste.id)}+ <div class="panel-row paste-row card" class:selected={selectedPasteId === paste.id}>+ <button+ class="panel-thumb"+ title="Select this overlay on the canvas"+ onclick={() => (selectedPasteId = selectedPasteId === paste.id ? null : paste.id)}+ >+ <img src={paste.img?.src} alt="" />+ <span class="row-badge" title="Z1 is the foreground">Z{index + 1}</span>+ </button>+ <div class="panel-actions">+ <button+ class="btn btn-ghost btn-sm"+ disabled={index === 0}+ title="Bring forward (toward Z1)"+ onclick={() => movePasteZ(index, -1)}+ ><Icon name="chevronUp" size={13} /></button>+ <button+ class="btn btn-ghost btn-sm"+ disabled={index === proof.pastes.length - 1}+ title="Send backward"+ onclick={() => movePasteZ(index, 1)}+ ><Icon name="chevronDown" size={13} /></button>+ {@render frameControl(paste)}+ <button+ class="btn btn-ghost btn-sm remove-panel"+ title="Remove overlay"+ onclick={() => removePaste(index)}+ ><Icon name="trash" size={13} /></button>+ </div>+ </div>+ {/each}+{/if}+<buttonclass="side-title collapsible spaced"onclick={() => (collapsed.annotations = !collapsed.annotations)}@@ -261,14 +359,31 @@padding: 0;cursor: pointer;text-align: left;- font: inherit;+ font-family: inherit;+ font-size: var(--fs-xs);+ font-weight: 600;+ line-height: 1.2;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 { display: flex; align-items: center; gap: 4px; margin-bottom: 8px; }+ .side-title-row.spaced { margin-top: 14px; }.side-title-row .side-title { margin-bottom: 0; }- .side-add { margin-left: auto; color: var(--text-3); }+ .side-add {+ margin-left: auto;+ padding: 2px 7px;+ gap: 5px;+ line-height: 1.1;+ background: var(--bg-2);+ border-color: var(--border-strong);+ color: var(--text-1);+ font-weight: 600;+ }+ .side-add:hover:not(:disabled, .disabled) {+ background: var(--bg-3);+ border-color: var(--text-3);+ }.count { color: var(--text-3); }.gone-note {display: flex;@@ -321,8 +436,16 @@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; }+ .panel-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 2px; row-gap: 4px; }.remove-panel { margin-left: auto; }+ .frame-ctl { display: flex; align-items: center; gap: 3px; }+ .frame-width {+ width: 44px;+ padding: 2px 4px;+ font-size: var(--fs-xs);+ text-align: center;+ font-variant-numeric: tabular-nums;+ }.panel-scale { display: flex; align-items: center; gap: 4px; margin: 0 auto; }.scale-val {min-width: 42px;diff --git a/frontend/src/tools/proof/ProofLayersPanel.test.js b/frontend/src/tools/proof/ProofLayersPanel.test.jsnew file mode 100644index 0000000..80a3470--- /dev/null+++ b/frontend/src/tools/proof/ProofLayersPanel.test.js@@ -0,0 +1,25 @@+import { describe, expect, it } from 'vitest';+import { readFileSync } from 'node:fs';++const source = readFileSync(new URL('./ProofLayersPanel.svelte', import.meta.url), 'utf8');++describe('Proof Layers panel hierarchy', () => {+ it('keeps section headings compact inside button styles', () => {+ const styles = source.slice(source.indexOf('<style>'));++ expect(styles).toContain('.side-title.collapsible');+ expect(styles).toContain('font-size: var(--fs-xs);');+ expect(styles).toContain('font-weight: 600;');+ expect(styles).not.toContain('font: inherit;');+ });++ it('makes the add-panel action explicit and prominent', () => {+ expect(source).toContain('class="btn btn-sm side-add"');+ expect(source).toContain('<Icon name="plus" size={13} /> Add panel');+ expect(source).toContain('background: var(--bg-2);');+ expect(source).toContain('border-color: var(--border-strong);');+ expect(source).toContain('line-height: 1.1;');+ expect(source).toContain('margin-bottom: 8px;');+ expect(source).not.toContain('btn-primary btn-sm side-add');+ });+});diff --git a/frontend/src/tools/satellite/MapToolCluster.svelte b/frontend/src/tools/satellite/MapToolCluster.svelteindex 8a83c96..28097b5 100644--- a/frontend/src/tools/satellite/MapToolCluster.svelte+++ b/frontend/src/tools/satellite/MapToolCluster.svelte@@ -11,6 +11,8 @@toggleTools,gridMode,toggleGridMode,+ savedOverlay = $bindable(),+ savedCount,referenceCount,openRefPicker,setMeasureMode,@@ -20,24 +22,8 @@} = $props();</script>+<!-- Tools: things that change what you are *doing* on the map. --><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><buttonclass="mtbtn"class:on={toolsOpen || measureMode}@@ -61,6 +47,39 @@><Icon name="image" size={16} /></button></div>+<!-- View: what the map *shows you* — the frame, the labels over the imagery,+ the case's own saved work. None of them is a tool, so they continue the+ zoom column instead of sitting among the tools. -->+<div class="view-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={savedOverlay}+ onclick={() => (savedOverlay = !savedOverlay)}+ disabled={!savedCount}+ title={savedCount+ ? 'Show this case\'s saved places and captures on the map'+ : 'Nothing is saved in this case yet'}+ aria-label="Show saved work on the map"+ ><Icon name="pin" size={16} /></button>+</div>+{#if toolsOpen}<div class="measure-panel card"><div class="measure-btns">@@ -97,6 +116,19 @@background: rgba(24, 24, 24, 0.88);backdrop-filter: blur(6px);}+ /* stacked directly under Leaflet's zoom bar (top 58px + 64px tall + its 8px+ margin), same width, so +/- and these read as one column of view controls */+ .view-cluster {+ position: absolute;+ top: 118px;+ left: 0;+ display: flex;+ flex-direction: column;+ gap: 2px;+ padding: 2px;+ background: rgba(24, 24, 24, 0.88);+ backdrop-filter: blur(6px);+ }.mtbtn {display: grid;place-items: center;diff --git a/frontend/src/tools/satellite/SavedOverlay.svelte b/frontend/src/tools/satellite/SavedOverlay.sveltenew file mode 100644index 0000000..4f40263--- /dev/null+++ b/frontend/src/tools/satellite/SavedOverlay.svelte@@ -0,0 +1,248 @@+<script>+ /**+ * Session-only Saved navigation layer.+ * Owns the Leaflet group and rebuilds it when items or zoom change.+ */+ import { mount, unmount } from 'svelte';+ import L from 'leaflet';+ import { paths } from '../../components/Icon.svelte';+ import { groupSavedMarkers, markerPrecision } from '../../lib/savedMarkers.js';+ import SavedPopup from './SavedPopup.svelte';++ let {+ map = null,+ items = [],+ caseId,+ coords,+ fullscreen = false,+ hoveredId = $bindable(null),+ onopen,+ onedit,+ onproof,+ onpost,+ onshowproofs,+ } = $props();++ const GLYPH = { place: 'pin', capture: 'satellite', screenshot: 'screen', proof: 'proof' };++ let zoom = $state(null);++ // Keep marker elements by item id for hover sync without a rebuild.+ let elements = $state(new Map());++ function glyph(name, size) {+ return (+ `<svg viewBox="0 0 24 24" width="${size}" height="${size}" fill="none" stroke="currentColor"` ++ ` stroke-width="2" stroke-linecap="round" stroke-linejoin="round">` ++ `<path d="${paths[name] ?? paths.alert}"/></svg>`+ );+ }++ function icon(mark) {+ // Mixed stacks use the shared place glyph.+ const kind = mark.kinds.length > 1 ? 'place' : mark.kinds[0];+ const count =+ mark.items.length > 1 ? `<i class="saved-mark-count">${mark.items.length}</i>` : '';+ // A proof borrowing capture coordinates appears as a dot on that capture.+ const worked = mark.items.some((row) => row.proofs > 0)+ ? '<i class="saved-mark-worked"></i>'+ : '';+ return L.divIcon({+ className: 'saved-mark-wrap',+ html: `<span class="saved-mark saved-mark-${kind}">${glyph(GLYPH[kind] ?? 'pin', 13)}${count}${worked}</span>`,+ iconSize: [24, 24],+ iconAnchor: [12, 12],+ });+ }++ // Mount popup content as a component inside Leaflet's container.+ let mounted = null;++ function popupContent(mark) {+ const host = document.createElement('div');+ if (mounted) unmount(mounted);+ mounted = mount(SavedPopup, {+ target: host,+ props: {+ items: mark.items,+ caseId,+ coords,+ fullscreen,+ onopen: (row) => {+ map.closePopup();+ onopen(row);+ },+ onedit: (row) => {+ map.closePopup();+ onedit(row);+ },+ onproof: (row) => {+ map.closePopup();+ onproof?.(row);+ },+ onpost: (post) => {+ map.closePopup();+ onpost?.(post);+ },+ onshowproofs: () => {+ map.closePopup();+ onshowproofs?.();+ },+ },+ });+ return host;+ }++ $effect(() => {+ if (!map) return;+ const sync = () => (zoom = map.getZoom());+ sync();+ map.on('zoomend', sync);+ return () => map.off('zoomend', sync);+ });++ $effect(() => {+ if (!map) return;+ const marks = groupSavedMarkers(items, markerPrecision(zoom));+ const next = new Map();+ const group = L.layerGroup(+ marks.map((mark) => {+ const marker = L.marker([mark.lat, mark.lon], {+ icon: icon(mark),+ title: mark.items.length > 1 ? `${mark.items.length} saved here` : mark.items[0].title,+ keyboard: false,+ });+ marker.on('add', () => {+ // one proof can hold two points, so identity here is the row key,+ // not the entity: hovering either place must light that place+ for (const row of mark.items) next.set(row.key ?? row.id, marker.getElement());+ });+ marker.on('mouseover', () => (hoveredId = mark.items[0].key ?? mark.items[0].id));+ marker.on('mouseout', () => (hoveredId = null));+ // every mark opens its card, one item or five: clicking a pin should+ // tell you what is there before it moves the map out from under you+ marker.bindPopup(() => popupContent(mark), {+ className: 'saved-popup',+ minWidth: 296,+ maxWidth: 330,+ autoPanPadding: [24, 24],+ });+ return marker;+ })+ ).addTo(map);+ elements = next;+ return () => {+ elements = new Map();+ group.remove();+ if (mounted) {+ unmount(mounted);+ mounted = null;+ }+ };+ });++ // hover sync, both directions: the tree and the modal set hoveredId, the+ // markers above set it too, and this is the one place that paints it+ let lit = null;+ $effect(() => {+ const id = hoveredId;+ if (lit && lit !== elements.get(id)) lit.classList.remove('is-hovered');+ lit = id ? (elements.get(id) ?? null) : null;+ lit?.classList.add('is-hovered');+ });+</script>++<style>+ /* Leaflet builds these elements itself, outside this component's markup, so+ the marker styles have to be global. One colour family throughout — the+ overlay must read as a single layer, not as a legend. */+ :global(.saved-mark-wrap) {+ background: none;+ border: none;+ }+ :global(.saved-mark) {+ position: relative;+ display: grid;+ place-items: center;+ width: 24px;+ height: 24px;+ border-radius: 50% 50% 50% 2px;+ transform: rotate(-45deg);+ background: var(--accent);+ color: var(--accent-text);+ box-shadow: 0 0 0 1.5px rgba(0, 0, 0, 0.55), 0 2px 5px rgba(0, 0, 0, 0.45);+ transition: transform 0.12s var(--ease);+ }+ :global(.saved-mark > svg) {+ transform: rotate(45deg);+ }+ /* a place is the point itself and carries no imagery — outlined, so a stack+ of captures never hides behind one */+ :global(.saved-mark-place) {+ background: rgba(20, 20, 20, 0.82);+ color: var(--accent);+ box-shadow: 0 0 0 1.5px var(--accent), 0 2px 5px rgba(0, 0, 0, 0.45);+ }+ :global(.saved-mark-count) {+ position: absolute;+ top: -5px;+ right: -5px;+ min-width: 15px;+ padding: 0 3px;+ border-radius: 8px;+ transform: rotate(45deg);+ background: #141414;+ color: #fff;+ font-size: 9px;+ font-weight: 700;+ font-style: normal;+ line-height: 15px;+ text-align: center;+ }+ /* One dot however many proofs: the mark says "already worked", the card says+ how many. The mark is rotated -45°, so the *top edge* of the box is what+ reads as up-left on screen — and the count badge, on the top-right corner,+ reads as straight up. They never collide. */+ :global(.saved-mark-worked) {+ position: absolute;+ top: -3px;+ left: 8px;+ width: 8px;+ height: 8px;+ border-radius: 50%;+ background: #fff;+ box-shadow: 0 0 0 1.5px rgba(0, 0, 0, 0.55);+ }+ :global(.saved-mark-wrap.is-hovered .saved-mark),+ :global(.saved-mark-wrap:hover .saved-mark) {+ transform: rotate(-45deg) scale(1.25);+ z-index: 500;+ }+ /* Leaflet's default popup is a white speech bubble; over imagery it has to be+ one of the app's own surfaces instead. */+ :global(.saved-popup .leaflet-popup-content-wrapper) {+ background: var(--bg-1);+ color: var(--text-1);+ border: 1px solid var(--border-strong);+ border-radius: var(--r-lg);+ box-shadow: var(--shadow-2);+ padding: 2px;+ }+ :global(.saved-popup .leaflet-popup-content) {+ margin: 10px 12px;+ line-height: 1.4;+ }+ :global(.saved-popup .leaflet-popup-tip) {+ background: var(--bg-1);+ border: 1px solid var(--border-strong);+ box-shadow: none;+ }+ :global(.saved-popup .leaflet-popup-close-button) {+ color: var(--text-3) !important;+ padding: 6px 7px 0 0 !important;+ }+ :global(.saved-popup .leaflet-popup-close-button:hover) {+ color: var(--text-1) !important;+ background: none !important;+ }+</style>diff --git a/frontend/src/tools/satellite/SavedPopup.svelte b/frontend/src/tools/satellite/SavedPopup.sveltenew file mode 100644index 0000000..503cf9e--- /dev/null+++ b/frontend/src/tools/satellite/SavedPopup.svelte@@ -0,0 +1,395 @@+<script>+ /**+ * What a mark on the map holds, when you click it.+ *+ * One point can hold several saved items — the same place captured on three+ * dates, a place plus its crop. So this is always a list, even of one: the+ * answer to "what do I already have here?" reads the same whether it is one+ * item or five. Ordered by imagery date, so a stack reads as a timeline of+ * the ground rather than of your clicks.+ */+ import Icon from '../../components/Icon.svelte';+ import { postTarget } from '../../lib/post.js';+ import { stackOrder } from '../../lib/savedMarkers.js';++ let {+ items = [],+ caseId,+ coords,+ fullscreen = false,+ onopen,+ onedit,+ onproof,+ onpost,+ onshowproofs,+ } = $props();++ const GLYPH = { place: 'pin', capture: 'satellite', screenshot: 'screen', proof: 'proof' };+ const KIND = { place: 'Place', capture: 'Capture', screenshot: 'Screenshot', proof: 'Proof' };++ const linkedPosts = (row) => Array.isArray(row.linked_posts) ? row.linked_posts : [];+ let expandedPostRows = $state([]);+ const rowKey = (row) => row.key ?? row.id;+ const postsExpanded = (row) => expandedPostRows.includes(rowKey(row));+ const visiblePosts = (row) =>+ postsExpanded(row) ? linkedPosts(row) : linkedPosts(row).slice(0, 2);+ const hiddenPostCount = (row) => Math.max(0, linkedPosts(row).length - 2);++ function expandPosts(event, row) {+ // Leaflet closes a popup when a click reaches the map. This control changes+ // only the popup's own contents, so keep the event inside the card.+ event.stopPropagation();+ if (!postsExpanded(row)) expandedPostRows = [...expandedPostRows, rowKey(row)];+ }++ /** What the dot on the mark meant. A proof borrows this capture's point, so+ * it is named here rather than drawn as a second mark. */+ const worked = (row) =>+ row.proofs > 0 ? `${row.proofs} proof${row.proofs > 1 ? 's' : ''} here` : null;++ const ordered = $derived(stackOrder(items));+ const here = $derived(ordered[0]);++ const day = (stamp) => (stamp ? String(stamp).slice(0, 10) : null);+</script>++<div class="pop">+ <header>+ <span class="mono where">{coords(here)}</span>+ {#if ordered.length > 1}<span class="tally">{ordered.length} saved here</span>{/if}+ </header>++ <div class="stack" class:scrolls={ordered.length > 2}>+ {#each ordered as row (row.key ?? row.id)}+ {@const flyable = row.lat != null && row.lon != null}+ {@const rowPosts = linkedPosts(row)}+ <div class="entry">+ <button+ type="button"+ class="preview"+ disabled={!flyable && !row.source_url}+ title={flyable ? 'Fly the map here' : 'Open the source page'}+ onclick={() => onopen(row)}+ >+ {#if row.thumbnail && caseId}+ <img src={`/files/${caseId}/${row.thumbnail}`} alt="" loading="lazy" decoding="async" />+ {:else}+ <Icon name={GLYPH[row.kind] ?? 'pin'} size={20} />+ {/if}+ </button>+ <div class="body">+ <button type="button" class="title" onclick={() => onopen(row)}>+ {row.title || 'Untitled'}+ </button>+ <p class="meta">+ <span class="kind"><Icon name={GLYPH[row.kind] ?? 'pin'} size={10} /> {KIND[row.kind]}</span>+ {#if row.provider ?? row.site}<span>{row.provider ?? row.site}</span>{/if}+ {#if row.zoom != null}<span>z{Math.round(row.zoom)}</span>{/if}+ </p>+ <p class="meta">+ {#if row.imagery_date}<span>Imagery {row.imagery_date}</span>{/if}+ {#if day(row.fetched_at)}<span>Saved {day(row.fetched_at)}</span>{/if}+ </p>+ {#if worked(row)}+ <p class="worked">+ <span class="worked-dot"></span>+ <span>{worked(row)}</span>+ <button type="button" class="link" onclick={() => onshowproofs?.()}>+ Show proofs+ </button>+ </p>+ {/if}+ {#if row.notes}<p class="note">{row.notes}</p>{/if}+ {#if rowPosts.length}+ <section class="linked-posts">+ <p class="post-heading">+ <Icon name="post" size={11} />+ {rowPosts.length === 1 ? 'Linked post' : `Linked posts · ${rowPosts.length}`}+ </p>+ <div class="post-list" class:expanded={postsExpanded(row)}>+ {#each visiblePosts(row) as post (post.id)}+ <button+ type="button"+ class="post-row"+ title={`Open "${post.title}" in Geo Report`}+ onclick={() => onpost?.(post)}+ >+ <span class="post-target">{postTarget(post.target).label}</span>+ <span class="post-title">{post.title}</span>+ <Icon name="chevronRight" size={11} />+ </button>+ {/each}+ {#if !postsExpanded(row) && hiddenPostCount(row)}+ <button type="button" class="more-posts" onclick={(event) => expandPosts(event, row)}>+ + {hiddenPostCount(row)} more+ </button>+ {/if}+ </div>+ </section>+ {/if}+ <p class="acts">+ {#if row.kind === 'proof'}+ <button type="button" class="link" onclick={() => onproof?.(row)}>+ Open in Geo Proof+ </button>+ {:else}+ <button type="button" class="link" onclick={() => onedit(row)}>Edit</button>+ {/if}+ {#if row.source_url}+ <a+ class="link"+ class:off={fullscreen}+ href={fullscreen ? undefined : row.source_url}+ target="_blank"+ rel="noreferrer"+ aria-disabled={fullscreen}+ title={fullscreen ? 'Exit fullscreen first. This leaves the map' : row.source_url}+ >Source <Icon name="external" size={10} /></a>+ {/if}+ {#if row.path}+ <a+ class="link"+ class:off={fullscreen}+ href={fullscreen ? undefined : `/files/${caseId}/${row.path}`}+ target="_blank"+ rel="noreferrer"+ aria-disabled={fullscreen}+ title={fullscreen ? 'Exit fullscreen first. This leaves the map' : 'Open the full image'}+ >Full image <Icon name="external" size={10} /></a>+ {/if}+ </p>+ </div>+ </div>+ {/each}+ </div>+</div>++<style>+ .pop {+ width: 296px;+ font-family: var(--font-sans);+ }+ header {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: 8px;+ padding-bottom: 6px;+ border-bottom: 1px solid var(--border);+ }+ .where {+ font-size: var(--fs-xs);+ color: var(--text-2);+ }+ .tally {+ font-size: var(--fs-xs);+ color: var(--accent);+ white-space: nowrap;+ }+ .stack {+ display: flex;+ flex-direction: column;+ }+ /* two entries fit; past that the popup scrolls rather than growing off-map */+ .stack.scrolls {+ max-height: 260px;+ overflow-y: auto;+ }+ .entry {+ display: flex;+ gap: 9px;+ padding: 8px 0;+ }+ .entry + .entry {+ border-top: 1px solid var(--border);+ }+ .preview {+ display: grid;+ place-items: center;+ position: relative;+ flex: 0 0 auto;+ width: 72px;+ height: 52px;+ border-radius: var(--r-sm);+ background: var(--bg-3);+ color: var(--text-3);+ overflow: hidden;+ cursor: pointer;+ }+ .preview img {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ object-fit: cover;+ }+ .preview:hover:not(:disabled) {+ box-shadow: 0 0 0 1px var(--accent);+ }+ .body {+ min-width: 0;+ display: flex;+ flex-direction: column;+ gap: 2px;+ }+ .title {+ padding: 0;+ background: none;+ border: none;+ font: inherit;+ font-size: var(--fs-sm);+ font-weight: 600;+ color: var(--text-1);+ text-align: left;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ cursor: pointer;+ }+ .title:hover {+ color: var(--accent);+ }+ .meta {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 7px;+ margin: 0;+ font-size: var(--fs-xs);+ color: var(--text-3);+ }+ .meta:empty {+ display: none;+ }+ /* the same dot separator the rest of the app uses between metadata bits */+ .meta > * + *::before {+ content: '·';+ margin-right: 7px;+ color: var(--border-strong);+ }+ .kind {+ display: inline-flex;+ align-items: center;+ gap: 3px;+ }+ /* the mark's dot, named: the card is where "already worked" becomes a number+ and a way into the proofs view */+ .worked {+ display: flex;+ align-items: center;+ gap: 6px;+ margin: 3px 0 0;+ font-size: var(--fs-xs);+ color: var(--text-2);+ }+ .worked-dot {+ flex: 0 0 auto;+ width: 7px;+ height: 7px;+ border-radius: 50%;+ background: #fff;+ box-shadow: 0 0 0 1.5px rgba(0, 0, 0, 0.55);+ }+ .note {+ margin: 2px 0 0;+ font-size: var(--fs-xs);+ font-style: italic;+ color: var(--text-2);+ overflow-wrap: anywhere;+ }+ .linked-posts {+ margin-top: 4px;+ padding-top: 5px;+ border-top: 1px solid var(--border);+ }+ .post-heading {+ display: flex;+ align-items: center;+ gap: 4px;+ margin: 0 0 3px;+ color: var(--text-3);+ font-size: 9px;+ font-weight: 650;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ }+ .post-list {+ display: flex;+ flex-direction: column;+ gap: 2px;+ }+ .post-list.expanded {+ max-height: 132px;+ overflow-y: auto;+ }+ .post-row {+ display: grid;+ grid-template-columns: auto minmax(0, 1fr) auto;+ align-items: center;+ gap: 5px;+ width: 100%;+ padding: 3px 4px;+ border: 0;+ border-radius: var(--r-sm);+ background: var(--bg-2);+ color: var(--text-2);+ text-align: left;+ cursor: pointer;+ }+ .post-row:hover {+ background: var(--bg-3);+ color: var(--text-1);+ }+ .post-target {+ min-width: 14px;+ padding: 0 3px;+ border: 1px solid var(--border-strong);+ border-radius: 3px;+ color: var(--text-3);+ font-size: 9px;+ line-height: 14px;+ text-align: center;+ }+ .post-title {+ overflow: hidden;+ font-size: var(--fs-xs);+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .more-posts {+ align-self: flex-start;+ padding: 1px 4px;+ border: 0;+ background: none;+ color: var(--accent);+ font-size: var(--fs-xs);+ cursor: pointer;+ }+ .more-posts:hover {+ text-decoration: underline;+ }+ .acts {+ display: flex;+ gap: 10px;+ margin: 4px 0 0;+ }+ .link {+ display: inline-flex;+ align-items: center;+ gap: 3px;+ padding: 0;+ background: none;+ border: none;+ font-size: var(--fs-xs);+ color: var(--accent);+ cursor: pointer;+ }+ .link:hover {+ text-decoration: underline;+ }+ .link.off {+ color: var(--text-3);+ cursor: not-allowed;+ text-decoration: none;+ }+</style>diff --git a/frontend/src/tools/satellite/SavedPopup.test.js b/frontend/src/tools/satellite/SavedPopup.test.jsnew file mode 100644index 0000000..5f72b29--- /dev/null+++ b/frontend/src/tools/satellite/SavedPopup.test.js@@ -0,0 +1,185 @@+import { describe, expect, it } from 'vitest';+import { render } from 'svelte/server';+import { readFileSync } from 'node:fs';+import SavedPopup from './SavedPopup.svelte';++const overlay = readFileSync(new URL('./SavedOverlay.svelte', import.meta.url), 'utf8');++const capture = {+ id: 'c1',+ kind: 'capture',+ title: 'bridge, north bank',+ lat: 48.0159,+ lon: 37.8029,+ zoom: 18,+ provider: 'Esri World Imagery',+ path: 'media/a.png',+ thumbnail: 'media/.thumbs/a.jpg',+ imagery_date: '2024-03',+ fetched_at: '2026-07-20T09:12:04Z',+ notes: 'two vehicles at the gate',+};+const older = { ...capture, id: 'c2', title: 'bridge, earlier pass', imagery_date: '2021-06' };+const place = {+ id: 'p1',+ kind: 'place',+ title: 'checkpoint north',+ lat: 48.0159,+ lon: 37.8029,+ zoom: 18,+ path: null,+ thumbnail: null,+ imagery_date: null,+ fetched_at: '2026-07-18T09:12:04Z',+ notes: '',+};++const noop = () => {};+const at = (items, props = {}) =>+ render(SavedPopup, {+ props: {+ items,+ caseId: 'case-1',+ coords: (row) => `${row.lat}, ${row.lon}`,+ onopen: noop,+ onedit: noop,+ ...props,+ },+ }).body;++describe('SavedPopup', () => {+ it('says what one saved item is, with its preview and both dates', () => {+ const body = at([capture]);++ expect(body).toContain('bridge, north bank');+ expect(body).toContain('/files/case-1/media/.thumbs/a.jpg');+ expect(body).toContain('Capture');+ expect(body).toContain('Esri World Imagery');+ expect(body).toContain('z18');+ expect(body).toContain('Imagery 2024-03');+ expect(body).toContain('Saved 2026-07-20');+ expect(body).toContain('two vehicles at the gate');+ });++ it('lists a stack as a timeline of the ground, newest imagery first', () => {+ const body = at([older, place, capture]);++ expect(body).toContain('3 saved here');+ expect(body.indexOf('bridge, north bank')).toBeLessThan(body.indexOf('bridge, earlier pass'));+ // the undated place falls to the end — it dates nothing on the ground+ expect(body.indexOf('bridge, earlier pass')).toBeLessThan(body.indexOf('checkpoint north'));+ });++ it('does not tally a single item as a stack', () => {+ expect(at([capture])).not.toContain('saved here');+ });++ it('falls back to the kind glyph when there is no preview to show', () => {+ expect(at([place])).not.toContain('/files/case-1/');+ expect(at([place])).toContain('Place');+ });++ it('offers the source page only for an item that recorded one', () => {+ expect(at([capture])).not.toContain('Source');+ expect(at([{ ...capture, source_url: 'https://yandex.com/maps/' }])).toContain(+ 'https://yandex.com/maps/'+ );+ });++ it('opens a proof in its composer and previews its linked posts', () => {+ const proof = {+ id: 'pr1',+ key: '[email protected],37.8029',+ kind: 'proof',+ name: 'kyiv-bridge',+ title: 'Kyiv bridge',+ lat: 48.0159,+ lon: 37.8029,+ path: 'proofs/kyiv-bridge.png',+ thumbnail: 'media/.thumbs/pr.jpg',+ fetched_at: '2026-07-21T09:12:04Z',+ posts: 3,+ linked_posts: [+ { id: 'post-1', name: 'panorama-publication', title: 'Panorama publication', target: 'x' },+ { id: 'post-2', name: 'source-follow-up', title: 'Follow-up with sources', target: 'bluesky' },+ { id: 'post-3', name: 'later-note', title: 'Later note', target: 'mastodon' },+ ],+ };++ const body = at([proof]);+ expect(body).toContain('Kyiv bridge');+ expect(body).toContain('Proof');+ expect(body).toContain('Open in Geo Proof');+ expect(body).toContain('Linked posts · 3');+ expect(body).toContain('Panorama publication');+ expect(body).toContain('Follow-up with sources');+ expect(body).not.toContain('Later note');+ expect(body).toContain('+ 1 more');++ // a post is two hops from a point: it is a chip here, never its own mark+ expect(at([{ ...proof, posts: 0, linked_posts: [] }])).not.toContain('Linked post');+ });++ it('names one linked post directly', () => {+ const body = at([{+ ...capture,+ kind: 'proof',+ linked_posts: [+ { id: 'post-1', name: 'panorama-publication', title: 'Panorama publication', target: 'x' },+ ],+ }]);++ expect(body).toContain('Linked post');+ expect(body).not.toContain('Linked posts ·');+ expect(body).toContain('Panorama publication');+ });++ it('says a capture is already worked, and offers the proofs view from there', () => {+ const body = at([{ ...capture, proofs: 2 }]);++ expect(body).toContain('2 proofs here');+ expect(body).toContain('Show proofs');+ // the same dot the mark wears, so the card explains the mark+ expect(body).toContain('worked-dot');++ expect(at([capture])).not.toContain('Show proofs');+ });++ it('holds back the links that would leave a fullscreen map', () => {+ const body = at([capture], { fullscreen: true });++ expect(body).toContain('Exit fullscreen first');+ expect(body).not.toContain('href="/files/case-1/media/a.png"');+ });+});++describe('SavedOverlay popup wiring', () => {+ it('mounts the card as a component rather than building HTML by hand', () => {+ expect(overlay).toContain("import { mount, unmount } from 'svelte'");+ expect(overlay).toContain('mount(SavedPopup');+ expect(overlay).toContain('unmount(mounted)');+ expect(overlay).toContain('onpost?.(post)');+ });++ it('opens a card for every mark, one item or a stack', () => {+ expect(overlay).toContain('marker.bindPopup(() => popupContent(mark)');+ // no shortcut path that flies straight there on a single-item mark+ expect(overlay).not.toContain("marker.on('click'");+ });++ it('dresses the Leaflet popup as one of the app\'s own surfaces', () => {+ expect(overlay).toContain('.saved-popup .leaflet-popup-content-wrapper');+ expect(overlay).toContain('background: var(--bg-1)');+ });++ it('marks a worked capture instead of letting a proof stack a mark on it', () => {+ // the dot is drawn from the count the saved index carries, and the proof+ // itself is never a second mark at the same point+ expect(overlay).toContain('saved-mark-worked');+ expect(overlay).toContain('proofs > 0');+ });++ it('keys marks on the row key, so one proof at two places lights both', () => {+ expect(overlay).toContain('row.key ?? row.id');+ });+});diff --git a/frontend/src/tools/satellite/SavedRow.svelte b/frontend/src/tools/satellite/SavedRow.sveltenew file mode 100644index 0000000..053d3f8--- /dev/null+++ b/frontend/src/tools/satellite/SavedRow.svelte@@ -0,0 +1,312 @@+<script>+ /**+ * One saved item, as it reads in the Saved tree and in the search modal.+ *+ * The row *is* the primary action: clicking it flies the map to the point, or+ * opens the source page for a screenshot of a site we cannot embed. The rest+ * of the actions stay out of the way until the row is hovered or focused, so+ * a long list scans as titles and coordinates rather than as rows of buttons.+ */+ import Icon from '../../components/Icon.svelte';++ let {+ row,+ caseId,+ coords,+ fullscreen = false,+ dense = false,+ active = false,+ hovered = false,+ // set only by the folder view of the tree, where there is somewhere to drop+ draggable = false,+ ondragstart = () => {},+ onopen,+ onedit,+ ondelete,+ onproof,+ onhover = () => {},+ } = $props();++ const GLYPH = { place: 'pin', capture: 'satellite', screenshot: 'screen', proof: 'proof' };++ const isPlace = $derived(row.kind === 'place');+ const isProof = $derived(row.kind === 'proof');+ // A proof borrows the point of the capture it composes, so `All` marks that+ // capture instead of stacking a second mark on it.+ const worked = $derived(row.proofs > 0 ? `${row.proofs} proof${row.proofs > 1 ? 's' : ''} built here` : null);+ const flyable = $derived(row.lat != null && row.lon != null);+ // a screenshot with no position can only be reopened where it came from+ const opensSource = $derived(!flyable && !!row.source_url);+ // one string, ellipsized as a whole: truncating bit by bit leaves stubs like+ // "· … ·" in a 300px panel+ const meta = $derived(+ [row.zoom != null ? `z${Math.round(row.zoom)}` : null, row.provider ?? row.site, row.imagery_date]+ .filter(Boolean)+ .join(' · ')+ );+ const blocked = $derived(fullscreen ? 'Exit fullscreen first. This leaves the map' : null);+</script>++<div+ class="row"+ class:dense+ class:active+ class:hovered+ class:draggable+ data-saved-id={row.key ?? row.id}+ {draggable}+ ondragstart={draggable ? ondragstart : undefined}+ onmouseenter={() => onhover(row.key ?? row.id)}+ onmouseleave={() => onhover(null)}+ role="presentation"+>+ <button+ type="button"+ class="open"+ disabled={!flyable && !opensSource}+ title={opensSource+ ? `Open the source page (${row.site ?? 'external map'})`+ : flyable+ ? 'Fly the map to this point'+ : 'No coordinates recorded'}+ onclick={() => onopen(row)}+ >+ <span class="thumb">+ {#if row.thumbnail && caseId}+ <img src={`/files/${caseId}/${row.thumbnail}`} alt="" loading="lazy" decoding="async" />+ {:else}+ <Icon name={GLYPH[row.kind] ?? 'pin'} size={dense ? 16 : 14} />+ {/if}+ {#if row.thumbnail}+ <span class="badge"><Icon name={GLYPH[row.kind] ?? 'pin'} size={9} /></span>+ {/if}+ {#if worked}<span class="worked" role="img" aria-label={worked} title={worked}></span>{/if}+ </span>+ <span class="text">+ <span class="title">{row.title || 'Untitled'}</span>+ <span class="sub">+ <!-- a screenshot filed from a URL that carried no position has none:+ say so rather than printing 0°, 0° -->+ {#if flyable}<span class="mono">{coords(row)}</span>{:else}<span>No coordinates</span>{/if}+ {#if meta}<span class="bits">{meta}</span>{/if}+ </span>+ {#if row.notes}<span class="note">{row.notes}</span>{/if}+ </span>+ </button>++ <div class="actions">+ {#if isProof}+ <!-- a proof is edited and deleted in the composer that owns it; here it+ is a point on the map, and the one thing to do with it is open it -->+ <button+ class="act"+ disabled={fullscreen}+ title={blocked ?? 'Open in Geo Proof'}+ onclick={() => onproof(row)}+ ><Icon name="proof" size={13} /></button>+ {:else}+ {#if row.source_url}+ <a+ class="act"+ class:disabled={fullscreen}+ href={fullscreen ? undefined : row.source_url}+ target="_blank"+ rel="noreferrer"+ aria-disabled={fullscreen}+ title={blocked ?? `Open the source page (${row.site ?? 'external map'})`}+ ><Icon name="external" size={13} /></a>+ {/if}+ <button class="act" title="Edit title & note" onclick={() => onedit(row)}>+ <Icon name="note" size={13} />+ </button>+ {#if !isPlace}+ <button+ class="act"+ disabled={fullscreen}+ title={blocked ?? 'Send to Geo Proof'}+ onclick={() => onproof(row)}+ ><Icon name="proof" size={13} /></button>+ {/if}+ <button class="act danger" title="Delete" onclick={() => ondelete(row)}>+ <Icon name="trash" size={13} />+ </button>+ {/if}+ </div>+</div>++<style>+ .row {+ position: relative;+ display: flex;+ align-items: stretch;+ border-radius: var(--r-sm);+ }+ .row:hover,+ .row.hovered {+ background: var(--bg-2);+ }+ .row.active {+ background: var(--accent-soft);+ box-shadow: inset 2px 0 0 var(--accent);+ }+ .row.draggable {+ cursor: grab;+ }+ .open {+ display: flex;+ align-items: flex-start;+ gap: 8px;+ flex: 1;+ min-width: 0;+ padding: 5px 6px;+ background: none;+ border: none;+ color: inherit;+ text-align: left;+ cursor: pointer;+ }+ .open:disabled {+ cursor: default;+ }+ /* one fixed frame for every kind, so titles and coordinates stay on a grid+ whether the item has an image or not */+ .thumb {+ position: relative;+ display: grid;+ place-items: center;+ flex: 0 0 auto;+ width: 40px;+ height: 28px;+ border-radius: 2px;+ background: var(--bg-3);+ color: var(--text-3);+ overflow: hidden;+ }+ .dense .thumb {+ width: 56px;+ height: 40px;+ }+ .thumb img {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ object-fit: cover;+ }+ .badge {+ position: absolute;+ right: 0;+ bottom: 0;+ display: grid;+ place-items: center;+ padding: 1px 2px;+ background: rgba(0, 0, 0, 0.62);+ color: #fff;+ border-top-left-radius: 2px;+ }+ /* one dot however many proofs: the row says "already worked", the popup+ says how many */+ .worked {+ position: absolute;+ top: 2px;+ right: 2px;+ width: 7px;+ height: 7px;+ border-radius: 50%;+ background: var(--accent);+ box-shadow: 0 0 0 1.5px rgba(0, 0, 0, 0.55);+ }+ .text {+ display: flex;+ flex-direction: column;+ min-width: 0;+ gap: 1px;+ }+ .title {+ font-size: var(--fs-sm);+ color: var(--text-1);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .open:hover:not(:disabled) .title {+ color: var(--accent);+ }+ .sub {+ display: flex;+ align-items: baseline;+ gap: 6px;+ font-size: var(--fs-xs);+ color: var(--text-3);+ overflow: hidden;+ white-space: nowrap;+ }+ .bits {+ overflow: hidden;+ text-overflow: ellipsis;+ }+ .bits::before {+ content: '·';+ margin-right: 6px;+ color: var(--border-strong);+ }+ .note {+ font-size: var(--fs-xs);+ color: var(--text-2);+ font-style: italic;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ /* actions ride on top of the row's right edge: they cost no layout until+ they are wanted, and a 300px panel has none to spare */+ .actions {+ position: absolute;+ top: 0;+ right: 0;+ bottom: 0;+ display: flex;+ align-items: center;+ gap: 1px;+ padding: 0 4px 0 16px;+ opacity: 0;+ pointer-events: none;+ background: linear-gradient(to right, transparent, var(--bg-2) 16px);+ border-radius: var(--r-sm);+ }+ .row:hover .actions,+ .row:focus-within .actions,+ .row.hovered .actions {+ opacity: 1;+ pointer-events: auto;+ }+ .row.active .actions {+ background: linear-gradient(to right, transparent, var(--bg-2) 16px);+ }+ .act {+ display: grid;+ place-items: center;+ width: 22px;+ height: 22px;+ border-radius: var(--r-sm);+ color: var(--text-3);+ cursor: pointer;+ }+ .act:hover {+ color: var(--text-1);+ background: var(--bg-3);+ }+ .act.danger:hover {+ color: var(--danger);+ }+ .act.disabled,+ .act:disabled {+ opacity: 0.35;+ cursor: not-allowed;+ }+ .act.disabled:hover,+ .act:disabled:hover {+ color: var(--text-3);+ background: none;+ }+</style>diff --git a/frontend/src/tools/satellite/SavedSearch.svelte b/frontend/src/tools/satellite/SavedSearch.sveltenew file mode 100644index 0000000..d46ab7d--- /dev/null+++ b/frontend/src/tools/satellite/SavedSearch.svelte@@ -0,0 +1,173 @@+<script>+ /**+ * Search across every saved item at full width — the same index the tree+ * reads, laid out flat with thumbnails and a sort. Nothing is fetched here:+ * the whole set is already in memory, so typing costs no network.+ *+ * Browsing the same set by My-work folder is the panel's job (its globe /+ * folder switch), not this modal's — one road to a folder, not two.+ *+ * It is a Modal, which portals itself into whatever element is fullscreen, so+ * this works over a fullscreen map — the one place the 300px panel does not.+ */+ import Modal from '../../components/Modal.svelte';+ import SearchInput from '../../components/SearchInput.svelte';+ import SavedRow from './SavedRow.svelte';+ import { KINDS, SORTS, filterSaved, oneEach, sortSaved } from '../../lib/geoTree.js';++ let {+ rows = [],+ caseId,+ coords,+ fullscreen = false,+ centre = null,+ kind = $bindable('all'),+ query = $bindable(''),+ hoveredId = $bindable(null),+ onclose,+ onopen,+ onedit,+ ondelete,+ onproof,+ } = $props();++ // A case can hold thousands of saved items; a modal that renders all of them+ // stalls on every keystroke. Narrow the search instead of scrolling forever.+ const CAP = 200;++ let sort = $state('newest');+ // one line per thing: a proof that touches two places is two marks on the+ // map, but repeating it here would read as two proofs+ const found = $derived(sortSaved(oneEach(filterSaved(rows, { kind, query })), sort, centre));+ const shown = $derived(found.slice(0, CAP));++ function open(row) {+ onopen(row);+ onclose();+ }+</script>++<Modal title="Saved work" {onclose} width="760px">+ <div class="bar">+ <SearchInput bind:value={query} placeholder="Search title, note, place, provider…" width="100%" />+ <div class="kinds" role="group" aria-label="What this list shows">+ {#each KINDS as k (k.id)}+ <button+ class="kind"+ class:mode={k.mode}+ class:on={kind === k.id}+ onclick={() => (kind = k.id)}+ >{k.label}</button>+ {/each}+ </div>+ <select class="select sort" bind:value={sort} aria-label="Sort results">+ {#each SORTS as s (s.id)}+ <option value={s.id} disabled={s.id === 'distance' && !centre}>{s.label}</option>+ {/each}+ </select>+ </div>++ {#snippet savedRow(entry)}+ <SavedRow+ row={entry}+ {caseId}+ {coords}+ {fullscreen}+ dense+ hovered={hoveredId === (entry.key ?? entry.id)}+ onhover={(id) => (hoveredId = id)}+ onopen={open}+ {onedit}+ {ondelete}+ {onproof}+ />+ {/snippet}++ <div class="results">+ {#if !rows.length}+ <p class="none">Nothing is saved in this case yet.</p>+ {:else if !found.length}+ <p class="none">No saved item matches that.</p>+ {:else}+ {#each shown as row (row.key ?? row.id)}+ {@render savedRow(row)}+ {/each}+ {/if}+ </div>++ {#if found.length > CAP}+ <p class="tally">Showing the first {CAP} of {found.length}. Narrow the search to see the rest.</p>+ {:else if found.length}+ <p class="tally">{found.length} of {rows.length} saved.</p>+ {/if}+</Modal>++<style>+ .bar {+ display: flex;+ align-items: center;+ gap: 8px;+ padding-bottom: 10px;+ }+ .bar :global(.search-box) {+ flex: 1;+ min-width: 0;+ }+ .kinds {+ display: flex;+ flex-shrink: 0;+ padding: 2px;+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ background: var(--bg-2);+ }+ .kind {+ padding: 3px 10px;+ border-radius: 2px;+ font-size: var(--fs-xs);+ color: var(--text-3);+ cursor: pointer;+ }+ .kind:hover {+ color: var(--text-1);+ }+ /* Proofs is a mode, not a refinement of the three to its left */+ .kind.mode {+ margin-left: 5px;+ border-left: 1px solid var(--border);+ padding-left: 12px;+ border-radius: 0 2px 2px 0;+ }+ .kind.on {+ background: var(--bg-3);+ color: var(--text-1);+ font-weight: 600;+ }+ /* the global .select is width:100% — a sort control that fills the bar+ leaves nothing for the search box */+ .sort {+ width: auto;+ flex-shrink: 0;+ font-size: var(--fs-xs);+ }+ .results {+ display: flex;+ flex-direction: column;+ min-height: 120px;+ max-height: min(58vh, 520px);+ overflow-y: auto;+ border-top: 1px solid var(--border);+ padding-top: 6px;+ }+ .none {+ padding: 24px 4px;+ font-size: var(--fs-sm);+ color: var(--text-3);+ text-align: center;+ }+ .tally {+ padding-top: 8px;+ font-size: var(--fs-xs);+ color: var(--text-3);+ }+</style>diff --git a/frontend/src/tools/satellite/SavedSearch.test.js b/frontend/src/tools/satellite/SavedSearch.test.jsnew file mode 100644index 0000000..5cd2329--- /dev/null+++ b/frontend/src/tools/satellite/SavedSearch.test.js@@ -0,0 +1,139 @@+import { describe, expect, it } from 'vitest';+import { render } from 'svelte/server';+import { readFileSync } from 'node:fs';+import SavedSearch from './SavedSearch.svelte';+import { sortSaved } from '../../lib/geoTree.js';++const source = readFileSync(new URL('./SavedSearch.svelte', import.meta.url), 'utf8');++const rows = [+ {+ id: 'p1',+ kind: 'place',+ title: 'checkpoint north',+ lat: 48.0159,+ lon: 37.8029,+ geo: { state: 'ok', country: 'Ukraine', country_code: 'ua', region: 'Donetsk Oblast' },+ continent: 'Europe',+ fetched_at: '2026-07-20T09:12:04Z',+ folder: 'recon',+ },+ {+ id: 'c1',+ kind: 'capture',+ title: 'bridge',+ lat: 52.23,+ lon: 21.01,+ provider: 'Esri World Imagery',+ geo: { state: 'ok', country: 'Poland', country_code: 'pl', region: 'Mazovia' },+ continent: 'Europe',+ fetched_at: '2026-07-19T09:12:04Z',+ path: 'media/a.png',+ thumbnail: 'media/thumbs/a.jpg',+ folder: 'recon/bridges',+ },+ {+ id: 's1',+ kind: 'screenshot',+ title: 'yandex view',+ lat: null,+ lon: null,+ site: 'yandex-maps',+ source_url: 'https://yandex.com/maps/?ll=1,2',+ geo: { state: 'nocoords' },+ continent: null,+ fetched_at: '2026-07-18T09:12:04Z',+ },+];++const noop = () => {};+const at = (props = {}) =>+ render(SavedSearch, {+ props: {+ rows,+ caseId: 'case-1',+ coords: (row) => `${row.lat}, ${row.lon}`,+ onclose: noop,+ onopen: noop,+ onedit: noop,+ ondelete: noop,+ onproof: noop,+ ...props,+ },+ }).body;++describe('SavedSearch', () => {+ it('searches title, country and provider across every kind', () => {+ expect(at({ query: 'checkpoint' })).toContain('checkpoint north');+ expect(at({ query: 'checkpoint' })).not.toContain('bridge');+ expect(at({ query: 'poland' })).toContain('bridge');+ expect(at({ query: 'esri' })).toContain('bridge');+ expect(at({ query: 'yandex' })).toContain('yandex view');+ });++ it('filters by kind alongside the search', () => {+ expect(at({ kind: 'places' })).not.toContain('bridge');+ expect(at({ kind: 'captures' })).not.toContain('checkpoint north');+ });++ it('offers the three sorts, with distance disabled until the map has a centre', () => {+ expect(at()).toContain('Newest');+ expect(at()).toContain('Title');+ expect(at()).toContain('Distance from map centre');+ expect(at()).toContain('disabled');+ expect(at({ centre: { lat: 48, lon: 37 } })).toContain('Distance from map centre');+ });++ it('gives a coordinate-less screenshot its source URL instead of a fly-to', () => {+ expect(at({ query: 'yandex' })).toContain('https://yandex.com/maps/?ll=1,2');+ });++ it('counts what it is showing, and says so when it has to stop short', () => {+ expect(at()).toContain('3 of 3 saved');+ const many = Array.from({ length: 250 }, (_, i) => ({ ...rows[0], id: `x${i}` }));+ expect(at({ rows: many })).toContain('Showing the first 200 of 250');+ });++ it('says what an empty case and a dead search each found', () => {+ expect(at({ rows: [] })).toContain('Nothing is saved in this case yet');+ expect(at({ query: 'zzzz' })).toContain('No saved item matches that');+ });+});++describe('SavedSearch has no folder browser', () => {+ it('leaves browsing by folder to the panel, so there is one road to a folder', () => {+ expect(source).not.toContain('FolderBrowser');+ expect(source).not.toContain('folderBrowse');+ expect(source).not.toContain('browsing');+ // the sort is always there now: nothing hides it any more+ expect(at({})).toContain('Distance from map centre');+ });+});++describe('SavedSearch sorting', () => {+ it('orders by newest, by title, and by distance from the map centre', () => {+ expect(sortSaved(rows, 'newest').map((r) => r.id)).toEqual(['p1', 'c1', 's1']);+ expect(sortSaved(rows, 'title').map((r) => r.id)).toEqual(['c1', 'p1', 's1']);+ // near Donetsk: the checkpoint first, Warsaw second, the placeless last+ expect(sortSaved(rows, 'distance', { lat: 48.0, lon: 37.8 }).map((r) => r.id)).toEqual([+ 'p1',+ 'c1',+ 's1',+ ]);+ });++ it('falls back to newest when distance has no origin to measure from', () => {+ expect(sortSaved(rows, 'distance', null).map((r) => r.id)).toEqual(['p1', 'c1', 's1']);+ });+});++describe('SavedSearch wiring', () => {+ it('reads the index already in memory — no fetch, no network', () => {+ expect(source).not.toContain('api.');+ expect(source).not.toContain('fetch(');+ });++ it('is a Modal, so it works over a fullscreen map', () => {+ expect(source).toContain("import Modal from '../../components/Modal.svelte'");+ });+});diff --git a/frontend/src/tools/satellite/SavedTree.svelte b/frontend/src/tools/satellite/SavedTree.sveltenew file mode 100644index 0000000..cd62bda--- /dev/null+++ b/frontend/src/tools/satellite/SavedTree.svelte@@ -0,0 +1,458 @@+<script>+ /**+ * The Saved panel: every place, capture and filed screenshot in the case,+ * browsed by geography instead of by scroll position.+ *+ * Two groupings over one set. **Geography** (lib/geoTree.js) is the default:+ * a case that sits in one country opens straight on its regions, one that+ * spans the world opens on continents. **Folders** (lib/folderView.js) shows+ * the same items through My work, and only there can a row be dragged onto a+ * folder to file it. Typing filters before grouping, so the counts always+ * describe what is on screen, and every branch opens while a search is+ * running — a filter that hides its own matches behind chevrons is no filter.+ */+ import Icon from '../../components/Icon.svelte';+ import SearchInput from '../../components/SearchInput.svelte';+ import SavedRow from './SavedRow.svelte';+ import {+ KINDS,+ branchKeys,+ buildGeoTree,+ isMode,+ keyFor,+ pendingLocate,+ } from '../../lib/geoTree.js';+ import { buildFolderTree, keyForFolder } from '../../lib/folderView.js';++ let {+ rows = [],+ folders = [],+ caseId,+ coords,+ fullscreen = false,+ kind = $bindable('all'),+ query = $bindable(''),+ group = $bindable('geo'), // 'geo' | 'folders'+ hoveredId = $bindable(null),+ revealId = null,+ locating = null,+ onopen,+ onedit,+ ondelete,+ onproof,+ onbrowse,+ onlocate,+ oncancelLocate,+ onmove,+ } = $props();++ const byFolder = $derived(group === 'folders');+ const geoTree = $derived(buildGeoTree(rows, { kind, query }));+ const folderTree = $derived(buildFolderTree(rows, folders, { kind, query }));+ // one shape for both, so the branch snippet below never asks which it is+ const tree = $derived(+ byFolder+ ? { levels: [], nodes: folderTree.nodes, trailing: folderTree.unfiled }+ : { levels: geoTree.levels, nodes: geoTree.nodes, trailing: geoTree.unlocated }+ );+ // Locate resolves saved entities. A proof states its own point or borrows one,+ // so the pass has nothing to look up there and the errand must not be offered.+ const pending = $derived(isMode(kind) ? 0 : pendingLocate(rows));+ const searching = $derived(!!query.trim());+ const shown = $derived(+ tree.nodes.reduce((sum, node) => sum + node.count, 0) + tree.trailing.count+ );++ let expanded = $state(new Set());+ const isOpen = (key) => searching || expanded.has(key);++ function toggle(key) {+ const next = new Set(expanded);+ if (!next.delete(key)) next.add(key);+ expanded = next;+ }++ // A case with a single root has nothing to choose between — open it rather+ // than making the analyst click through one node to reach their work.+ let seededRoots = null;+ $effect(() => {+ const roots = tree.nodes.map((node) => node.key).join('|');+ if (roots === seededRoots) return;+ seededRoots = roots;+ if (tree.nodes.length === 1) expanded = new Set([...expanded, tree.nodes[0].key]);+ });++ // Something elsewhere (the case sidebar, a search result) asked to show one+ // saved item: open the branch it lives in and scroll it into view.+ let revealed = null;+ $effect(() => {+ if (!revealId || revealId === revealed) return;+ const row = rows.find((r) => r.id === revealId);+ if (!row) return;+ revealed = revealId;+ const key = byFolder ? keyForFolder(row) : keyFor(row, tree.levels);+ expanded = new Set([...expanded, ...branchKeys(key)]);+ requestAnimationFrame(() =>+ document+ .querySelector(`[data-saved-id="${CSS.escape(row.key ?? row.id)}"]`)+ ?.scrollIntoView({ behavior: 'smooth', block: 'nearest' })+ );+ });++ // --- filing by drag (folder view only) ------------------------------------+ // The dragged row is held here rather than read back out of the drop event:+ // the id travels in dataTransfer for the platform's sake, the object travels+ // in memory so the drop needs no lookup. Same shape the case sidebar uses.+ let dragRow = null;+ let dropTarget = $state(undefined);++ function startDrag(event, row) {+ dragRow = row;+ event.dataTransfer.effectAllowed = 'move';+ event.dataTransfer.setData('text/plain', row.id);+ }++ function drop(event, folder) {+ event.preventDefault();+ dropTarget = undefined;+ const row = dragRow;+ dragRow = null;+ // dropping an item where it already lives is a no-op, not a round-trip+ if (row && (row.folder || '') !== folder) onmove?.(row, folder);+ }+</script>++<div class="controls">+ <div class="head">+ <SearchInput bind:value={query} placeholder="Filter saved…" width="100%" />+ <!-- the same set, seen through where it is or through how you filed it -->+ <div class="group" role="group" aria-label="Group saved work by">+ <button+ class="sq"+ class:on={!byFolder}+ aria-pressed={!byFolder}+ title="Group by place"+ onclick={() => (group = 'geo')}+ ><Icon name="globe" size={13} /></button>+ <button+ class="sq"+ class:on={byFolder}+ aria-pressed={byFolder}+ title="Group by My-work folder · drag rows to file them"+ onclick={() => (group = 'folders')}+ ><Icon name="folder" size={13} /></button>+ </div>+ <button class="sq browse" onclick={onbrowse} title="Search saved work with previews">…</button>+ </div>++ <div class="kinds" role="group" aria-label="What this panel lists">+ {#each KINDS as k (k.id)}+ <button+ class="kind"+ class:mode={k.mode}+ class:on={kind === k.id}+ onclick={() => (kind = k.id)}+ >{k.label}</button>+ {/each}+ </div>+</div>++{#snippet leaves(items, depth)}+ <div class="leaves" style:padding-left={`${6 + depth * 13}px`}>+ {#each items as item (item.key ?? item.id)}+ <SavedRow+ row={item}+ {caseId}+ {coords}+ {fullscreen}+ draggable={byFolder}+ hovered={hoveredId === (item.key ?? item.id)}+ onhover={(id) => (hoveredId = id)}+ ondragstart={(event) => startDrag(event, item)}+ {onopen}+ {onedit}+ {ondelete}+ {onproof}+ />+ {/each}+ </div>+{/snippet}++{#snippet branch(nodes, depth)}+ {#each nodes as node (node.key)}+ <button+ type="button"+ class="node"+ class:root={depth === 0}+ class:target={dropTarget === node.key}+ style:padding-left={`${4 + depth * 13}px`}+ onclick={() => toggle(node.key)}+ aria-expanded={isOpen(node.key)}+ ondragover={byFolder+ ? (event) => {+ event.preventDefault();+ dropTarget = node.key;+ }+ : undefined}+ ondragleave={byFolder ? () => (dropTarget = undefined) : undefined}+ ondrop={byFolder ? (event) => drop(event, node.key) : undefined}+ >+ <Icon name={isOpen(node.key) ? 'chevronDown' : 'chevronRight'} size={12} />+ <span class="name">{node.label ?? node.name}</span>+ <span class="n">{node.count}</span>+ </button>+ {#if isOpen(node.key)}+ <!-- a folder holds subfolders and items at once; a geography node never+ does, so this renders one or the other there -->+ {#if node.children.length}+ {@render branch(node.children, depth + 1)}+ {/if}+ {#if node.items.length}+ {@render leaves(node.items, depth + 1)}+ {/if}+ {/if}+ {/each}+{/snippet}++<div class="tree">+ {#if !rows.length}+ <p class="none">Save a place or capture a crop. Both land here, grouped by where they are.</p>+ {:else if !shown}+ <p class="none">Nothing saved matches that.</p>+ {:else}+ {@render branch(tree.nodes, 0)}++ <!-- the bucket that always closes the list: items with no country in the+ geography view, items you have not filed in the folder view -->+ {#if tree.trailing.count}+ <div+ class="node trailing"+ class:target={dropTarget === tree.trailing.key}+ ondragover={byFolder+ ? (event) => {+ event.preventDefault();+ dropTarget = tree.trailing.key;+ }+ : undefined}+ ondragleave={byFolder ? () => (dropTarget = undefined) : undefined}+ ondrop={byFolder ? (event) => drop(event, '') : undefined}+ role="presentation"+ >+ <button+ type="button"+ class="node-main"+ onclick={() => toggle(tree.trailing.key)}+ aria-expanded={isOpen(tree.trailing.key)}+ >+ <Icon name={isOpen(tree.trailing.key) ? 'chevronDown' : 'chevronRight'} size={12} />+ <span class="name">{tree.trailing.label}</span>+ <span class="n">{tree.trailing.count}</span>+ </button>+ {#if !byFolder}+ {#if locating}+ <span class="locating">+ {locating.done}/{locating.total}+ <button class="link" onclick={oncancelLocate}>Cancel</button>+ </span>+ {:else if pending}+ <button class="link" onclick={onlocate} title="Look up the country of {pending} item(s)">+ Locate+ </button>+ {/if}+ {/if}+ </div>+ {#if isOpen(tree.trailing.key)}+ {@render leaves(tree.trailing.items, 1)}+ {/if}+ {/if}+ {/if}+</div>++<style>+ /* the filter follows the list down: a tree hundreds of rows deep must never+ make you scroll back up to change what it is showing */+ .controls {+ position: sticky;+ top: 0;+ z-index: 2;+ background: var(--bg-1);+ border-bottom: 1px solid var(--border);+ margin-bottom: 4px;+ }+ .head {+ display: flex;+ align-items: center;+ gap: 4px;+ padding: 2px 0 8px;+ }+ .head :global(.search-box) {+ flex: 1;+ min-width: 0;+ }+ .sq {+ display: grid;+ place-items: center;+ width: 26px;+ height: 26px;+ flex-shrink: 0;+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ background: var(--bg-2);+ color: var(--text-2);+ font-size: var(--fs-md);+ line-height: 1;+ cursor: pointer;+ }+ .sq:hover {+ color: var(--accent);+ border-color: var(--accent);+ }+ /* the two groupings share a frame, so they read as one switch */+ .group {+ display: flex;+ flex-shrink: 0;+ }+ .group .sq:first-child {+ border-radius: var(--r-sm) 0 0 var(--r-sm);+ }+ .group .sq:last-child {+ border-left: none;+ border-radius: 0 var(--r-sm) var(--r-sm) 0;+ }+ .sq.on {+ background: var(--bg-3);+ color: var(--accent);+ }+ /* one control — the segments share a frame so they read as a single switch+ rather than four buttons that happen to be adjacent */+ .kinds {+ display: flex;+ padding: 2px;+ margin-bottom: 8px;+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ background: var(--bg-2);+ }+ .kind {+ flex: 1;+ padding: 3px 0;+ border-radius: 2px;+ font-size: var(--fs-xs);+ color: var(--text-3);+ cursor: pointer;+ }+ .kind:hover {+ color: var(--text-1);+ }+ /* Proofs is a mode, not a refinement of the three to its left: the rule says+ so without spending a word on it */+ .kind.mode {+ margin-left: 5px;+ border-left: 1px solid var(--border);+ padding-left: 5px;+ border-radius: 0 2px 2px 0;+ }+ .kind.on {+ background: var(--bg-3);+ color: var(--text-1);+ font-weight: 600;+ }+ .tree {+ display: flex;+ flex-direction: column;+ }+ .node {+ display: flex;+ align-items: center;+ gap: 5px;+ width: 100%;+ padding: 5px 6px 5px 4px;+ border-radius: var(--r-sm);+ background: none;+ border: none;+ font: inherit;+ font-size: var(--fs-sm);+ color: var(--text-2);+ text-align: left;+ cursor: pointer;+ }+ .node.root {+ color: var(--text-1);+ font-weight: 600;+ }+ .node:hover {+ background: var(--bg-2);+ }+ .name {+ flex: 1;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .n {+ font-size: var(--fs-xs);+ color: var(--text-3);+ font-variant-numeric: tabular-nums;+ }+ .leaves {+ display: flex;+ flex-direction: column;+ }+ /* the trailing bucket can carry an errand (Locate), so its label and its+ action sit side by side instead of the whole row being one button */+ .trailing {+ padding-right: 4px;+ cursor: default;+ color: var(--text-3);+ }+ .trailing:hover {+ background: none;+ }+ /* the folder currently under a dragged row */+ .node.target {+ background: var(--bg-3);+ box-shadow: inset 0 0 0 1px var(--accent);+ }+ .node-main {+ display: flex;+ align-items: center;+ gap: 5px;+ flex: 1;+ min-width: 0;+ padding: 0;+ background: none;+ border: none;+ font: inherit;+ color: inherit;+ text-align: left;+ cursor: pointer;+ }+ .node-main:hover .name {+ color: var(--text-1);+ }+ .locating {+ display: flex;+ align-items: center;+ gap: 8px;+ font-size: var(--fs-xs);+ color: var(--text-2);+ font-variant-numeric: tabular-nums;+ }+ .link {+ font-size: var(--fs-xs);+ color: var(--accent);+ background: none;+ border: none;+ padding: 0;+ cursor: pointer;+ }+ .link:hover {+ text-decoration: underline;+ }+ .none {+ padding: 10px 4px;+ font-size: var(--fs-xs);+ color: var(--text-3);+ }+</style>diff --git a/frontend/src/tools/satellite/SavedTree.test.js b/frontend/src/tools/satellite/SavedTree.test.jsnew file mode 100644index 0000000..8190d5a--- /dev/null+++ b/frontend/src/tools/satellite/SavedTree.test.js@@ -0,0 +1,272 @@+import { describe, expect, it } from 'vitest';+import { render } from 'svelte/server';+import { readFileSync } from 'node:fs';+import SavedTree from './SavedTree.svelte';++const source = readFileSync(new URL('./SavedTree.svelte', import.meta.url), 'utf8');++const ua = (region) => ({+ state: 'ok',+ country: 'Ukraine',+ country_code: 'ua',+ region,+});++const rows = [+ {+ id: 'p1',+ kind: 'place',+ title: 'checkpoint north',+ lat: 48.0159,+ lon: 37.8029,+ zoom: 18,+ notes: 'two vehicles',+ geo: ua('Donetsk Oblast'),+ continent: 'Europe',+ fetched_at: '2026-07-20T09:12:04Z',+ },+ {+ id: 'c1',+ kind: 'capture',+ title: 'bridge',+ lat: 50.45,+ lon: 30.52,+ zoom: 17,+ provider: 'Esri World Imagery',+ geo: ua('Kyiv Oblast'),+ continent: 'Europe',+ fetched_at: '2026-07-19T09:12:04Z',+ path: 'media/a.png',+ thumbnail: 'media/.thumbs/a.jpg',+ },+ {+ id: 's1',+ kind: 'screenshot',+ title: 'yandex view',+ lat: null,+ lon: null,+ site: 'yandex-maps',+ source_url: 'https://yandex.com/maps/?ll=1,2',+ geo: { state: 'nocoords' },+ continent: null,+ fetched_at: '2026-07-18T09:12:04Z',+ },+];++const noop = () => {};+const at = (props = {}) =>+ render(SavedTree, {+ props: {+ rows,+ caseId: 'case-1',+ coords: (row) => `${row.lat}, ${row.lon}`,+ onopen: noop,+ onedit: noop,+ ondelete: noop,+ onproof: noop,+ onbrowse: noop,+ onlocate: noop,+ oncancelLocate: noop,+ ...props,+ },+ }).body;++describe('SavedTree', () => {+ it('groups located work by region and buckets the rest under Unlocated', () => {+ const body = at();++ expect(body).toContain('Donetsk Oblast');+ expect(body).toContain('Kyiv Oblast');+ expect(body).toContain('Unlocated');+ });++ it('labels a branch in English with the native name beside it', () => {+ const native = rows.map((r) =>+ r.geo.state === 'ok'+ ? {+ ...r,+ country_en: 'Russia',+ geo: {+ ...r.geo,+ country: 'Россия',+ country_code: 'ru',+ region: 'Московская область',+ region_en: 'Moscow Oblast',+ },+ }+ : r+ );++ expect(at({ rows: native })).toContain('Moscow Oblast (Московская область)');+ });++ it('filters by kind, with screenshots counted as captures', () => {+ expect(at()).toContain('Places');+ expect(at({ kind: 'places', query: 'a' })).toContain('checkpoint north');+ expect(at({ kind: 'places', query: 'a' })).not.toContain('bridge');+ // a screenshot rides the Captures position rather than getting its own+ const captures = at({ kind: 'captures', query: 'a' });+ expect(captures).toContain('bridge');+ expect(captures).toContain('yandex view');+ expect(captures).not.toContain('checkpoint north');+ });++ it('marks a capture a proof was built on rather than drawing a second point', () => {+ // a proof sits on its capture's coordinates, so a second mark there would+ // read as two places+ const worked = rows.map((r) => (r.id === 'c1' ? { ...r, proofs: 2 } : r));++ expect(at({ rows: worked, query: 'bridge' })).toContain('2 proofs built here');+ expect(at({ query: 'bridge' })).not.toContain('built here');+ });++ it('does not offer Locate on proofs, which the pass cannot resolve', () => {+ // Locate walks saved entities; a proof borrows or states its point, so the+ // button would run and change nothing+ const unplaced = { ...rows[0], id: 'pr1', key: 'pr1@x', kind: 'proof', geo: null };++ expect(at({ rows: [unplaced], kind: 'proofs' })).not.toContain('Locate');+ expect(at({ rows: [unplaced], kind: 'all' })).toContain('Locate');+ });++ it('groups proofs by folder too, since a proof is filed like anything else', () => {+ const proof = {+ id: 'pr1',+ key: '[email protected],30.52',+ kind: 'proof',+ name: 'kyiv-bridge',+ title: 'Kyiv bridge',+ lat: 50.45,+ lon: 30.52,+ geo: ua('Kyiv Oblast'),+ continent: 'Europe',+ fetched_at: '2026-07-21T09:12:04Z',+ posts: 0,+ };+ const body = at({ rows: [proof], kind: 'proofs', query: 'kyiv' });++ expect(body).toContain('Kyiv bridge');+ expect(body).toContain('Kyiv Oblast');+ // and the folder grouping works there like anywhere else+ expect(body).toContain('Group by My-work folder');+ expect(body).not.toContain('disabled=""');++ const filed = at({+ rows: [{ ...proof, folder: 'recon/bridges' }],+ kind: 'proofs',+ group: 'folders',+ folders: ['recon', 'recon/bridges'],+ query: 'kyiv',+ });+ expect(filed).toContain('bridges');+ });++ it('opens every branch while a search is running', () => {+ // a filter that hides its own matches behind chevrons is no filter+ expect(at({ query: 'bridge' })).toContain('bridge');+ expect(at()).not.toContain('bridge');+ });++ it('offers Locate only when something is still resolvable', () => {+ // nocoords and nocountry are settled — asking again would waste a lookup+ expect(at()).not.toContain('Locate');+ expect(at({ rows: [...rows, { ...rows[0], id: 'p2', geo: null }] })).toContain('Locate');+ expect(at({ rows: [...rows, { ...rows[0], id: 'p2', geo: { state: 'failed' } }] })).toContain(+ 'Locate'+ );+ });++ it('reports progress and offers a way out while a pass runs', () => {+ const body = at({ locating: { done: 12, total: 134 }, rows: [...rows, { ...rows[0], id: 'p2', geo: null }] });++ expect(body).toContain('12');+ expect(body).toContain('134');+ expect(body).toContain('Cancel');+ expect(body).not.toContain('Locate');+ });++ it('gives a screenshot the link back to the site it came from', () => {+ const body = at({ query: 'yandex' });++ expect(body).toContain('https://yandex.com/maps/?ll=1,2');+ });++ it('says what an empty panel is empty of, and what a dead search found', () => {+ expect(at({ rows: [] })).toContain('Save a place or capture a crop');+ expect(at({ query: 'zzzz' })).toContain('Nothing saved matches that');+ });+});++describe('SavedTree wiring', () => {+ it('keeps the filter in view while the tree scrolls', () => {+ const controls = source.slice(source.indexOf('.controls {'), source.indexOf('.head {'));++ expect(controls).toContain('position: sticky');+ expect(controls).toContain('top: 0');+ });++ it('shares the search input and the term matcher the other pickers use', () => {+ expect(source).toContain("import SearchInput from '../../components/SearchInput.svelte'");+ expect(source).toContain("from '../../lib/geoTree.js'");+ });+});++describe('SavedTree folder view', () => {+ const filed = [+ { ...rows[0], folder: 'recon' },+ { ...rows[1], folder: 'recon/bridges' },+ { ...rows[2] }, // never filed+ ];+ const inFolders = (props = {}) =>+ at({ rows: filed, group: 'folders', folders: ['recon', 'recon/bridges', 'imagery'], ...props });++ it('offers both groupings, geography first', () => {+ const body = at();+ expect(body).toContain('Group by place');+ expect(body).toContain('Group by My-work folder');+ });++ it('groups by folder, and keeps the unfiled ones in their own bucket', () => {+ const body = inFolders();++ expect(body).toContain('recon');+ expect(body).toContain('Unfiled');+ expect(body).not.toContain('Donetsk Oblast'); // the geography tree is gone+ expect(body).not.toContain('Unlocated');+ });++ it("shows the case's empty folders, so anything can be dropped into them", () => {+ expect(inFolders()).toContain('imagery');+ });++ it('renders a folder that holds both subfolders and items', () => {+ // a search opens every branch, which is how the items become visible here+ const body = inFolders({ query: 'e' });++ expect(body).toContain('bridges');+ expect(body).toContain('checkpoint north'); // filed in recon itself+ expect(body).toContain('bridge'); // filed one level down+ });++ it('makes rows draggable in the folder view only', () => {+ expect(inFolders({ query: 'e' })).toContain('draggable="true"');+ expect(at({ rows: filed, query: 'e' })).not.toContain('draggable="true"');+ });++ it('offers no Locate errand in the folder view', () => {+ expect(inFolders()).not.toContain('Locate');+ });++ it('files a dropped row through onmove, and unfiles it on the Unfiled bucket', () => {+ expect(source).toContain('onmove?.(row, folder)');+ expect(source).toContain('ondrop={byFolder ? (event) => drop(event, node.key) : undefined}');+ expect(source).toContain("ondrop={byFolder ? (event) => drop(event, '') : undefined}");+ // dropping an item back where it already is costs no request+ expect(source).toContain("if (row && (row.folder || '') !== folder) onmove?.(row, folder)");+ });++ it('never files anything itself — the parent owns the request', () => {+ expect(source).not.toContain('api.');+ expect(source).not.toContain('assignFolder');+ });+});diff --git a/pyproject.toml b/pyproject.tomlindex 73a6e97..fd4e18e 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -14,7 +14,7 @@ license = { text = "AGPL-3.0-only" }authors = [{ name = "OsintMeThat" }]keywords = ["osint", "geoint", "geolocation", "investigation", "verification"]classifiers = [- "Development Status :: 3 - Alpha",+ "Development Status :: 4 - Beta","Environment :: Web Environment","Intended Audience :: Other Audience","Operating System :: OS Independent",diff --git a/scripts/vendor_ffmpeg.py b/scripts/vendor_ffmpeg.pynew file mode 100644index 0000000..588b8b0--- /dev/null+++ b/scripts/vendor_ffmpeg.py@@ -0,0 +1,246 @@+"""Download the exact ffmpeg build used by standalone release binaries.++Release artifacts are pinned here rather than resolved through moving URLs in+the workflow. Each archive is size-bounded, SHA-256 verified, and read through+an exact member allowlist before ffmpeg and ffprobe enter the PyInstaller build.+"""++from __future__ import annotations++import argparse+import hashlib+import json+import os+import shutil+import stat+import tempfile+import urllib.request+import zipfile+from pathlib import Path, PurePosixPath+from typing import NamedTuple+++MAX_ARCHIVE_BYTES = 192 * 1024 * 1024+MAX_TOOL_BYTES = 160 * 1024 * 1024+DOWNLOAD_CHUNK_BYTES = 1024 * 1024+TOOL_NAMES = {"ffmpeg", "ffprobe", "ffmpeg.exe", "ffprobe.exe"}+++class Archive(NamedTuple):+ source: str+ version: str+ url: str+ sha256: str+ members: tuple[tuple[str, str], ...]+++ARTIFACTS: dict[str, tuple[Archive, ...]] = {+ "windows-x86_64": (+ Archive(+ source="BtbN FFmpeg Builds",+ version="autobuild-2026-06-30-13-34 / N-125365-g9a01c1cb6a",+ url=(+ "https://github.com/BtbN/FFmpeg-Builds/releases/download/"+ "autobuild-2026-06-30-13-34/"+ "ffmpeg-N-125365-g9a01c1cb6a-win64-gpl.zip"+ ),+ sha256="52c0383c460f0ec1039088f1591921fb82e3b870b32aab8faf2ff1e5ae14bf9d",+ members=(+ (+ "ffmpeg-N-125365-g9a01c1cb6a-win64-gpl/bin/ffmpeg.exe",+ "ffmpeg.exe",+ ),+ (+ "ffmpeg-N-125365-g9a01c1cb6a-win64-gpl/bin/ffprobe.exe",+ "ffprobe.exe",+ ),+ ),+ ),+ ),+ "linux-x86_64": (+ Archive(+ source="FFmpeg Build Server",+ version="8.1.2 / 1783011670",+ url=(+ "https://ffmpeg.martin-riedl.de/download/"+ "linux/amd64/1783011670_8.1.2/ffmpeg.zip"+ ),+ sha256="56452c0bfc4ee0325cd615d62f46ba8264f62eed34f727c2224c6c84fa7b8719",+ members=(("ffmpeg", "ffmpeg"),),+ ),+ Archive(+ source="FFmpeg Build Server",+ version="8.1.2 / 1783011670",+ url=(+ "https://ffmpeg.martin-riedl.de/download/"+ "linux/amd64/1783011670_8.1.2/ffprobe.zip"+ ),+ sha256="c6f2d36e98f9a4445fad0b0be539f4c4faf13fd502116bf131becd53f56cd390",+ members=(("ffprobe", "ffprobe"),),+ ),+ ),+ "macos-arm64": (+ Archive(+ source="FFmpeg Build Server",+ version="8.1.2 / 1783011502",+ url=(+ "https://ffmpeg.martin-riedl.de/download/"+ "macos/arm64/1783011502_8.1.2/ffmpeg.zip"+ ),+ sha256="ef1aa60006c7b77ce170c1608c08d8e4ba1c30c5746f2ac986ded932d0ac2c3c",+ members=(("ffmpeg", "ffmpeg"),),+ ),+ Archive(+ source="FFmpeg Build Server",+ version="8.1.2 / 1783011502",+ url=(+ "https://ffmpeg.martin-riedl.de/download/"+ "macos/arm64/1783011502_8.1.2/ffprobe.zip"+ ),+ sha256="c39787f4af7a3932502d2d48db6f6feaaa836b48a73ef78c32cc3285df61dfaf",+ members=(("ffprobe", "ffprobe"),),+ ),+ ),+}+++def _download(archive: Archive, destination: Path) -> None:+ request = urllib.request.Request(+ archive.url,+ headers={"User-Agent": "Azimut-release-vendoring"},+ )+ digest = hashlib.sha256()+ total = 0++ with urllib.request.urlopen(request, timeout=60) as response:+ declared = response.headers.get("Content-Length")+ if declared is not None and int(declared) > MAX_ARCHIVE_BYTES:+ raise RuntimeError(f"archive is too large: {archive.url}")++ with destination.open("xb") as output:+ while chunk := response.read(DOWNLOAD_CHUNK_BYTES):+ total += len(chunk)+ if total > MAX_ARCHIVE_BYTES:+ raise RuntimeError(f"archive exceeded the size limit: {archive.url}")+ digest.update(chunk)+ output.write(chunk)++ actual = digest.hexdigest()+ if actual != archive.sha256:+ destination.unlink(missing_ok=True)+ raise RuntimeError(+ f"SHA-256 mismatch for {archive.url}: expected {archive.sha256}, got {actual}"+ )+++def _validate_member_names(names: list[str], archive: Archive) -> None:+ expected = {member for member, _destination in archive.members}+ tool_basenames = {PurePosixPath(member).name for member in expected}+ candidates = {+ name+ for name in names+ if PurePosixPath(name).name in tool_basenames and not name.endswith("/")+ }+ if candidates != expected:+ raise RuntimeError(+ f"archive member mismatch for {archive.url}: "+ f"expected {sorted(expected)}, found {sorted(candidates)}"+ )+++def _copy_member(source, destination: Path, size: int, archive: Archive) -> None:+ if size > MAX_TOOL_BYTES:+ raise RuntimeError(f"archive member is too large: {archive.url}")+ with destination.open("xb") as output:+ shutil.copyfileobj(source, output, length=DOWNLOAD_CHUNK_BYTES)+++def _extract(path: Path, archive: Archive, output_dir: Path) -> None:+ with zipfile.ZipFile(path) as bundle:+ _validate_member_names(bundle.namelist(), archive)+ for member_name, destination_name in archive.members:+ info = bundle.getinfo(member_name)+ if info.is_dir():+ raise RuntimeError(f"expected a file in {archive.url}: {member_name}")+ with bundle.open(info) as source:+ _copy_member(source, output_dir / destination_name, info.file_size, archive)+++def vendor(target: str, output_dir: Path) -> dict[str, object]:+ archives = ARTIFACTS[target]+ expected_files = {+ destination+ for archive in archives+ for _member, destination in archive.members+ }+ if {PurePosixPath(name).name for name in expected_files} - TOOL_NAMES:+ raise RuntimeError(f"invalid destination allowlist for {target}")++ output_dir.parent.mkdir(parents=True, exist_ok=True)+ with tempfile.TemporaryDirectory(+ prefix=".azimut-ffmpeg-",+ dir=output_dir.parent,+ ) as temporary:+ staging = Path(temporary)+ extracted = staging / "tools"+ extracted.mkdir()++ for index, archive in enumerate(archives):+ download = staging / f"archive-{index}"+ _download(archive, download)+ _extract(download, archive, extracted)++ installed = {path.name for path in extracted.iterdir() if path.is_file()}+ if installed != expected_files:+ raise RuntimeError(+ f"vendored file mismatch for {target}: "+ f"expected {sorted(expected_files)}, found {sorted(installed)}"+ )++ output_dir.mkdir(parents=True, exist_ok=True)+ for name in TOOL_NAMES:+ stale = output_dir / name+ if stale.is_file() or stale.is_symlink():+ stale.unlink()+ for name in sorted(expected_files):+ source = extracted / name+ if not name.endswith(".exe"):+ source.chmod(source.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)+ os.replace(source, output_dir / name)++ provenance: dict[str, object] = {+ "schema": 1,+ "target": target,+ "files": sorted(expected_files),+ "archives": [+ {+ "source": archive.source,+ "version": archive.version,+ "url": archive.url,+ "sha256": archive.sha256,+ }+ for archive in archives+ ],+ }+ provenance_path = output_dir / "ffmpeg-provenance.json"+ temporary_path = output_dir / ".ffmpeg-provenance.json.tmp"+ temporary_path.write_text(+ json.dumps(provenance, indent=2, sort_keys=True) + "\n",+ encoding="utf-8",+ )+ os.replace(temporary_path, provenance_path)+ return provenance+++def main() -> None:+ parser = argparse.ArgumentParser()+ parser.add_argument("target", choices=sorted(ARTIFACTS))+ parser.add_argument("--output", type=Path, default=Path("packaging/vendor"))+ args = parser.parse_args()++ provenance = vendor(args.target, args.output)+ print(json.dumps(provenance, indent=2, sort_keys=True))+++if __name__ == "__main__":+ main()diff --git a/src/azimut/__init__.py b/src/azimut/__init__.pyindex 4e64957..9aa7930 100644--- a/src/azimut/__init__.py+++ b/src/azimut/__init__.py@@ -1,5 +1,7 @@"""Azimut, a local OSINT workspace."""+import warnings+from PIL import Image as _Image# The single source of truth for the app version. pyproject.toml reads it back@@ -7,7 +9,7 @@ from PIL import Image as _Image# extension manifest is kept in lock-step by a test, so a release is bumped in# exactly one place. Getting this wrong nags every user with a false update# (the binary's self-check compares this against the latest GitHub tag).-__version__ = "0.2.3"+__version__ = "0.2.4"# Cap the pixels Pillow will decode from a file, process-wide. A tiny,# highly-compressed image can otherwise expand to gigabytes in memory and take@@ -17,3 +19,4 @@ __version__ = "0.2.3"# files*; composites built with Image.new() are unaffected. Set here because# importing azimut is the one thing every entry point does first._Image.MAX_IMAGE_PIXELS = 100_000_000+warnings.filterwarnings("error", category=_Image.DecompressionBombWarning)diff --git a/src/azimut/api/cases.py b/src/azimut/api/cases.pyindex 5e5140b..8a6bd84 100644--- a/src/azimut/api/cases.py+++ b/src/azimut/api/cases.py@@ -165,8 +165,8 @@ class FolderIn(BaseModel):@router.get("")-def list_cases() -> list[dict[str, Any]]:- return Case.list_all()+def list_cases(q: str | None = None, limit: int | None = None) -> list[dict[str, Any]]:+ return Case.list_all(q=q, limit=limit)@router.post("")@@ -259,13 +259,15 @@ def catalog_entities(q: str | None = None,folder: str | None = None,unfiled: bool = False,+ recursive: 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.+ ``folder`` path, optionally including descendants) 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))@@ -276,7 +278,7 @@ def catalog_entities(try:return case.page_entities(limit=limit, cursor=cursor, types=types, status=valid_status,- query=q, folder=folder, unfiled=unfiled,+ query=q, folder=folder, unfiled=unfiled, recursive=recursive,)except CaseError as exc:raise HTTPException(status_code=400, detail=str(exc)) from excdiff --git a/src/azimut/api/drafts.py b/src/azimut/api/drafts.pyindex f6a9d01..bb53a05 100644--- a/src/azimut/api/drafts.py+++ b/src/azimut/api/drafts.py@@ -10,7 +10,6 @@ human publishes it (spec §6 non-goals).from __future__ import annotationsimport json-import refrom datetime import datetime, timezonefrom pathlib import PurePosixPath, PureWindowsPathfrom typing import Any@@ -21,6 +20,7 @@ from pydantic import BaseModel, Fieldfrom ..engine import links as link_enginefrom ..workspace import CaseErrorfrom .cases import delete_by_path, get_case+from .naming import read_created_at, slugifyrouter = APIRouter(prefix="/api", tags=["drafts"])@@ -32,16 +32,15 @@ MAX_ARTIFACT_PATH_LENGTH = 512class DraftIn(BaseModel):- name: str | None = None # slug; None → derived from title+ # The filename always follows the title, so renaming a saved draft moves its+ # file. ``rename_from`` is the slug the composer is currently bound to+ # (absent on a first save); a save that lands elsewhere renames that file in+ # place instead of leaving a copy behind under the old name.+ rename_from: str | None = Nonetitle: str = Field(min_length=1, max_length=200)state: dict[str, Any] # opaque Post Composer state (fields + tweets)-def _slug(text: str) -> str:- slug = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")- return slug[:80] or "draft"--def _now() -> str:return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")@@ -125,12 +124,16 @@ def list_drafts(case_id: str) -> list[dict[str, Any]]:continueif data.get("azimut_draft") != DRAFT_MARKER:continue+ state = data.get("state")drafts.append({"name": path.stem,"title": data.get("title", path.stem),"updated_at": data.get("updated_at"),"created_at": data.get("created_at"),+ # The Saved map popup uses this small listing to identify the+ # destination without loading every full draft state.+ "target": state.get("target") if isinstance(state, dict) else None,})drafts.sort(key=lambda d: d.get("updated_at") or "", reverse=True)@@ -152,22 +155,25 @@ def load_draft(case_id: str, name: str) -> dict[str, Any]:@router.post("/cases/{case_id}/drafts")def save_draft(case_id: str, body: DraftIn) -> dict[str, Any]:case = get_case(case_id)- name = _slug(body.name or body.title)+ name = slugify(body.title, "draft")exports_dir = case.subdir("exports")source_paths = _draft_source_paths(body.state)-+ rel = f"exports/{name}.json"path = exports_dir / f"{name}.json"- existing_created = None- if path.exists():- try:- existing_created = json.loads(path.read_text(encoding="utf-8")).get("created_at")- except (OSError, json.JSONDecodeError):- existing_created = None++ # A rename lands on a free name or not at all: taking a name another draft+ # holds would leave two entities pointing at one file, and there is no sane+ # merge of the two. The first save of an unbound composer still writes over+ # a same-named draft — there the analyst is updating that one.+ old = slugify(body.rename_from, "draft") if body.rename_from else None+ old_rel = f"exports/{old}.json" if old and old != name else None+ if old_rel and path.exists():+ raise HTTPException(status_code=409, detail="another draft already uses that name")data = {"azimut_draft": DRAFT_MARKER,"title": body.title,- "created_at": existing_created or _now(),+ "created_at": read_created_at(exports_dir / f"{old or name}.json") or _now(),"updated_at": _now(),"state": body.state,}@@ -175,18 +181,25 @@ def save_draft(case_id: str, body: DraftIn) -> dict[str, Any]:json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")- # upsert the post entity (analyst action → confirmed)- existing = case.find_entity(attr="draft", value=f"exports/{name}.json")+ # upsert the post entity (analyst action → confirmed). A rename rebinds the+ # entity the old name held rather than filing a second one, so the draft+ # keeps its folder, notes and links.+ existing = case.find_entity(attr="draft", value=old_rel or rel)if existing:- case.update_entity(existing["id"], {"label": body.title})+ patch: dict[str, Any] = {"label": body.title}+ if old_rel:+ patch["attrs"] = {"draft": rel}+ case.update_entity(existing["id"], patch)entity_id = existing["id"]else:entity_id = case.add_entity("post",body.title,- attrs={"draft": f"exports/{name}.json"},+ attrs={"draft": rel},by="post-composer",)["id"]+ if old_rel:+ (exports_dir / f"{old}.json").unlink(missing_ok=True)# A post is derived from the proof it announces and the media it attaches —# it carries their coordinates and source in its own text, so it outlives@@ -199,7 +212,7 @@ def save_draft(case_id: str, body: DraftIn) -> dict[str, Any]:by="post-composer",)- return {"name": name, "draft": f"exports/{name}.json"}+ return {"name": name, "draft": rel}@router.delete("/cases/{case_id}/drafts/{name}")diff --git a/src/azimut/api/files.py b/src/azimut/api/files.pyindex 5c024c3..fc24dae 100644--- a/src/azimut/api/files.py+++ b/src/azimut/api/files.py@@ -2,21 +2,30 @@Only paths inside a case directory are reachable (Case.resolve_inside refusestraversal), and the server itself binds to localhost only.++Every response carries an ETag and revalidates, so reopening a picker costs one+conditional request per image instead of a full redownload. Thumbnail URLs+embed the content hash and a generation counter, so they are handed out as+immutable and the browser stops asking at all."""from __future__ import annotations-from fastapi import APIRouter, HTTPException+from fastapi import APIRouter, HTTPException, Request, Responsefrom fastapi.responses import FileResponse+from ..engine.thumbnails import THUMB_DIRfrom ..workspace import CaseErrorfrom .cases import get_caserouter = APIRouter(prefix="/files", tags=["files"])+IMMUTABLE = "public, max-age=31536000, immutable"+REVALIDATE = "no-cache"+@router.get("/{case_id}/{rel_path:path}")-def case_file(case_id: str, rel_path: str) -> FileResponse:+def case_file(case_id: str, rel_path: str, request: Request) -> Response:case = get_case(case_id)try:path = case.resolve_inside(rel_path)@@ -24,4 +33,13 @@ def case_file(case_id: str, rel_path: str) -> FileResponse:raise HTTPException(status_code=403, detail=str(exc)) from excif not path.is_file():raise HTTPException(status_code=404, detail="file not found")- return FileResponse(path)++ cache = IMMUTABLE if path.parent.name == THUMB_DIR else REVALIDATE+ # stat here so the ETag is on the response before we answer, and so a file+ # edited in place (Inspect writes back) invalidates its own cache entry.+ response = FileResponse(path, stat_result=path.stat())+ response.headers["cache-control"] = cache+ etag = response.headers.get("etag", "")+ if etag and request.headers.get("if-none-match") == etag:+ return Response(status_code=304, headers={"etag": etag, "cache-control": cache})+ return responsediff --git a/src/azimut/api/ingest.py b/src/azimut/api/ingest.pyindex 2e724d1..d4eae7f 100644--- a/src/azimut/api/ingest.py+++ b/src/azimut/api/ingest.py@@ -24,6 +24,7 @@ from __future__ import annotationsimport ioimport jsonimport secrets+import warningsimport zipfilefrom datetime import datetime, timezonefrom pathlib import Path@@ -39,6 +40,7 @@ from ..workspace import Casefrom . import eventsfrom .cases import get_casefrom .limits import MAX_IMAGE_BYTES+from .satellite import locate_on_saverouter = APIRouter(prefix="/api/ingest", tags=["ingest"])@@ -177,7 +179,13 @@ async def ingest_screenshot(detail=f"screenshot must be under {MAX_IMAGE_BYTES // 1024 // 1024} MB",)try:- img = Image.open(io.BytesIO(raw)).convert("RGB")+ # Keep this edge explicit even when a test runner or embedding process+ # installs its own warning policy after Azimut starts.+ with warnings.catch_warnings():+ warnings.simplefilter("error", Image.DecompressionBombWarning)+ img = Image.open(io.BytesIO(raw)).convert("RGB")+ except (Image.DecompressionBombWarning, Image.DecompressionBombError) as exc:+ raise HTTPException(status_code=413, detail="image exceeds the 100 MP limit") from excexcept Exception as exc:raise HTTPException(status_code=422, detail=f"not a readable image: {exc}") from exc@@ -210,6 +218,7 @@ async def ingest_screenshot("provider": site,"provider_label": parsed["label"],"imagery_date": parsed["imagery_date"],+ "imagery_mode": parsed["imagery_mode"],"lat": lat,"lon": lon,"zoom": zoom,@@ -252,6 +261,9 @@ async def ingest_screenshot(title=label,dedupe=False,)+ # a screenshot whose URL carried no position is settled as `nocoords`: there+ # is nothing to look up, and the Locate pass must not keep retrying it+ locate_on_save(case, result["entity"]["id"], lat, lon)# nudge any open app tab so the capture shows up without a reloadevents.publish({"type": "capture", "case_id": case.id, "path": result["item"]["path"],@@ -265,6 +277,60 @@ async def ingest_screenshot(}[email protected]("/place", dependencies=[Depends(require_token)])+def ingest_place(+ url: str = Form(min_length=1, max_length=4000),+ case_id: str = Form(default=""),+ lat: float | None = Form(default=None, ge=-90, le=90),+ lon: float | None = Form(default=None, ge=-180, le=180),+ zoom: float | None = Form(default=None, ge=0, le=23),+ bearing: float | None = Form(default=None, ge=0, lt=360),+ title: str = Form(default="", max_length=200),+ extension: str = Form(default="", max_length=32),+) -> dict[str, Any]:+ """File the point you are looking at as a ``place`` — no screenshot.++ The third extension flow, between a capture (map pixels) and a bookmark (a+ page with no position): a saved point the Saved panel can fly back to. The+ URL is parsed here as everywhere else, popup values win over the parse, and+ coordinates are required — without a position there is no place to save,+ and the page belongs in a bookmark instead. An empty ``case_id`` opens a+ fresh scratch session.+ """+ parsed = mapsites.parse_map_url(url)+ if parsed is None:+ raise HTTPException(status_code=422, detail="not a recognized map site")++ lat = lat if lat is not None else parsed["lat"]+ lon = lon if lon is not None else parsed["lon"]+ zoom = zoom if zoom is not None else parsed["zoom"]+ bearing = bearing if bearing is not None else parsed["bearing"]+ if lat is None or lon is None:+ raise HTTPException(+ status_code=422, detail="a place needs both coordinates; save the page as a bookmark"+ )++ case = get_case(case_id) if case_id else Case.create("Scratch session", scratch=True)+ # provenance a place saved inside the app has no source for: which page it+ # came from, and which extension build filed it+ extra: dict[str, Any] = {"source_url": url, "site": parsed["site"]}+ if extension.strip():+ extra["extension"] = extension.strip()+ entity = satellite_engine.save_place(+ case, lat, lon, zoom, bearing,+ title.strip() or (parsed["title"] or ""),+ by="ingest",+ extra_attrs=extra,+ )+ locate_on_save(case, entity["id"], lat, lon)+ events.publish(+ {"type": "place", "case_id": case.id, "entity_id": entity["id"],+ "title": entity["label"], "site": parsed["site"]}+ )+ return {"entity_id": entity["id"], "case_id": case.id, "title": entity["label"],+ "lat": lat, "lon": lon, "site": parsed["site"]}++@router.post("/bookmark", dependencies=[Depends(require_token)])def ingest_bookmark(url: str = Form(min_length=1, max_length=4000),diff --git a/src/azimut/api/inspect.py b/src/azimut/api/inspect.pyindex 12ff7c9..a134a00 100644--- a/src/azimut/api/inspect.py+++ b/src/azimut/api/inspect.py@@ -8,7 +8,6 @@ the Proof Composer picker with zero extra plumbing). Long scans run as jobs.from __future__ import annotationsimport json-import refrom datetime import datetime, timezonefrom typing import Any, Literal@@ -20,6 +19,7 @@ from ..engine import inspect as inspect_enginefrom ..engine import links as link_enginefrom ..workspace import CaseErrorfrom .cases import delete_by_path, get_case+from .naming import read_created_at, slugifyrouter = APIRouter(prefix="/api", tags=["inspect"])@@ -47,12 +47,13 @@ class FrameSpec(BaseModel):path: strtime: float | None = Field(default=None, ge=0)ops: list[Op] = []- label: str | None = None+ label: str | None = Field(default=None, max_length=200)class SaveFramesIn(BaseModel):items: list[FrameSpec] = Field(min_length=1)folder: str | None = None+ notes: str | None = Field(default=None, max_length=2000)class NodeSrc(BaseModel):@@ -71,8 +72,9 @@ class ComposeIn(BaseModel):height: int = Field(ge=16, le=8192)nodes: list[ComposeNode] = Field(min_length=1)background: str | None = "#12141c" # None → transparent (RGBA) canvas- label: str | None = None+ label: str | None = Field(default=None, max_length=200)folder: str | None = None+ notes: str | None = Field(default=None, max_length=2000)class StitchIn(BaseModel):@@ -88,8 +90,9 @@ class EnhanceVideoIn(BaseModel):path: strparams: dict[str, Any] = {}rotation: Literal[-180, -90, 0, 90, 180] = 0- label: str | None = None+ label: str | None = Field(default=None, max_length=200)folder: str | None = None+ notes: str | None = Field(default=None, max_length=2000)class AnalyzeIn(BaseModel):@@ -101,7 +104,11 @@ class AnalyzeIn(BaseModel):class SessionIn(BaseModel):- name: str | None = None # slug; None → derived from title+ # The filename always follows the title, so renaming a saved session moves+ # its file. ``rename_from`` is the slug the workspace is currently bound to+ # (absent on a first save); a save that lands elsewhere renames that file in+ # place instead of leaving a copy behind under the old name.+ rename_from: str | None = Nonetitle: str = Field(min_length=1, max_length=200)spec: dict[str, Any]@@ -164,7 +171,7 @@ def save_frames(case_id: str, body: SaveFramesIn) -> dict[str, Any]:results.append(inspect_engine.save_frame(case, item.path, time_s=item.time, ops=ops,- label=item.label, folder=body.folder,+ label=item.label, folder=body.folder, notes=body.notes,))except CaseError as exc:@@ -187,6 +194,7 @@ def compose(case_id: str, body: ComposeIn) -> dict[str, Any]:return inspect_engine.compose_perspective(case, width=body.width, height=body.height, nodes=nodes,background=body.background, label=body.label, folder=body.folder,+ notes=body.notes,)except CaseError as exc:raise HTTPException(status_code=400, detail=str(exc)) from exc@@ -244,7 +252,7 @@ def enhance_video(case_id: str, body: EnhanceVideoIn) -> dict[str, Any]:try:return inspect_engine.enhance_video(case, body.path, body.params, rotation=body.rotation,- label=body.label, folder=body.folder,+ label=body.label, folder=body.folder, notes=body.notes,)except CaseError as exc:raise HTTPException(status_code=400, detail=str(exc)) from exc@@ -273,11 +281,6 @@ def analyze(case_id: str, body: AnalyzeIn) -> dict[str, Any]:# ----------------------------------------------------------------------------def _slug(text: str) -> str:- slug = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")- return slug[:80] or "session"--def _now() -> str:return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")@@ -326,25 +329,42 @@ def load_session(case_id: str, name: str) -> dict[str, Any]:@router.post("/cases/{case_id}/inspect/sessions")def save_session(case_id: str, body: SessionIn) -> dict[str, Any]:case = get_case(case_id)- name = _slug(body.name or body.title)+ sessions_dir = case.subdir("inspect")+ name = slugify(body.title, "session")+ rel = f"inspect/{name}.json"+ spec_path = sessions_dir / f"{name}.json"++ # A rename lands on a free name or not at all: taking a name another session+ # holds would leave two entities pointing at one file, and there is no sane+ # merge of the two. The first save of an unbound workspace still writes over+ # a same-named session — there the analyst is updating that one.+ old = slugify(body.rename_from, "session") if body.rename_from else None+ old_rel = f"inspect/{old}.json" if old and old != name else None+ if old_rel and spec_path.exists():+ raise HTTPException(status_code=409, detail="another session already uses that name")+spec = dict(body.spec)spec["azimut_inspect"] = 1spec["title"] = body.title- spec.setdefault("created_at", _now())+ spec.setdefault("created_at", read_created_at(sessions_dir / f"{old or name}.json") or _now())spec["updated_at"] = _now()-- spec_path = case.subdir("inspect") / f"{name}.json"spec_path.write_text(json.dumps(spec, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")- rel = f"inspect/{name}.json"- existing = case.find_entity(attr="spec", value=rel)+ # Rebind the entity the old name held rather than filing a second one, so a+ # rename keeps the session's folder, notes and links.+ existing = case.find_entity(attr="spec", value=old_rel or rel)if existing:- case.update_entity(existing["id"], {"label": body.title})+ patch: dict[str, Any] = {"label": body.title}+ if old_rel:+ patch["attrs"] = {"spec": rel}+ case.update_entity(existing["id"], patch)entity_id = existing["id"]else:entity_id = case.add_entity("inspect-session", body.title, attrs={"spec": rel}, by="inspect")["id"]+ if old_rel:+ (sessions_dir / f"{old}.json").unlink(missing_ok=True)# A session is only adjustments and crops over its subject — nothing usable# is left of it once the subject is gone, so it depends on it and is deleteddiff --git a/src/azimut/api/media.py b/src/azimut/api/media.pyindex 33afecb..ffe79e7 100644--- a/src/azimut/api/media.py+++ b/src/azimut/api/media.py@@ -5,7 +5,7 @@ from __future__ import annotationsfrom typing import Anyfrom fastapi import APIRouter, HTTPException, UploadFile-from pydantic import BaseModel, HttpUrl+from pydantic import BaseModel, Field, HttpUrlfrom .. import config, jobsfrom ..engine import media as media_engine@@ -40,7 +40,11 @@ class ThumbRegenIn(BaseModel):path: str | None = None-def _with_thumb_state(case: Case, items: list[dict[str, Any]]) -> list[dict[str, Any]]:+class MediaMetadataIn(BaseModel):+ paths: list[str] = Field(max_length=500)+++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`` whenthe cached file is present, ``queued``/``running``/``failed`` from itsthumbnail job while the worker is on it, else ``none`` (no thumbnail, e.g. an@@ -67,7 +71,54 @@ def _with_thumb_state(case: Case, items: list[dict[str, Any]]) -> list[dict[str,@router.get("/cases/{case_id}/media")def list_media(case_id: str) -> list[dict[str, Any]]:case = get_case(case_id)- return _with_thumb_state(case, media_engine.list_media(case))+ return with_thumb_state(case, media_engine.list_media(case))++[email protected]("/cases/{case_id}/media/page")+def page_media(+ case_id: str,+ q: str | None = None,+ kind: str | None = None,+ category: str | None = None,+ folder: str | None = None,+ sort: str = "newest",+ direction: str | None = None,+ limit: int = 200,+ cursor: str | None = None,+) -> dict[str, Any]:+ """A bounded, filterable page of the media list for the browse surfaces+ (Media Library, Files). Small cases return one page with a null+ ``next_cursor``, so the client filters in memory with no further calls; a+ large case pages via ``cursor`` and searches server-side via ``q``.+ ``facets`` counts the whole filtered set so category/folder controls stay+ accurate. The unbounded ``GET .../media`` stays for consumers that need the+ full index (pickers, satellite crops, derivation)."""+ case = get_case(case_id)+ limit = max(1, min(limit, 500))+ offset = int(cursor) if cursor and cursor.isdigit() else 0+ result = case.page_media_items(+ q=q,+ kind=kind,+ category=category,+ folder=folder,+ sort=sort,+ direction=direction,+ limit=limit,+ offset=offset,+ )+ result["items"] = with_thumb_state(case, result["items"])+ return result++[email protected]("/cases/{case_id}/media/metadata")+def media_metadata(case_id: str, body: MediaMetadataIn) -> list[dict[str, Any]]:+ """Thumbnail, kind and size metadata for the paths on the current Files page."""+ case = get_case(case_id)+ try:+ items = case.media_items_by_paths(body.paths)+ except CaseError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ return with_thumb_state(case, items)@router.post("/cases/{case_id}/media/thumbnails/regenerate")diff --git a/src/azimut/api/naming.py b/src/azimut/api/naming.pynew file mode 100644index 0000000..34af4a2--- /dev/null+++ b/src/azimut/api/naming.py@@ -0,0 +1,44 @@+"""Naming rules shared by everything the analyst saves under a name.++Inspect sessions, proofs, post drafts and satellite grids all turn a free-text+title into the filename that holds it. They must agree: a session and a proof+called "Rooftop angle" land on the same stem, and the frontend mirrors this in+``lib/naming.js`` so it can predict a collision before it posts.+"""++from __future__ import annotations++import json+import re+from pathlib import Path+from typing import Any++# Long enough to stay readable, short enough that the path survives Windows'+# 260-character limit under a deep workspace root.+MAX_SLUG = 80+++def slugify(text: str | None, fallback: str) -> str:+ """URL- and filesystem-safe stem from free text.++ Everything outside ``[a-z0-9]`` collapses to a single dash, so accents and+ punctuation drop out rather than reaching the filesystem. Text that leaves+ nothing behind ("!!!", "") falls back to the caller's word.+ """+ slug = re.sub(r"[^a-z0-9]+", "-", (text or "").lower()).strip("-")+ return slug[:MAX_SLUG] or fallback+++def read_created_at(path: Path) -> str | None:+ """``created_at`` already on disk at ``path``, or None if it isn't readable.++ A save rewrites the spec from what the client holds, and the client does not+ carry the birth date. Reading it back keeps "created" meaning created —+ including across a rename, where ``path`` is the file about to be moved.+ """+ try:+ data: Any = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ return None+ stamp = data.get("created_at") if isinstance(data, dict) else None+ return stamp if isinstance(stamp, str) else Nonediff --git a/src/azimut/api/proofs.py b/src/azimut/api/proofs.pyindex 20cb103..4116d2f 100644--- a/src/azimut/api/proofs.py+++ b/src/azimut/api/proofs.py@@ -1,44 +1,189 @@"""REST API for proofs: save (PNG + re-editable JSON spec), list, load, delete.The spec is the source of truth — a proof saved once reopens for re-editing-(spec §6 v1). The PNG is the publishable export of that spec.+(spec §6 v1). The PNG is the publishable export of that spec, and its cached+thumbnail is what the open dialog shows.++A proof may also hold pasted images: pixels that belong to the composition+alone, with no source in the case. They live in a ``<name>.assets`` folder+beside the spec, named by their own hash, and they are never filed as media or+as an entity — nothing in the graph claims a paste came from anywhere."""from __future__ import annotationsimport base64import binascii+import hashlibimport jsonimport re+import shutilfrom datetime import datetime, timezone+from pathlib import Pathfrom typing import Anyfrom fastapi import APIRouter, HTTPExceptionfrom pydantic import BaseModel, Fieldfrom ..engine import links as link_engine-from ..workspace import CaseError+from ..engine import media as media_engine+from ..engine import satellite as satellite_engine+from ..engine import thumbnails as thumbnail_engine+from ..workspace import Case, CaseErrorfrom .cases import delete_by_path, get_case+from .drafts import list_drafts+from .naming import read_created_at, slugifyrouter = APIRouter(prefix="/api", tags=["proofs"])+ASSETS_SUFFIX = ".assets"+ASSET_NAME = re.compile(r"^[0-9a-f]{16}\.(?:png|jpe?g|webp)$")+MAX_ASSET_BYTES = 20 * 1024 * 1024+MAX_ASSETS = 12+++class AssetIn(BaseModel):+ """A pasted image the composer is holding but has never written.++ ``name`` is the first 16 hex digits of the payload's own sha256 plus its+ extension. The server checks that, so the same paste never lands twice and a+ save cannot address a file it did not bring.+ """++ name: str = Field(min_length=1, max_length=40)+ data: str # base64 body++class ProofIn(BaseModel):- name: str | None = None # slug; None → derived from title+ # The filename always follows the title, so renaming a saved proof moves its+ # spec and its export. ``rename_from`` is the slug the composer is currently+ # bound to (absent on a first save); a save that lands elsewhere renames+ # those files in place instead of leaving a copy under the old name.+ rename_from: str | None = Nonetitle: str = Field(min_length=1, max_length=200)spec: dict[str, Any]png_base64: str | None = None # rendered export, data URL body---def _slug(text: str) -> str:- slug = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")- return slug[:80] or "proof"+ # Pasted images the spec references but the case does not hold yet. They ride+ # along with the save rather than through an upload of their own, so a proof+ # the analyst never saves leaves nothing behind.+ assets: list[AssetIn] = Field(default_factory=list)def _now() -> str:return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+def _write_spec(path: Path, spec: dict[str, Any]) -> None:+ path.write_text(json.dumps(spec, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")+++def _proof_thumb(case: Case, name: str, data: bytes | None = None) -> str | None:+ """Cached thumbnail for a proof's export, or None if it can't be produced.++ The export is a full-resolution PNG, far too heavy for the open dialog's+ rows. It goes through the media thumbnail cache: content-addressed, so two+ identical exports share one file and a re-export lands on a new immutable+ URL, and disposable, so eviction just means the next listing regenerates it.+ ``data`` skips re-reading bytes we already hold (the save path).+ """+ png_rel = f"proofs/{name}.png"+ path = case.resolve_inside(png_rel)+ if not path.is_file():+ return None+ digest = (+ hashlib.sha256(data).hexdigest() if data is not None else media_engine.sha256_file(path)+ )+ try:+ return thumbnail_engine.generate(case, png_rel, digest, "image")+ except thumbnail_engine.ThumbnailError:+ return None # the dialog falls back to the export itself+++def _decode_assets(assets: list[AssetIn]) -> dict[str, bytes]:+ """Decode and check the whole batch before a single file is written."""+ if len(assets) > MAX_ASSETS:+ raise HTTPException(+ status_code=422, detail=f"a proof holds at most {MAX_ASSETS} pasted images"+ )+ decoded: dict[str, bytes] = {}+ for asset in assets:+ if not ASSET_NAME.match(asset.name):+ raise HTTPException(status_code=422, detail="invalid asset name")+ try:+ data = base64.b64decode(asset.data, validate=True)+ except (binascii.Error, ValueError) as exc:+ raise HTTPException(status_code=422, detail="invalid asset payload") from exc+ if not data or len(data) > MAX_ASSET_BYTES:+ raise HTTPException(status_code=422, detail="pasted image too large")+ if hashlib.sha256(data).hexdigest()[:16] != asset.name.split(".")[0]:+ raise HTTPException(status_code=422, detail="asset name does not match its content")+ decoded[asset.name] = data+ return decoded+++def _referenced_assets(spec: dict[str, Any]) -> set[str]:+ """Asset filenames the spec still shows."""+ pastes = spec.get("pastes")+ if not isinstance(pastes, list):+ return set()+ return {+ p["asset"] for p in pastes if isinstance(p, dict) and isinstance(p.get("asset"), str)+ }+++def _move_assets(src: Path, dst: Path) -> None:+ """Carry a proof's assets folder over to its new name.++ Windows refuses to rename onto an existing directory, so anything already+ sitting at the destination is moved aside and deleted last.+ """+ if not src.is_dir():+ return+ if dst.exists():+ stale = dst.with_name(dst.name + ".stale")+ shutil.rmtree(stale, ignore_errors=True)+ dst.rename(stale)+ src.rename(dst)+ shutil.rmtree(stale, ignore_errors=True)+ else:+ src.rename(dst)+++def _write_assets(folder: Path, incoming: dict[str, bytes], keep: set[str]) -> None:+ """Land the pasted images this save brings, then drop the ones it dropped.++ Names are content hashes, so writing is idempotent and pruning by "not in the+ spec" can never take a file the proof still shows. A proof left with no+ pasted images keeps no folder either.+ """+ if incoming:+ folder.mkdir(parents=True, exist_ok=True)+ for asset_name, data in incoming.items():+ path = folder / asset_name+ if not path.exists():+ path.write_bytes(data)+ if not folder.is_dir():+ return+ for path in folder.iterdir():+ if path.is_file() and path.name not in keep:+ path.unlink(missing_ok=True)+ if not any(folder.iterdir()):+ folder.rmdir()++[email protected]("/cases/{case_id}/proofs/index")+def proof_index(case_id: str) -> list[dict[str, Any]]:+ """Proofs as map rows, for the Saved panel's Proofs position.++ Declared above ``/proofs/{name}`` so ``index`` is read as this route and not+ as a proof called "index". Lazy by design: the Saved panel loads it the+ first time that position is opened, never on case open.+ """+ case = get_case(case_id)+ return satellite_engine.proof_index(case, list_proofs(case_id), list_drafts(case_id))++@router.get("/cases/{case_id}/proofs")def list_proofs(case_id: str) -> list[dict[str, Any]]:case = get_case(case_id)@@ -52,6 +197,17 @@ def list_proofs(case_id: str) -> list[dict[str, Any]]:continuename = spec_path.stempng = spec_path.with_suffix(".png")+ # Proofs saved before thumbnails existed (or whose cached file was+ # evicted) produce one here and record it, so this costs a hash of the+ # export once per proof rather than a full-size download per open.+ thumb = spec.get("thumb")+ if png.exists() and not (thumb and case.resolve_inside(thumb).exists()):+ thumb = _proof_thumb(case, name)+ spec["thumb"] = thumb+ try:+ _write_spec(spec_path, spec)+ except OSError:+ pass # a read-only case still lists; it just re-renders next timeproofs.append({"name": name,@@ -59,7 +215,11 @@ def list_proofs(case_id: str) -> list[dict[str, Any]]:"updated_at": spec.get("updated_at"),"panels": len(spec.get("panels", [])),"shapes": len(spec.get("shapes", [])),+ # the point the proof states for itself, read before its+ # derivation so it keeps it when the capture is deleted+ "coords": satellite_engine.own_point(spec),"png": f"proofs/{png.name}" if png.exists() else None,+ "thumb": thumb,"spec_path": f"proofs/{spec_path.name}",})@@ -82,21 +242,39 @@ def load_proof(case_id: str, name: str) -> dict[str, Any]:@router.post("/cases/{case_id}/proofs")def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:case = get_case(case_id)- name = _slug(body.name or body.title)+ name = slugify(body.title, "proof")proofs_dir = case.subdir("proofs")+ rel = f"proofs/{name}.json"+ spec_path = proofs_dir / f"{name}.json"- spec = dict(body.spec)- spec["azimut_proof"] = 1- spec["title"] = body.title- spec.setdefault("created_at", _now())- spec["updated_at"] = _now()+ # A rename lands on a free name or not at all: taking a name another proof+ # holds would leave two entities pointing at one spec, and there is no sane+ # merge of the two. The first save of an unbound composer still writes over+ # a same-named proof — there the analyst is updating that one.+ old = slugify(body.rename_from, "proof") if body.rename_from else None+ old_rel = f"proofs/{old}.json" if old and old != name else None+ if old_rel and spec_path.exists():+ raise HTTPException(status_code=409, detail="another proof already uses that name")- spec_path = proofs_dir / f"{name}.json"- spec_path.write_text(- json.dumps(spec, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"- )+ # Decoded up front: a bad batch must be refused before anything is written.+ incoming = _decode_assets(body.assets)++ # The export moves with the spec, so a rename saved without fresh pixels+ # keeps the PNG the proof already had rather than dropping it.+ if old_rel:+ old_png = proofs_dir / f"{old}.png"+ if old_png.exists():+ if body.png_base64:+ old_png.unlink()+ else:+ old_png.replace(proofs_dir / f"{name}.png")+ # the pasted images follow the proof, exactly as its export does+ _move_assets(+ proofs_dir / f"{old}{ASSETS_SUFFIX}", proofs_dir / f"{name}{ASSETS_SUFFIX}"+ )- png_rel = None+ # the export lands first: its thumbnail is recorded in the spec written below+ png_rel = thumb_rel = Noneif body.png_base64:try:png_bytes = base64.b64decode(body.png_base64, validate=True)@@ -104,24 +282,51 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:raise HTTPException(status_code=422, detail="invalid PNG payload") from exc(proofs_dir / f"{name}.png").write_bytes(png_bytes)png_rel = f"proofs/{name}.png"+ thumb_rel = _proof_thumb(case, name, png_bytes)+ elif old_rel and (proofs_dir / f"{name}.png").exists():+ png_rel = f"proofs/{name}.png"+ thumb_rel = _proof_thumb(case, name)++ spec = dict(body.spec)+ spec["azimut_proof"] = 1+ spec["title"] = body.title+ spec.setdefault("created_at", read_created_at(proofs_dir / f"{old or name}.json") or _now())+ spec["updated_at"] = _now()+ if png_rel:+ spec["thumb"] = thumb_rel++ _write_spec(spec_path, spec)++ # The spec is the truth about which pasted images the proof shows, so its+ # folder is reconciled against what we just wrote.+ _write_assets(+ proofs_dir / f"{name}{ASSETS_SUFFIX}", incoming, _referenced_assets(spec)+ )- # upsert the proof entity (analyst action → confirmed)- existing = case.find_entity(attr="spec", value=f"proofs/{name}.json")+ # upsert the proof entity (analyst action → confirmed). A rename rebinds the+ # entity the old name held rather than filing a second one, so the proof+ # keeps its folder, notes and links.+ existing = case.find_entity(attr="spec", value=old_rel or rel)if existing:patch: dict[str, Any] = {"label": body.title}+ attrs: dict[str, Any] = {"spec": rel} if old_rel else {}if png_rel and existing["attrs"].get("path") != png_rel:# a spec-only proof exported later gains its PNG here — without the# path the sidebar preview and delete_by_path can't see the file- patch["attrs"] = {"path": png_rel}+ attrs["path"] = png_rel+ if attrs:+ patch["attrs"] = attrscase.update_entity(existing["id"], patch)entity_id = existing["id"]else:entity_id = case.add_entity("proof",body.title,- attrs={"spec": f"proofs/{name}.json", **({"path": png_rel} if png_rel else {})},+ attrs={"spec": rel, **({"path": png_rel} if png_rel else {})},by="proof-composer",)["id"]+ if old_rel:+ (proofs_dir / f"{old}.json").unlink(missing_ok=True)# A proof is derived from the panels it composes: the same click that saves# it files the chain (ONTOLOGY §3). Restated on every save, so a panel@@ -134,7 +339,12 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:by="proof-composer",)- return {"name": name, "png": png_rel, "spec_path": f"proofs/{name}.json"}+ return {+ "name": name,+ "png": png_rel,+ "thumb": thumb_rel,+ "spec_path": rel,+ }@router.delete("/cases/{case_id}/proofs/{name}")@@ -148,4 +358,7 @@ def delete_proof(case_id: str, name: str) -> dict[str, Any]:if not result["deleted"]: # never filed as an entity: drop the files anywayspec_path.unlink(missing_ok=True)spec_path.with_suffix(".png").unlink(missing_ok=True)+ # The graph knows the spec and the export; the pasted images are known only+ # by where they sit, so they are dropped here either way.+ shutil.rmtree(spec_path.with_suffix(ASSETS_SUFFIX), ignore_errors=True)return resultdiff --git a/src/azimut/api/satellite.py b/src/azimut/api/satellite.pyindex 6d3c626..da6e66c 100644--- a/src/azimut/api/satellite.py+++ b/src/azimut/api/satellite.py@@ -7,6 +7,7 @@ import mathimport osimport reimport tempfile+import timefrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any@@ -27,9 +28,11 @@ from ..engine import (tilecache,tiles,)-from ..workspace import CaseError+from ..workspace import Case, CaseErrorfrom .cases import delete_by_path, get_casefrom .limits import MAX_IMAGE_BYTES+from .naming import slugify+from .media import with_thumb_staterouter = APIRouter(prefix="/api", tags=["satellite"])@@ -80,6 +83,7 @@ class PlaceIn(BaseModel):bearing: float = Field(default=0.0, ge=0, le=360)title: str | None = Nonenotes: str | None = None+ folder: str | None = Noneclass ParseIn(BaseModel):@@ -90,6 +94,7 @@ class SatelliteUpdateIn(BaseModel):path: strnotes: str | None = Nonetitle: str | None = None+ folder: str | None = Noneclass GridSaveIn(BaseModel):@@ -106,15 +111,29 @@ GRID_STATUSES = {"cleared", "flagged"}GRID_MAX_STATUSES = 50000-def _slug(text: str) -> str:- slug = re.sub(r"[^a-z0-9]+", "-", (text or "").lower()).strip("-")- return slug[:80] or "grid"--def _now() -> str:return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+# A save waits this long for a country, and no longer. Online, the answer is+# there in a few hundred milliseconds and the item lands in the Saved panel+# already grouped; offline, the save is a fraction of a second slower and the+# item lands under Unlocated for the Locate pass to pick up.+SAVE_LOOKUP_TIMEOUT = 4+++def locate_on_save(case: Case, entity_id: str, lat: Any, lon: Any) -> None:+ """Resolve a freshly saved item's country, so it is filed where it belongs+ the moment it appears in the Saved panel.++ The entity is written *before* this runs and this never raises, so saving+ cannot fail because of Nominatim — the worst case is a bounded wait and a+ ``failed`` verdict the Locate pass retries. An item with no position is+ settled on the spot: there is nothing to look up.+ """+ satellite_engine.resolve_geo(case, entity_id, lat, lon, SAVE_LOOKUP_TIMEOUT)++@router.get("/satellite/providers")def providers() -> list[dict[str, Any]]:# the user's per-provider eco threshold (Settings) beats the provider's@@ -514,6 +533,7 @@ def capture(case_id: str, body: CaptureIn) -> dict[str, Any]:title=label,dedupe=False, # a capture is 1:1 with its entity — never collapse re-captures)+ locate_on_save(case, result["entity"]["id"], marker_lat, marker_lon)return {"path": result["item"]["path"], "title": label, **provenance}@@ -611,6 +631,7 @@ async def capture_screenshot(title=label,dedupe=False,)+ locate_on_save(case, result["entity"]["id"], lat, lon)return {"path": result["item"]["path"], "title": label, **provenance}@@ -619,19 +640,80 @@ def save_place(case_id: str, body: PlaceIn) -> dict[str, Any]:"""Save just a point (the pin, or the crop center) as a navigable ``place`` —no image. Clicking it in the sidebar flies the map back to it."""case = get_case(case_id)- label = (body.title or "").strip() or satellite_engine.coords_label(body.lat, body.lon)- attrs = {"coords": satellite_engine.coords_label(body.lat, body.lon, "dd"),- "lat": body.lat, "lon": body.lon,- "plus_code": geo.plus_code(body.lat, body.lon),- "zoom": body.zoom, "bearing": body.bearing}+ extra: dict[str, Any] = {}if body.notes and body.notes.strip():- attrs["notes"] = body.notes.strip()- return case.add_entity("place", label, attrs=attrs, by="satellite", status="confirmed")+ extra["notes"] = body.notes.strip()+ if body.folder and body.folder.strip():+ extra["folder"] = body.folder.strip()+ entity = satellite_engine.save_place(+ case, body.lat, body.lon, body.zoom, body.bearing, body.title, extra_attrs=extra+ )+ locate_on_save(case, entity["id"], body.lat, body.lon)+ return entity@router.get("/cases/{case_id}/satellite")def list_captures(case_id: str) -> list[dict[str, Any]]:- return satellite_engine.list_captures(get_case(case_id))+ # tagged like the media listing: the proof pickers render captures in small+ # cells and need the thumbnail, not the full-size crop.+ case = get_case(case_id)+ return with_thumb_state(case, satellite_engine.list_captures(case))++[email protected]("/cases/{case_id}/satellite/index")+def saved_index(case_id: str) -> list[dict[str, Any]]:+ """The case's saved work — places, captures, ingested screenshots — as one+ compact list, newest first.++ This is what the Saved panel opens on: the tree, the search modal and the+ map overlay all read it and nothing else, so opening a case costs one+ request of tens of KB instead of every capture row and every image. It+ makes no network call of its own.+ """+ return satellite_engine.saved_index(get_case(case_id))+++# Nominatim asks for at most one request a second. A backfill is the only place+# we make more than one lookup in a row, so it is the only place that waits.+NOMINATIM_INTERVAL = 1.1++[email protected]("/cases/{case_id}/satellite/locate")+def locate_saved(+ case_id: str, limit: int = Query(default=10, ge=1, le=25)+) -> dict[str, Any]:+ """Resolve the country of up to ``limit`` saved items that still have none.++ Progress is the stored geography itself, so the pass resumes after a restart+ and re-running it is a no-op: ``remaining`` is what the client loops on. The+ cap keeps one request comfortably inside a timeout at Nominatim's one-per-+ second pace.+ """+ case = get_case(case_id)+ located = failed = 0+ looked_up = False+ for entity in satellite_engine.unlocated_entities(case, limit):+ attrs = entity.get("attrs") or {}+ lat, lon = attrs.get("lat"), attrs.get("lon")+ if lat is None or lon is None:+ # nothing to look up, and nothing will ever change that+ satellite_engine.set_geo(case, entity["id"], {"state": "nocoords"})+ located += 1+ continue+ if looked_up:+ time.sleep(NOMINATIM_INTERVAL)+ looked_up = True+ result = geo.locate_point(float(lat), float(lon))+ satellite_engine.set_geo(case, entity["id"], result)+ if result["state"] == "failed":+ failed += 1+ else:+ located += 1+ return {+ "located": located,+ "failed": failed,+ "remaining": len(satellite_engine.unlocated_entities(case)),+ }@router.delete("/cases/{case_id}/satellite")@@ -657,6 +739,10 @@ def update_capture(case_id: str, body: SatelliteUpdateIn) -> dict[str, Any]:patch: dict[str, Any] = {}if body.notes is not None:patch["notes"] = body.notes+ # the My-work folder lives on the sidecar and is mirrored onto the entity by+ # update_media, so filing a capture stays one request+ if body.folder is not None:+ patch["folder"] = body.folder# empty title falls back to the coordinates (mirrored onto the entity label)if body.title is not None:source = item.get("source") or {}@@ -812,7 +898,7 @@ def get_search_grid(case_id: str, name: str) -> dict[str, Any]:def save_search_grid(case_id: str, name: str, body: GridSaveIn) -> dict[str, Any]:"""Create or replace one grid. The client owns the name (a stable slug)."""case = get_case(case_id)- slug = _slug(name)+ slug = slugify(name, "grid")spec = dict(body.spec)aoi = spec.get("aoi")if not isinstance(aoi, dict) or aoi.get("type") not in {"rect", "polygon"}:diff --git a/src/azimut/api/settings.py b/src/azimut/api/settings.pyindex 441f65f..e0ab5a6 100644--- a/src/azimut/api/settings.py+++ b/src/azimut/api/settings.py@@ -1,10 +1,6 @@-"""REST API for app-wide settings: API keys, usage counters, and the signature.+"""REST API for app-wide keys, preferences, usage and proof branding.-Keys are the user's own billing identity (docs/IMAGERY_PROVIDERS.md): stored-locally in settings.json, app-wide (never per-case), never written into a case-folder or export bundle. Usage counters are local bookkeeping only. The-signature (the analyst's logo) follows the same rule — one file beside-settings.json, reaching a case only as pixels in a rendered proof PNG.+Keys and branding stay beside settings.json, outside cases and exports."""from __future__ import annotations@@ -24,11 +20,10 @@ from .ingest import bundled_extension_versionrouter = APIRouter(prefix="/api", tags=["settings"])-# the keyed providers the settings tab manages — matching api_keys entries-# light up the built-in basemaps (engine/tiles.py all_providers)+# Providers managed by the Settings imagery tab.KEYED_PROVIDERS = ("mapbox", "google", "google_js", "sentinelhub")-# tile APIs whose eco threshold the user may tune per provider; the Maps JS-# widget is deliberately absent (eco re-bills a map load per swap — never worth it)+# Providers with configurable eco thresholds. Maps JS is excluded because each+# widget reload is billed.ECO_TUNABLE = ("mapbox", "google", "sentinelhub")DEFAULT_HOME_VIEW = config.DEFAULT_SETTINGS["home_view"]@@ -56,16 +51,14 @@ class HomeView(BaseModel):class DownloadCookiesIn(BaseModel):- """The login source for gated downloads the user picks in Settings. The- ``file`` source is set by the cookies-file upload, not here — through this- field the user only chooses a browser or turns cookies off."""+ """Browser login source for gated downloads; file uploads use another route."""source: Literal["none", "browser"]browser: str | None = None # required and validated when source == "browser"class PrefsIn(BaseModel):- """Keyed-provider and display preferences — None leaves a field untouched."""+ """Keyed-provider and display preferences; None leaves a field untouched."""# {"mapbox": bool, "google": bool}: basemap on/off without touching the keyproviders_enabled: dict[str, bool] | None = Nonediff --git a/src/azimut/config.py b/src/azimut/config.pyindex da90d1b..3bde9ff 100644--- a/src/azimut/config.py+++ b/src/azimut/config.py@@ -11,7 +11,7 @@ overridable with the ``AZIMUT_HOME`` environment variable):├── settings.json└── templates.json # reusable proof and post styles-No database server — plain files only (spec §4).+No external database server; the workspace remains self-contained (spec §4)."""from __future__ import annotations@@ -423,7 +423,7 @@ def record_usage(meter: str, count: int = 1, when: datetime | None = None) -> inLocal bookkeeping only (docs/IMAGERY_PROVIDERS.md): billed keyed providers(Mapbox, Google) get a per-month tally so the user can watch their quota.- No telemetry — the counter never leaves settings.json.+ The counter stays in settings.json and is never transmitted as telemetry."""with _usage_lock:settings = load_settings()diff --git a/src/azimut/engine/continents.py b/src/azimut/engine/continents.pynew file mode 100644index 0000000..3b04b5b--- /dev/null+++ b/src/azimut/engine/continents.py@@ -0,0 +1,127 @@+"""ISO 3166-1 alpha-2 → continent, as a static table.++The continent of a saved item is never stored: it is derived from the country+code every time the saved index is read. That way correcting or extending this+table repairs every existing case at once — no migration, no re-geocoding, no+network.++The table gives one verdict per country, which is wrong for the countries that+straddle two continents: a capture in Vladivostok is not Europe. So for those+few, the point's own coordinates decide, and the table verdict is only the+fallback for a row that has none. The boundaries below are the geographic ones+(the Urals, the Ural river, the Bosphorus) traced coarsely — close enough to+file a point in the right branch of a panel, not a border survey. Countries the+UN geoscheme splits on political rather than geographic grounds (Egypt's Sinai,+Indonesian Papua, the Spanish and Portuguese Atlantic islands) keep their single+verdict.+"""++from __future__ import annotations++from bisect import bisect_left++AFRICA = "Africa"+ANTARCTICA = "Antarctica"+ASIA = "Asia"+EUROPE = "Europe"+NORTH_AMERICA = "North America"+OCEANIA = "Oceania"+SOUTH_AMERICA = "South America"++_BY_CONTINENT: dict[str, str] = {+ AFRICA: (+ "ao bf bi bj bw cd cf cg ci cm cv dj dz eg eh er et ga gh gm gn gq gw ke km "+ "ls lr ly ma mg ml mr mu mw mz na ne ng re rw sc sd sh sl sn so ss st sz td "+ "tg tn tz ug yt za zm zw"+ ),+ ANTARCTICA: "aq bv gs hm tf",+ ASIA: (+ "ae af am az bd bh bn bt cc cn cx cy ge hk id il in io iq ir jo jp kg kh kp "+ "kr kw kz la lb lk mm mn mo mv my np om ph pk ps qa sa sg sy th tj tl tm tr "+ "tw uz vn ye"+ ),+ EUROPE: (+ "ad al at ax ba be bg by ch cz de dk ee es fi fo fr gb gg gi gr hr hu ie im "+ "is it je li lt lu lv mc md me mk mt nl no pl pt ro rs ru se si sj sk sm ua "+ "va"+ ),+ NORTH_AMERICA: (+ "ag ai aw bb bl bm bq bs bz ca cr cu cw dm do gd gl gp gt hn ht jm kn ky lc "+ "mf mq ms mx ni pa pm pr sv sx tc tt us vc vg vi"+ ),+ OCEANIA: (+ "as au ck fj fm gu ki mh mp nc nf nr nu nz pf pg pn pw sb tk to tv um vu wf "+ "ws"+ ),+ SOUTH_AMERICA: "ar bo br cl co ec fk gf gy pe py sr uy ve",+}++CONTINENTS: dict[str, str] = {+ code: continent+ for continent, codes in _BY_CONTINENT.items()+ for code in codes.split()+}+++# The Ural crest as longitudes read off a few latitudes, south to north: the+# divide is not a meridian, it leans east as it climbs (Yekaterinburg sits just+# inside Asia, Vorkuta stays in Europe six degrees further east).+_URAL_CREST: list[tuple[float, float]] = [+ (50.0, 61.5), (52.0, 60.0), (58.0, 59.5), (62.0, 60.0),+ (65.0, 62.5), (67.5, 65.5), (71.0, 68.0),+]+++def _crest_lon(lat: float) -> float:+ """The dividing longitude at this latitude, interpolated along the crest."""+ lats = [point[0] for point in _URAL_CREST]+ i = bisect_left(lats, lat)+ if i == 0:+ return _URAL_CREST[0][1]+ if i == len(_URAL_CREST):+ return _URAL_CREST[-1][1]+ (lat0, lon0), (lat1, lon1) = _URAL_CREST[i - 1], _URAL_CREST[i]+ return lon0 + (lon1 - lon0) * (lat - lat0) / (lat1 - lat0)+++def _split_ru(lat: float, lon: float) -> str:+ # Chukotka reaches past the antimeridian and comes back as a negative+ # longitude; unwrap it before comparing, or the far east reads as Europe+ if lon < -30.0:+ lon += 360.0+ return EUROPE if lon < _crest_lon(lat) else ASIA+++def _split_kz(lat: float, lon: float) -> str:+ # west of the Ural river, so the two western provinces+ return EUROPE if lon < 51.5 else ASIA+++def _split_tr(lat: float, lon: float) -> str:+ # East Thrace: the Bosphorus splits Istanbul, and the Dardanelles cut the+ # Gallipoli peninsula and Imbros off the Anatolian coast further south+ if lat > 40.7 and lon < 29.0:+ return EUROPE+ if lat > 40.0 and lon < 26.9:+ return EUROPE+ return ASIA+++_SPLIT = {"ru": _split_ru, "kz": _split_kz, "tr": _split_tr}+++def continent_for(+ code: str | None, lat: float | None = None, lon: float | None = None+) -> str | None:+ """The continent of an ISO 3166-1 alpha-2 code, or None if it isn't one.++ For a country that spans two continents the coordinates decide, when the+ point has them; otherwise the country's own verdict stands.+ """+ if not code:+ return None+ code = code.strip().lower()+ split = _SPLIT.get(code)+ if split is not None and lat is not None and lon is not None:+ return split(float(lat), float(lon))+ return CONTINENTS.get(code)diff --git a/src/azimut/engine/coords.py b/src/azimut/engine/coords.pyindex 3a10498..7d577ac 100644--- a/src/azimut/engine/coords.py+++ b/src/azimut/engine/coords.py@@ -1,7 +1,7 @@"""Latitude/longitude presentation — the server-side mirror of``frontend/src/lib/coords.js``.-The app stores decimal degrees everywhere (case.json, sidecars, proof specs).+The app stores decimal degrees in its SQLite graph, sidecars and proof specs.This module only decides how a pair is *written out* in a human-facing label,following the user's ``coord_format`` preference (Settings → Preferences).diff --git a/src/azimut/engine/countries.py b/src/azimut/engine/countries.pynew file mode 100644index 0000000..c794dc8--- /dev/null+++ b/src/azimut/engine/countries.py@@ -0,0 +1,113 @@+"""ISO 3166-1 alpha-2 → English country name, as a static table.++Nominatim answers in the local language, so a case filed across three countries+comes back as ``Россия`` / ``Deutschland`` / ``中国``. The Saved tree wants an+English name beside the native one, and for countries there is no reason to ask+a geocoder for it: the country code is already stored, so the English name is+derived on read exactly the way the continent is. Correcting this table repairs+every existing case at once — no migration, no re-geocoding, no network.++Regions have no such table and are looked up (see ``geo.locate_point``).++The names are the common English short forms, not the ISO long forms: this is a+label to scan in a 300px panel, not a diplomatic register.+"""++from __future__ import annotations++COUNTRY_NAMES_EN: dict[str, str] = {+ # Africa+ "ao": "Angola", "bf": "Burkina Faso", "bi": "Burundi", "bj": "Benin",+ "bw": "Botswana", "cd": "DR Congo", "cf": "Central African Republic",+ "cg": "Republic of the Congo", "ci": "Ivory Coast", "cm": "Cameroon",+ "cv": "Cape Verde", "dj": "Djibouti", "dz": "Algeria", "eg": "Egypt",+ "eh": "Western Sahara", "er": "Eritrea", "et": "Ethiopia", "ga": "Gabon",+ "gh": "Ghana", "gm": "Gambia", "gn": "Guinea", "gq": "Equatorial Guinea",+ "gw": "Guinea-Bissau", "ke": "Kenya", "km": "Comoros", "ls": "Lesotho",+ "lr": "Liberia", "ly": "Libya", "ma": "Morocco", "mg": "Madagascar",+ "ml": "Mali", "mr": "Mauritania", "mu": "Mauritius", "mw": "Malawi",+ "mz": "Mozambique", "na": "Namibia", "ne": "Niger", "ng": "Nigeria",+ "re": "Réunion", "rw": "Rwanda", "sc": "Seychelles", "sd": "Sudan",+ "sh": "Saint Helena", "sl": "Sierra Leone", "sn": "Senegal",+ "so": "Somalia", "ss": "South Sudan", "st": "São Tomé and Príncipe",+ "sz": "Eswatini", "td": "Chad", "tg": "Togo", "tn": "Tunisia",+ "tz": "Tanzania", "ug": "Uganda", "yt": "Mayotte", "za": "South Africa",+ "zm": "Zambia", "zw": "Zimbabwe",+ # Antarctica+ "aq": "Antarctica", "bv": "Bouvet Island",+ "gs": "South Georgia and the South Sandwich Islands",+ "hm": "Heard Island and McDonald Islands",+ "tf": "French Southern Territories",+ # Asia+ "ae": "United Arab Emirates", "af": "Afghanistan", "am": "Armenia",+ "az": "Azerbaijan", "bd": "Bangladesh", "bh": "Bahrain", "bn": "Brunei",+ "bt": "Bhutan", "cc": "Cocos (Keeling) Islands", "cn": "China",+ "cx": "Christmas Island", "cy": "Cyprus", "ge": "Georgia",+ "hk": "Hong Kong", "id": "Indonesia", "il": "Israel", "in": "India",+ "io": "British Indian Ocean Territory", "iq": "Iraq", "ir": "Iran",+ "jo": "Jordan", "jp": "Japan", "kg": "Kyrgyzstan", "kh": "Cambodia",+ "kp": "North Korea", "kr": "South Korea", "kw": "Kuwait",+ "kz": "Kazakhstan", "la": "Laos", "lb": "Lebanon", "lk": "Sri Lanka",+ "mm": "Myanmar", "mn": "Mongolia", "mo": "Macao", "mv": "Maldives",+ "my": "Malaysia", "np": "Nepal", "om": "Oman", "ph": "Philippines",+ "pk": "Pakistan", "ps": "Palestine", "qa": "Qatar", "sa": "Saudi Arabia",+ "sg": "Singapore", "sy": "Syria", "th": "Thailand", "tj": "Tajikistan",+ "tl": "Timor-Leste", "tm": "Turkmenistan", "tr": "Turkey", "tw": "Taiwan",+ "uz": "Uzbekistan", "vn": "Vietnam", "ye": "Yemen",+ # Europe+ "ad": "Andorra", "al": "Albania", "at": "Austria", "ax": "Åland Islands",+ "ba": "Bosnia and Herzegovina", "be": "Belgium", "bg": "Bulgaria",+ "by": "Belarus", "ch": "Switzerland", "cz": "Czechia", "de": "Germany",+ "dk": "Denmark", "ee": "Estonia", "es": "Spain", "fi": "Finland",+ "fo": "Faroe Islands", "fr": "France", "gb": "United Kingdom",+ "gg": "Guernsey", "gi": "Gibraltar", "gr": "Greece", "hr": "Croatia",+ "hu": "Hungary", "ie": "Ireland", "im": "Isle of Man", "is": "Iceland",+ "it": "Italy", "je": "Jersey", "li": "Liechtenstein", "lt": "Lithuania",+ "lu": "Luxembourg", "lv": "Latvia", "mc": "Monaco", "md": "Moldova",+ "me": "Montenegro", "mk": "North Macedonia", "mt": "Malta",+ "nl": "Netherlands", "no": "Norway", "pl": "Poland", "pt": "Portugal",+ "ro": "Romania", "rs": "Serbia", "ru": "Russia", "se": "Sweden",+ "si": "Slovenia", "sj": "Svalbard and Jan Mayen", "sk": "Slovakia",+ "sm": "San Marino", "ua": "Ukraine", "va": "Vatican City",+ # Kosovo has no continent verdict (it is not in the UN geoscheme table),+ # but Nominatim files points there under "xk" and the name is still useful.+ "xk": "Kosovo",+ # North America+ "ag": "Antigua and Barbuda", "ai": "Anguilla", "aw": "Aruba",+ "bb": "Barbados", "bl": "Saint Barthélemy", "bm": "Bermuda",+ "bq": "Caribbean Netherlands", "bs": "Bahamas", "bz": "Belize",+ "ca": "Canada", "cr": "Costa Rica", "cu": "Cuba", "cw": "Curaçao",+ "dm": "Dominica", "do": "Dominican Republic", "gd": "Grenada",+ "gl": "Greenland", "gp": "Guadeloupe", "gt": "Guatemala",+ "hn": "Honduras", "ht": "Haiti", "jm": "Jamaica",+ "kn": "Saint Kitts and Nevis", "ky": "Cayman Islands", "lc": "Saint Lucia",+ "mf": "Saint Martin", "mq": "Martinique", "ms": "Montserrat",+ "mx": "Mexico", "ni": "Nicaragua", "pa": "Panama",+ "pm": "Saint Pierre and Miquelon", "pr": "Puerto Rico",+ "sv": "El Salvador", "sx": "Sint Maarten",+ "tc": "Turks and Caicos Islands", "tt": "Trinidad and Tobago",+ "us": "United States", "vc": "Saint Vincent and the Grenadines",+ "vg": "British Virgin Islands", "vi": "United States Virgin Islands",+ # Oceania+ "as": "American Samoa", "au": "Australia", "ck": "Cook Islands",+ "fj": "Fiji", "fm": "Micronesia", "gu": "Guam", "ki": "Kiribati",+ "mh": "Marshall Islands", "mp": "Northern Mariana Islands",+ "nc": "New Caledonia", "nf": "Norfolk Island", "nr": "Nauru",+ "nu": "Niue", "nz": "New Zealand", "pf": "French Polynesia",+ "pg": "Papua New Guinea", "pn": "Pitcairn Islands", "pw": "Palau",+ "sb": "Solomon Islands", "tk": "Tokelau", "to": "Tonga", "tv": "Tuvalu",+ "um": "United States Minor Outlying Islands", "vu": "Vanuatu",+ "wf": "Wallis and Futuna", "ws": "Samoa",+ # South America+ "ar": "Argentina", "bo": "Bolivia", "br": "Brazil", "cl": "Chile",+ "co": "Colombia", "ec": "Ecuador", "fk": "Falkland Islands",+ "gf": "French Guiana", "gy": "Guyana", "pe": "Peru", "py": "Paraguay",+ "sr": "Suriname", "uy": "Uruguay", "ve": "Venezuela",+}+++def name_for(code: str | None) -> str | None:+ """The English name of an ISO 3166-1 alpha-2 code, or None if it isn't one."""+ if not code:+ return None+ return COUNTRY_NAMES_EN.get(code.strip().lower())diff --git a/src/azimut/engine/geo.py b/src/azimut/engine/geo.pyindex e767859..da91ef0 100644--- a/src/azimut/engine/geo.py+++ b/src/azimut/engine/geo.py@@ -275,11 +275,16 @@ def map_links(lat: float, lon: float, zoom: int = 17) -> dict[str, str]:def geocode(query: str) -> dict[str, Any] | None:- """Best-effort forward geocoding via Nominatim. Returns None on any failure."""+ """Best-effort forward geocoding via Nominatim. Returns None on any failure.++ Nominatim reads a query in any language; ``accept-language=en`` only decides+ what it answers with, so typing ``Москва`` comes back as "Moscow, Russia"+ and the analyst can tell they landed where they meant to.+ """try:response = httpx.get("https://nominatim.openstreetmap.org/search",- params={"q": query, "format": "jsonv2", "limit": 1},+ params={"q": query, "format": "jsonv2", "limit": 1, "accept-language": "en"},headers={"User-Agent": USER_AGENT},timeout=8,)@@ -298,14 +303,28 @@ def geocode(query: str) -> dict[str, Any] | None:return None-def reverse_geocode(lat: float, lon: float) -> dict[str, Any] | None:- """Best-effort place name via Nominatim. Returns None on any failure."""+def reverse_geocode(+ lat: float, lon: float, timeout: float = 8, language: str | None = None+) -> dict[str, Any] | None:+ """Best-effort place name via Nominatim. Returns None on any failure.++ ``timeout`` is short on the save path — a filed capture must not sit behind+ a slow geocoder — and generous on the explicit backfill, where waiting is+ the whole point.++ ``language`` is unset by default, which is Nominatim's local-language+ answer. Keep it that way for anything the Post and Proof composers read:+ they name a place the way it is named where it is.+ """+ params: dict[str, Any] = {"lat": lat, "lon": lon, "format": "jsonv2", "zoom": 14}+ if language:+ params["accept-language"] = languagetry:response = httpx.get("https://nominatim.openstreetmap.org/reverse",- params={"lat": lat, "lon": lon, "format": "jsonv2", "zoom": 14},+ params=params,headers={"User-Agent": USER_AGENT},- timeout=8,+ timeout=timeout,)response.raise_for_status()data = response.json()@@ -316,3 +335,75 @@ def reverse_geocode(lat: float, lon: float) -> dict[str, Any] | None:}except Exception:return None+++# Nominatim spells the first administrative level differently by country. Read+# in this order and take the first one present — the goal is one honest label+# per country, not a faithful reproduction of each country's admin hierarchy.+_REGION_KEYS = ("state", "region", "province", "county")+++def locate_point(lat: float, lon: float, timeout: float = 8) -> dict[str, Any]:+ """Which country (and region) a point falls in — the ``attrs.geo`` record.++ Never raises: callers file the verdict as-is and move on. The four states+ are the whole vocabulary, and three of them are permanent:++ - ``ok`` — country resolved, ``country_code``/``country`` (and ``region``+ when Nominatim has one) ride along;+ - ``nocountry`` — the lookup answered but the point is in no country+ (open sea);+ - ``failed`` — the lookup itself did not answer (offline, timeout, 5xx),+ the one state a later backfill pass retries.++ ``nocoords`` is the fourth, written by callers for items that have no+ position to look up at all.++ The native answer is the authority. When it named a region, a second+ English lookup fills ``region_en`` so the Saved tree can label the branch in+ both languages; the English country name needs no lookup at all (see+ ``engine.countries``). That second call is best-effort in the strongest+ sense: if it fails the verdict is filed native-only and nothing retries it.+ """+ try:+ result = reverse_geocode(lat, lon, timeout)+ except Exception:+ return {"state": "failed"}+ if result is None:+ return {"state": "failed"}+ address = result.get("address") or {}+ code = str(address.get("country_code") or "").strip().lower()+ if not code:+ return {"state": "nocountry"}+ geo: dict[str, Any] = {+ "state": "ok",+ "country_code": code,+ "country": str(address.get("country") or "").strip() or code.upper(),+ }+ region = _region_of(address)+ if region:+ geo["region"] = region+ english = _region_in_english(lat, lon, timeout)+ if english and english != region:+ geo["region_en"] = english+ return geo+++def _region_of(address: dict[str, Any]) -> str:+ """The first administrative level Nominatim spelled, or ``""``."""+ for key in _REGION_KEYS:+ region = str(address.get(key) or "").strip()+ if region:+ return region+ return ""+++def _region_in_english(lat: float, lon: float, timeout: float) -> str:+ """The same region asked for again in English, or ``""`` if that fails."""+ try:+ result = reverse_geocode(lat, lon, timeout, language="en")+ except Exception:+ return ""+ if result is None:+ return ""+ return _region_of(result.get("address") or {})diff --git a/src/azimut/engine/inspect.py b/src/azimut/engine/inspect.pyindex 219e55c..9979a9e 100644--- a/src/azimut/engine/inspect.py+++ b/src/azimut/engine/inspect.py@@ -21,6 +21,7 @@ from __future__ import annotationsimport base64import ioimport json+import reimport subprocessimport tempfileimport threading@@ -462,6 +463,36 @@ def _stamp() -> str:return datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")+def _name_stem(label: str | None, fallback: str) -> str:+ """Filename stem for a filed item: the name the user typed, else the source's.++ ``media_engine.safe_filename`` still scrubs what comes out of here, so this+ only has to fold whitespace and keep the stem short enough to read.+ """+ stem = re.sub(r"\s+", "_", (label or "").strip())+ return stem[:60] if stem else fallback[:40]+++def _apply_meta(+ case: Case,+ result: dict[str, Any],+ *,+ label: str | None = None,+ folder: str | None = None,+ notes: str | None = None,+) -> None:+ """Write the Save gate's chosen name, folder and note onto the filed item.++ This applies to a deduped save too. Re-saving an unchanged collage lands on+ the same pixels and so on the same entity, and dropping the name there is+ exactly the case where a name the user just typed seems to vanish. The gate+ is an explicit act: the last one through it wins.+ """+ patch = {k: v for k, v in (("title", label), ("folder", folder), ("notes", notes)) if v}+ if patch:+ media_engine.update_media(case, result["item"]["path"], patch)++def scan_focus(case: Case, video_rel: str, set_progress: Callable[[dict], None] | None = None) -> list[dict[str, Any]]:@@ -624,29 +655,25 @@ def save_frame(ops: list[dict[str, Any]] | None = None,label: str | None = None,folder: str | None = None,+ notes: str | None = None,) -> dict[str, Any]:"""File one tray frame (a video frame or an adjusted image) as case media."""image = _source_image(case, rel_path, time_s, ops)- stem = Path(rel_path).stem[:40]+ stem = _name_stem(label, Path(rel_path).stem)if time_s is not None:tag, op = f"_t{time_s:.2f}s", "frame"else:tag, op = "_edit", "adjust"- name = f"{stem}{tag}_{_stamp()}.png"+ # A named item keeps its name on disk; the timecode tag only makes sense on+ # the fallback stem, where nothing else says which instant this is.+ name = f"{stem}{'' if label else tag}_{_stamp()}.png"source = _derivation(rel_path, _source_sha(case, rel_path), op=op,**({"time": round(time_s, 3)} if time_s is not None else {}),**({"ops": ops} if ops else {}),)result = media_engine.import_image(case, image, name, source, by="inspect")- if not result.get("duplicate"):- patch: dict[str, Any] = {}- if label:- patch["title"] = label- if folder:- patch["folder"] = folder- if patch:- media_engine.update_media(case, result["item"]["path"], patch)+ _apply_meta(case, result, label=label, folder=folder, notes=notes)return result@@ -766,6 +793,7 @@ def compose_perspective(background: str | None = "#12141c",label: str | None = None,folder: str | None = None,+ notes: str | None = None,) -> dict[str, Any]:"""Composite tray/case images, each warped into a 4-point quad, onto a canvas.@@ -778,16 +806,9 @@ def compose_perspective(case, width=width, height=height, nodes=nodes, background=background)source = _derivation("", None, op="collage", sources=sources, perspective=True)- name = f"collage_{_stamp()}.png"+ name = f"{_name_stem(label, 'collage')}_{_stamp()}.png"result = media_engine.import_image(case, canvas, name, source, by="inspect")- if not result.get("duplicate"):- patch: dict[str, Any] = {}- if label:- patch["title"] = label- if folder:- patch["folder"] = folder- if patch:- media_engine.update_media(case, result["item"]["path"], patch)+ _apply_meta(case, result, label=label, folder=folder, notes=notes)return result@@ -890,6 +911,7 @@ def enhance_video(rotation: int = 0,label: str | None = None,folder: str | None = None,+ notes: str | None = None,) -> dict[str, Any]:"""Re-encode a video with its adjustments and orientation, then file it."""if not media_engine.ffmpeg_available():@@ -899,7 +921,7 @@ def enhance_video(raise ValueError("no adjustments or rotation to apply")src = case.resolve_inside(video_rel)- stem = Path(src.name).stem[:40]+ stem = _name_stem(label, Path(src.name).stem)tmp = case.subdir("media") / f".enhance_{_stamp()}.mp4"try:proc = subprocess.run(@@ -911,7 +933,7 @@ def enhance_video(raise RuntimeError((proc.stderr or b"").decode("utf-8", "replace").strip() or "video enhance failed")- name = f"{stem}_enhanced_{_stamp()}.mp4"+ name = f"{stem}{'' if label else '_enhanced'}_{_stamp()}.mp4"source = _derivation(video_rel, _source_sha(case, video_rel), op="enhance-video",params=params, rotation=rotation,@@ -919,12 +941,5 @@ def enhance_video(result = media_engine.import_produced_file(case, tmp, name, source, by="inspect")finally:tmp.unlink(missing_ok=True)- if not result.get("duplicate"):- patch: dict[str, Any] = {}- if label:- patch["title"] = label- if folder:- patch["folder"] = folder- if patch:- media_engine.update_media(case, result["item"]["path"], patch)+ _apply_meta(case, result, label=label, folder=folder, notes=notes)return resultdiff --git a/src/azimut/engine/links.py b/src/azimut/engine/links.pyindex af519f1..99cd77c 100644--- a/src/azimut/engine/links.py+++ b/src/azimut/engine/links.py@@ -1,10 +1,10 @@"""The derivation link layer (ONTOLOGY §3), and what deleting an entity means.-Every tool that files an artifact already knows the case paths it was made from-— a proof's panels, a post's proof, a frame's video. This module turns those-paths into typed edges in ``case.json`` so the chain becomes traversable: the-Details panel's relations, the derivation breadcrumbs and the dependency-aware-delete all read the same edges.+Every tool that files an artifact already knows the case paths it was made from:+a proof's panels, a post's proof or a frame's video. This module turns those+paths into typed edges in the case graph so the chain becomes traversable. The+Details panel, derivation breadcrumbs and dependency-aware delete all read the+same edges.Two link types carry it, and the delete policy reads off the **link type**, notoff the producing tool, so a new tool inherits the right behaviour just bydiff --git a/src/azimut/engine/mapsites.py b/src/azimut/engine/mapsites.pyindex aefc6a8..4309bdd 100644--- a/src/azimut/engine/mapsites.py+++ b/src/azimut/engine/mapsites.py@@ -13,9 +13,10 @@ verifiable by anyone with the recorded source URL.``parse_map_url(url)`` returns None for a non-map URL (the extension refusesto capture there — maps only), else a dict with ``site``/``label`` always set-and ``lat``/``lon``/``zoom``/``bearing``/``title``/``imagery_date`` set to-values when the URL carries them, None when it doesn't. A malformed URL on a-known host degrades to "known site, nothing parsed" — parsers never raise.+and ``lat``/``lon``/``zoom``/``bearing``/``title``/``imagery_date``/+``imagery_mode`` set to values when the URL carries them, None when it+doesn't. A malformed URL on a known host degrades to "known site, nothing+parsed" — parsers never raise."""from __future__ import annotations@@ -82,6 +83,29 @@ def _param(u, name: str) -> str | None:return values[0] if values else None+def _imagery_mode(site_id: str, u) -> str | None:+ """Identify satellite imagery only when the URL makes it explicit.++ The capture extension sees pixels but deliberately does not inspect the+ page DOM. Generic map URLs therefore remain unclassified rather than being+ guessed as satellite imagery. Satellite-only sites and explicit layer+ parameters are safe to classify from the address bar.+ """+ if site_id in {"google-earth", "zoom-earth", "satellites-pro", "copernicus-browser"}:+ return "satellite"+ if site_id == "google-maps":+ return "satellite" if "!1e3" in unquote(u.geturl()) else None+ if site_id == "bing-maps":+ return "satellite" if (_param(u, "style") or "").lower() in {"a", "h"} else None+ if site_id == "yandex-maps":+ layers = {part.strip().lower() for part in (_param(u, "l") or "").split(",")}+ return "satellite" if layers & {"sat", "satellite"} else None+ if site_id == "apple-maps":+ layer = (_param(u, "map") or _param(u, "t") or "").lower()+ return "satellite" if layer in {"satellite", "hybrid", "k", "h"} else None+ return None++# --- per-site parsers (each takes a SplitResult) -------------------------------@@ -232,5 +256,10 @@ def parse_map_url(url: str) -> dict[str, Any] | None:parsed = parse(u)except Exception:parsed = _no_view() # a weird URL on a known site still captures- return {"site": site_id, "label": label, **parsed}+ return {+ "site": site_id,+ "label": label,+ **parsed,+ "imagery_mode": _imagery_mode(site_id, u),+ }return Nonediff --git a/src/azimut/engine/media.py b/src/azimut/engine/media.pyindex 591f3d1..5ddc0c3 100644--- a/src/azimut/engine/media.py+++ b/src/azimut/engine/media.py@@ -1,8 +1,7 @@-"""Media engine: import local files, download by URL (yt-dlp), hash, thumbnail.+"""Import, download, hash and thumbnail case media.-Every media item gets a *sidecar* JSON (``<name>.azimut.json``) recording how it-entered the case — source, timestamps, hashes (spec §3.6 honest output) — and a-``media`` entity in ``case.json``.+Each item has a sidecar recording its source, timestamps and hashes, plus a+media entity in the case graph."""from __future__ import annotations@@ -31,20 +30,15 @@ from . import thumbnails as thumbnail_engine# test fixtures that build a case's `.thumbs/` directly.THUMB_DIR = thumbnail_engine.THUMB_DIRSIDECAR_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-# item, same as the old noplaylist behavior — no picker with hundreds of rows+# Attachment collections fit under this limit. Larger collections use the+# playlist path and select the first item.MAX_PICKER_ITEMS = 20-# Chromium-family browsers whose cookie store is OS-encrypted and locked while-# the browser runs. On Windows they're also app-bound-encrypted (Chrome 127+),-# so yt-dlp can't read them even when closed — we route those to the cookies.txt-# how-to instead of attempting the read.+# Chromium cookie stores are OS-encrypted and locked while the browser runs.+# Windows app-bound encryption routes these browsers to cookies.txt._CHROMIUM_BROWSERS = {"chrome", "chromium", "edge", "brave", "vivaldi", "opera", "whale"}-# Substrings that mark a download failure as "you need to be logged in", as-# opposed to a dead link or a network hiccup. Best-effort: a miss just means the-# cookie prompt doesn't appear (no worse than before the feature existed).+# Best-effort phrases that identify an authentication failure._AUTH_FAILURE_PHRASES = ("log in","login",@@ -85,8 +79,7 @@ def _resolve_cookie_file(file: str) -> Path:def _cookie_ydl_opts(cookies: dict[str, Any] | None) -> dict[str, Any]:- """Translate a cookie source into yt-dlp options. Empty when no source —- the first attempt is always cookie-less (local-first)."""+ """Translate a cookie source into yt-dlp options; empty means cookie-less."""if not cookies:return {}if cookies.get("browser"):@@ -256,12 +249,14 @@ def _register(by=by,source=source.get("url"),)+ indexed = {**sidecar, "path": rel_path}+ case.upsert_media_item(indexed, entity_id=entity["id"])# Every media derivative is filed through here, so the derivation chain is# wired once for every tool that produces imagery — present and future.link_engine.link_all(case, entity["id"], link_engine.DERIVED_FROM, _source_paths(source), by=by)- return {"duplicate": False, "entity": entity, "item": {**sidecar, "path": rel_path}}+ return {"duplicate": False, "entity": entity, "item": indexed}def import_stream(case: Case, filename: str, stream: BinaryIO) -> dict[str, Any]:@@ -711,6 +706,7 @@ def set_thumbnail(case: Case, rel_path: str, thumb_rel: str | None) -> None:data = json.loads(sidecar.read_text(encoding="utf-8"))data["thumbnail"] = thumb_rel_write_sidecar(media_path, data)+ case.upsert_media_item({**data, "path": rel_path})def read_item(case: Case, rel_path: str) -> dict[str, Any] | None:@@ -724,17 +720,7 @@ def read_item(case: Case, rel_path: str) -> dict[str, Any] | None:def list_media(case: Case) -> list[dict[str, Any]]:- media_dir = case.subdir("media")- items = []- for sidecar in sorted(media_dir.glob(f"*{SIDECAR_SUFFIX}")):- media_name = sidecar.name[: -len(SIDECAR_SUFFIX)]- if not (media_dir / media_name).exists():- continue- data = json.loads(sidecar.read_text(encoding="utf-8"))- data["path"] = f"media/{media_name}"- items.append(data)- items.sort(key=lambda d: d.get("added_at") or "", reverse=True)- return items+ return case.list_media_items()def update_media(case: Case, rel_path: str, patch: dict[str, Any]) -> dict[str, Any]:@@ -774,7 +760,9 @@ def update_media(case: Case, rel_path: str, patch: dict[str, Any]) -> dict[str,if entity_patch:case.update_entity(entity["id"], entity_patch)- return {**data, "path": rel_path}+ indexed = {**data, "path": rel_path}+ case.upsert_media_item(indexed, entity_id=entity["id"] if entity else None)+ return indexeddef delete_media_files(case: Case, rel_path: str) -> None:@@ -788,6 +776,7 @@ def delete_media_files(case: Case, rel_path: str) -> None:data = Noneif sidecar.exists():data = json.loads(sidecar.read_text(encoding="utf-8"))+ case.remove_media_item(rel_path)media_path.unlink(missing_ok=True)sidecar.unlink(missing_ok=True)if data and data.get("thumbnail"):diff --git a/src/azimut/engine/satellite.py b/src/azimut/engine/satellite.pyindex 06d686c..5930a0d 100644--- a/src/azimut/engine/satellite.py+++ b/src/azimut/engine/satellite.py@@ -10,18 +10,33 @@ holds the full capture provenance (provider, attribution, acquisition, …) withmedia item both here and in the Media Library facet.Because a capture *is* a media item, all of its lifecycle (list/patch/delete)-funnels through the media engine; this module only adds the satellite-flavoured-listing view the Satellite tool's "Saved › Captures" panel consumes.+funnels through the media engine; this module adds the satellite-flavoured+listing view on top of it, plus the compact saved index the Map's Saved panel+navigates (places and captures together, with the geography each was resolved+to)."""from __future__ import annotations+from datetime import datetime, timezonefrom typing import Anyfrom ..workspace import Case+from . import continentsfrom . import coords as coords_engine+from . import countries+from . import geo as geo_engine+from . import linksfrom . import media as media_engine+# Saved work is places plus captures; a screenshot filed by the capture+# extension is a capture with a different origin, not a third entity type.+SAVED_TYPES = ["place", "capture"]++# One page of the catalog per query while collecting saved entities: bounded+# memory per round-trip, and the whole set is still tens of KB on the wire.+_ENTITY_PAGE = 500+def coords_label(lat: float, lon: float, fmt: str | None = None) -> str:"""Default capture title / place label: the point's coordinates, written in@@ -35,6 +50,38 @@ def coords_label(lat: float, lon: float, fmt: str | None = None) -> str:return coords_engine.format_coords(lat, lon, fmt)+def save_place(+ case: Case,+ lat: float,+ lon: float,+ zoom: Any = None,+ bearing: Any = None,+ title: str | None = None,+ by: str = "satellite",+ extra_attrs: dict[str, Any] | None = None,+) -> dict[str, Any]:+ """Register a point as a navigable ``place`` — no image, no download.++ Two callers save places: the map's own pin (api/satellite.py) and the+ capture extension filing the map site you are looking at (api/ingest.py).+ They agree on what a place *is* here, so the Saved panel renders both the+ same way whatever route wrote them. The caller resolves the geography+ afterwards (``locate_on_save``); ``extra_attrs`` carries whatever only one+ of them has, such as the extension's source URL.+ """+ attrs: dict[str, Any] = {+ "coords": coords_label(lat, lon, "dd"),+ "lat": lat,+ "lon": lon,+ "plus_code": geo_engine.plus_code(lat, lon),+ "zoom": zoom,+ "bearing": bearing,+ }+ attrs.update(extra_attrs or {})+ label = (title or "").strip() or coords_label(lat, lon)+ return case.add_entity("place", label, attrs=attrs, by=by, status="confirmed")++def is_capture(item: dict[str, Any]) -> bool:"""True if a media listing item is a capture: a satellite crop, or anexternal-map screenshot filed by the capture extension (api/ingest.py) —@@ -63,3 +110,358 @@ def list_captures(case: Case) -> list[dict[str, Any]]:captures.append(merged)captures.sort(key=lambda d: d.get("fetched_at") or d.get("added_at") or "", reverse=True)return captures+++# -- saved work: the compact index the Saved panel navigates ----------------------+++def _page_all(case: Case, types: list[str]) -> list[dict[str, Any]]:+ """Every entity of these types, read a bounded page at a time.++ Never materialises the whole graph — the panels above these lists are the+ screens that must stay fast on a case with hundreds of saved points.+ """+ out: list[dict[str, Any]] = []+ cursor: str | None = None+ while True:+ page = case.page_entities(limit=_ENTITY_PAGE, cursor=cursor, types=types)+ out.extend(page["items"])+ cursor = page.get("next_cursor")+ if not cursor:+ return out+++def saved_entities(case: Case) -> list[dict[str, Any]]:+ """Every ``place`` and ``capture`` entity, in insertion order."""+ return _page_all(case, SAVED_TYPES)+++def _utc_stamp(value: Any) -> str:+ """One timestamp spelling for the whole index: ``2026-07-20T09:12:04Z``.++ Places carry the entity's ``provenance.at`` (already Z-suffixed), captures+ the media sidecar's ``fetched_at`` (an offset-aware isoformat). Both mean+ the same instant, but they don't sort against each other as text — and both+ the "newest first" order here and the client's own sort are text sorts. So+ normalise once, at the edge, rather than parsing dates in three places.+ """+ text = str(value or "").strip()+ if not text:+ return ""+ try:+ moment = datetime.fromisoformat(text.replace("Z", "+00:00"))+ except ValueError:+ return text+ if moment.tzinfo is not None:+ moment = moment.astimezone(timezone.utc)+ return moment.strftime("%Y-%m-%dT%H:%M:%SZ")+++def _saved_when(entity: dict[str, Any], capture: dict[str, Any] | None) -> str:+ """The one timestamp the saved list orders on: when the item was filed."""+ if capture:+ stamp = capture.get("fetched_at") or capture.get("added_at")+ if stamp:+ return _utc_stamp(stamp)+ return _utc_stamp((entity.get("provenance") or {}).get("at"))+++def _saved_row(+ case: Case, entity: dict[str, Any], capture: dict[str, Any] | None, proofs: int = 0+) -> dict[str, Any]:+ attrs = entity.get("attrs") or {}+ source = capture or {}+ geo = attrs.get("geo") if isinstance(attrs.get("geo"), dict) else None+ lat, lon = attrs.get("lat"), attrs.get("lon")+ if capture is None:+ kind = "place"+ else:+ kind = "screenshot" if source.get("method") == "screenshot" else "capture"++ thumbnail = source.get("thumbnail")+ # a thumbnail the LRU budget has evicted must read as absent, not as a+ # broken image — the row falls back to its kind glyph+ if thumbnail and not case.resolve_inside(str(thumbnail)).exists():+ thumbnail = None++ return {+ "id": entity["id"],+ # a saved point is one row, so its render key is its id. Proof rows+ # repeat one entity across its source points and key themselves apart.+ "key": entity["id"],+ "kind": kind,+ "title": source.get("title") or entity.get("label") or "",+ # the My-work folder, so the saved-work modal can browse by folder. The+ # capture sidecar is the authority for images; places carry their own.+ "folder": source.get("folder") or attrs.get("folder") or "",+ "lat": lat,+ "lon": lon,+ "geo": geo,+ # the point decides for a country that straddles two continents, so an+ # eastern-Russia capture files under Asia and not under its country's+ # single verdict+ "continent": continents.continent_for((geo or {}).get("country_code"), lat, lon),+ # derived on read like the continent, so every row saved before the+ # tree spoke English gets its English country name without a lookup+ "country_en": countries.name_for((geo or {}).get("country_code")),+ "path": source.get("path"),+ "thumbnail": thumbnail,+ "zoom": attrs.get("zoom") if attrs.get("zoom") is not None else source.get("zoom"),+ "bearing": attrs.get("bearing") if attrs.get("bearing") is not None else source.get("bearing"),+ "provider": source.get("provider_label") or source.get("provider"),+ "site": attrs.get("site") or source.get("site"),+ "source_url": attrs.get("source_url") or source.get("source_url"),+ "fetched_at": _saved_when(entity, capture),+ "imagery_date": source.get("imagery_date"),+ "notes": source.get("notes") or attrs.get("notes") or "",+ # how many proofs were built on this point. `All` draws every point+ # once, so a worked row is marked rather than doubled by a proof+ # marker landing on the capture it composes.+ "proofs": proofs,+ }+++def saved_index(case: Case) -> list[dict[str, Any]]:+ """Places and captures as one flat list, newest first.++ Everything the Saved tree, the search modal and the map overlay read, and+ nothing else: no media rows, no derivation, no provenance. Hundreds of rows+ stay in the tens of KB, which is what lets the panel load the whole set on+ case open instead of paging it.+ """+ by_path = {c["path"]: c for c in list_captures(case)}+ # one grouped query for the whole case rather than one per row: this list+ # is read on case open and must not walk the graph row by row+ worked = case.count_dependents(link_type=links.DERIVED_FROM, from_type="proof")+ rows = []+ for entity in saved_entities(case):+ is_image = entity["type"] == "capture"+ capture = by_path.get((entity.get("attrs") or {}).get("path")) if is_image else None+ if is_image and capture is None:+ continue # the image is gone; the media listing is the authority+ rows.append(_saved_row(case, entity, capture, worked.get(entity["id"], 0)))+ # newest first, and within one second the later save wins — saving a place+ # and capturing it are one gesture, and they must not come back shuffled+ order = {row["id"]: i for i, row in enumerate(rows)}+ rows.sort(key=lambda r: (r["fetched_at"], order[r["id"]]), reverse=True)+ return rows+++def own_point(spec: dict[str, Any]) -> dict[str, float] | None:+ """The point a proof states for itself, or None if it states none.++ A proof is not only placed by what it composes. ``coordsText`` is what the+ analyst typed into the composer's coordinate field, in whatever format they+ use, and it wins: it is their own assertion, and it is the reason the field+ exists. ``coords`` is what the panels gave the proof, frozen at save — which+ is what keeps a proof on the map after the capture it was built from is+ deleted, since outputs outlive their sources (ONTOLOGY §3).+ """+ text = str(spec.get("coordsText") or "").strip()+ if text:+ parsed = geo_engine.parse_coords(text)+ if parsed: # prose in the field is a caption, not a point+ return {"lat": parsed[0], "lon": parsed[1]}+ coords = spec.get("coords")+ if isinstance(coords, dict) and coords.get("lat") is not None and coords.get("lon") is not None:+ try:+ return {"lat": float(coords["lat"]), "lon": float(coords["lon"])}+ except (TypeError, ValueError):+ return None+ return None+++def _source_points(+ case: Case, proof_id: str, incident: list[dict[str, Any]] | None = None+) -> list[dict[str, Any]]:+ """The distinct points a proof's panels were composed from.++ Read one hop back along ``derived-from``: a proof carries no coordinates of+ its own, only the sources it composes. Two panels cropped from one capture,+ or two captures of one roof, are one point and come back once — the point is+ what they share. Panels with no point (a photo, a frame) contribute nothing.+ """+ seen: dict[tuple[Any, Any], dict[str, Any]] = {}+ for link in incident if incident is not None else case.links_of(proof_id):+ if link["type"] != links.DERIVED_FROM or link["from"] != proof_id:+ continue+ source = case.get_entity(link["to"])+ attrs = (source or {}).get("attrs") or {}+ lat, lon = attrs.get("lat"), attrs.get("lon")+ if lat is None or lon is None:+ continue+ seen.setdefault((lat, lon), attrs)+ return [{"lat": lat, "lon": lon, "attrs": attrs} for (lat, lon), attrs in seen.items()]+++def _linked_posts(+ proof_id: str,+ incident: list[dict[str, Any]],+ post_entities: dict[str, dict[str, Any]],+ drafts: dict[str, dict[str, Any]],+) -> list[dict[str, Any]]:+ """Saved post drafts directly derived from this proof, newest first."""+ linked: list[dict[str, Any]] = []+ for link in incident:+ if link["type"] != links.DERIVED_FROM or link["to"] != proof_id:+ continue+ entity = post_entities.get(link["from"])+ if entity is None:+ continue+ draft_path = (entity.get("attrs") or {}).get("draft")+ draft = drafts.get(draft_path) if isinstance(draft_path, str) else None+ draft = draft or {}+ draft_name = draft.get("name")+ if not draft_name and isinstance(draft_path, str):+ draft_name = draft_path.removeprefix("exports/").removesuffix(".json")+ linked.append(+ {+ "id": entity["id"],+ "name": draft_name,+ "title": draft.get("title") or entity.get("label") or "Untitled post",+ "target": draft.get("target"),+ "updated_at": draft.get("updated_at"),+ }+ )+ linked.sort(+ key=lambda post: (post.get("updated_at") or "", post["title"].casefold()),+ reverse=True,+ )+ return linked+++def _geo_at(sources: list[dict[str, Any]], point: dict[str, float]) -> dict[str, Any]:+ """The attrs of the source standing on this exact point, or nothing.++ Five decimals is about a metre — the same precision the map groups marks at.+ """+ here = (round(point["lat"], 5), round(point["lon"], 5))+ for source in sources:+ if (round(float(source["lat"]), 5), round(float(source["lon"]), 5)) == here:+ return dict(source["attrs"])+ return {}+++def _proof_row(+ proof: dict[str, Any], entity: dict[str, Any], point: dict[str, Any] | None+) -> dict[str, Any]:+ entity_id = entity["id"]+ attrs = (point or {}).get("attrs") or {}+ geo = attrs.get("geo") if isinstance(attrs.get("geo"), dict) else None+ lat, lon = (point or {}).get("lat"), (point or {}).get("lon")+ return {+ "id": entity_id,+ # one proof can hold two points, and the two rows must not collide as+ # render keys or as marker identities+ "key": f"{entity_id}@{lat},{lon}",+ "kind": "proof",+ "name": proof["name"],+ "title": proof.get("title") or proof["name"],+ # a proof is filed like any other artifact, so the panel groups it by+ # folder as well as by place+ "folder": (entity.get("attrs") or {}).get("folder") or "",+ "notes": "",+ "lat": lat,+ "lon": lon,+ "geo": geo,+ "continent": continents.continent_for((geo or {}).get("country_code"), lat, lon),+ "country_en": countries.name_for((geo or {}).get("country_code")),+ "path": proof.get("png"),+ "thumbnail": proof.get("thumb"),+ "fetched_at": _utc_stamp(proof.get("updated_at")),+ "posts": proof.get("posts", 0),+ "linked_posts": proof.get("linked_posts", []),+ }+++def proof_index(+ case: Case,+ listing: list[dict[str, Any]],+ draft_listing: list[dict[str, Any]] | None = None,+) -> list[dict[str, Any]]:+ """Proofs as map rows, newest first — one row per distinct source point.++ ``listing`` is the proofs listing (title, export, thumbnail), which the+ proofs API owns; everything geographic is read here so the Saved panel gets+ the row shape it already knows. A proof whose panels are all unlocated still+ comes back, without a point, and files under ``Unlocated`` in the tree.++ Kept out of ``saved_index`` on purpose: that one is read on every case open,+ this one only when the Proofs position of the switch is first opened.+ """+ by_spec = {+ (entity.get("attrs") or {}).get("spec"): entity+ for entity in _page_all(case, ["proof"])+ }+ post_entities = {entity["id"]: entity for entity in _page_all(case, ["post"])}+ drafts = {+ f"exports/{draft['name']}.json": draft for draft in (draft_listing or [])+ }+ rows: list[dict[str, Any]] = []+ for proof in listing:+ entity = by_spec.get(proof.get("spec_path"))+ if entity is None:+ continue # a spec file with no entity is not in the graph to place+ incident = case.links_of(entity["id"])+ linked_posts = _linked_posts(entity["id"], incident, post_entities, drafts)+ proof = {**proof, "posts": len(linked_posts), "linked_posts": linked_posts}+ sources = _source_points(case, entity["id"], incident)+ stated = proof.get("coords")+ if stated:+ # the proof says where it is, so it says it once. Its geography is+ # borrowed only from a source standing on that same point — a+ # neighbouring capture's country would be a guess, and a wrong+ # country files the proof under the wrong branch.+ points: list[dict[str, Any] | None] = [{**stated, "attrs": _geo_at(sources, stated)}]+ else:+ # a proof none of whose panels carry a point still lists, without+ # one: it files under Unlocated rather than leaving its own tool+ points = list(sources) or [None]+ rows.extend(_proof_row(proof, entity, point) for point in points)+ rows.sort(key=lambda r: r["fetched_at"], reverse=True)+ return rows+++def is_unlocated(entity: dict[str, Any]) -> bool:+ """True when geography was never resolved for this entity, or the lookup+ failed. ``nocoords``/``nocountry``/``ok`` are settled and never retried."""+ geo = (entity.get("attrs") or {}).get("geo")+ if not isinstance(geo, dict):+ return True+ return geo.get("state") == "failed"+++def unlocated_entities(case: Case, limit: int | None = None) -> list[dict[str, Any]]:+ """Saved entities still waiting on a country, oldest first.++ Oldest first so a long backfill works forward through the case's history+ and the analyst watches the tree fill from the top. ``limit`` caps the+ batch; None counts the whole backlog.+ """+ found = [e for e in saved_entities(case) if is_unlocated(e)]+ return found if limit is None else found[:limit]+++def resolve_geo(case: Case, entity_id: str, lat: Any, lon: Any, timeout: float = 8) -> None:+ """Look up one saved item's geography and file it. Never raises.++ The entity is already written by the time this runs, so a failed or slow+ lookup can only leave ``state: failed`` behind for a later Locate pass — it+ can never turn a filed capture into an error the analyst sees.+ """+ if lat is None or lon is None:+ set_geo(case, entity_id, {"state": "nocoords"})+ return+ set_geo(case, entity_id, geo_engine.locate_point(float(lat), float(lon), timeout))+++def set_geo(case: Case, entity_id: str, geo: dict[str, Any]) -> None:+ """File a geography verdict on an entity, leaving every other attr alone.++ Tolerant of a vanished entity: the lookup that produced ``geo`` runs after+ the response was sent, and the item may have been deleted meanwhile.+ """+ try:+ case.update_entity(entity_id, {"attrs": {"geo": geo}})+ except Exception:+ passdiff --git a/src/azimut/engine/thumbnails.py b/src/azimut/engine/thumbnails.pyindex 1d10b0e..4cf61e9 100644--- a/src/azimut/engine/thumbnails.py+++ b/src/azimut/engine/thumbnails.py@@ -23,6 +23,7 @@ to the original file. This module owns their whole lifecycle.from __future__ import annotations+import jsonimport subprocessimport threadingimport time@@ -270,9 +271,25 @@ def cache_size(case: "CaseType") -> int:return sum(p.stat().st_size for p in thumbs.iterdir() if p.is_file())+def _proof_thumbs(case: "CaseType") -> set[str]:+ """Thumbnails the saved proofs point at. Proofs are not media items, but+ their exports share this cache, so the sweep below has to count them as+ referenced or it would delete every one of them."""+ names = set()+ for spec_path in case.subdir("proofs").glob("*.json"):+ try:+ spec = json.loads(spec_path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ continue+ thumb = spec.get("thumb")+ if isinstance(thumb, str) and thumb:+ names.add(thumb.rsplit("/", 1)[-1])+ return names++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).+ """Sweep the cache: delete abandoned temp files and thumbnails nothing live+ 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@@ -283,7 +300,7 @@ def repair(case: "CaseType") -> int:item["thumbnail"].rsplit("/", 1)[-1]for item in media_engine.list_media(case)if item.get("thumbnail")- }+ } | _proof_thumbs(case)removed = 0for path in thumbs.iterdir():if not path.is_file():diff --git a/src/azimut/engine/tiles.py b/src/azimut/engine/tiles.pyindex bd8f716..8fc608d 100644--- a/src/azimut/engine/tiles.py+++ b/src/azimut/engine/tiles.py@@ -40,15 +40,8 @@ class Provider:url: str # template with {x} {y} {z}, optionally {key}attribution: strmax_zoom: int = 19- # Deepest zoom the provider has *pixels* for, when that is shallower than- # the deepest zoom worth showing. None = they're the same (the usual case).- # Sentinel-2 resolves 10 m/px and stops at z14, but a z14 ceiling makes the- # basemap unusable for its actual job — you cannot look at 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 upscaled: identical pixels, magnified, for- # zero extra requests. Asking Sentinel Hub for z18 instead would buy their- # upsampling of the same pixels at 256× the quota (16× the tiles, each- # billed) — the same image, paid for.+ # Deepest zoom with native pixels. The view may continue farther by upscaling+ # the last native tile without issuing higher-zoom provider requests.max_native_zoom: int | None = Noneneeds_key: bool = Falsesubdomains: tuple[str, ...] = field(default_factory=tuple) # for {s} templates@@ -62,18 +55,11 @@ class Provider:# usage-counter bucket in settings.json (docs/IMAGERY_PROVIDERS.md);# None = unmetered. Billed keyed providers count every tile request.meter: str | None = None- # px per tile edge. Providers billing per request regardless of tile size- # get the biggest tile that keeps full imagery detail: Mapbox 512 (its @2x- # 1024 variant is upsampled — verified softer, not used), Google 1024- # (hi-DPI 4x, verified pixel-identical). The visual zoom stays the- # caller's; the URL z is offset down (512 → z-1, 1024 → z-2).+ # Tile edge in pixels. Larger native tiles reduce billed requests; URL zoom+ # is offset while the visual zoom remains unchanged.tile_size: int = 256- # Live-map display oversampling: 2 = the map shows tiles from one zoom- # deeper, downscaled 2× in CSS. Google's mid-zoom mosaics are genuinely- # softer than its deep ones (verified 2026-07: z18-detail downscaled to a- # z16 footprint beats the native z16 tile), so the layer trades 4× the- # requests (still ¼ of plain 256px tiles) for crisp imagery. Captures are- # unaffected: they stay 1:1 provider pixels for evidential integrity.+ # Live-map oversampling fetches one deeper zoom and downscales it in CSS.+ # Captures remain at native provider resolution.oversample: int = 1# Levels to re-add to the URL z after tile_size shifted it down. WMTS# services number their 512px levels by *resolution* where Mapbox numbers@@ -85,13 +71,7 @@ class Provider:# no tiles, no proxy, no fetch_crop — `url` is the widget's script loader# and the frontend does the rest. Backend still owns key storage + meter.widget: str | None = None- # Eco-mode threshold for *this* provider: the visual zoom at or below which- # free imagery replaces it. None = the user's global eco_max_zoom, which is- # tuned for providers that run to z22. A shallow provider needs its own: at- # Sentinel-2's z14 ceiling the global z15 rule would fire everywhere and the- # basemap could never be seen at all. Its threshold is instead set where its- # imagery stops earning the quota — the swap costs a known date for an- # unknown one, which is only worth it where 10 m/px adds nothing anyway.+ # Provider-specific eco threshold; None uses the global setting.eco_max_zoom: int | None = Nonediff --git a/src/azimut/repository.py b/src/azimut/repository.pyindex 5380900..7557cf4 100644--- a/src/azimut/repository.py+++ b/src/azimut/repository.py@@ -1,9 +1,9 @@"""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.+a case's entities, links, folders, durable jobs and media browse index. The+active implementation stores that structured state 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 theSQLite implementation. Legacy JSON cases migrate on open before using this@@ -11,7 +11,8 @@ contract. Keep the Protocol limited to operations with real consumers.File-backed content (media bytes, note bodies) is deliberately **not** here: itstays on the case shell (`Case`), which owns the filesystem layout, lifecycle-and path resolution. This Protocol is the graph, not the folder.+and path resolution. The media index mirrors sidecar fields needed for bounded+browsing; it is not a second copy of the media bytes."""from __future__ import annotations@@ -31,17 +32,16 @@ JobState = Literal["queued", "running", "ready", "failed", "cancelled"]@runtime_checkableclass CaseRepository(Protocol):- """Graph read/write contract for one case. `Case` is the JSON backend."""+ """Structured-data contract for one SQLite-backed case."""# -- 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.+ The format-agnostic whole-case read for graph algorithms that need+ entities and links together. The case-open response uses the bounded+ overview instead."""...@@ -58,16 +58,19 @@ class CaseRepository(Protocol):query: str | None = None,folder: str | None = None,unfiled: bool = False,+ recursive: bool = False,) -> dict[str, Any]:"""A bounded, filtered slice of the catalog (Step 5, "Bounded loading").Returns ``{"items": [...], "next_cursor": str | None}`` in a stableinsertion 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.+ ``status``, a label/type/folder/notes ``query``, and folder —+ ``unfiled`` or an exact ``folder`` path, optionally including+ descendants) 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."""...@@ -90,6 +93,17 @@ class CaseRepository(Protocol):"""...+ def count_dependents(self, *, link_type: str, from_type: str) -> dict[str, int]:+ """``{to_id: n}`` — how many entities of ``from_type`` point at each+ target through ``link_type``, in one grouped query for the whole case.++ The bulk counterpart of ``links_of``: a listing that needs "how much+ work hangs off each of these rows?" would otherwise pay one query per+ row on a screen that must stay fast. Targets nothing points at are+ absent from the map rather than present with a zero.+ """+ ...+def get_entity(self, entity_id: str) -> dict[str, Any] | None:...@@ -99,6 +113,36 @@ class CaseRepository(Protocol):def list_folders(self) -> list[str]:...+ # -- media browse index ------------------------------------------------++ def upsert_media_item(self, item: dict[str, Any], *, entity_id: str | None = None) -> None:+ """Insert or refresh one sidecar-derived media browse row."""+ ...++ def remove_media_item(self, path: str) -> None:+ ...++ def list_media_items(self) -> list[dict[str, Any]]:+ ...++ def media_items_by_paths(self, paths: list[str]) -> list[dict[str, Any]]:+ ...++ def page_media_items(+ self,+ *,+ q: str | None = None,+ kind: str | None = None,+ category: str | None = None,+ folder: str | None = None,+ sort: str = "newest",+ direction: str | None = None,+ limit: int = 200,+ offset: int = 0,+ ) -> dict[str, Any]:+ """Filter, sort and page media without scanning sidecar files."""+ ...+# -- entity mutations --------------------------------------------------def add_entity(diff --git a/src/azimut/sqlite_backend.py b/src/azimut/sqlite_backend.pyindex 9f8e5ab..d8ea346 100644--- a/src/azimut/sqlite_backend.py+++ b/src/azimut/sqlite_backend.py@@ -1,16 +1,9 @@"""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.+`SqliteCase` implements the graph and media browse contracts in+`repository.py`. Production cases use one `case.db`, so a mutation touches one+row and one short transaction instead of rewriting the complete graph. The+small case manifest only identifies the case and selects this backend.Frozen-binary constraints (see the doc): SQLite is the stdlib `sqlite3` module,already bundled by PyInstaller, so this adds no runtime dependency. Anything@@ -28,6 +21,7 @@ from dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Callable, Iterator, TypeVar+from .engine import mapsitesfrom .repository import EntityStatusfrom .workspace import Case, CaseError, _new_id, _now, _parse_cursor, _replace_with_retry@@ -44,7 +38,10 @@ if TYPE_CHECKING:# 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 4 adds a browse index for sidecar-backed media. Sidecars remain the+# file-level record; the index avoids opening and sorting every sidecar for each+# bounded Media Library page.+SQLITE_SCHEMA = 4_SCHEMA = """CREATE TABLE meta (@@ -61,6 +58,7 @@ CREATE TABLE entities (label TEXT NOT NULL,attrs_json TEXT NOT NULL DEFAULT '{}',folder TEXT,+ search_text TEXT NOT NULL DEFAULT '',prov_by TEXT NOT NULL,prov_at TEXT NOT NULL,prov_status TEXT NOT NULL DEFAULT 'confirmed',@@ -91,6 +89,21 @@ CREATE TABLE jobs (created_at TEXT NOT NULL,updated_at TEXT NOT NULL);+CREATE TABLE media_items (+ path TEXT PRIMARY KEY,+ entity_id TEXT UNIQUE,+ item_json TEXT NOT NULL,+ filename TEXT NOT NULL,+ kind TEXT NOT NULL,+ folder TEXT,+ name_sort TEXT NOT NULL,+ size INTEGER NOT NULL DEFAULT 0,+ added_at TEXT NOT NULL,+ search_text TEXT NOT NULL,+ source_type TEXT,+ source_op TEXT,+ imagery_mode TEXT+);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);@@ -99,6 +112,12 @@ 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;+CREATE INDEX idx_media_kind ON media_items(kind);+CREATE INDEX idx_media_folder ON media_items(folder);+CREATE INDEX idx_media_name ON media_items(name_sort);+CREATE INDEX idx_media_size ON media_items(size);+CREATE INDEX idx_media_added ON media_items(added_at);+CREATE INDEX idx_media_source ON media_items(source_type);"""# Job lifecycle (doc "Job states"): a fresh job is `queued`; the worker claims it@@ -119,6 +138,11 @@ def _like_contains(term: str) -> str:return f"%{escaped}%"+def _like_prefix(term: str) -> str:+ 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 Nonewhen unfiled — an absent or empty folder both read as unfiled."""@@ -126,6 +150,15 @@ def _folder_of(attrs: dict[str, Any] | None) -> str | None:return folder or None+def _entity_search_text(type_: str, label: str, attrs: dict[str, Any] | None) -> str:+ attrs = attrs or {}+ return "\n".join(+ str(value)+ for value in (label, type_, attrs.get("folder"), attrs.get("notes"))+ if value+ ).casefold()++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."""@@ -150,15 +183,128 @@ def _migrate_2_to_3(conn: sqlite3.Connection) -> None:conn.execute("CREATE UNIQUE INDEX idx_jobs_key ON jobs(kind, job_key) WHERE job_key IS NOT NULL")+def _migrate_3_to_4(conn: sqlite3.Connection) -> None:+ """Add the sidecar-derived media browse index.++ Backfilling needs the case directory as well as the database connection, so+ ``SqliteCase.open`` performs it after the schema transaction and records a+ durable ``media_index_ready`` marker. A crash between the two simply retries+ the backfill on the next open.+ """+ conn.execute("ALTER TABLE entities ADD COLUMN search_text TEXT NOT NULL DEFAULT ''")+ for row in conn.execute("SELECT id, type, label, attrs_json FROM entities"):+ attrs = json.loads(row["attrs_json"])+ conn.execute(+ "UPDATE entities SET search_text = ? WHERE id = ?",+ (_entity_search_text(row["type"], row["label"], attrs), row["id"]),+ )+ conn.execute(+ "CREATE TABLE media_items ("+ " path TEXT PRIMARY KEY, entity_id TEXT UNIQUE, item_json TEXT NOT NULL,"+ " filename TEXT NOT NULL, kind TEXT NOT NULL, folder TEXT,"+ " name_sort TEXT NOT NULL, size INTEGER NOT NULL DEFAULT 0,"+ " added_at TEXT NOT NULL, search_text TEXT NOT NULL,"+ " source_type TEXT, source_op TEXT, imagery_mode TEXT)"+ )+ conn.execute("CREATE INDEX idx_media_kind ON media_items(kind)")+ conn.execute("CREATE INDEX idx_media_folder ON media_items(folder)")+ conn.execute("CREATE INDEX idx_media_name ON media_items(name_sort)")+ conn.execute("CREATE INDEX idx_media_size ON media_items(size)")+ conn.execute("CREATE INDEX idx_media_added ON media_items(added_at)")+ conn.execute("CREATE INDEX idx_media_source ON media_items(source_type)")++# 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,+ 3: _migrate_3_to_4,+}++_MEDIA_CATEGORIES = (+ "image",+ "video",+ "collage",+ "satellite",+ "upload",+ "download",+ "other",+)+_SATELLITE_SQL = (+ "(COALESCE(source_type, '') = 'satellite' OR "+ "(COALESCE(source_type, '') = 'screenshot' AND imagery_mode = 'satellite'))"+)+_MEDIA_CATEGORY_SQL = {+ "image": f"(kind = 'image' AND NOT {_SATELLITE_SQL})",+ "video": "kind = 'video'",+ "collage": "source_op = 'collage'",+ "satellite": _SATELLITE_SQL,+ "upload": "source_type = 'upload'",+ "download": "source_type = 'download'",+ "other": "kind NOT IN ('image', 'video')",}+def _normalise_media_item(item: dict[str, Any]) -> tuple[dict[str, Any], tuple[Any, ...]]:+ """Return a JSON-safe browse item plus its indexed column values."""+ clean = json.loads(json.dumps(item, ensure_ascii=False))+ source = clean.get("source")+ if not isinstance(source, dict):+ source = {}+ clean["source"] = source+ if (+ source.get("type") == "screenshot"+ and "imagery_mode" not in source+ and isinstance(source.get("source_url"), str)+ ):+ parsed = mapsites.parse_map_url(source["source_url"])+ if parsed and parsed.get("imagery_mode"):+ source = {**source, "imagery_mode": parsed["imagery_mode"]}+ clean["source"] = source++ path = str(clean.get("path") or "")+ filename = str(clean.get("filename") or Path(path).name)+ kind = str(clean.get("kind") or "file")+ folder = str(clean.get("folder") or "") or None+ title = str(clean.get("title") or "")+ notes = str(clean.get("notes") or "")+ name_sort = (title or filename).casefold()+ try:+ size = max(0, int(clean.get("size") or 0))+ except (TypeError, ValueError):+ size = 0+ added_at = str(clean.get("added_at") or "")+ search_text = "\n".join(+ str(value)+ for value in (+ filename,+ title,+ notes,+ folder,+ source.get("title"),+ source.get("uploader"),+ source.get("webpage_url") or source.get("url"),+ )+ if value+ ).casefold()+ return clean, (+ path,+ json.dumps(clean, ensure_ascii=False),+ filename,+ kind,+ folder,+ name_sort,+ size,+ added_at,+ search_text,+ source.get("type"),+ source.get("op"),+ source.get("imagery_mode"),+ )++class SqliteCase:"""SQLite implementation of `CaseRepository` over one `case.db` file."""@@ -225,6 +371,7 @@ class SqliteCase:)if version < SQLITE_SCHEMA:store._upgrade()+ store._ensure_media_index()return storedef _upgrade(self) -> None:@@ -256,6 +403,65 @@ class SqliteCase:conn.execute("ROLLBACK")raise+ def _ensure_media_index(self) -> None:+ """Backfill media sidecars once after schema 4 reaches a case.++ The marker is written in the same transaction as the rows, so an+ interrupted scan is retried rather than leaving a partial index active.+ Normal media writes keep the index current after this one-time pass.+ """+ with self._connect() as conn:+ ready = conn.execute(+ "SELECT value FROM meta WHERE key = 'media_index_ready'"+ ).fetchone()+ if ready is not None and ready["value"] == "1":+ return+ entity_by_path: dict[str, str] = {}+ for row in conn.execute("SELECT id, attrs_json FROM entities"):+ attrs = json.loads(row["attrs_json"])+ path = attrs.get("path")+ if isinstance(path, str):+ entity_by_path[path] = row["id"]++ rows: list[tuple[dict[str, Any], str | None]] = []+ media_dir = self.db_path.parent / "media"+ for sidecar in sorted(media_dir.glob("*.azimut.json")):+ media_name = sidecar.name[: -len(".azimut.json")]+ if not (media_dir / media_name).is_file():+ continue+ try:+ item = json.loads(sidecar.read_text(encoding="utf-8"))+ except (OSError, ValueError, TypeError):+ continue+ path = f"media/{media_name}"+ item["path"] = path+ rows.append((item, entity_by_path.get(path)))++ with self._connect() as conn:+ conn.execute("BEGIN IMMEDIATE")+ try:+ # Several download workers can reach the first schema-4 open at+ # once. They may all scan before one acquires the write lock, so+ # re-check the marker inside the transaction. Otherwise a late+ # opener can delete rows registered after an earlier backfill.+ ready = conn.execute(+ "SELECT value FROM meta WHERE key = 'media_index_ready'"+ ).fetchone()+ if ready is not None and ready["value"] == "1":+ conn.execute("COMMIT")+ return+ conn.execute("DELETE FROM media_items")+ for item, entity_id in rows:+ self._upsert_media_conn(conn, item, entity_id=entity_id)+ conn.execute(+ "INSERT INTO meta(key, value) VALUES('media_index_ready', '1')"+ " ON CONFLICT(key) DO UPDATE SET value = excluded.value"+ )+ conn.execute("COMMIT")+ except BaseException:+ conn.execute("ROLLBACK")+ raise+# -- connection / transaction plumbing ---------------------------------@contextmanager@@ -382,6 +588,17 @@ class SqliteCase:).fetchall()return [self._link(r) for r in rows]+ def count_dependents(self, *, link_type: str, from_type: str) -> dict[str, int]:+ with self._connect() as conn:+ rows = conn.execute(+ "SELECT links.to_id AS to_id, COUNT(*) AS n FROM links"+ " JOIN entities ON entities.id = links.from_id"+ " WHERE links.type = ? AND entities.type = ?"+ " GROUP BY links.to_id",+ (link_type, from_type),+ ).fetchall()+ return {r["to_id"]: int(r["n"]) for r in rows}+def page_entities(self,*,@@ -392,6 +609,7 @@ class SqliteCase:query: str | None = None,folder: str | None = None,unfiled: bool = False,+ recursive: bool = False,) -> dict[str, Any]:"""A bounded, cursor-paginated slice of entities in insertion order.@@ -400,14 +618,12 @@ class SqliteCase:scrolled past — new rows land after the current tail. Filters compose inSQL: ``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.+ ``folder`` path (or its descendants when ``recursive`` is true). 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)@@ -417,14 +633,29 @@ class SqliteCase: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))+ if recursive:+ where.append("(folder = ? OR folder LIKE ? ESCAPE '\\')")+ params.extend((folder, _like_prefix(folder + "/")))+ else:+ where.append("folder = ?")+ params.append(folder)+ for term in (query or "").casefold().split():+ where.append("search_text LIKE ? ESCAPE '\\'")+ params.append(_like_contains(term))+ filter_clause = (" WHERE " + " AND ".join(where)) if where else ""+ filter_params = list(params)+ if cursor is not None:+ where.append("rowid > ?")+ params.append(_parse_cursor(cursor))clause = (" WHERE " + " AND ".join(where)) if where else ""params.append(limit + 1)with self._connect() as conn:+ total = int(+ conn.execute(+ f"SELECT COUNT(*) FROM entities{filter_clause}",+ filter_params,+ ).fetchone()[0]+ )rows = conn.execute(f"SELECT rowid AS _rowid, * FROM entities{clause} ORDER BY rowid LIMIT ?",params,@@ -432,7 +663,11 @@ class SqliteCase:has_more = len(rows) > limitrows = 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}+ return {+ "items": [self._entity(r) for r in rows],+ "next_cursor": next_cursor,+ "total": total,+ }def catalog_summary(self) -> dict[str, Any]:"""Total plus per-type, per-status and per-folder counts in grouped scans@@ -485,6 +720,181 @@ class SqliteCase:for r in conn.execute("SELECT path FROM folders ORDER BY path COLLATE NOCASE")]+ # -- media browse index ------------------------------------------------++ @staticmethod+ def _upsert_media_conn(+ conn: sqlite3.Connection,+ item: dict[str, Any],+ *,+ entity_id: str | None = None,+ ) -> None:+ clean, values = _normalise_media_item(item)+ if not clean.get("path"):+ raise CaseError("media item has no path")+ conn.execute(+ "INSERT INTO media_items("+ " path, entity_id, item_json, filename, kind, folder, name_sort,"+ " size, added_at, search_text, source_type, source_op, imagery_mode"+ ") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"+ " ON CONFLICT(path) DO UPDATE SET"+ " entity_id = COALESCE(excluded.entity_id, media_items.entity_id),"+ " item_json = excluded.item_json,"+ " filename = excluded.filename, kind = excluded.kind,"+ " folder = excluded.folder, name_sort = excluded.name_sort,"+ " size = excluded.size, added_at = excluded.added_at,"+ " search_text = excluded.search_text, source_type = excluded.source_type,"+ " source_op = excluded.source_op, imagery_mode = excluded.imagery_mode",+ (values[0], entity_id, *values[1:]),+ )++ def upsert_media_item(+ self, item: dict[str, Any], *, entity_id: str | None = None+ ) -> None:+ def op(conn: sqlite3.Connection) -> None:+ self._upsert_media_conn(conn, item, entity_id=entity_id)++ self._write(op)++ def remove_media_item(self, path: str) -> None:+ def op(conn: sqlite3.Connection) -> None:+ conn.execute("DELETE FROM media_items WHERE path = ?", (path,))++ self._write(op)++ @staticmethod+ def _media_item(row: sqlite3.Row) -> dict[str, Any]:+ return json.loads(row["item_json"])++ def list_media_items(self) -> list[dict[str, Any]]:+ with self._connect() as conn:+ rows = conn.execute(+ "SELECT item_json FROM media_items"+ " ORDER BY added_at DESC, path COLLATE NOCASE"+ ).fetchall()+ return [self._media_item(row) for row in rows]++ def media_items_by_paths(self, paths: list[str]) -> list[dict[str, Any]]:+ unique = list(dict.fromkeys(paths))+ if not unique:+ return []+ if len(unique) > 500:+ raise CaseError("media metadata lookup is limited to 500 paths")+ placeholders = ", ".join("?" for _ in unique)+ with self._connect() as conn:+ rows = conn.execute(+ f"SELECT item_json FROM media_items WHERE path IN ({placeholders})",+ unique,+ ).fetchall()+ by_path = {+ item["path"]: item for item in (self._media_item(row) for row in rows)+ }+ return [by_path[path] for path in unique if path in by_path]++ def page_media_items(+ self,+ *,+ q: str | None = None,+ kind: str | None = None,+ category: str | None = None,+ folder: str | None = None,+ sort: str = "newest",+ direction: str | None = None,+ limit: int = 200,+ offset: int = 0,+ ) -> dict[str, Any]:+ base_where: list[str] = []+ base_params: list[Any] = []+ if kind:+ base_where.append("kind = ?")+ base_params.append(kind)+ if folder is not None:+ if folder:+ base_where.append("folder = ?")+ base_params.append(folder)+ else:+ base_where.append("folder IS NULL")+ for term in (q or "").casefold().split():+ base_where.append("search_text LIKE ? ESCAPE '\\'")+ base_params.append(_like_contains(term))++ selected_where = list(base_where)+ selected_params = list(base_params)+ if category in _MEDIA_CATEGORY_SQL:+ selected_where.append(_MEDIA_CATEGORY_SQL[category])++ def clause(parts: list[str]) -> str:+ return (" WHERE " + " AND ".join(parts)) if parts else ""++ sort_columns = {+ "name": "name_sort",+ "size": "size",+ "type": "kind",+ "folder": "COALESCE(folder, '')",+ "oldest": "added_at",+ "newest": "added_at",+ }+ order_col = sort_columns.get(sort, "added_at")+ descending = direction == "desc" or (+ direction not in {"asc", "desc"} and sort in {"newest", "size"}+ )+ order = "DESC" if descending else "ASC"++ selected_clause = clause(selected_where)+ with self._connect() as conn:+ total = int(+ conn.execute(+ f"SELECT COUNT(*) FROM media_items{selected_clause}",+ selected_params,+ ).fetchone()[0]+ )+ rows = conn.execute(+ f"SELECT item_json FROM media_items{selected_clause}"+ f" ORDER BY {order_col} {order}, path COLLATE NOCASE {order}"+ " LIMIT ? OFFSET ?",+ [*selected_params, limit, offset],+ ).fetchall()+ kind_counts = {+ row["kind"]: int(row["n"])+ for row in conn.execute(+ f"SELECT kind, COUNT(*) AS n FROM media_items{selected_clause}"+ " GROUP BY kind",+ selected_params,+ )+ }+ folder_counts = {+ row["folder"]: int(row["n"])+ for row in conn.execute(+ f"SELECT folder, COUNT(*) AS n FROM media_items{selected_clause}"+ f" {'AND' if selected_clause else 'WHERE'} folder IS NOT NULL"+ " GROUP BY folder",+ selected_params,+ ).fetchall()+ }+ # The category chooser remains useful after one category is+ # selected, so its counts use the text/kind/folder base but exclude+ # the current category.+ category_counts: dict[str, int] = {}+ for key in _MEDIA_CATEGORIES:+ category_counts[key] = int(+ conn.execute(+ f"SELECT COUNT(*) FROM media_items{clause([*base_where, _MEDIA_CATEGORY_SQL[key]])}",+ base_params,+ ).fetchone()[0]+ )++ next_offset = offset + len(rows)+ return {+ "items": [self._media_item(row) for row in rows],+ "next_cursor": str(next_offset) if next_offset < total else None,+ "total": total,+ "facets": {+ "kind_counts": kind_counts,+ "folder_counts": folder_counts,+ "category_counts": category_counts,+ },+ }+def count_entities(self) -> int:"""Entity total via one indexed count — the case switcher's per-casebadge without materialising the graph."""@@ -524,14 +934,16 @@ class SqliteCase: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(?, ?, ?, ?, ?, ?, ?, ?, ?)",+ "(id, type, label, attrs_json, folder, search_text,"+ " prov_by, prov_at, prov_status, prov_source)"+ " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",(entity["id"],type_,label,json.dumps(entity["attrs"], ensure_ascii=False),_folder_of(entity["attrs"]),+ _entity_search_text(type_, label, entity["attrs"]),by,entity["provenance"]["at"],status,@@ -558,12 +970,15 @@ class SqliteCase:entity["provenance"]["status"] = patch["status"]conn.execute("UPDATE entities SET type = ?, label = ?, attrs_json = ?, folder = ?,"- " prov_status = ? WHERE id = ?",+ " search_text = ?, prov_status = ? WHERE id = ?",(entity["type"],entity["label"],json.dumps(entity["attrs"], ensure_ascii=False),_folder_of(entity["attrs"]),+ _entity_search_text(+ entity["type"], entity["label"], entity["attrs"]+ ),entity["provenance"]["status"],entity_id,),@@ -729,14 +1144,21 @@ class SqliteCase: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():+ for row in conn.execute(+ "SELECT id, type, label, 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"]),+ "UPDATE entities SET attrs_json = ?, folder = NULL,"+ " search_text = ? WHERE id = ?",+ (+ json.dumps(attrs, ensure_ascii=False),+ _entity_search_text(row["type"], row["label"], attrs),+ row["id"],+ ),)self._touch(conn)return [@@ -947,9 +1369,8 @@ def convert_json_to_sqlite(data: dict[str, Any], db_path: Path) -> MigrationRepoWrites a `case.db.tmp` beside the target, imports the whole graph in onetransaction, runs `foreign_key_check` / `integrity_check`, then renames itinto 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.+ target untouched. A crash before the manifest change leaves the legacy case+ active; ``Case._activate_sqlite`` flips the manifest only after this returns."""db_path = Path(db_path)tmp = db_path.with_name(db_path.name + ".tmp")@@ -995,14 +1416,20 @@ def _import_graph(conn: sqlite3.Connection, data: dict[str, Any], report: Migratprov = entity.get("provenance", {})conn.execute("INSERT INTO entities"- "(id, type, label, attrs_json, folder, prov_by, prov_at, prov_status, prov_source)"- " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)",+ "(id, type, label, attrs_json, folder, search_text,"+ " 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")),+ _entity_search_text(+ entity.get("type", ""),+ entity.get("label", ""),+ entity.get("attrs"),+ ),prov.get("by", ""),prov.get("at", ""),prov.get("status", "confirmed"),diff --git a/src/azimut/workspace.py b/src/azimut/workspace.pyindex f515691..2dbfa03 100644--- a/src/azimut/workspace.py+++ b/src/azimut/workspace.py@@ -1,16 +1,17 @@-"""Case workspace: create/list/open cases, scratch cases, entities and links.+"""Create, list and open case and scratch workspaces.A case is a plain directory (spec §4):<case>/- ├── case.json # metadata + entities + links+ ├── case.json # case manifest+ ├── case.db # entities, links, folders and jobs├── notes.md # free-form case notes├── media/ # imported/downloaded media + satellite crops + sidecars├── proofs/ # composed proofs (PNG + editable JSON spec)└── exports/ # post drafts, reports-One-shot mode uses a *scratch* case under ``scratch/`` — same layout, same code-path — which can be promoted (moved) into ``cases/`` at any time (spec §3.3).+One-shot mode uses the same layout under ``scratch/`` and can be promoted into+``cases/`` (spec §3.3)."""from __future__ import annotations@@ -35,17 +36,11 @@ if TYPE_CHECKING: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.+# On-disk schema. Older cases migrate on open; newer schemas are refused.+# Bump CASE_SCHEMA with every 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.+# Schema 3 moves the graph from case.json into case.db. JSON_SCHEMA marks the+# last JSON graph schema used by migration.JSON_SCHEMA = 2CASE_SCHEMA = 3@@ -386,7 +381,9 @@ class Case:return removed@classmethod- def list_all(cls) -> list[dict[str, Any]]:+ def list_all(+ cls, *, q: str | None = None, limit: int | None = None+ ) -> list[dict[str, Any]]:out: list[dict[str, Any]] = []for parent, scratch in ((config.cases_dir(), False), (config.scratch_dir(), True)):if not parent.is_dir():@@ -410,6 +407,11 @@ class Case:})out.sort(key=lambda c: c.get("updated_at") or "", reverse=True)+ if q:+ needle = q.strip().lower()+ out = [c for c in out if needle in str(c.get("name", "")).lower()]+ if limit is not None:+ out = out[: max(0, limit)]return out# -- json io -----------------------------------------------------------@@ -439,9 +441,9 @@ class Case:# -- 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.+ # the raw case.json shape. The SQLite backend answers these without+ # materialising the manifest. `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@@ -490,12 +492,13 @@ class Case:query: str | None = None,folder: str | None = None,unfiled: bool = False,+ recursive: bool = False,) -> dict[str, Any]:"""A bounded, filtered page of the catalog (Step 5), paged with an indexedrowid keyset."""return self._graph().page_entities(limit=limit, cursor=cursor, types=types, status=status,- query=query, folder=folder, unfiled=unfiled,+ query=query, folder=folder, unfiled=unfiled, recursive=recursive,)def catalog_summary(self) -> dict[str, Any]:@@ -505,9 +508,49 @@ class Case:def list_links(self) -> list[dict[str, Any]]:return self._graph().list_links()+ def upsert_media_item(+ self, item: dict[str, Any], *, entity_id: str | None = None+ ) -> None:+ self._graph().upsert_media_item(item, entity_id=entity_id)++ def remove_media_item(self, path: str) -> None:+ self._graph().remove_media_item(path)++ def list_media_items(self) -> list[dict[str, Any]]:+ return self._graph().list_media_items()++ def media_items_by_paths(self, paths: list[str]) -> list[dict[str, Any]]:+ return self._graph().media_items_by_paths(paths)++ def page_media_items(+ self,+ *,+ q: str | None = None,+ kind: str | None = None,+ category: str | None = None,+ folder: str | None = None,+ sort: str = "newest",+ direction: str | None = None,+ limit: int = 200,+ offset: int = 0,+ ) -> dict[str, Any]:+ return self._graph().page_media_items(+ q=q,+ kind=kind,+ category=category,+ folder=folder,+ sort=sort,+ direction=direction,+ limit=limit,+ offset=offset,+ )+def links_of(self, entity_id: str) -> list[dict[str, Any]]:return self._graph().links_of(entity_id)+ def count_dependents(self, *, link_type: str, from_type: str) -> dict[str, int]:+ return self._graph().count_dependents(link_type=link_type, from_type=from_type)+def get_entity(self, entity_id: str) -> dict[str, Any] | None:return self._graph().get_entity(entity_id)diff --git a/tests/bigcase.py b/tests/bigcase.pyindex c164abf..0b67f3d 100644--- a/tests/bigcase.py+++ b/tests/bigcase.py@@ -1,14 +1,8 @@-"""Synthetic large-case generator for the storage/performance baseline.+"""Synthetic large-case generator for storage and migration tests.-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.+The fixture builds a repeatable legacy graph for the one-way SQLite importer.+It writes the import source once so large tests stay fast, then callers open it+through the same migration boundary as the application.Standard library only, and it lives under ``tests/`` so hatchling never packagesit into the wheel or the frozen binaries (see the doc's packaging constraints).@@ -39,7 +33,7 @@ _BASE_TIME = datetime(2024, 1, 1, tzinfo=timezone.utc)@dataclassclass BigCaseSummary:- """What was planted, so tests and the bench can assert against it."""+ """What was planted so storage and release tests can assert against it."""case_id: strentities: int = 0@@ -94,10 +88,9 @@ def build_big_case(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.+ # Build the legacy import source in one write. `Case.create` only makes+ # SQLite cases, so this fixture creates the directory directly and callers+ # open it through the one-way migration path.parent = config.cases_dir()parent.mkdir(parents=True, exist_ok=True)path = parent / _slugify(name)diff --git a/tests/conftest.py b/tests/conftest.pyindex e738ac3..321c9f0 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -3,6 +3,21 @@ import tempfileimport pytestfrom fastapi.testclient import TestClient+from azimut.engine import geo++[email protected](autouse=True)+def offline_reverse_geocode(monkeypatch):+ """Nominatim is unreachable unless a test says otherwise.++ Saving a place or a capture now resolves its country as part of the save, so+ without this the suite would fire a live lookup per saved item. Tests that+ care about the located path stub ``geo.reverse_geocode`` themselves; every+ other one gets the offline verdict (``failed``), which is what the app is+ designed to survive.+ """+ monkeypatch.setattr(geo, "reverse_geocode", lambda lat, lon, timeout=8, language=None: None)+@pytest.fixture()def tmp_workspace(monkeypatch):diff --git a/tests/test_bigcase.py b/tests/test_bigcase.pyindex 02f2cc8..e0f049f 100644--- a/tests/test_bigcase.py+++ b/tests/test_bigcase.py@@ -1,8 +1,7 @@-"""The synthetic large-case generator produces a valid, deterministic case.+"""The synthetic large-case fixture is valid and deterministic.-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.+These tests pin the import shape used by the SQLite storage and release suites.+Counts stay small here so the fixture contract remains fast to verify."""from __future__ import annotationsdiff --git a/tests/test_cases_api.py b/tests/test_cases_api.pyindex 43d615d..7374af4 100644--- a/tests/test_cases_api.py+++ b/tests/test_cases_api.py@@ -28,6 +28,22 @@ def test_entity_status_is_validated_consistently(client):assert saved["provenance"]["status"] == "suggested"+def test_list_cases_filters_by_name(client):+ for name in ("Kharkiv Strike", "Bakhmut Front", "Kharkiv Bridge"):+ client.post("/api/cases", json={"name": name})++ hits = client.get("/api/cases", params={"q": "kharkiv"}).json()+ assert {c["name"] for c in hits} == {"Kharkiv Strike", "Kharkiv Bridge"}+ # unfiltered still returns everything+ assert len(client.get("/api/cases").json()) == 3+++def test_list_cases_respects_limit(client):+ for name in ("One", "Two", "Three", "Four"):+ client.post("/api/cases", json={"name": name})+ assert len(client.get("/api/cases", params={"limit": 2}).json()) == 2++def test_case_lifecycle(client):created = client.post("/api/cases", json={"name": "Kharkiv Strike"}).json()assert created["id"] == "kharkiv-strike"@@ -228,6 +244,29 @@ def test_catalog_filters_by_folder(client):assert client.get(f"/api/cases/{cid}/catalog/summary").json()["by_folder"] == {"Alpha": 1}+def test_catalog_searches_notes_and_descendant_folders(client):+ cid = client.post("/api/cases", json={"name": "Search"}).json()["id"]+ client.post(+ f"/api/cases/{cid}/entities",+ json={+ "type": "media",+ "label": "frame",+ "attrs": {"folder": "Sources/Telegram", "notes": "bridge crossing"},+ },+ )+ client.post(+ f"/api/cases/{cid}/entities",+ json={"type": "media", "label": "other", "attrs": {"folder": "Research"}},+ )++ page = client.get(+ f"/api/cases/{cid}/catalog/entities",+ params={"folder": "Sources", "recursive": "true", "q": "bridge"},+ ).json()+ assert page["total"] == 1+ assert [entity["label"] for entity in page["items"]] == ["frame"]++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"})diff --git a/tests/test_drafts_api.py b/tests/test_drafts_api.pyindex 7a86822..46c7329 100644--- a/tests/test_drafts_api.py+++ b/tests/test_drafts_api.py@@ -33,6 +33,7 @@ def test_save_load_roundtrip(client):listed = client.get(f"/api/cases/{cid}/drafts").json()assert len(listed) == 1assert listed[0]["title"] == "Helicopter formation"+ assert listed[0]["target"] == "bluesky"draft = client.get(f"/api/cases/{cid}/drafts/helicopter-formation").json()assert draft["title"] == "Helicopter formation"@@ -49,28 +50,69 @@ def test_draft_filed_as_post_entity_and_updated_on_resave(client):json={"title": "First title", "state": STATE},).json()- # resave under the same name with a new title updates the single entity+ # resaving the same draft updates the single entity rather than filing a new oneclient.post(f"/api/cases/{cid}/drafts",- json={"name": saved["name"], "title": "Renamed draft", "state": STATE},+ json={"rename_from": saved["name"], "title": "First title", "state": STATE},)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"-def test_created_at_preserved_on_resave(client):+def test_draft_rename_moves_the_file_and_keeps_one_entity(client):+ cid = client.post("/api/cases", json={"name": "Drafts"}).json()["id"]+ saved = client.post(+ f"/api/cases/{cid}/drafts", json={"title": "Post 1", "state": STATE}+ ).json()+ before = next(e for e in graph_read.entities(cid) if e["type"] == "post")++ renamed = client.post(+ f"/api/cases/{cid}/drafts",+ json={"rename_from": saved["name"], "title": "Helicopter thread", "state": STATE},+ ).json()+ assert renamed["name"] == "helicopter-thread"+ assert client.get(f"/api/cases/{cid}/drafts/post-1").status_code == 404++ posts = [e for e in graph_read.entities(cid) if e["type"] == "post"]+ assert len(posts) == 1+ assert posts[0]["id"] == before["id"]+ assert posts[0]["label"] == "Helicopter thread"+ assert posts[0]["attrs"]["draft"] == "exports/helicopter-thread.json"+++def test_draft_rename_onto_a_taken_name_is_refused(client):+ cid = client.post("/api/cases", json={"name": "Drafts"}).json()["id"]+ client.post(f"/api/cases/{cid}/drafts", json={"title": "Post 1", "state": STATE})+ client.post(f"/api/cases/{cid}/drafts", json={"title": "Post 2", "state": STATE})++ res = client.post(+ f"/api/cases/{cid}/drafts",+ json={"rename_from": "post-2", "title": "Post 1", "state": STATE},+ )+ assert res.status_code == 409+ listed = client.get(f"/api/cases/{cid}/drafts").json()+ assert sorted(d["name"] for d in listed) == ["post-1", "post-2"]+++def test_created_at_preserved_on_resave_and_rename(client):cid = client.post("/api/cases", json={"name": "Drafts"}).json()["id"]client.post(f"/api/cases/{cid}/drafts", json={"title": "Keep created", "state": STATE})first = client.get(f"/api/cases/{cid}/drafts/keep-created").json()client.post(f"/api/cases/{cid}/drafts",- json={"name": "keep-created", "title": "Keep created", "state": STATE},+ json={"rename_from": "keep-created", "title": "Keep created", "state": STATE},)second = client.get(f"/api/cases/{cid}/drafts/keep-created").json()assert first["created_at"] == second["created_at"]+ client.post(+ f"/api/cases/{cid}/drafts",+ json={"rename_from": "keep-created", "title": "Moved along", "state": STATE},+ )+ third = client.get(f"/api/cases/{cid}/drafts/moved-along").json()+ assert third["created_at"] == first["created_at"]+def test_delete_removes_file_and_entity(client):cid = client.post("/api/cases", json={"name": "Drafts"}).json()["id"]diff --git a/tests/test_files_api.py b/tests/test_files_api.pynew file mode 100644index 0000000..dc035ba--- /dev/null+++ b/tests/test_files_api.py@@ -0,0 +1,66 @@+"""Serving case files: revalidation and cache policy.++The pickers (proof panels, media grid, Files) re-render the same images every+time a dialog opens. Without these headers the browser refetches every byte on+each open, which is what made those dialogs feel slow.+"""++import io++from PIL import Image+++def _png_bytes(color=(200, 30, 30), size=(64, 48)) -> bytes:+ buf = io.BytesIO()+ Image.new("RGB", size, color).save(buf, "PNG")+ return buf.getvalue()+++def _upload(client, cid, name="shot.png"):+ return client.post(+ f"/api/cases/{cid}/media/upload",+ files={"file": (name, io.BytesIO(_png_bytes()), "image/png")},+ ).json()["item"]+++def test_unchanged_file_revalidates_to_304(client):+ cid = client.post("/api/cases", json={"name": "Files"}).json()["id"]+ item = _upload(client, cid)++ first = client.get(f"/files/{cid}/{item['path']}")+ assert first.status_code == 200+ etag = first.headers["etag"]++ again = client.get(f"/files/{cid}/{item['path']}", headers={"If-None-Match": etag})+ assert again.status_code == 304+ assert again.content == b""+ assert again.headers["etag"] == etag+++def test_thumbnails_are_cached_forever_and_other_files_revalidate(client):+ cid = client.post("/api/cases", json={"name": "Files"}).json()["id"]+ item = _upload(client, cid)++ # thumbnail names carry the content hash and a generation, so a given URL+ # can never change meaning: the browser may keep it without asking again.+ thumb = client.get(f"/files/{cid}/{item['thumbnail']}")+ assert "immutable" in thumb.headers["cache-control"]++ # the original can be re-imported or edited in place under the same name+ original = client.get(f"/files/{cid}/{item['path']}")+ assert original.headers["cache-control"] == "no-cache"+++def test_edited_file_is_served_fresh(client):+ cid = client.post("/api/cases", json={"name": "Files"}).json()["id"]+ item = _upload(client, cid)+ stale = client.get(f"/files/{cid}/{item['path']}").headers["etag"]++ from azimut.api.cases import get_case++ target = get_case(cid).resolve_inside(item["path"])+ target.write_bytes(_png_bytes(color=(10, 10, 200), size=(80, 80)))++ res = client.get(f"/files/{cid}/{item['path']}", headers={"If-None-Match": stale})+ assert res.status_code == 200+ assert res.headers["etag"] != stalediff --git a/tests/test_geo_api.py b/tests/test_geo_api.pyindex 8c5aa5b..00c0985 100644--- a/tests/test_geo_api.py+++ b/tests/test_geo_api.py@@ -4,6 +4,11 @@ import pytestfrom azimut.engine import geo+# The suite's autouse fixture replaces geo.reverse_geocode with an offline stub,+# so the two tests below — the ones that care about what goes out on the wire —+# hold on to the real function, captured at import time.+_REAL_REVERSE = geo.reverse_geocode+class _FakeResponse:def __init__(self, payload):@@ -45,6 +50,37 @@ def test_geocode_returns_top_match(client, monkeypatch):assert calls["headers"]["User-Agent"]+def test_geocode_answers_in_english(client, monkeypatch):+ # the query goes out in whatever language it was typed; only the answer is+ # pinned, so "Москва" comes back as a name the analyst can read+ fake, calls = _fake_get([{"lat": "55.75", "lon": "37.61", "display_name": "Moscow, Russia"}])+ monkeypatch.setattr(geo.httpx, "get", fake)++ result = client.get("/api/geo/geocode", params={"q": "Москва"}).json()+ assert calls["params"]["q"] == "Москва"+ assert calls["params"]["accept-language"] == "en"+ assert result["display_name"] == "Moscow, Russia"+++def test_reverse_stays_in_the_local_language(monkeypatch):+ # the Post and Proof composers read this endpoint and name a place the way+ # it is named where it is — asking for English here would change their copy+ fake, calls = _fake_get({"display_name": "Москва, Россия", "address": {"country": "Россия"}})+ monkeypatch.setattr(geo.httpx, "get", fake)++ result = _REAL_REVERSE(55.75, 37.61)+ assert "accept-language" not in calls["params"]+ assert result["display_name"] == "Москва, Россия"+++def test_reverse_asks_for_a_language_only_when_told_to(monkeypatch):+ fake, calls = _fake_get({"display_name": "Moscow, Russia", "address": {}})+ monkeypatch.setattr(geo.httpx, "get", fake)++ _REAL_REVERSE(55.75, 37.61, language="en")+ assert calls["params"]["accept-language"] == "en"++def test_geocode_no_match_is_404(client, monkeypatch):fake, _ = _fake_get([])monkeypatch.setattr(geo.httpx, "get", fake)diff --git a/tests/test_geo_locate.py b/tests/test_geo_locate.pynew file mode 100644index 0000000..9230355--- /dev/null+++ b/tests/test_geo_locate.py@@ -0,0 +1,233 @@+"""Country/region lookup behind the Saved tree: continents and country names+(offline tables) and ``geo.locate_point`` (Nominatim behind a stub, never the+network)."""++from azimut.engine import continents, countries, geo+++def _address(payload):+ """Stub reverse_geocode with one Nominatim address, whatever language it+ is asked for."""+ return lambda lat, lon, timeout=8, language=None: {+ "display_name": "x", "address": payload, "attribution": "x",+ }+++def _by_language(native, english):+ """Stub reverse_geocode answering with a different address per language."""++ def fake(lat, lon, timeout=8, language=None):+ return {+ "display_name": "x",+ "address": english if language == "en" else native,+ "attribution": "x",+ }++ return fake+++# -- continents: pure data, no network -------------------------------------------+++def test_continent_for_maps_known_codes():+ assert continents.continent_for("ua") == "Europe"+ assert continents.continent_for("UA") == "Europe"+ assert continents.continent_for("cd") == "Africa"+ assert continents.continent_for("kh") == "Asia"+ assert continents.continent_for("br") == "South America"+ assert continents.continent_for("mx") == "North America"+ assert continents.continent_for("fj") == "Oceania"+ assert continents.continent_for("aq") == "Antarctica"+++def test_continent_for_is_none_for_unknown_or_missing():+ assert continents.continent_for("zz") is None+ assert continents.continent_for("") is None+ assert continents.continent_for(None) is None+++def test_every_continent_name_is_one_of_the_seven():+ assert set(continents.CONTINENTS.values()) == {+ "Africa", "Antarctica", "Asia", "Europe",+ "North America", "Oceania", "South America",+ }+++def test_a_country_without_coordinates_falls_back_to_its_table_verdict():+ assert continents.continent_for("ru") == "Europe"+ assert continents.continent_for("tr") == "Asia"+ assert continents.continent_for("kz") == "Asia"+ assert continents.continent_for("ru", 55.0, None) == "Europe"+++def test_the_caucasus_keeps_its_single_verdict_wherever_the_point_is():+ # Georgia, Armenia and Azerbaijan are Asia whole; coordinates change nothing+ assert continents.continent_for("ge", 42.3, 43.4) == "Asia"+ assert continents.continent_for("az", 41.7, 48.5) == "Asia"+++def test_russia_splits_on_the_urals():+ assert continents.continent_for("ru", 55.75, 37.62) == "Europe" # Moscow+ assert continents.continent_for("ru", 58.01, 56.25) == "Europe" # Perm+ assert continents.continent_for("ru", 67.50, 64.00) == "Europe" # Vorkuta+ assert continents.continent_for("ru", 56.84, 60.60) == "Asia" # Yekaterinburg+ assert continents.continent_for("ru", 66.53, 66.60) == "Asia" # Salekhard+ assert continents.continent_for("ru", 43.12, 131.89) == "Asia" # Vladivostok+++def test_russia_places_chukotka_past_the_antimeridian_in_asia():+ assert continents.continent_for("ru", 66.16, -179.50) == "Asia"+++def test_kazakhstan_splits_on_the_ural_river():+ assert continents.continent_for("kz", 51.23, 51.37) == "Europe" # Oral+ assert continents.continent_for("kz", 43.24, 76.89) == "Asia" # Almaty+++def test_turkey_splits_on_the_straits():+ assert continents.continent_for("tr", 41.04, 28.99) == "Europe" # Beşiktaş+ assert continents.continent_for("tr", 40.41, 26.40) == "Europe" # Gallipoli+ assert continents.continent_for("tr", 40.99, 29.03) == "Asia" # Kadıköy+ assert continents.continent_for("tr", 38.42, 27.14) == "Asia" # İzmir+ assert continents.continent_for("tr", 39.93, 32.86) == "Asia" # Ankara+++# -- English country names: pure data, no network --------------------------------+++def test_country_name_for_maps_known_codes():+ assert countries.name_for("ru") == "Russia"+ assert countries.name_for("RU") == "Russia"+ assert countries.name_for(" de ") == "Germany"+ assert countries.name_for("cn") == "China"+++def test_country_name_for_is_none_for_unknown_or_missing():+ assert countries.name_for("zz") is None+ assert countries.name_for("") is None+ assert countries.name_for(None) is None+++def test_every_code_the_tree_can_place_has_an_english_name():+ # the tree groups on the continent table, so a code there with no name+ # would render a country branch in one language only+ missing = sorted(set(continents.CONTINENTS) - set(countries.COUNTRY_NAMES_EN))+ assert missing == []+++# -- locate_point ------------------------------------------------------------------+++def test_locate_point_reports_country_and_region(monkeypatch):+ monkeypatch.setattr(+ geo, "reverse_geocode",+ _address({"country_code": "UA", "country": "Ukraine", "state": "Donetsk Oblast"}),+ )++ assert geo.locate_point(48.0159, 37.8029) == {+ "state": "ok",+ "country_code": "ua", # lowercased, whatever Nominatim sent+ "country": "Ukraine",+ "region": "Donetsk Oblast",+ }+++def test_locate_point_without_a_region_is_still_ok(monkeypatch):+ monkeypatch.setattr(geo, "reverse_geocode", _address({"country_code": "mc", "country": "Monaco"}))++ assert geo.locate_point(43.73, 7.42) == {+ "state": "ok", "country_code": "mc", "country": "Monaco",+ }+++def test_region_falls_back_through_the_admin_spellings(monkeypatch):+ for key, name in (("state", "A"), ("region", "B"), ("province", "C"), ("county", "D")):+ monkeypatch.setattr(+ geo, "reverse_geocode", _address({"country_code": "fr", "country": "France", key: name})+ )+ assert geo.locate_point(48.8, 2.3)["region"] == name+++def test_region_prefers_state_over_the_later_spellings(monkeypatch):+ monkeypatch.setattr(+ geo, "reverse_geocode",+ _address({"country_code": "fr", "country": "France", "county": "Paris", "state": "Ile-de-France"}),+ )+ assert geo.locate_point(48.8, 2.3)["region"] == "Ile-de-France"+++def test_a_point_in_no_country_is_nocountry(monkeypatch):+ # open sea: Nominatim answers, the answer just has no country in it+ monkeypatch.setattr(geo, "reverse_geocode", _address({}))+ assert geo.locate_point(0.0, -30.0) == {"state": "nocountry"}+++def test_a_lookup_that_does_not_answer_is_failed(monkeypatch):+ monkeypatch.setattr(geo, "reverse_geocode", lambda lat, lon, timeout=8: None)+ assert geo.locate_point(48.8, 2.3) == {"state": "failed"}+++def test_region_en_is_filed_beside_the_native_region(monkeypatch):+ monkeypatch.setattr(+ geo, "reverse_geocode",+ _by_language(+ {"country_code": "ru", "country": "Россия", "state": "Московская область"},+ {"country_code": "ru", "country": "Russia", "state": "Moscow Oblast"},+ ),+ )++ assert geo.locate_point(55.7, 37.6) == {+ "state": "ok",+ "country_code": "ru",+ "country": "Россия", # the native answer stays the authority+ "region": "Московская область",+ "region_en": "Moscow Oblast",+ }+++def test_region_en_is_dropped_when_it_matches_the_native_region(monkeypatch):+ monkeypatch.setattr(+ geo, "reverse_geocode",+ _address({"country_code": "fr", "country": "France", "state": "Normandie"}),+ )+ assert "region_en" not in geo.locate_point(49.1, 0.1)+++def test_a_failed_english_lookup_still_files_the_native_verdict(monkeypatch):+ def fake(lat, lon, timeout=8, language=None):+ if language == "en":+ raise OSError("network down")+ return {"display_name": "x", "attribution": "x", "address": {+ "country_code": "ua", "country": "Україна", "state": "Донецька область",+ }}++ monkeypatch.setattr(geo, "reverse_geocode", fake)++ assert geo.locate_point(48.0, 37.8) == {+ "state": "ok",+ "country_code": "ua",+ "country": "Україна",+ "region": "Донецька область",+ }+++def test_no_english_lookup_when_there_is_no_region(monkeypatch):+ # a second request buys nothing here: the country name is offline data+ asked = []++ def fake(lat, lon, timeout=8, language=None):+ asked.append(language)+ return {"display_name": "x", "attribution": "x",+ "address": {"country_code": "mc", "country": "Monaco"}}++ monkeypatch.setattr(geo, "reverse_geocode", fake)+ geo.locate_point(43.73, 7.42)+ assert asked == [None]+++def test_locate_point_never_raises(monkeypatch):+ def boom(lat, lon, timeout=8):+ raise OSError("network down")++ monkeypatch.setattr(geo, "reverse_geocode", boom)+ assert geo.locate_point(48.8, 2.3) == {"state": "failed"}diff --git a/tests/test_hardening.py b/tests/test_hardening.pyindex 56d5196..293d2b6 100644--- a/tests/test_hardening.py+++ b/tests/test_hardening.py@@ -3,6 +3,7 @@import osimport statimport sys+import warningsimport pytestfrom PIL import Image@@ -11,9 +12,20 @@ from azimut import configdef test_decompression_bomb_guard_is_set():- import azimut # noqa: F401 (importing the package installs the clamp)+ import importlib++ import azimut++ # Pytest resets warning filters after package import. Reloading reproduces+ # normal process startup and proves the package installs its policy.+ importlib.reload(azimut)assert Image.MAX_IMAGE_PIXELS == 100_000_000+ assert any(+ action == "error"+ and category is Image.DecompressionBombWarning+ for action, _message, category, _module, _line in warnings.filters+ )@pytest.mark.skipif(sys.platform == "win32", reason="POSIX file modes")diff --git a/tests/test_ingest_api.py b/tests/test_ingest_api.pyindex acc5d06..bc8c6ec 100644--- a/tests/test_ingest_api.py+++ b/tests/test_ingest_api.py@@ -8,6 +8,8 @@ of those walls."""import io+import struct+import zlibimport graph_read@@ -22,6 +24,16 @@ def _png_bytes(w=320, h=200, color=(30, 90, 30)):return buf.getvalue()+def _png_header(w: int, h: int) -> bytes:+ """A complete PNG header whose dimensions Pillow reads before pixel data."""+ def chunk(kind: bytes, data: bytes) -> bytes:+ payload = kind + data+ return struct.pack(">I", len(data)) + payload + struct.pack(">I", zlib.crc32(payload))++ ihdr = struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)+ return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IEND", b"")++def _token(client):# minting is an explicit user action (POST), never a side effect of opening# Settings — see mint_ingest_token in api/settings.py@@ -81,6 +93,7 @@ def test_screenshot_files_as_a_capture_with_provenance(client):assert body["method"] == "screenshot"assert body["framed"] is False # URL-derived view coords, not a crop frameassert body["site"] == "google-maps"+ assert body["imagery_mode"] is Noneassert body["source_url"].startswith("https://www.google.com/maps/")assert body["attribution"] == "Map data © Google"assert body["attribution_burned"] is True@@ -93,6 +106,34 @@ def test_screenshot_files_as_a_capture_with_provenance(client):assert listed[0]["method"] == "screenshot"+def test_screenshot_over_100_mp_is_rejected_before_decode(client):+ token = _token(client)+ response = _post(client, token=token, image=_png_header(10_001, 10_000))++ assert response.status_code == 413+ assert response.json()["detail"] == "image exceeds the 100 MP limit"+++def test_satellite_extension_url_is_marked_for_media_library(client):+ token = _token(client)+ cid = client.post("/api/cases", json={"name": "Satellite ingest"}).json()["id"]+ body = _post(+ client,+ token=token,+ case_id=cid,+ url="https://www.google.com/maps/@48.8584,2.2945,2000m/data=!3m1!1e3",+ lat=None,+ lon=None,+ zoom=None,+ ).json()++ assert body["imagery_mode"] == "satellite"+ item = client.get(f"/api/cases/{cid}/media").json()[0]+ assert item["kind"] == "image"+ assert item["source"]["type"] == "screenshot"+ assert item["source"]["imagery_mode"] == "satellite"++def test_coords_are_optional_but_only_as_a_pair(client):token = _token(client)cid = client.post("/api/cases", json={"name": "NoCoords"}).json()["id"]@@ -262,6 +303,93 @@ def test_bookmark_empty_case_files_into_a_scratch_session(client):assert match and match[0]["scratch"] is True+def _place(client, token=None, **overrides):+ data = {"url": "https://www.google.com/maps/@48.8584,2.2945,17z"}+ data.update(overrides)+ data = {k: v for k, v in data.items() if v is not None}+ headers = {"X-Azimut-Token": token} if token else {}+ return client.post("/api/ingest/place", data=data, headers=headers)+++def test_place_needs_the_token(client):+ _token(client)+ assert _place(client).status_code == 401+ assert _place(client, token="wrong").status_code == 401+++def test_place_files_a_point_from_the_url_alone(client):+ """Same thin-extension contract as a screenshot: the URL carries the+ coordinates, the title and the site — the popup may send nothing else."""+ token = _token(client)+ cid = client.post("/api/cases", json={"name": "Points"}).json()["id"]+ r = _place(+ client, token=token, case_id=cid,+ url="https://www.google.com/maps/place/Tour+Eiffel/@48.8583701,2.2944813,17z/data=!3m1",+ )+ assert r.status_code == 200+ body = r.json()+ assert body["case_id"] == cid and body["title"] == "Tour Eiffel"+ places = [e for e in graph_read.entities(cid) if e["type"] == "place"]+ assert len(places) == 1+ attrs = places[0]["attrs"]+ assert (attrs["lat"], attrs["lon"], attrs["zoom"]) == (48.8583701, 2.2944813, 17)+ assert attrs["plus_code"] and attrs["coords"]+ # provenance the app's own place saves have no source for+ assert attrs["source_url"].startswith("https://www.google.com/maps/place/")+ assert attrs["site"] == "google-maps"+ # a place is a point: nothing was downloaded+ assert client.get(f"/api/cases/{cid}/media").json() == []+++def test_place_popup_values_win_over_the_url(client):+ token = _token(client)+ cid = client.post("/api/cases", json={"name": "Corrections"}).json()["id"]+ _place(client, token=token, case_id=cid, lat="48.9", lon="2.4",+ zoom="12", bearing="90", title="Corrected spot")+ place = [e for e in graph_read.entities(cid) if e["type"] == "place"][0]+ assert place["label"] == "Corrected spot"+ assert (place["attrs"]["lat"], place["attrs"]["lon"]) == (48.9, 2.4)+ assert (place["attrs"]["zoom"], place["attrs"]["bearing"]) == (12, 90)+++def test_place_needs_coordinates_and_a_map_url(client):+ token = _token(client)+ # a map URL with no position: there is no point to save (bookmark is that flow)+ assert _place(client, token=token,+ url="https://www.google.com/maps").status_code == 422+ # half a coordinate is never a point+ assert _place(client, token=token, url="https://www.google.com/maps",+ lat="48.9").status_code == 422+ # not a map at all+ assert _place(client, token=token,+ url="https://twitter.com/somebody/status/1").status_code == 422+++def test_place_empty_case_files_into_a_scratch_session(client):+ token = _token(client)+ body = _place(client, token=token).json()+ cases = client.get("/api/cases").json()+ match = [c for c in cases if c["id"] == body["case_id"]]+ assert match and match[0]["scratch"] is True+++def test_place_shows_up_in_the_saved_index_and_nudges_open_tabs(client, monkeypatch):+ from azimut.api import ingest as ingest_api++ seen = []+ monkeypatch.setattr(ingest_api.events, "publish", seen.append)+ token = _token(client)+ cid = client.post("/api/cases", json={"name": "Saved"}).json()["id"]+ body = _place(client, token=token, case_id=cid, title="Watchpoint").json()+ assert [e for e in seen if e["type"] == "place"] == [+ {"type": "place", "case_id": cid, "entity_id": body["entity_id"],+ "title": "Watchpoint", "site": "google-maps"}+ ]+ # the Saved panel reads this one index and nothing else+ index = client.get(f"/api/cases/{cid}/satellite/index").json()+ assert [(row["kind"], row["title"]) for row in index] == [("place", "Watchpoint")]++def test_extension_zip_serves_the_packaged_runtime_files(client):import zipfile as zfdiff --git a/tests/test_inspect_api.py b/tests/test_inspect_api.pyindex 4577da3..7d5690d 100644--- a/tests/test_inspect_api.py+++ b/tests/test_inspect_api.py@@ -831,9 +831,10 @@ def test_session_delete_via_sidebar_entity_removes_spec(client):assert client.get(f"/api/cases/{cid}/inspect/sessions/doomed").status_code == 404-def test_session_resave_by_name_overwrites_after_rename(client):- # Reopening a session then saving it re-uses its slug (name), so a title- # change updates the same session in place instead of forking a new one.+def test_session_rename_moves_the_spec_and_keeps_one_entity(client):+ # The name shown in the Inspect header is the filename. Renaming a saved+ # session moves its spec instead of leaving a copy behind, and the entity is+ # rebound rather than duplicated, so its folder and links survive.cid = client.post("/api/cases", json={"name": "Rename"}).json()["id"]item = _upload(client, cid, "clip.png")spec = {"source": {"path": item["path"], "kind": "image"}, "frames": [], "collage": {"nodes": []}}@@ -842,16 +843,61 @@ def test_session_resave_by_name_overwrites_after_rename(client):f"/api/cases/{cid}/inspect/sessions", json={"title": "Original", "spec": spec}).json()assert first["name"] == "original"+ before = next(e for e in graph_read.entities(cid) if e["type"] == "inspect-session")+ client.patch(f"/api/cases/{cid}/entities/{before['id']}", json={"attrs": {"folder": "Angles"}})++ renamed = client.post(+ f"/api/cases/{cid}/inspect/sessions",+ json={"rename_from": first["name"], "title": "Rooftop angle", "spec": spec},+ ).json()+ assert renamed["name"] == "rooftop-angle"++ listing = client.get(f"/api/cases/{cid}/inspect/sessions").json()+ assert len(listing) == 1+ assert listing[0]["name"] == "rooftop-angle" and listing[0]["title"] == "Rooftop angle"+ assert client.get(f"/api/cases/{cid}/inspect/sessions/original").status_code == 404++ after = [e for e in graph_read.entities(cid) if e["type"] == "inspect-session"]+ assert len(after) == 1+ assert after[0]["id"] == before["id"] # same entity, so its filing survives+ assert after[0]["attrs"]["spec"] == "inspect/rooftop-angle.json"+ assert after[0]["attrs"]["folder"] == "Angles"+++def test_session_rename_keeps_the_creation_date(client):+ cid = client.post("/api/cases", json={"name": "Born"}).json()["id"]+ item = _upload(client, cid, "clip.png")+ spec = {"source": {"path": item["path"], "kind": "image"}, "frames": [], "collage": {"nodes": []}}++ client.post(f"/api/cases/{cid}/inspect/sessions", json={"title": "Original", "spec": spec})+ born = client.get(f"/api/cases/{cid}/inspect/sessions/original").json()["created_at"]client.post(f"/api/cases/{cid}/inspect/sessions",- json={"name": first["name"], "title": "Renamed", "spec": spec},+ json={"rename_from": "original", "title": "Renamed", "spec": spec},)+ assert client.get(f"/api/cases/{cid}/inspect/sessions/renamed").json()["created_at"] == born+++def test_session_rename_onto_a_taken_name_is_refused(client):+ # Two sessions under one file would leave two entities pointing at it, and+ # there is no sane merge — the save is refused and both survive untouched.+ cid = client.post("/api/cases", json={"name": "Clash"}).json()["id"]+ item = _upload(client, cid, "clip.png")+ spec = {"source": {"path": item["path"], "kind": "image"}, "frames": [], "collage": {"nodes": []}}++ client.post(f"/api/cases/{cid}/inspect/sessions", json={"title": "Inspect 1", "spec": spec})+ client.post(f"/api/cases/{cid}/inspect/sessions", json={"title": "Inspect 2", "spec": spec})++ res = client.post(+ f"/api/cases/{cid}/inspect/sessions",+ json={"rename_from": "inspect-2", "title": "Inspect 1", "spec": spec},+ )+ assert res.status_code == 409+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 = graph_read.entities(cid)- assert sum(1 for e in entities if e["type"] == "inspect-session") == 1+ assert sorted(s["name"] for s in listing) == ["inspect-1", "inspect-2"]+ assert sum(1 for e in graph_read.entities(cid) if e["type"] == "inspect-session") == 2@pytest.mark.skipif(not media_engine.ffmpeg_available(), reason="ffmpeg not installed")@@ -919,3 +965,143 @@ def test_frame_capture_from_video(client, tmp_path):time.sleep(0.1)assert job["status"] == "done"assert len(job["result"]["frames"]) >= 1+++def test_saved_frame_filename_follows_the_typed_name(client):+ cid = client.post("/api/cases", json={"name": "Naming"}).json()["id"]+ item = _upload(client, cid, "dsc_00421.png")++ res = client.post(+ f"/api/cases/{cid}/inspect/save-frames",+ json={+ "items": [+ {"path": item["path"], "ops": [{"op": "brightness", "params": {"amount": 1.4}}],+ "label": "Hangar roof"}+ ],+ "notes": "Roof line matches the satellite view",+ },+ ).json()["saved"][0]++ name = res["item"]["path"].rsplit("/", 1)[-1]+ assert name.startswith("Hangar_roof_") and name.endswith(".png")+ assert "dsc_00421" not in name++ media = next(+ m for m in client.get(f"/api/cases/{cid}/media").json()+ if m["path"] == res["item"]["path"]+ )+ assert media["title"] == "Hangar roof"+ assert media["notes"] == "Roof line matches the satellite view"+++def test_saved_frame_name_is_scrubbed_for_the_filesystem(client):+ cid = client.post("/api/cases", json={"name": "Scrub"}).json()["id"]+ item = _upload(client, cid, "orig.png")++ res = client.post(+ f"/api/cases/{cid}/inspect/save-frames",+ json={+ "items": [+ {"path": item["path"], "ops": [{"op": "contrast", "params": {"amount": 1.3}}],+ "label": 'a/b:c*d?"e'}+ ]+ },+ ).json()["saved"][0]++ name = res["item"]["path"].rsplit("/", 1)[-1]+ assert not set(name) & set('/:*?"<>|\\')+ # the title keeps what was typed; only the file on disk is scrubbed+ media = next(+ m for m in client.get(f"/api/cases/{cid}/media").json()+ if m["path"] == res["item"]["path"]+ )+ assert media["title"] == 'a/b:c*d?"e'+++def test_unnamed_frame_keeps_the_source_stem_and_tag(client):+ cid = client.post("/api/cases", json={"name": "Unnamed"}).json()["id"]+ item = _upload(client, cid, "orig.png")++ res = client.post(+ f"/api/cases/{cid}/inspect/save-frames",+ json={+ "items": [+ {"path": item["path"], "ops": [{"op": "brightness", "params": {"amount": 1.6}}]}+ ]+ },+ ).json()["saved"][0]++ name = res["item"]["path"].rsplit("/", 1)[-1]+ assert name.startswith("orig_edit_")+++def test_composed_collage_filename_follows_the_typed_name(client):+ cid = client.post("/api/cases", json={"name": "ComposeName"}).json()["id"]+ a = _upload(client, cid, "a.png", _png_bytes(color=(10, 20, 30)))+ b = _upload(client, cid, "b.png", _png_bytes(color=(200, 100, 50)))++ res = client.post(+ f"/api/cases/{cid}/inspect/compose",+ json={+ "width": 400, "height": 300,+ "nodes": [+ {"src": {"path": a["path"]}, "quad": [[0, 0], [200, 10], [190, 300], [0, 290]]},+ {"src": {"path": b["path"]}, "quad": [[200, 10], [400, 0], [400, 300], [190, 300]]},+ ],+ "label": "Yard panorama",+ "notes": "Two angles of the same yard",+ },+ ).json()++ assert res["item"]["path"].rsplit("/", 1)[-1].startswith("Yard_panorama_")+ media = next(+ m for m in client.get(f"/api/cases/{cid}/media").json()+ if m["path"] == res["item"]["path"]+ )+ assert media["title"] == "Yard panorama"+ assert media["notes"] == "Two angles of the same yard"+++def test_duplicate_save_renames_the_media_it_landed_on(client):+ """Re-saving an unchanged collage hits the same pixels, so it hits the same+ entity. The name typed at the gate has to reach it anyway — that silent drop+ is what made a collage look like it ignored its name."""+ cid = client.post("/api/cases", json={"name": "Dupe"}).json()["id"]+ a = _upload(client, cid, "a.png", _png_bytes(color=(10, 20, 30)))+ b = _upload(client, cid, "b.png", _png_bytes(color=(200, 100, 50)))+ body = {+ "width": 400, "height": 300,+ "nodes": [+ {"src": {"path": a["path"]}, "quad": [[0, 0], [200, 10], [190, 300], [0, 290]]},+ {"src": {"path": b["path"]}, "quad": [[200, 10], [400, 0], [400, 300], [190, 300]]},+ ],+ "label": "First name",+ }+ first = client.post(f"/api/cases/{cid}/inspect/compose", json=body).json()+ assert first["duplicate"] is False++ body["label"] = "Second name"+ again = client.post(f"/api/cases/{cid}/inspect/compose", json=body).json()+ assert again["duplicate"] is True+ assert again["item"]["path"] == first["item"]["path"]++ media = next(+ m for m in client.get(f"/api/cases/{cid}/media").json()+ if m["path"] == first["item"]["path"]+ )+ assert media["title"] == "Second name"+++def test_duplicate_save_files_no_second_copy(client):+ cid = client.post("/api/cases", json={"name": "DupeCount"}).json()["id"]+ item = _upload(client, cid, "orig.png")+ body = {+ "items": [+ {"path": item["path"], "ops": [{"op": "brightness", "params": {"amount": 1.4}}],+ "label": "Roof"}+ ]+ }+ client.post(f"/api/cases/{cid}/inspect/save-frames", json=body)+ after_first = len(client.get(f"/api/cases/{cid}/media").json())+ client.post(f"/api/cases/{cid}/inspect/save-frames", json=body)+ assert len(client.get(f"/api/cases/{cid}/media").json()) == after_firstdiff --git a/tests/test_links_api.py b/tests/test_links_api.pyindex e950750..d93c0a7 100644--- a/tests/test_links_api.py+++ b/tests/test_links_api.py@@ -55,18 +55,16 @@ def _new_case(client, name):return client.post("/api/cases", json={"name": name}).json()["id"]-def _save_proof(client, cid, title, srcs, name=None):+# The filename follows the title everywhere (api/naming.slugify), so these pass+# short titles and read the slug straight off them.+def _save_proof(client, cid, title, srcs):spec = {"panels": [{"id": f"p{i}", "src": s} for i, s in enumerate(srcs)]}body = {"title": title, "spec": spec, "png_base64": _png_b64()}- if name:- body["name"] = namereturn client.post(f"/api/cases/{cid}/proofs", json=body).json()-def _save_session(client, cid, title, source_path, name=None):+def _save_session(client, cid, title, source_path):body = {"title": title, "spec": {"source": {"path": source_path, "kind": "image"}}}- if name:- body["name"] = namereturn client.post(f"/api/cases/{cid}/inspect/sessions", json=body).json()@@ -103,11 +101,11 @@ def test_resaving_a_proof_reconciles_rather_than_stacks(client):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")- _save_proof(client, cid, "P", [a, b], name="p") # same panels, saved twice+ _save_proof(client, cid, "P", [a, b])+ _save_proof(client, cid, "P", [a, b]) # same panels, saved twiceassert len(_links(client, cid, "derived-from")) == 2- _save_proof(client, cid, "P", [a], name="p") # panel b dropped from the proof+ _save_proof(client, cid, "P", [a]) # panel b dropped from the prooflinks = _links(client, cid, "derived-from")assert len(links) == 1assert links[0]["to"] == _entity(client, cid, path=a)["id"]@@ -118,16 +116,16 @@ def test_resaving_keeps_the_untouched_edge_identical(client):# its timestamp, so case.json stays a readable diff.cid = _new_case(client, "Stable")a = _upload(client, cid, "a.png")["item"]["path"]- _save_proof(client, cid, "P", [a], name="p")+ _save_proof(client, cid, "P", [a])before = _links(client, cid, "derived-from")[0]- _save_proof(client, cid, "P", [a], name="p")+ _save_proof(client, cid, "P", [a])assert _links(client, cid, "derived-from")[0] == beforedef test_post_save_links_to_its_proof_and_media(client):cid = _new_case(client, "Post links")a = _upload(client, cid, "a.png", _png_bytes((7, 8, 9)))["item"]["path"]- _save_proof(client, cid, "P", [a], name="p")+ _save_proof(client, cid, "P", [a])client.post(f"/api/cases/{cid}/drafts",@@ -241,7 +239,7 @@ def test_a_source_deleted_before_the_save_leaves_a_tombstone(client):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")+ _save_proof(client, cid, "P", [a])proof = _entity(client, cid, spec="proofs/p.json")assert _links(client, cid) == []@@ -282,8 +280,8 @@ def test_missing_sources_are_tombstoned_in_one_case_update():def test_deleting_a_subject_deletes_its_session_but_spares_its_outputs(client):cid = _new_case(client, "Cascade")a = _upload(client, cid, "a.png", _png_bytes((1, 1, 1)))["item"]["path"]- _save_session(client, cid, "S", a, name="s")- _save_proof(client, cid, "P", [a], name="p")+ _save_session(client, cid, "S", a)+ _save_proof(client, cid, "P", [a])subject = _entity(client, cid, path=a)res = client.delete(f"/api/cases/{cid}/entities/{subject['id']}").json()@@ -301,7 +299,7 @@ def test_deleting_a_subject_deletes_its_session_but_spares_its_outputs(client):def test_a_survivor_keeps_a_tombstone_of_what_it_lost(client):cid = _new_case(client, "Tombstone")a = _upload(client, cid, "strike.png")["item"]["path"]- _save_proof(client, cid, "P", [a], name="p")+ _save_proof(client, cid, "P", [a])subject = _entity(client, cid, path=a)sha = subject["attrs"]["sha256"]@@ -322,8 +320,8 @@ def test_a_survivor_is_only_scarred_by_what_it_derived_from(client):# that merely died in the same breath.cid = _new_case(client, "Only mine")a = _upload(client, cid, "a.png")["item"]["path"]- _save_session(client, cid, "S", a, name="s")- _save_proof(client, cid, "P", [a], name="p")+ _save_session(client, cid, "S", a)+ _save_proof(client, cid, "P", [a])client.delete(f"/api/cases/{cid}/entities/{_entity(client, cid, path=a)['id']}")@@ -335,10 +333,10 @@ def test_tombstones_never_stack_on_a_second_delete(client):cid = _new_case(client, "Once")a = _upload(client, cid, "a.png", _png_bytes((2, 2, 2)))["item"]["path"]b = _upload(client, cid, "b.png", _png_bytes((3, 3, 3)))["item"]["path"]- _save_proof(client, cid, "P", [a, b], name="p")+ _save_proof(client, cid, "P", [a, b])client.delete(f"/api/cases/{cid}/entities/{_entity(client, cid, path=a)['id']}")- _save_proof(client, cid, "P", [a, b], name="p") # re-save still names the dead path+ _save_proof(client, cid, "P", [a, b]) # re-save still names the dead pathclient.delete(f"/api/cases/{cid}/entities/{_entity(client, cid, path=b)['id']}")lost = _entity(client, cid, spec="proofs/p.json")["attrs"]["lost_sources"]@@ -350,7 +348,7 @@ def test_deleting_a_proof_spares_the_post_that_announces_it(client):# its proof and only loses the attachment.cid = _new_case(client, "Post survives")a = _upload(client, cid, "a.png")["item"]["path"]- _save_proof(client, cid, "P", [a], name="p")+ _save_proof(client, cid, "P", [a])client.post(f"/api/cases/{cid}/drafts",json={"title": "T", "state": {"proofPng": "proofs/p.png", "description": "kept"}},@@ -368,7 +366,7 @@ def test_deleting_a_proof_spares_the_post_that_announces_it(client):def test_cascade_is_transitive_through_depends_on(client):cid = _new_case(client, "Deep")a = _upload(client, cid, "a.png")["item"]["path"]- _save_session(client, cid, "S1", a, name="s1")+ _save_session(client, cid, "S1", a)# a second session opened over the first one's spec — contrived, but it is# what a future tool nesting sessions would produce, and it must follow.s1 = _entity(client, cid, spec="inspect/s1.json")@@ -397,20 +395,20 @@ def test_a_session_over_a_frame_survives_the_frames_video_going(client):_entity(client, cid, path=video)["id"],"derived-from",)- _save_session(client, cid, "On the video", video, name="onvideo")- _save_session(client, cid, "On the frame", frame, name="onframe")+ _save_session(client, cid, "On the video", video)+ _save_session(client, cid, "On the frame", frame)client.delete(f"/api/cases/{cid}/entities/{_entity(client, cid, path=video)['id']}")- assert _entity(client, cid, spec="inspect/onvideo.json") is None- assert _entity(client, cid, spec="inspect/onframe.json") is not None+ assert _entity(client, cid, spec="inspect/on-the-video.json") is None+ assert _entity(client, cid, spec="inspect/on-the-frame.json") is not Noneassert _entity(client, cid, path=frame) is not Nonedef test_deleting_an_entity_drops_the_links_touching_it(client):cid = _new_case(client, "Edges")a = _upload(client, cid, "a.png")["item"]["path"]- _save_proof(client, cid, "P", [a], name="p")+ _save_proof(client, cid, "P", [a])assert len(_links(client, cid)) == 1client.delete(f"/api/cases/{cid}/entities/{_entity(client, cid, path=a)['id']}")@@ -425,8 +423,8 @@ def test_the_media_library_delete_honours_the_graph(client):# same media from its own tool must do exactly the same thing.cid = _new_case(client, "Via library")a = _upload(client, cid, "a.png")["item"]["path"]- _save_session(client, cid, "S", a, name="s")- _save_proof(client, cid, "P", [a], name="p")+ _save_session(client, cid, "S", a)+ _save_proof(client, cid, "P", [a])client.delete(f"/api/cases/{cid}/media?path={a}")@@ -437,7 +435,7 @@ def test_the_media_library_delete_honours_the_graph(client):def test_the_inspect_delete_honours_the_graph(client):cid = _new_case(client, "Via inspect")a = _upload(client, cid, "a.png")["item"]["path"]- _save_session(client, cid, "S", a, name="s")+ _save_session(client, cid, "S", a)client.delete(f"/api/cases/{cid}/inspect/sessions/s")@@ -450,7 +448,7 @@ def test_the_inspect_delete_honours_the_graph(client):def test_the_satellite_delete_honours_the_graph(client):cid = _new_case(client, "Via satellite")a = _upload(client, cid, "cap.png")["item"]["path"]- _save_session(client, cid, "S", a, name="s")+ _save_session(client, cid, "S", a)client.delete(f"/api/cases/{cid}/satellite?path={a}")@@ -478,8 +476,8 @@ def test_a_tool_delete_still_drops_an_unfiled_artifact(client):def test_dependents_endpoint_reports_the_plan(client):cid = _new_case(client, "Preview")a = _upload(client, cid, "a.png")["item"]["path"]- _save_session(client, cid, "S", a, name="s")- _save_proof(client, cid, "P", [a], name="p")+ _save_session(client, cid, "S", a)+ _save_proof(client, cid, "P", [a])subject = _entity(client, cid, path=a)plan = client.get(f"/api/cases/{cid}/entities/{subject['id']}/dependents").json()@@ -510,7 +508,7 @@ def test_dependents_endpoint_404s_on_an_unknown_entity(client):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")+ _save_proof(client, cid, "P", [a])media = _entity(client, cid, path=a)proof = _entity(client, cid, spec="proofs/p.json")@@ -532,7 +530,7 @@ 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+ _save_proof(client, cid, "P", [a]) # source gone → tombstone, no edgeproof = _entity(client, cid, spec="proofs/p.json")chain = client.get(f"/api/cases/{cid}/entities/{proof['id']}/chain").json()@@ -567,7 +565,7 @@ 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")+ _save_proof(client, cid, "P", [a, b])proof = _entity(client, cid, spec="proofs/p.json")sub = client.get(f"/api/cases/{cid}/entities/{proof['id']}/derivation").json()diff --git a/tests/test_mapsites.py b/tests/test_mapsites.pyindex 019986e..c33cd2e 100644--- a/tests/test_mapsites.py+++ b/tests/test_mapsites.py@@ -44,6 +44,36 @@ def test_satellites_pro_still_parses():assert (p["site"], p["lat"], p["lon"], p["zoom"]) == ("satellites-pro", LAT, LON, Z)+def test_explicit_satellite_urls_are_classified():+ urls = [+ f"https://www.google.com/maps/@{LAT},{LON},2000m/data=!3m1!1e3",+ f"https://earth.google.com/web/@{LAT},{LON},0a,1000d,35y,0h,0t,0r",+ f"https://maps.apple.com/?ll={LAT},{LON}&z={Z}&t=k",+ f"https://maps.apple.com/?ll={LAT},{LON}&z={Z}&map=satellite",+ f"https://maps.apple.com/?ll={LAT},{LON}&z={Z}&map=hybrid",+ f"https://www.bing.com/maps?cp={LAT}~{LON}&lvl={Z}&style=h",+ f"https://yandex.com/maps/?ll={LON},{LAT}&z={Z}&l=sat",+ f"https://zoom.earth/#view={LAT},{LON},{Z}z",+ f"https://satellites.pro/#{LAT},{LON},{Z}",+ f"https://browser.dataspace.copernicus.eu/?zoom={Z}&lat={LAT}&lng={LON}",+ ]++ assert all(parse_map_url(url)["imagery_mode"] == "satellite" for url in urls)+++def test_generic_map_urls_are_not_guessed_as_satellite():+ urls = [+ f"https://www.google.com/maps/@{LAT},{LON},{Z}z",+ f"https://www.bing.com/maps?cp={LAT}~{LON}&lvl={Z}&style=r",+ f"https://yandex.com/maps/?ll={LON},{LAT}&z={Z}&l=map",+ f"https://maps.apple.com/?ll={LAT},{LON}&z={Z}&t=m",+ f"https://maps.apple.com/?ll={LAT},{LON}&z={Z}&map=explore",+ f"https://www.openstreetmap.org/#map={Z}/{LAT}/{LON}",+ ]++ assert all(parse_map_url(url)["imagery_mode"] is None for url in urls)++def test_google_maps_forms():p = parse_map_url("https://www.google.com/maps/place/Tour+Eiffel/@48.8583701,2.2944813,17z/data=!3m1!4b1"diff --git a/tests/test_media_api.py b/tests/test_media_api.pyindex 6e5fc5d..ea2dbd2 100644--- a/tests/test_media_api.py+++ b/tests/test_media_api.py@@ -102,6 +102,184 @@ def test_listing_carries_category_fields(client):assert item["source"]["type"] == "upload" # drives the Imports facet+def test_listing_derives_satellite_mode_for_legacy_extension_capture(client):+ from azimut.engine import media as media_engine+ from azimut.workspace import Case++ cid = client.post("/api/cases", json={"name": "Legacy satellite"}).json()["id"]+ media_engine.import_image(+ Case.open(cid),+ Image.new("RGB", (32, 24), (20, 80, 20)),+ "legacy-screenshot.png",+ {+ "type": "screenshot",+ "source_url": "https://www.google.com/maps/@48.8584,2.2945,2000m/data=!3m1!1e3",+ },+ entity_type="capture",+ dedupe=False,+ )++ item = client.get(f"/api/cases/{cid}/media").json()[0]+ assert item["source"]["imagery_mode"] == "satellite"+++def _set(client, cid, path, **patch):+ return client.patch(f"/api/cases/{cid}/media", json={"path": path, **patch}).json()+++def test_media_page_paginates(client):+ cid = client.post("/api/cases", json={"name": "Page"}).json()["id"]+ for i in range(5):+ _upload(client, cid, f"shot{i}.png", _png_bytes(color=(i, 0, 0)))++ first = client.get(f"/api/cases/{cid}/media/page", params={"limit": 2}).json()+ assert len(first["items"]) == 2+ assert first["total"] == 5+ assert first["next_cursor"] == "2"++ mid = client.get(+ f"/api/cases/{cid}/media/page", params={"limit": 2, "cursor": first["next_cursor"]}+ ).json()+ assert len(mid["items"]) == 2+ assert mid["next_cursor"] == "4"++ last = client.get(+ f"/api/cases/{cid}/media/page", params={"limit": 2, "cursor": mid["next_cursor"]}+ ).json()+ assert len(last["items"]) == 1+ assert last["next_cursor"] is None+++def test_media_page_query_matches_title_notes_folder(client):+ cid = client.post("/api/cases", json={"name": "Q"}).json()["id"]+ a = _upload(client, cid, "alpha.png", _png_bytes(color=(1, 0, 0))).json()["item"]+ b = _upload(client, cid, "beta.png", _png_bytes(color=(2, 0, 0))).json()["item"]+ _set(client, cid, a["path"], notes="bridge over the river", folder="ukraine")+ _set(client, cid, b["path"], title="Harbour view")++ hit = client.get(f"/api/cases/{cid}/media/page", params={"q": "bridge"}).json()+ assert [i["path"] for i in hit["items"]] == [a["path"]]+ # folder + a source/title term both match+ assert client.get(f"/api/cases/{cid}/media/page", params={"q": "harbour"}).json()["total"] == 1+ # two space-split terms must both be present (AND)+ assert client.get(f"/api/cases/{cid}/media/page", params={"q": "bridge river"}).json()["total"] == 1+ assert client.get(f"/api/cases/{cid}/media/page", params={"q": "bridge harbour"}).json()["total"] == 0+++def test_media_page_kind_and_folder_filters(client):+ cid = client.post("/api/cases", json={"name": "Filt"}).json()["id"]+ a = _upload(client, cid, "a.png", _png_bytes(color=(3, 0, 0))).json()["item"]+ _upload(client, cid, "b.png", _png_bytes(color=(4, 0, 0)))+ _set(client, cid, a["path"], folder="kyiv")++ assert client.get(f"/api/cases/{cid}/media/page", params={"kind": "image"}).json()["total"] == 2+ assert client.get(f"/api/cases/{cid}/media/page", params={"folder": "kyiv"}).json()["total"] == 1+++def test_media_page_sort_name_and_size(client):+ cid = client.post("/api/cases", json={"name": "Sort"}).json()["id"]+ small = _upload(client, cid, "s.png", _png_bytes(color=(5, 0, 0), size=(16, 16))).json()["item"]+ big = _upload(client, cid, "b.png", _png_bytes(color=(6, 0, 0), size=(256, 256))).json()["item"]+ _set(client, cid, small["path"], title="Zebra")+ _set(client, cid, big["path"], title="Alpha")++ by_name = client.get(f"/api/cases/{cid}/media/page", params={"sort": "name"}).json()+ assert [i["title"] for i in by_name["items"]] == ["Alpha", "Zebra"]++ by_size = client.get(f"/api/cases/{cid}/media/page", params={"sort": "size"}).json()+ assert by_size["items"][0]["path"] == big["path"]++ name_desc = client.get(+ f"/api/cases/{cid}/media/page", params={"sort": "name", "direction": "desc"}+ ).json()+ assert [item["title"] for item in name_desc["items"]] == ["Zebra", "Alpha"]++ size_asc = client.get(+ f"/api/cases/{cid}/media/page", params={"sort": "size", "direction": "asc"}+ ).json()+ assert size_asc["items"][0]["path"] == small["path"]+++def test_media_page_facets_count_full_set(client):+ cid = client.post("/api/cases", json={"name": "Facets2"}).json()["id"]+ a = _upload(client, cid, "a.png", _png_bytes(color=(7, 0, 0))).json()["item"]+ _upload(client, cid, "b.png", _png_bytes(color=(8, 0, 0)))+ _set(client, cid, a["path"], folder="kyiv")++ # facets reflect the whole filtered set even when a page slices it+ page = client.get(f"/api/cases/{cid}/media/page", params={"limit": 1}).json()+ assert len(page["items"]) == 1 # only one item on the page+ assert page["facets"]["kind_counts"]["image"] == 2 # ...but both counted+ assert page["facets"]["folder_counts"]["kyiv"] == 1+ assert page["facets"]["category_counts"]["image"] == 2+ assert page["facets"]["category_counts"]["upload"] == 2+++def test_media_page_filters_categories_without_page_local_counts(client):+ from azimut.engine import media as media_engine+ from azimut.workspace import Case++ cid = client.post("/api/cases", json={"name": "Categories"}).json()["id"]+ generic = _upload(client, cid, "generic.png", _png_bytes()).json()["item"]+ satellite = media_engine.import_image(+ Case.open(cid),+ Image.new("RGB", (32, 24)),+ "map.png",+ {"type": "satellite"},+ entity_type="capture",+ dedupe=False,+ )["item"]++ images = client.get(+ f"/api/cases/{cid}/media/page", params={"category": "image", "limit": 1}+ ).json()+ assert images["total"] == 1+ assert [item["path"] for item in images["items"]] == [generic["path"]]+ # Counts describe all matching media, not only the selected page/category.+ assert images["facets"]["category_counts"]["image"] == 1+ assert images["facets"]["category_counts"]["satellite"] == 1++ maps = client.get(+ f"/api/cases/{cid}/media/page", params={"category": "satellite"}+ ).json()+ assert [item["path"] for item in maps["items"]] == [satellite["path"]]+++def test_media_page_does_not_scan_sidecars_for_each_request(client, monkeypatch):+ from azimut.engine import media as media_engine++ cid = client.post("/api/cases", json={"name": "Indexed page"}).json()["id"]+ _upload(client, cid, "shot.png", _png_bytes())+ monkeypatch.setattr(+ media_engine,+ "list_media",+ lambda _case: (_ for _ in ()).throw(AssertionError("sidecar list called")),+ )++ page = client.get(f"/api/cases/{cid}/media/page").json()+ assert page["total"] == 1+++def test_media_metadata_returns_only_requested_paths(client):+ cid = client.post("/api/cases", json={"name": "Metadata"}).json()["id"]+ first = _upload(client, cid, "first.png", _png_bytes(color=(10, 0, 0))).json()["item"]+ second = _upload(client, cid, "second.png", _png_bytes(color=(20, 0, 0))).json()["item"]++ items = client.post(+ f"/api/cases/{cid}/media/metadata",+ json={"paths": [second["path"], "media/missing.png", first["path"]]},+ ).json()+ assert [item["path"] for item in items] == [second["path"], first["path"]]+ assert all(item["thumb_state"] == "ready" for item in items)+++def test_media_page_items_carry_thumb_state(client):+ cid = client.post("/api/cases", json={"name": "PageThumb"}).json()["id"]+ _upload(client, cid, "shot.png", _png_bytes())+ page = client.get(f"/api/cases/{cid}/media/page").json()+ assert page["items"][0]["thumb_state"] == "ready"++def test_duplicate_detection(client):cid = client.post("/api/cases", json={"name": "Dup"}).json()["id"]data = _png_bytes(color=(1, 2, 3))diff --git a/tests/test_naming.py b/tests/test_naming.pynew file mode 100644index 0000000..c589fd4--- /dev/null+++ b/tests/test_naming.py@@ -0,0 +1,50 @@+"""Shared naming rules: the slug every saved item's filename follows.++The frontend mirrors `slugify` in `lib/naming.js` so it can tell before it posts+whether a name is free. These cases are the contract both sides implement.+"""++import json++from azimut.api.naming import MAX_SLUG, read_created_at, slugify+++def test_slug_lowercases_hyphenates_and_trims():+ assert slugify("Inspect 1", "session") == "inspect-1"+ assert slugify(" Rooftop! @ 12:30 ", "proof") == "rooftop-12-30"+ assert slugify("Café déjà", "proof") == "caf-d-j"+++def test_slug_falls_back_per_caller_and_is_bounded():+ assert slugify("", "proof") == "proof"+ assert slugify("!!!", "session") == "session"+ assert slugify(None, "draft") == "draft"+ assert len(slugify("a" * 200, "proof")) == MAX_SLUG+++def test_slug_cannot_reach_outside_its_folder():+ # The slug is the only guard on a client-supplied `rename_from`: nothing but+ # [a-z0-9-] survives it, so no separator or dot-dot can reach the filesystem.+ for hostile in ("../../etc/passwd", "..\\..\\windows", "a/b", "."):+ assert "/" not in slugify(hostile, "proof")+ assert "\\" not in slugify(hostile, "proof")+ assert ".." not in slugify(hostile, "proof")+++def test_read_created_at_returns_the_stamp_on_disk(tmp_path):+ path = tmp_path / "spec.json"+ path.write_text(json.dumps({"created_at": "2026-07-26T10:00:00Z"}), encoding="utf-8")+ assert read_created_at(path) == "2026-07-26T10:00:00Z"+++def test_read_created_at_is_none_when_unreadable(tmp_path):+ assert read_created_at(tmp_path / "missing.json") is None+ bad = tmp_path / "bad.json"+ bad.write_text("{not json", encoding="utf-8")+ assert read_created_at(bad) is None+ empty = tmp_path / "empty.json"+ empty.write_text("{}", encoding="utf-8")+ assert read_created_at(empty) is None+ wrong = tmp_path / "wrong.json"+ wrong.write_text(json.dumps({"created_at": 17}), encoding="utf-8")+ assert read_created_at(wrong) is Nonediff --git a/tests/test_proofs_api.py b/tests/test_proofs_api.pyindex 0033ca0..5b7a4d1 100644--- a/tests/test_proofs_api.py+++ b/tests/test_proofs_api.py@@ -5,6 +5,7 @@ import base64import graph_readimport io+import pytestfrom PIL import Image@@ -67,11 +68,11 @@ def test_save_load_roundtrip(client):# proof entity filed once, updated on resaveclient.post(f"/api/cases/{cid}/proofs",- json={"name": saved["name"], "title": "Renamed proof", "spec": SPEC},+ json={"rename_from": saved["name"], "title": "Kharkiv strike proof", "spec": SPEC},)entities = [e for e in graph_read.entities(cid) if e["type"] == "proof"]assert len(entities) == 1- assert entities[0]["label"] == "Renamed proof"+ assert entities[0]["label"] == "Kharkiv strike proof"def test_resave_with_png_adds_the_path_to_the_entity(client):@@ -90,7 +91,12 @@ def test_resave_with_png_adds_the_path_to_the_entity(client):# or the sidebar preview and delete_by_path can't see the fileclient.post(f"/api/cases/{cid}/proofs",- json={"name": saved["name"], "title": "Draft proof", "spec": SPEC, "png_base64": _png_b64()},+ json={+ "rename_from": saved["name"],+ "title": "Draft proof",+ "spec": SPEC,+ "png_base64": _png_b64(),+ },)entity = next(e for e in graph_read.entities(cid) if e["type"] == "proof"@@ -107,6 +113,99 @@ def test_invalid_png_rejected(client):assert res.status_code == 422+def test_rename_moves_the_spec_and_the_export(client):+ # The name in the composer header is the filename. Renaming a saved proof+ # takes its spec, its PNG and its entity along, so nothing is orphaned and+ # the proof keeps its folder and links.+ cid = client.post("/api/cases", json={"name": "RenameProof"}).json()["id"]+ saved = client.post(+ f"/api/cases/{cid}/proofs",+ json={"title": "Proof 1", "spec": SPEC, "png_base64": _png_b64()},+ ).json()+ before = next(e for e in graph_read.entities(cid) if e["type"] == "proof")+ client.patch(f"/api/cases/{cid}/entities/{before['id']}", json={"attrs": {"folder": "Reports"}})++ renamed = client.post(+ f"/api/cases/{cid}/proofs",+ json={+ "rename_from": saved["name"],+ "title": "Rooftop angle",+ "spec": SPEC,+ "png_base64": _png_b64(),+ },+ ).json()+ assert renamed["name"] == "rooftop-angle"+ assert renamed["png"] == "proofs/rooftop-angle.png"+ assert client.get(f"/api/cases/{cid}/proofs/proof-1").status_code == 404+ assert client.get(f"/files/{cid}/proofs/proof-1.png").status_code == 404+ assert client.get(f"/files/{cid}/proofs/rooftop-angle.png").status_code == 200++ proofs = [e for e in graph_read.entities(cid) if e["type"] == "proof"]+ assert len(proofs) == 1+ assert proofs[0]["id"] == before["id"]+ assert proofs[0]["attrs"]["spec"] == "proofs/rooftop-angle.json"+ assert proofs[0]["attrs"]["path"] == "proofs/rooftop-angle.png"+ assert proofs[0]["attrs"]["folder"] == "Reports"+++def test_rename_without_fresh_pixels_carries_the_export_along(client):+ # A save that ships no PNG (spec-only) must not strand the export under the+ # old name — the proof would lose its picture on a pure rename.+ cid = client.post("/api/cases", json={"name": "CarryPng"}).json()["id"]+ client.post(+ f"/api/cases/{cid}/proofs",+ json={"title": "Proof 1", "spec": SPEC, "png_base64": _png_b64()},+ )+ renamed = client.post(+ f"/api/cases/{cid}/proofs",+ json={"rename_from": "proof-1", "title": "Carried", "spec": SPEC},+ ).json()++ assert renamed["png"] == "proofs/carried.png"+ assert client.get(f"/files/{cid}/proofs/carried.png").status_code == 200+ assert client.get(f"/files/{cid}/proofs/proof-1.png").status_code == 404+ entity = next(e for e in graph_read.entities(cid) if e["type"] == "proof")+ assert entity["attrs"]["path"] == "proofs/carried.png"+++def test_rename_onto_a_taken_name_is_refused(client):+ cid = client.post("/api/cases", json={"name": "ClashProof"}).json()["id"]+ client.post(+ f"/api/cases/{cid}/proofs",+ json={"title": "Proof 1", "spec": SPEC, "png_base64": _png_b64()},+ )+ client.post(+ f"/api/cases/{cid}/proofs",+ json={"title": "Proof 2", "spec": SPEC, "png_base64": _png_b64()},+ )++ res = client.post(+ f"/api/cases/{cid}/proofs",+ json={+ "rename_from": "proof-2",+ "title": "Proof 1",+ "spec": SPEC,+ "png_base64": _png_b64(),+ },+ )+ assert res.status_code == 409+ listed = sorted(p["name"] for p in client.get(f"/api/cases/{cid}/proofs").json())+ assert listed == ["proof-1", "proof-2"]+ assert client.get(f"/files/{cid}/proofs/proof-2.png").status_code == 200+++def test_rename_keeps_the_creation_date(client):+ cid = client.post("/api/cases", json={"name": "BornProof"}).json()["id"]+ client.post(f"/api/cases/{cid}/proofs", json={"title": "Proof 1", "spec": SPEC})+ born = client.get(f"/api/cases/{cid}/proofs/proof-1").json()["created_at"]++ client.post(+ f"/api/cases/{cid}/proofs",+ json={"rename_from": "proof-1", "title": "Renamed", "spec": SPEC},+ )+ assert client.get(f"/api/cases/{cid}/proofs/renamed").json()["created_at"] == born++def test_delete_proof(client):cid = client.post("/api/cases", json={"name": "DelProof"}).json()["id"]saved = client.post(@@ -117,3 +216,316 @@ def test_delete_proof(client):assert client.get(f"/api/cases/{cid}/proofs").json() == []assert client.get(f"/api/cases/{cid}/proofs/{saved['name']}").status_code == 404assert [e for e in graph_read.entities(cid) if e["type"] == "proof"] == []+++def _big_png_b64(size=(2400, 1600)) -> str:+ buf = io.BytesIO()+ Image.new("RGB", size, (30, 90, 140)).save(buf, "PNG")+ return base64.b64encode(buf.getvalue()).decode()+++def test_save_produces_a_thumbnail_of_the_export(client):+ from azimut.api.cases import get_case++ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]+ saved = client.post(+ f"/api/cases/{cid}/proofs",+ json={"title": "Wide proof", "spec": SPEC, "png_base64": _big_png_b64()},+ ).json()++ assert saved["thumb"] and saved["thumb"] != saved["png"]+ case = get_case(cid)+ thumb, png = case.resolve_inside(saved["thumb"]), case.resolve_inside(saved["png"])+ assert thumb.stat().st_size < png.stat().st_size+ assert client.get(f"/files/{cid}/{saved['thumb']}").status_code == 200++ # the listing hands it to the open dialog, so the row never loads the export+ assert client.get(f"/api/cases/{cid}/proofs").json()[0]["thumb"] == saved["thumb"]+++def test_listing_backfills_a_proof_saved_before_thumbnails(client):+ import json++ from azimut.api.cases import get_case++ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]+ saved = client.post(+ f"/api/cases/{cid}/proofs",+ json={"title": "Old proof", "spec": SPEC, "png_base64": _big_png_b64()},+ ).json()++ # roll the proof back to what an older save left on disk: a spec with no+ # thumbnail recorded, and nothing in the cache+ case = get_case(cid)+ spec_path = case.resolve_inside(saved["spec_path"])+ spec = json.loads(spec_path.read_text(encoding="utf-8"))+ del spec["thumb"]+ spec_path.write_text(json.dumps(spec), encoding="utf-8")+ case.resolve_inside(saved["thumb"]).unlink()++ listed = client.get(f"/api/cases/{cid}/proofs").json()[0]+ assert listed["thumb"] == saved["thumb"]+ assert case.resolve_inside(listed["thumb"]).is_file()+ # recorded, so the next listing costs nothing+ assert json.loads(spec_path.read_text(encoding="utf-8"))["thumb"] == saved["thumb"]+++def test_listing_falls_back_to_the_export_when_no_thumbnail_can_be_made(client):+ from azimut.api.cases import get_case++ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]+ saved = client.post(+ f"/api/cases/{cid}/proofs",+ json={"title": "Broken proof", "spec": SPEC, "png_base64": _png_b64()},+ ).json()++ case = get_case(cid)+ case.resolve_inside(saved["thumb"]).unlink()+ case.resolve_inside(saved["png"]).write_bytes(b"not an image")+ # rewrite the spec so the recorded thumbnail is not simply reused+ spec_path = case.resolve_inside(saved["spec_path"])+ spec_path.write_text(spec_path.read_text(encoding="utf-8").replace(saved["thumb"], ""), encoding="utf-8")++ listed = client.get(f"/api/cases/{cid}/proofs").json()[0]+ assert not listed["thumb"]+ assert listed["png"] == saved["png"] # the row still shows something+++def test_cache_repair_keeps_proof_thumbnails(client):+ from azimut.api.cases import get_case+ from azimut.engine import thumbnails++ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]+ saved = client.post(+ f"/api/cases/{cid}/proofs",+ json={"title": "Kept proof", "spec": SPEC, "png_base64": _big_png_b64()},+ ).json()++ case = get_case(cid)+ thumbnails.repair(case) # no media sidecar references it, but a proof does+ assert case.resolve_inside(saved["thumb"]).is_file()+++# -- the proofs index: proofs placed on the map ---------------------------------------+# A proof carries no coordinates of its own (ONTOLOGY: `spec` + `path`), so the+# map reads them one hop back through `derived-from`. What must hold: the point+# is inherited, a proof composed of panels from two places is at both, and one+# with no located source still lists.+++def sat_tiles(monkeypatch):+ """Captures without the network: every tile is a solid green square."""+ from azimut.engine import tiles++ monkeypatch.setattr(+ tiles, "_default_fetch", lambda client, url: Image.new("RGB", (256, 256), (10, 120, 10))+ )+++def _panels(*srcs):+ return {"panels": [{"id": f"p{i}", "src": s} for i, s in enumerate(srcs)]}+++def _sat(client, cid, lat, lon):+ """A saved capture — the only kind of panel that carries a point."""+ return client.post(+ f"/api/cases/{cid}/satellite/capture",+ json={"lat": lat, "lon": lon, "zoom": 16, "width": 256, "height": 256},+ ).json()+++def _proof_index(client, cid):+ return client.get(f"/api/cases/{cid}/proofs/index").json()+++def test_index_inherits_the_point_from_the_capture_it_composes(client, sat_tiles):+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]+ cap = _sat(client, cid, 50.4501, 30.5234)+ client.post(+ f"/api/cases/{cid}/proofs", json={"title": "Kyiv bridge", "spec": _panels(cap["path"])}+ )++ row = _proof_index(client, cid)[0]+ assert row["kind"] == "proof"+ assert row["title"] == "Kyiv bridge"+ assert row["name"] == "kyiv-bridge"+ assert (row["lat"], row["lon"]) == (50.4501, 30.5234)+ assert row["notes"] == ""+ assert row["folder"] == "" # unfiled, never null+++def test_index_places_a_proof_at_each_of_its_source_points(client, sat_tiles):+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]+ kyiv = _sat(client, cid, 50.4501, 30.5234)+ paris = _sat(client, cid, 48.8584, 2.2945)+ client.post(+ f"/api/cases/{cid}/proofs",+ json={"title": "Two cities", "spec": _panels(kyiv["path"], paris["path"])},+ )++ rows = _proof_index(client, cid)+ assert len({r["id"] for r in rows}) == 1 # one proof…+ assert sorted(r["lat"] for r in rows) == [48.8584, 50.4501] # …at both its places+ assert len({r["key"] for r in rows}) == 2 # but two marks, so two render keys+++def test_index_folds_panels_that_share_one_point_into_one_row(client, sat_tiles):+ """Two zooms of the same roof are one place, so they are one mark."""+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]+ a = _sat(client, cid, 50.4501, 30.5234)+ b = _sat(client, cid, 50.4501, 30.5234)+ client.post(+ f"/api/cases/{cid}/proofs",+ json={"title": "Same roof", "spec": _panels(a["path"], b["path"])},+ )++ rows = _proof_index(client, cid)+ assert [(r["title"], r["lat"]) for r in rows] == [("Same roof", 50.4501)]+++def test_index_lists_a_proof_with_no_located_source_without_a_point(client):+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]+ client.post(+ f"/api/cases/{cid}/proofs", json={"title": "Photos only", "spec": _panels("media/x.jpg")}+ )++ row = _proof_index(client, cid)[0]+ assert row["lat"] is None and row["lon"] is None # it files under Unlocated+ assert row["title"] == "Photos only"+++def test_index_carries_the_geography_of_the_source(client, sat_tiles, monkeypatch):+ from azimut.engine import geo++ monkeypatch.setattr(+ geo,+ "reverse_geocode",+ lambda lat, lon, timeout=8, language=None: {+ "display_name": "x",+ "attribution": "x",+ "address": {"country_code": "ua", "country": "Ukraine", "state": "Donetsk Oblast"},+ },+ )+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]+ cap = _sat(client, cid, 48.0159, 37.8029)+ client.post(f"/api/cases/{cid}/proofs", json={"title": "Donetsk", "spec": _panels(cap["path"])})++ row = _proof_index(client, cid)[0]+ assert row["geo"]["country"] == "Ukraine"+ assert row["continent"] == "Europe"+ assert row["country_en"] == "Ukraine"+++def test_index_lists_the_posts_written_from_a_proof(client, sat_tiles):+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]+ cap = _sat(client, cid, 50.4501, 30.5234)+ saved = client.post(+ f"/api/cases/{cid}/proofs",+ json={"title": "Cited", "spec": _panels(cap["path"]), "png_base64": _png_b64()},+ ).json()+ client.post(+ f"/api/cases/{cid}/drafts",+ json={+ "title": "First thread",+ "state": {"proofPng": saved["png"], "target": "bluesky"},+ },+ )+ client.post(+ f"/api/cases/{cid}/drafts",+ json={+ "title": "Follow-up",+ "state": {"proofPng": saved["png"], "target": "mastodon"},+ },+ )++ row = _proof_index(client, cid)[0]+ assert row["posts"] == 2+ assert {post["title"] for post in row["linked_posts"]} == {+ "First thread",+ "Follow-up",+ }+ assert {post["target"] for post in row["linked_posts"]} == {+ "bluesky",+ "mastodon",+ }+ assert {post["name"] for post in row["linked_posts"]} == {+ "first-thread",+ "follow-up",+ }+++# -- a proof's own point ---------------------------------------------------------------+# A proof does carry coordinates: `coordsText` is what the analyst typed in the+# composer, `coords` is what the panels gave it, frozen at save. Both outlive the+# capture they came from, so they are read before the derivation is walked.+++def test_index_prefers_the_coordinates_typed_into_the_composer(client, sat_tiles):+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]+ cap = _sat(client, cid, 50.4501, 30.5234)+ client.post(+ f"/api/cases/{cid}/proofs",+ json={+ "title": "Corrected",+ "spec": {**_panels(cap["path"]), "coordsText": "48.8584, 2.2945"},+ },+ )++ rows = _proof_index(client, cid)+ # the analyst overrode the imagery: one point, theirs+ assert [(r["lat"], r["lon"]) for r in rows] == [(48.8584, 2.2945)]+++def test_index_reads_a_hand_typed_point_in_any_supported_format(client):+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]+ client.post(+ f"/api/cases/{cid}/proofs",+ json={"title": "Typed", "spec": {"panels": [], "coordsText": "48°51'30.2\"N 2°17'40.2\"E"}},+ )++ row = _proof_index(client, cid)[0]+ assert row["lat"] == pytest.approx(48.8584, abs=1e-3)+ assert row["lon"] == pytest.approx(2.2945, abs=1e-3)+++def test_index_keeps_the_point_after_the_capture_is_deleted(client, sat_tiles):+ """The whole reason a proof stores its own point: outputs outlive sources."""+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]+ cap = _sat(client, cid, 50.4501, 30.5234)+ client.post(+ f"/api/cases/{cid}/proofs",+ json={+ "title": "Orphaned",+ "spec": {**_panels(cap["path"]), "coords": {"lat": 50.4501, "lon": 30.5234}},+ },+ )+ entity = next(e for e in graph_read.entities(cid) if e["type"] == "capture")+ client.delete(f"/api/cases/{cid}/entities/{entity['id']}")++ row = _proof_index(client, cid)[0]+ assert (row["lat"], row["lon"]) == (50.4501, 30.5234) # scarred, not unplaced+++def test_index_ignores_a_hand_typed_point_it_cannot_read(client, sat_tiles):+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]+ cap = _sat(client, cid, 50.4501, 30.5234)+ client.post(+ f"/api/cases/{cid}/proofs",+ json={"title": "Prose", "spec": {**_panels(cap["path"]), "coordsText": "near the bridge"}},+ )++ # unreadable text is not a point, so the derivation still answers+ assert [(r["lat"], r["lon"]) for r in _proof_index(client, cid)] == [(50.4501, 30.5234)]+++def test_index_carries_the_my_work_folder_of_the_proof(client, sat_tiles):+ """A proof is filed like any other artifact, so the panel can group it by+ folder as well as by place."""+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]+ cap = _sat(client, cid, 50.4501, 30.5234)+ client.post(f"/api/cases/{cid}/proofs", json={"title": "Filed", "spec": _panels(cap["path"])})+ entity = next(e for e in graph_read.entities(cid) if e["type"] == "proof")+ client.patch(f"/api/cases/{cid}/entities/{entity['id']}", json={"attrs": {"folder": "recon/bridges"}})++ assert _proof_index(client, cid)[0]["folder"] == "recon/bridges"diff --git a/tests/test_proofs_assets_api.py b/tests/test_proofs_assets_api.pynew file mode 100644index 0000000..e8e791c--- /dev/null+++ b/tests/test_proofs_assets_api.py@@ -0,0 +1,245 @@+"""Pasted images: pixels a proof shows that the case does not hold.++A paste rides along with the save, lands in ``proofs/<name>.assets/`` under its+own hash, follows the proof through a rename, and goes away with it. What it must+never do is claim a source: no media, no entity, no ``derived-from`` edge.+"""++import base64+import hashlib+import io++import graph_read+from PIL import Image+++def _png(size=(60, 40), color=(90, 30, 30)) -> bytes:+ buf = io.BytesIO()+ Image.new("RGB", size, color).save(buf, "PNG")+ return buf.getvalue()+++def _asset(data: bytes) -> dict[str, str]:+ """The payload the composer sends: content hash for a name, base64 body."""+ return {+ "name": f"{hashlib.sha256(data).hexdigest()[:16]}.png",+ "data": base64.b64encode(data).decode(),+ }+++def _spec(*asset_names: str, panels=()) -> dict:+ return {+ "panels": [{"id": f"p{i}", "src": s, "natural": [800, 600]} for i, s in enumerate(panels)],+ "shapes": [],+ "pastes": [+ {+ "id": f"x{i}",+ "asset": n,+ "natural": [60, 40],+ "x": 10,+ "y": 20,+ "scale": 1,+ "frame": {"color": "#40c4ff", "width": 6},+ }+ for i, n in enumerate(asset_names)+ ],+ }+++def _case(client, name: str) -> str:+ return client.post("/api/cases", json={"name": name}).json()["id"]+++def test_a_pasted_image_lands_beside_the_proof_and_is_served(client):+ cid = _case(client, "Pastes")+ data = _png()+ asset = _asset(data)++ saved = client.post(+ f"/api/cases/{cid}/proofs",+ json={"title": "Pasted proof", "spec": _spec(asset["name"]), "assets": [asset]},+ ).json()++ rel = f"proofs/{saved['name']}.assets/{asset['name']}"+ served = client.get(f"/files/{cid}/{rel}")+ assert served.status_code == 200+ assert served.content == data # the exact bytes, so reopening renders the paste++ # the paste round-trips through the spec, frame and all+ paste = client.get(f"/api/cases/{cid}/proofs/{saved['name']}").json()["pastes"][0]+ assert paste["asset"] == asset["name"]+ assert paste["frame"] == {"color": "#40c4ff", "width": 6}+++def test_a_paste_claims_no_source(client):+ """The guarantee: a paste is pixels, not evidence. Nothing in the graph."""+ cid = _case(client, "NoSource")+ asset = _asset(_png())++ client.post(+ f"/api/cases/{cid}/proofs",+ json={"title": "Pasted proof", "spec": _spec(asset["name"]), "assets": [asset]},+ )++ # the proof itself, and nothing filed for the paste+ entities = graph_read.entities(cid)+ assert [e["type"] for e in entities] == ["proof"]+ assert not any(asset["name"] in str(e["attrs"]) for e in entities)+ # a panel would have earned a derived-from edge here; a paste earns none+ assert graph_read.links(cid, "derived-from") == []+++def test_dropping_a_paste_takes_its_file_and_its_folder(client):+ cid = _case(client, "Pruned")+ keep, drop = _asset(_png(color=(10, 90, 10))), _asset(_png(color=(90, 10, 90)))+ body = {"title": "Two pastes", "spec": _spec(keep["name"], drop["name"])}+ saved = client.post(+ f"/api/cases/{cid}/proofs", json={**body, "assets": [keep, drop]}+ ).json()+ folder = f"proofs/{saved['name']}.assets"+ assert client.get(f"/files/{cid}/{folder}/{drop['name']}").status_code == 200++ # resave with only one paste left: the other file goes, no new upload needed+ client.post(+ f"/api/cases/{cid}/proofs",+ json={"rename_from": saved["name"], "title": "Two pastes", "spec": _spec(keep["name"])},+ )+ assert client.get(f"/files/{cid}/{folder}/{keep['name']}").status_code == 200+ assert client.get(f"/files/{cid}/{folder}/{drop['name']}").status_code == 404++ # drop the last one and the folder itself goes+ from azimut.api.cases import get_case++ client.post(+ f"/api/cases/{cid}/proofs",+ json={"rename_from": saved["name"], "title": "Two pastes", "spec": _spec()},+ )+ assert not get_case(cid).resolve_inside(folder).exists()+++def test_rename_carries_the_pasted_images(client):+ cid = _case(client, "RenamePastes")+ asset = _asset(_png())+ client.post(+ f"/api/cases/{cid}/proofs",+ json={"title": "Before", "spec": _spec(asset["name"]), "assets": [asset]},+ )++ # renamed with no fresh upload: the folder moves rather than the paste dying+ renamed = client.post(+ f"/api/cases/{cid}/proofs",+ json={"rename_from": "before", "title": "After", "spec": _spec(asset["name"])},+ ).json()++ assert renamed["name"] == "after"+ assert client.get(f"/files/{cid}/proofs/after.assets/{asset['name']}").status_code == 200+ assert client.get(f"/files/{cid}/proofs/before.assets/{asset['name']}").status_code == 404+++def test_delete_removes_the_pasted_images(client):+ from azimut.api.cases import get_case++ cid = _case(client, "DeletePastes")+ asset = _asset(_png())+ saved = client.post(+ f"/api/cases/{cid}/proofs",+ json={"title": "Temp", "spec": _spec(asset["name"]), "assets": [asset]},+ ).json()++ client.delete(f"/api/cases/{cid}/proofs/{saved['name']}")+ assert not get_case(cid).resolve_inside(f"proofs/{saved['name']}.assets").exists()+++def test_the_same_paste_reuploaded_lands_once(client):+ cid = _case(client, "Idempotent")+ asset = _asset(_png())+ for _ in range(2):+ client.post(+ f"/api/cases/{cid}/proofs",+ json={+ "rename_from": "same",+ "title": "Same",+ "spec": _spec(asset["name"]),+ "assets": [asset],+ },+ )++ from azimut.api.cases import get_case++ folder = get_case(cid).resolve_inside("proofs/same.assets")+ assert [p.name for p in folder.iterdir()] == [asset["name"]]+++def test_an_asset_name_that_does_not_match_its_content_is_refused(client):+ cid = _case(client, "Tampered")+ asset = _asset(_png())+ asset["data"] = base64.b64encode(_png(color=(1, 2, 3))).decode() # other pixels++ res = client.post(+ f"/api/cases/{cid}/proofs",+ json={"title": "Tampered", "spec": _spec(asset["name"]), "assets": [asset]},+ )+ assert res.status_code == 422+++def test_an_asset_name_outside_the_folder_is_refused(client):+ cid = _case(client, "Traversal")+ data = _png()+ res = client.post(+ f"/api/cases/{cid}/proofs",+ json={+ "title": "Traversal",+ "spec": _spec("../../case.db"),+ "assets": [{"name": "../../case.db", "data": base64.b64encode(data).decode()}],+ },+ )+ assert res.status_code == 422+++def test_too_many_pasted_images_are_refused(client):+ cid = _case(client, "TooMany")+ assets = [_asset(_png(color=(i, i, i))) for i in range(13)]+ res = client.post(+ f"/api/cases/{cid}/proofs",+ json={+ "title": "Too many",+ "spec": _spec(*[a["name"] for a in assets]),+ "assets": assets,+ },+ )+ assert res.status_code == 422+++def test_a_refused_batch_writes_nothing(client):+ """Assets are decoded before the spec is touched, so a bad save is a no-op."""+ cid = _case(client, "AllOrNothing")+ good = _asset(_png())+ client.post(+ f"/api/cases/{cid}/proofs",+ json={"title": "Kept", "spec": _spec(good["name"]), "assets": [good]},+ )+ before = client.get(f"/api/cases/{cid}/proofs/kept").json()++ res = client.post(+ f"/api/cases/{cid}/proofs",+ json={+ "rename_from": "kept",+ "title": "Kept",+ "spec": _spec(good["name"], "0123456789abcdef.png"),+ "assets": [good, {"name": "0123456789abcdef.png", "data": "not base64!!"}],+ },+ )+ assert res.status_code == 422+ after = client.get(f"/api/cases/{cid}/proofs/kept").json()+ assert after == before # untouched, down to updated_at+ assert client.get(f"/files/{cid}/proofs/kept.assets/{good['name']}").status_code == 200+++def test_a_proof_without_pastes_keeps_no_assets_folder(client):+ from azimut.api.cases import get_case++ cid = _case(client, "Plain")+ client.post(+ f"/api/cases/{cid}/proofs", json={"title": "Plain", "spec": _spec(panels=["media/a.jpg"])}+ )+ assert not get_case(cid).resolve_inside("proofs/plain.assets").exists()diff --git a/tests/test_release_gate.py b/tests/test_release_gate.pyindex b2619d5..2367313 100644--- a/tests/test_release_gate.py+++ b/tests/test_release_gate.py@@ -141,12 +141,11 @@ 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")+ # The synthetic fixture lives outside the packaged tree, so hatchling never+ # ships it (doc "dev-only tooling stays out of the artifact").root = Path(__file__).resolve().parent.parentassert (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():@@ -232,8 +231,29 @@ def test_release_binary_runs_the_application_smoke_test():root = Path(__file__).resolve().parent.parentworkflow = (root / ".github" / "workflows" / "release.yml").read_text(encoding="utf-8")smoke = (root / "scripts" / "smoke_binary.py").read_text(encoding="utf-8")+ vendor = (root / "scripts" / "vendor_ffmpeg.py").read_text(encoding="utf-8")assert "scripts/smoke_binary.py" in workflowassert "/api/health" in smokeassert "/api/settings/ffmpeg" in smokeassert 'ffmpeg.get("source") != "bundled"' in smoke+ assert "scripts/vendor_ffmpeg.py" in workflow+ assert "/redirect/" not in vendor+ assert "/latest/" not in vendor+ assert "SHA-256 mismatch" in vendor+ for target in ("windows-x86_64", "linux-x86_64", "macos-arm64"):+ assert f"ffmpeg_target: {target}" in workflow+++def test_intel_macos_package_support_floor_matches_the_lock():+ root = Path(__file__).resolve().parent.parent+ readme = (root / "README.md").read_text(encoding="utf-8")+ lock = (root / "uv.lock").read_text(encoding="utf-8")+ opencv = lock.split(+ '[[package]]\nname = "opencv-python-headless"',+ maxsplit=1,+ )[1]+ opencv = opencv.split("[[package]]", maxsplit=1)[0]++ assert "macOS (Intel, 14+)" in readme+ assert "macosx_14_0_x86_64.whl" in opencvdiff --git a/tests/test_repository.py b/tests/test_repository.pyindex ca6c37e..e02c54f 100644--- a/tests/test_repository.py+++ b/tests/test_repository.py@@ -135,6 +135,23 @@ def test_derivation_subgraph_walks_the_derived_from_closure(repo):assert link_engine.derivation_subgraph(repo, "ghost") is None+def test_count_dependents_groups_incoming_edges_by_target(repo):+ capture = repo.add_entity("capture", "worked", {"lat": 50.4}, by="user")+ quiet = repo.add_entity("capture", "untouched", {"lat": 51.5}, by="user")+ photo = repo.add_entity("media", "photo", {"path": "media/x.jpg"}, by="user")+ for name in ("P1", "P2"):+ proof = repo.add_entity("proof", name, {"spec": f"proofs/{name}.json"}, by="user")+ repo.add_link(proof["id"], capture["id"], "derived-from", by="user")+ repo.add_link(photo["id"], capture["id"], "derived-from", by="user") # wrong source type+ post = repo.add_entity("post", "draft", {"draft": "exports/d.json"}, by="user")+ repo.add_link(post["id"], capture["id"], "mentions", by="user") # wrong link type++ counts = repo.count_dependents(link_type="derived-from", from_type="proof")+ assert counts == {capture["id"]: 2} # untouched targets are absent, not zero+ assert quiet["id"] not in counts+ assert repo.count_dependents(link_type="derived-from", from_type="post") == {}++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")@@ -170,8 +187,13 @@ def test_page_entities_walks_the_whole_catalog_in_order(repo):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")+ p = repo.add_entity(+ "person",+ "Ada Lovelace",+ {"folder": "Researchers", "notes": "analytical engine"},+ by="user",+ )+ account = 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"])@@ -182,6 +204,11 @@ def test_page_entities_filters_by_type_status_and_query(repo):hits = repo.page_entities(limit=50, query="lovelace") # case-insensitive label searchassert [e["id"] for e in hits["items"]] == [p["id"]]+ assert [e["id"] for e in repo.page_entities(query="analytical engine")["items"]] == [+ p["id"]+ ]+ assert [e["id"] for e in repo.page_entities(query="researchers")["items"]] == [p["id"]]+ assert [e["id"] for e in repo.page_entities(query="account")["items"]] == [account["id"]]def test_page_entities_cursor_is_stable_when_an_import_appends(repo):@@ -230,6 +257,20 @@ def test_page_entities_filters_by_folder_and_unfiled(repo):assert [e["id"] for e in unfiled["items"]] == [loose["id"]]+def test_page_entities_can_include_descendant_folders(repo):+ parent = repo.add_entity("media", "parent", {"folder": "Sources"}, by="user")+ child = repo.add_entity(+ "media", "child", {"folder": "Sources/Telegram"}, by="user"+ )+ repo.add_entity("media", "other", {"folder": "Research"}, by="user")++ exact = repo.page_entities(folder="Sources")+ recursive = repo.page_entities(folder="Sources", recursive=True)++ assert [e["id"] for e in exact["items"]] == [parent["id"]]+ assert [e["id"] for e in recursive["items"]] == [parent["id"], child["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")diff --git a/tests/test_satellite_api.py b/tests/test_satellite_api.pyindex e5fa2f8..0e34797 100644--- a/tests/test_satellite_api.py+++ b/tests/test_satellite_api.py@@ -1,11 +1,14 @@"""Satellite capture API: bearing is honored and persisted with provenance."""+import io+import pytestimport graph_readfrom PIL import Image-from azimut.engine import tiles+from azimut.api import satellite as satellite_api+from azimut.engine import geo, tilesdef _fake_tile(client, url): # offline: every tile is a solid green square@@ -741,3 +744,330 @@ def test_search_grids_are_not_entities(client):client.put(f"/api/cases/{cid}/search-grids/g", json=_rect_grid())# grids are working aids, filed under search/, never in the case graphassert graph_read.entities(cid) == []+++def test_capture_listing_carries_its_thumbnail_and_state(client, monkeypatch):+ # the proof panel pickers render this list in 150px cells: without a+ # thumbnail they would fall back to the full-size capture PNG.+ monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]+ client.post(+ f"/api/cases/{cid}/satellite/capture",+ json={"lat": 48.8584, "lon": 2.2945, "zoom": 16, "width": 640, "height": 480},+ )++ capture = client.get(f"/api/cases/{cid}/satellite").json()[0]+ assert capture["thumbnail"] and capture["thumbnail"] != capture["path"]+ assert capture["thumb_state"] == "ready"+++# -- saved index & the Locate backfill ------------------------------------------------+# The Saved panel navigates hundreds of items off one compact list. What must+# hold: the list carries every kind of saved work with the fields the tree, the+# search modal and the map overlay read; reading it never touches the network;+# and the geography behind it is filled in without a save ever blocking on it.+++def _address(payload):+ return lambda lat, lon, timeout=8, language=None: {+ "display_name": "x", "address": payload, "attribution": "x",+ }+++_UKRAINE = _address({"country_code": "ua", "country": "Ukraine", "state": "Donetsk Oblast"})+++def _index(client, cid):+ return client.get(f"/api/cases/{cid}/satellite/index").json()+++def test_index_lists_places_and_captures_newest_first(client, monkeypatch):+ monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]+ client.post(+ f"/api/cases/{cid}/satellite/place",+ json={"lat": 48.0159, "lon": 37.8029, "title": "checkpoint north", "notes": "two vehicles"},+ )+ cap = _capture(client, cid, 50.4501, 30.5234)++ rows = _index(client, cid)+ assert [r["kind"] for r in rows] == ["capture", "place"] # newest first++ capture, place = rows+ assert capture["path"] == cap["path"]+ assert capture["thumbnail"] and capture["thumbnail"] != capture["path"]+ assert capture["zoom"] == 16+ assert capture["provider"] == "Esri World Imagery"+ assert capture["lat"] == 50.4501++ assert place["title"] == "checkpoint north"+ assert place["notes"] == "two vehicles"+ assert place["path"] is None and place["thumbnail"] is None+ assert place["lat"] == 48.0159 and place["lon"] == 37.8029+++def test_index_carries_the_geography_and_derives_the_continent(client, monkeypatch):+ monkeypatch.setattr(geo, "reverse_geocode", _UKRAINE)+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]+ client.post(f"/api/cases/{cid}/satellite/place", json={"lat": 48.0159, "lon": 37.8029})++ row = _index(client, cid)[0]+ assert row["geo"] == {+ "state": "ok", "country_code": "ua", "country": "Ukraine", "region": "Donetsk Oblast",+ }+ # never stored, always derived — fixing the tables repairs old cases+ assert row["continent"] == "Europe"+ assert row["country_en"] == "Ukraine"+++def test_index_files_a_transcontinental_country_by_the_point(client, monkeypatch):+ # one country, two continents: the coordinates decide, not the country+ monkeypatch.setattr(+ geo, "reverse_geocode",+ _address({"country_code": "ru", "country": "Russia", "state": "Primorsky Krai"}),+ )+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]+ client.post(f"/api/cases/{cid}/satellite/place", json={"lat": 43.1155, "lon": 131.8855})+ client.post(f"/api/cases/{cid}/satellite/place", json={"lat": 55.7558, "lon": 37.6173})++ moscow, vladivostok = _index(client, cid)+ assert moscow["continent"] == "Europe"+ assert vladivostok["continent"] == "Asia"+++def test_index_names_the_country_in_english_beside_the_native_one(client, monkeypatch):+ # Nominatim answers in the local language; the English name is derived from+ # the code, so rows filed long before the tree spoke English gain it too+ monkeypatch.setattr(+ geo, "reverse_geocode",+ _address({"country_code": "ua", "country": "Україна", "state": "Донецька область"}),+ )+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]+ client.post(f"/api/cases/{cid}/satellite/place", json={"lat": 48.0159, "lon": 37.8029})++ row = _index(client, cid)[0]+ assert row["geo"]["country"] == "Україна"+ assert row["country_en"] == "Ukraine"+++def test_index_carries_the_my_work_folder(client, monkeypatch):+ """The saved-work modal browses by folder, so the index has to say which one+ each item is in — the capture reads its sidecar, the place its own attrs."""+ monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]+ cap = _capture(client, cid, 50.4501, 30.5234)+ client.patch(+ f"/api/cases/{cid}/satellite", json={"path": cap["path"], "folder": "recon/bridges"}+ )+ client.post(+ f"/api/cases/{cid}/satellite/place",+ json={"lat": 48.0159, "lon": 37.8029, "title": "checkpoint", "folder": "recon"},+ )+ client.post(f"/api/cases/{cid}/satellite/place", json={"lat": 48.02, "lon": 37.81})++ folders = {row["title"]: row["folder"] for row in _index(client, cid)}+ assert folders["checkpoint"] == "recon"+ assert folders["50.450100, 30.523400"] == "recon/bridges"+ assert folders["48.020000, 37.810000"] == "" # unfiled, never null+++def _proof(client, cid, title, *srcs):+ return client.post(+ f"/api/cases/{cid}/proofs",+ json={+ "title": title,+ "spec": {"panels": [{"id": f"p{i}", "src": s} for i, s in enumerate(srcs)]},+ },+ ).json()+++def test_index_counts_the_proofs_built_on_each_row(client, monkeypatch):+ """`All` shows every point once, so a worked capture is marked rather than+ doubled. The count is what the mark reads."""+ monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]+ worked = _capture(client, cid, 50.4501, 30.5234)+ _capture(client, cid, 48.8584, 2.2945) # untouched+ client.post(f"/api/cases/{cid}/satellite/place", json={"lat": 48.0159, "lon": 37.8029})+ _proof(client, cid, "First", worked["path"])+ _proof(client, cid, "Second", worked["path"])++ counts = {row["title"]: row["proofs"] for row in _index(client, cid)}+ assert counts["50.450100, 30.523400"] == 2+ assert counts["48.858400, 2.294500"] == 0 # never null, so the mark is a plain test+ assert counts["48.015900, 37.802900"] == 0+++def test_filing_a_capture_moves_the_entity_with_it(client, monkeypatch):+ monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]+ cap = _capture(client, cid, 48.8584, 2.2945)++ client.patch(f"/api/cases/{cid}/satellite", json={"path": cap["path"], "folder": "paris"})+ assert _captures(client, cid)[0]["attrs"]["folder"] == "paris"++ # a patch that says nothing about the folder leaves it where it was+ client.patch(f"/api/cases/{cid}/satellite", json={"path": cap["path"], "notes": "hangar"})+ assert _index(client, cid)[0]["folder"] == "paris"++ client.patch(f"/api/cases/{cid}/satellite", json={"path": cap["path"], "folder": ""})+ assert _index(client, cid)[0]["folder"] == ""+++def test_index_makes_no_network_call(client, monkeypatch):+ monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]+ _capture(client, cid, 48.8584, 2.2945)+ client.post(f"/api/cases/{cid}/satellite/place", json={"lat": 48.8584, "lon": 2.2945})++ def boom(*args, **kwargs):+ raise AssertionError("reading saved work must never touch the network")++ monkeypatch.setattr(geo.httpx, "get", boom)+ assert len(_index(client, cid)) == 2+++def test_index_reports_an_ingested_screenshot_as_its_own_kind(client):+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]+ token = client.post("/api/settings/ingest-token").json()["ingest_token"]+ buf = io.BytesIO()+ Image.new("RGB", (320, 200), (30, 90, 30)).save(buf, format="PNG")+ client.post(+ "/api/ingest/screenshot",+ files={"image": ("shot.png", buf.getvalue(), "image/png")},+ data={"url": "https://yandex.com/maps/?ll=37.8029,48.0159&z=17&l=sat", "case_id": cid},+ headers={"X-Azimut-Token": token},+ )++ row = _index(client, cid)[0]+ assert row["kind"] == "screenshot"+ assert row["site"] == "yandex-maps"+ # the way back to a site we cannot embed is the recorded URL itself+ assert row["source_url"].startswith("https://yandex.com/maps/")+++# -- geography on save ----------------------------------------------------------------+++def test_saving_resolves_the_country_before_it_answers(client, monkeypatch):+ # the item must land in the Saved panel already grouped, not appear under+ # Unlocated and jump elsewhere a moment later+ monkeypatch.setattr(geo, "reverse_geocode", _UKRAINE)+ monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]+ client.post(f"/api/cases/{cid}/satellite/place", json={"lat": 48.0159, "lon": 37.8029})+ _capture(client, cid, 48.0159, 37.8029)++ assert [r["geo"]["country"] for r in _index(client, cid)] == ["Ukraine", "Ukraine"]+++def test_the_save_lookup_is_bounded(client, monkeypatch):+ # a filed capture must never sit behind a slow geocoder: the save path asks+ # for a short timeout, the explicit backfill keeps the generous one+ seen = []+ monkeypatch.setattr(+ geo, "reverse_geocode",+ lambda lat, lon, timeout=8: seen.append(timeout) or _UKRAINE(lat, lon),+ )+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]+ client.post(f"/api/cases/{cid}/satellite/place", json={"lat": 48.0159, "lon": 37.8029})+ assert seen == [satellite_api.SAVE_LOOKUP_TIMEOUT]+ assert satellite_api.SAVE_LOOKUP_TIMEOUT < 8+++def test_a_save_succeeds_when_the_lookup_fails(client, monkeypatch):+ # the conftest fixture already has Nominatim unreachable — saving is local+ monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]+ assert client.post(+ f"/api/cases/{cid}/satellite/place", json={"lat": 48.0159, "lon": 37.8029}+ ).status_code == 200+ _capture(client, cid, 48.0159, 37.8029)++ assert [r["geo"] for r in _index(client, cid)] == [{"state": "failed"}, {"state": "failed"}]++ # …and a later Locate pass resolves what the failure left behind+ monkeypatch.setattr(geo, "reverse_geocode", _UKRAINE)+ assert client.post(f"/api/cases/{cid}/satellite/locate").json() == {+ "located": 2, "failed": 0, "remaining": 0,+ }+ assert {r["geo"]["country"] for r in _index(client, cid)} == {"Ukraine"}+++def test_a_screenshot_without_coordinates_is_never_looked_up(client, monkeypatch):+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]+ token = client.post("/api/settings/ingest-token").json()["ingest_token"]+ buf = io.BytesIO()+ Image.new("RGB", (320, 200), (30, 90, 30)).save(buf, format="PNG")+ client.post(+ "/api/ingest/screenshot",+ files={"image": ("shot.png", buf.getvalue(), "image/png")},+ data={"url": "https://www.openstreetmap.org/", "case_id": cid},+ headers={"X-Azimut-Token": token},+ )++ row = _index(client, cid)[0]+ assert row["lat"] is None+ assert row["geo"] == {"state": "nocoords"}++ def boom(lat, lon, timeout=8):+ raise AssertionError("a point with no coordinates has nothing to look up")++ monkeypatch.setattr(geo, "reverse_geocode", boom)+ assert client.post(f"/api/cases/{cid}/satellite/locate").json()["remaining"] == 0+++# -- the Locate backfill ---------------------------------------------------------------+++def _places_at(client, cid, count):+ for i in range(count):+ client.post(+ f"/api/cases/{cid}/satellite/place", json={"lat": 48.0 + i / 100, "lon": 37.8}+ )+++def test_locate_works_through_the_backlog_and_reports_what_is_left(client, monkeypatch):+ monkeypatch.setattr(satellite_api, "NOMINATIM_INTERVAL", 0)+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]+ _places_at(client, cid, 5) # all saved offline → all failed++ monkeypatch.setattr(geo, "reverse_geocode", _UKRAINE)+ first = client.post(f"/api/cases/{cid}/satellite/locate", params={"limit": 2}).json()+ assert first == {"located": 2, "failed": 0, "remaining": 3}++ second = client.post(f"/api/cases/{cid}/satellite/locate", params={"limit": 25}).json()+ assert second == {"located": 3, "failed": 0, "remaining": 0}+ # settled items are never looked up again — re-running is a no-op+ assert client.post(f"/api/cases/{cid}/satellite/locate").json() == {+ "located": 0, "failed": 0, "remaining": 0,+ }+++def test_locate_leaves_a_failure_for_the_next_pass(client, monkeypatch):+ monkeypatch.setattr(satellite_api, "NOMINATIM_INTERVAL", 0)+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]+ _places_at(client, cid, 2)++ assert client.post(f"/api/cases/{cid}/satellite/locate").json() == {+ "located": 0, "failed": 2, "remaining": 2,+ }+++def test_locate_settles_open_sea_without_retrying_it(client, monkeypatch):+ monkeypatch.setattr(satellite_api, "NOMINATIM_INTERVAL", 0)+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]+ client.post(f"/api/cases/{cid}/satellite/place", json={"lat": 0.0, "lon": -30.0})++ monkeypatch.setattr(geo, "reverse_geocode", _address({}))+ assert client.post(f"/api/cases/{cid}/satellite/locate").json() == {+ "located": 1, "failed": 0, "remaining": 0,+ }+ assert _index(client, cid)[0]["geo"] == {"state": "nocountry"}+ assert _index(client, cid)[0]["continent"] is None+++def test_locate_clamps_its_batch_size(client):+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]+ assert client.post(f"/api/cases/{cid}/satellite/locate", params={"limit": 26}).status_code == 422+ assert client.post(f"/api/cases/{cid}/satellite/locate", params={"limit": 0}).status_code == 422diff --git a/tests/test_sqlite_backend.py b/tests/test_sqlite_backend.pyindex c466d10..353e2e3 100644--- a/tests/test_sqlite_backend.py+++ b/tests/test_sqlite_backend.py@@ -11,6 +11,7 @@ that must never leave a half-built database or touch the legacy `case.json`.from __future__ import annotationsimport sqlite3+import threadingimport pytestfrom bigcase import build_big_case@@ -142,13 +143,13 @@ INSERT INTO entities(id, type, label, attrs_json, prov_by, prov_at)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."""+ column is added and backfilled (1->2), the jobs table is created (2->3), and+ search/media browse indexes arrive in schema 4. A second open 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+ store = SqliteCase.open(db) # runs 1 -> 2 -> 3 -> 4 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"]@@ -157,20 +158,139 @@ def test_open_upgrades_a_v1_db_through_every_migration(tmp_path):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"+ assert conn.execute("SELECT value FROM meta WHERE key='schema_version'").fetchone()[0] == "4"applied = {r[0] for r in conn.execute("SELECT version FROM schema_migrations").fetchall()}- assert {2, 3} <= applied+ assert {2, 3, 4} <= applied+ columns = {+ row[1] for row in conn.execute("PRAGMA table_info(entities)").fetchall()+ }+ assert "search_text" in columns+ assert conn.execute(+ "SELECT value FROM meta WHERE key='media_index_ready'"+ ).fetchone()[0] == "1"SqliteCase.open(db) # idempotent — the second open applies nothingwith sqlite3.connect(db) as conn:- for version in (2, 3):+ for version in (2, 3, 4):assert conn.execute("SELECT COUNT(*) FROM schema_migrations WHERE version = ?", (version,)).fetchone()[0] == 1+def test_media_browse_index_pages_searches_and_counts_categories(tmp_path):+ store = SqliteCase.create(tmp_path / "case.db", name="Media index")+ store.upsert_media_item(+ {+ "path": "media/photo.png",+ "filename": "photo.png",+ "kind": "image",+ "size": 12,+ "added_at": "2026-01-01T00:00:00Z",+ "title": "Bridge",+ "notes": "river crossing",+ "folder": "Sources",+ "source": {"type": "upload"},+ },+ entity_id="e_photo",+ )+ store.upsert_media_item(+ {+ "path": "media/map.png",+ "filename": "map.png",+ "kind": "image",+ "size": 30,+ "added_at": "2026-01-02T00:00:00Z",+ "source": {"type": "satellite"},+ },+ entity_id="e_map",+ )+ store.upsert_media_item(+ {+ "path": "media/clip.mp4",+ "filename": "clip.mp4",+ "kind": "video",+ "size": 50,+ "added_at": "2026-01-03T00:00:00Z",+ "source": {"type": "download"},+ },+ entity_id="e_clip",+ )++ first = store.page_media_items(limit=2)+ assert [item["path"] for item in first["items"]] == [+ "media/clip.mp4",+ "media/map.png",+ ]+ assert first["next_cursor"] == "2"+ assert first["facets"]["category_counts"] == {+ "image": 1,+ "video": 1,+ "collage": 0,+ "satellite": 1,+ "upload": 1,+ "download": 1,+ "other": 0,+ }++ hit = store.page_media_items(q="bridge river", category="image")+ assert [item["path"] for item in hit["items"]] == ["media/photo.png"]+ assert hit["facets"]["folder_counts"] == {"Sources": 1}+ assert store.page_media_items(category="satellite")["total"] == 1+ assert store.media_items_by_paths(+ ["media/map.png", "media/photo.png", "media/missing.png"]+ ) == [+ store.page_media_items(category="satellite")["items"][0],+ store.page_media_items(q="bridge")["items"][0],+ ]+++def test_concurrent_first_open_cannot_replace_registered_media_rows(tmp_path):+ db = tmp_path / "case.db"+ SqliteCase.create(db, name="Concurrent index")+ media_dir = tmp_path / "media"+ media_dir.mkdir()+ for i in range(8):+ name = f"item-{i}.png"+ (media_dir / name).write_bytes(bytes([i]))+ (media_dir / f"{name}.azimut.json").write_text(+ (+ '{"filename": "%s", "kind": "image", "size": 1,'+ ' "added_at": "2026", "source": {"type": "upload"}}'+ )+ % name,+ encoding="utf-8",+ )++ errors: list[BaseException] = []++ def open_and_register(i: int) -> None:+ try:+ store = SqliteCase.open(db)+ store.upsert_media_item(+ {+ "path": f"media/live-{i}.png",+ "filename": f"live-{i}.png",+ "kind": "image",+ "size": 1,+ "added_at": "2026",+ "source": {"type": "upload"},+ }+ )+ except BaseException as exc: # pragma: no cover - asserted below+ errors.append(exc)++ workers = [threading.Thread(target=open_and_register, args=(i,)) for i in range(8)]+ for worker in workers:+ worker.start()+ for worker in workers:+ worker.join()++ assert errors == []+ assert len(SqliteCase.open(db).list_media_items()) == 16++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 rowbetween page fetches never makes the next page skip a live entity."""diff --git a/tests/test_vendor_ffmpeg.py b/tests/test_vendor_ffmpeg.pynew file mode 100644index 0000000..30e97fe--- /dev/null+++ b/tests/test_vendor_ffmpeg.py@@ -0,0 +1,143 @@+"""Tests for integrity-checked ffmpeg release vendoring."""++from __future__ import annotations++import hashlib+import importlib.util+import json+import os+import zipfile+from pathlib import Path++import pytest+++SCRIPT = Path(__file__).parents[1] / "scripts" / "vendor_ffmpeg.py"+SPEC = importlib.util.spec_from_file_location("azimut_vendor_ffmpeg", SCRIPT)+assert SPEC is not None and SPEC.loader is not None+vendor_ffmpeg = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(vendor_ffmpeg)+++def _zip(path: Path, members: dict[str, bytes]) -> str:+ with zipfile.ZipFile(path, "w") as archive:+ for name, payload in members.items():+ archive.writestr(name, payload)+ return hashlib.sha256(path.read_bytes()).hexdigest()+++def test_vendor_verifies_and_extracts_exact_members(tmp_path, monkeypatch):+ ffmpeg_archive = tmp_path / "ffmpeg.zip"+ ffprobe_archive = tmp_path / "ffprobe.zip"+ ffmpeg_hash = _zip(+ ffmpeg_archive,+ {+ "bundle/bin/ffmpeg": b"ffmpeg",+ "bundle/README.txt": b"ignored",+ },+ )+ ffprobe_hash = _zip(+ ffprobe_archive,+ {+ "bundle/bin/ffprobe": b"ffprobe",+ "bundle/LICENSE.txt": b"ignored",+ },+ )+ monkeypatch.setitem(+ vendor_ffmpeg.ARTIFACTS,+ "test",+ (+ vendor_ffmpeg.Archive(+ "Fixture",+ "1",+ ffmpeg_archive.as_uri(),+ ffmpeg_hash,+ (("bundle/bin/ffmpeg", "ffmpeg"),),+ ),+ vendor_ffmpeg.Archive(+ "Fixture",+ "1",+ ffprobe_archive.as_uri(),+ ffprobe_hash,+ (("bundle/bin/ffprobe", "ffprobe"),),+ ),+ ),+ )++ output = tmp_path / "vendor"+ provenance = vendor_ffmpeg.vendor("test", output)++ assert (output / "ffmpeg").read_bytes() == b"ffmpeg"+ assert (output / "ffprobe").read_bytes() == b"ffprobe"+ if os.name != "nt":+ assert (output / "ffmpeg").stat().st_mode & 0o111+ assert provenance["target"] == "test"+ assert json.loads((output / "ffmpeg-provenance.json").read_text()) == provenance+++def test_vendor_rejects_a_bad_digest_without_installing_tools(tmp_path, monkeypatch):+ archive_path = tmp_path / "ffmpeg.zip"+ _zip(archive_path, {"ffmpeg": b"payload"})+ monkeypatch.setitem(+ vendor_ffmpeg.ARTIFACTS,+ "test",+ (+ vendor_ffmpeg.Archive(+ "Fixture",+ "1",+ archive_path.as_uri(),+ "0" * 64,+ (("ffmpeg", "ffmpeg"),),+ ),+ ),+ )++ output = tmp_path / "vendor"+ with pytest.raises(RuntimeError, match="SHA-256 mismatch"):+ vendor_ffmpeg.vendor("test", output)++ assert not (output / "ffmpeg").exists()+++def test_vendor_rejects_duplicate_tool_members_outside_the_allowlist(+ tmp_path,+ monkeypatch,+):+ archive_path = tmp_path / "ffmpeg.zip"+ digest = _zip(+ archive_path,+ {+ "expected/ffmpeg": b"expected",+ "unexpected/ffmpeg": b"unexpected",+ },+ )+ monkeypatch.setitem(+ vendor_ffmpeg.ARTIFACTS,+ "test",+ (+ vendor_ffmpeg.Archive(+ "Fixture",+ "1",+ archive_path.as_uri(),+ digest,+ (("expected/ffmpeg", "ffmpeg"),),+ ),+ ),+ )++ with pytest.raises(RuntimeError, match="archive member mismatch"):+ vendor_ffmpeg.vendor("test", tmp_path / "vendor")+++def test_release_artifacts_are_pinned_and_have_sha256_digests():+ assert set(vendor_ffmpeg.ARTIFACTS) == {+ "windows-x86_64",+ "linux-x86_64",+ "macos-arm64",+ }+ for archives in vendor_ffmpeg.ARTIFACTS.values():+ for archive in archives:+ assert "/latest/" not in archive.url+ assert "/redirect/" not in archive.url+ assert len(archive.sha256) == 64+ assert set(archive.sha256) <= set("0123456789abcdef")