The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.
JavaScript
Import enrichment, and relations between entities (#39)
OsintMeThat55893374d8fc
diff --git a/docs/ONTOLOGY.md b/docs/ONTOLOGY.mdindex 83ff495..74a00c3 100644--- a/docs/ONTOLOGY.md+++ b/docs/ONTOLOGY.md@@ -2,12 +2,13 @@> This is the filing contract for every tool and the detailed companion to> [SPEC.md §5](SPEC.md). Extend and version it only when implemented tools need-> new vocabulary. Nothing enters a case without analyst confirmation.+> new vocabulary. Tool proposals enter as `suggested` and remain distinct from+> analyst-confirmed findings.**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 manifest schema bump and migration. The internal SQLite schema is version 4;+a manifest schema bump and migration. The internal SQLite schema is version 5;it adds search and media browse indexes without changing this logical model.Legend: ✅ implemented in code · 🔶 machinery exists, unused · ⬜ proposed.@@ -27,9 +28,12 @@ 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. A- SQLite browse index mirrors searchable fields. Entities retain only what the- graph needs for identity, links and deduplication.+- Media sidecars hold kind, size, uploader, duration, thumbnail data, image EXIF+ and perceptual hashes, plus ffprobe's video container and stream metadata. A+ stated position lands on one field, `gps`, whichever of the two read it. A+ SQLite browse index mirrors searchable fields, plus whether that position+ exists. Entities retain only what the graph needs for identity, links and+ deduplication.## 2. Entity@@ -60,7 +64,7 @@ read time, so extending those tables repairs existing cases with no migration.|---|---|---|---|---|| `media` | ✅ | media-library | `path`, `sha256`, `source_url?` | yes (+ sidecar) || `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) |+| `place` | ✅ | satellite, ingest, enrich | `coords`, `lat`, `lon`, `plus_code`, `zoom`, `bearing`, `notes?`, `geo?`, `source_url?`, `site?`, `enrich_coord_key?` | no (a point) || `proof` | ✅ | proof-composer | `spec` (json), `path` (png) | yes || `post` | ✅ | post-composer | `draft` (json) | yes || `inspect-session` | ✅ | inspect | `spec` (json) | yes |@@ -100,8 +104,10 @@ incident links. The link type decides whether dependent entities also disappear.|---|---|---|---|| `derived-from` | artifact → source | made from that, and outlives it | ✅ || `depends-on` | session → subject | only a pointer at that: dies with it | ✅ |-| `located-at` | media/proof/event → place | happened / shot at this point | ⬜ |-| `depicts` / `appears-in` | media → place/vehicle/person | subject shown in the media | ⬜ |+| `located-at` | media/capture → place | shot at this point | ✅ |+| `depicts` | media/capture → place | the place is shown in the file | ✅ |+| `same-image-as` | media → media | perceptual hashes are within 10 bits | ✅ |+| `appears-in` | media → vehicle/person | subject shown in the media | ⬜ || `same-as` | entity → entity | two records, one real thing (merge) | ⬜ || `owns` | person/org → account/asset | ownership | ⬜ || `posted` | account → media/post | authorship | ⬜ |@@ -135,9 +141,49 @@ A tool selects one of two deletion behaviours through its link type:lists cascading deletions and surviving outputs before the action.- Losing a secondary source leaves a placeholder. Only losing the subject caninvalidate a dependent session.+- Relations are not chain types. Deleting either endpoint removes the edge but+ never cascades and never leaves a tombstone: a claim nobody has looked at must+ not decide what a delete destroys.+- Exact-byte duplicates never produce `same-image-as`: import deduplicates them+ on SHA-256 before perceptual hashing runs.-Free-typed labels remain valid. The registry defines what the UI understands,-not a closed list.+Free-typed labels remain valid in stored data. The registry defines what the UI+understands and what the API will mint, not what a case may hold.++### Relations++Everything outside the two chain types is a **relation**: a statement about the+world rather than about how a file was produced. `engine/links.py` holds the one+registry — how each type reads in words, the entity types either end accepts, and+whether an analyst may state it — and `GET /api/cases/relation-types` serves it to+every surface, so the vocabulary is never copied per screen.++| | Chain (`derived-from`, `depends-on`) | Relation (`located-at`, `depicts`, …) |+|---|---|---|+| Says | how the file was made | what is true of the subject |+| Written by | the save that produced the artifact | enrichment, or the analyst |+| Status | always `confirmed` | `suggested` from a tool, `confirmed` by hand |+| Delete | cascades or tombstones | drops the edge, nothing else |++- A relation stated by hand is `confirmed` and validated against the registry: the+ API refuses a chain type, an unregistered type, a self-link, and any pair of+ endpoint types the table above has no reading for.+- **Relations stay editable.** Add one, correct its reading, or take it back at any+ time, from any surface that shows them. Correcting the reading keeps the edge —+ same id, same provenance — because the two entities were always related and only+ the verb was wrong; the same validation applies, plus a refusal to collapse onto+ a relation the pair already holds. Removal is one gesture whatever the status:+ dismissing a proposal and retracting an accepted statement are the same act on+ the graph, and a statement that cannot be taken back is a trap. A chain edge is+ refused there too — dropping a derivation behind the relation path would lose it+ without the tombstone the delete rules depend on.+- `same-image-as` is registered but **machine-only**. It is a claim about+ perceptual hashes, which is enrichment's to make; a person comparing two+ pictures is not measuring a hash. It is also narrower than `same-as`: two files+ showing the same pixels, never one merged graph identity.+- Where they appear: the Details panel, the map popup, and the case board next.+ One component renders all three (`RelationList.svelte`), one collects a new one+ (`RelationPicker.svelte`).### The derivation chain@@ -175,13 +221,30 @@ How it is wired (`engine/links.py`):(UTC), `status` and optional source URL. It borrows the entity/activity/agentshape of W3C PROV without implementing the full standard.- **Confidence** = `status`: `confirmed` (analyst-made or analyst-accepted) vs- `suggested` (a tool proposed it, awaiting a click). 🔶 `suggested` has no- producer yet. The sidebar and PATCH validator exist, but no tool emits it until- the v3 EXIF/OCR tools land. Keep the status binary until a real workflow needs- finer grading. ✅+ `suggested` (a tool proposed it, awaiting a click). Import enrichment emits+ suggested places and `located-at` / `same-image-as` links from image or video+ metadata.+ Keep the status binary until a real workflow needs finer grading. ✅+ Confirming a suggested entity confirms its incident suggested relations *and the+ entity at each far end*; a relation is also confirmed or dismissed on its own,+ from Details, from the point's own card on the map, or from the dialog that edits+ it. Confirming a relation likewise confirms whichever endpoint is still+ `suggested`. Both directions carry one rule — "this file was shot at this point"+ cannot be true while the point is only proposed — and without both, the+ Suggestions list and the relation rows would disagree about the same click. The+ spread stops at one hop: accepting a photo's own point is a reading of that+ photo, not a licence to accept whatever else that point was separately proposed+ to be. Dismissing is not the reverse — the edge goes, the entities stay, because+ a place can be real while one file's claim about it is wrong. A dismissal also+ sticks: re-reading a file refreshes its facts without re-proposing edges it has+ already been through, so the Enrich button never undoes a triage. Anything still `suggested` is marked as such+ wherever it appears — a proposed place reads as a proposal in the Saved tree and+ in its card, never as work the analyst did.**A derivation is `confirmed`**: `derived-from`/`depends-on` record what theanalyst's own click just made, not what a tool inferred. `suggested` is for- inference, such as OCR reading a street name or EXIF proposing a `place`.+ inference, such as OCR reading a street name or EXIF proposing a `place`. A+ relation stated by hand is `confirmed` for the same reason: there is nothing+ left to review.- **`same-as` / merge** (⬜ open, SPEC §10): when two entities are one real thing,link `same-as` rather than destructively merging; a resolver treats a `same-as`cluster as one node in views and unions its attributes and links. Collapse rulesdiff --git a/docs/SPEC.md b/docs/SPEC.mdindex 4288fe5..d6bfbe7 100644--- a/docs/SPEC.md+++ b/docs/SPEC.md@@ -113,9 +113,10 @@ proof for publication.| ✅ **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. |+| ✅ **Import enrichment** | Reads image EXIF/dHash and video container/stream metadata locally in the background; parsed GPS produces linked Suggestions and all fields appear in Details. |+| ✅ **GPS in Media** | A GPS filter and a per-row pin in the Media list send a stated position to the map, images and videos alike. |+| ✅ **Relation vocabulary** | One registry for the non-chain edges, stated or settled from Details and from a point's card on the map. |---@@ -132,9 +133,7 @@ Each version delivers one complete daily workflow. Firm ideas move here from|------|--------------|| **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 Board / Relations** | Browses, creates and merges entities; graph view over the schema filled since v1, on the shipped relation vocabulary. || **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. |@@ -148,13 +147,13 @@ 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. |+| **Metadata follow-up** | Explains which common image/video fields were stripped and proposes events from capture times. || **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. |+| **OCR** | Reads signs and plates on import (tesseract, a native binary rather than a wheel), and detects script and 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. |diff --git a/docs/STORAGE_AND_PERFORMANCE.md b/docs/STORAGE_AND_PERFORMANCE.mdindex a1405dd..71fe317 100644--- a/docs/STORAGE_AND_PERFORMANCE.md+++ b/docs/STORAGE_AND_PERFORMANCE.md@@ -109,7 +109,7 @@ review.## Database shape-`case.db` is at SQLite schema 4. The schema counter is independent of the JSON+`case.db` is at SQLite schema 5. 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.@@ -143,8 +143,17 @@ format counts its own shape upgrades.`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.+ kind, folder, display name, size, date, source, imagery mode, the media entity+ it belongs to and whether the file states a position (`has_gps`). The+ coordinates themselves travel in the mirrored sidecar JSON and need no column;+ presence does, because "only the files that carry a position" has to filter over+ the whole case rather than over the page the client holds. Enrichment's full+ metadata dumps (`exif`, `video_metadata` — hundreds of rows per file) are the+ one thing the mirror leaves out: this index is read 200 rows at a time by the+ grid and whole by the pickers, and one fat field would multiply every one of+ those responses. A surface showing a single file reads it from the sidecar+ through `GET /api/cases/{id}/media/item`. The original files and sidecars remain+ the file-level records.### Indexes and migrations@@ -154,8 +163,10 @@ job from being enqueued twice. `SqliteCase.open` upgrades an older `case.db` inthrough `_SQLITE_MIGRATIONS`, each step in its own immediate transaction, re-readingthe version inside the transaction so a raced second opener applies nothing; anewer 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).+indexed `folder` column (1→2), the `jobs` table (2→3), entity search text and+the media browse index (3→4), then the `has_gps` flag (4→5). The 4→5 backfill+reads the sidecar JSON already held in each index row, so a case enriched before+the column existed gains its position filter on open with no file scan.The schema-4 media backfill scans sidecars once on first open. Its completionmarker and index rows commit together, so an interrupted backfill retries safely.diff --git a/docs/UI.md b/docs/UI.mdindex 9593062..aeb2b95 100644--- a/docs/UI.md+++ b/docs/UI.md@@ -20,7 +20,7 @@ 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, Edit Provenance, Shot contact sheet, OCR, Image Compare, Hints, Shadow Clock, audio |+| **Examine** | Inspect (Selection / Frame / Collage / Analyze) | 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 | v2: Relations, Sheet; v4: Notes, Timeline; v5: Orchestrator |@@ -68,7 +68,37 @@ remembered per workspace for the current session. Reloading restores the defaultso selecting a row never pushes the case out of view. It edits an artifact'spreview, title, notes, provenance, derivation chain and folder, and providesopen, locate and delete actions. The sidebar and Media Library modal share- `EntityDetails.svelte`.+ `EntityDetails.svelte`. Image Details include a closed EXIF section with the+ parsed capture date, GPS and every readable tag. Video Details use the same+ pattern for local ffprobe container, stream and tag fields.++## Relations++Relations (ONTOLOGY §3) render through one component wherever they appear — the+Details panel, the point's card on the map, and the case board next. One row per+relation: the neighbour, how the edge reads in words, and, while it is only+suggested, confirm. Any row can be taken back, whatever its status. Where the pair+reads more than one way the verb is a select, so a wrong reading is corrected in+place instead of deleted and restated. A neighbour that carries a point offers the+map, because confirming "shot here" without seeing where is signing blind. Past six+rows the list hides the rest behind one click, suggestions first.++Stating one is a second component: pick the other entity from a bounded search of+the types the vocabulary accepts, then the reading if the pair allows more than+one. Details files it with Save; Satellite's Save-place dialog files it once the+place exists. Both dialogs show the existing relations above the picker, so+nowhere can a relation be added but not removed.++## Sources++The Media Library toolbar keeps explicit maintenance actions beside Import:+**Thumbnails** repairs missing previews; **Enrich** queues local image+EXIF/perceptual-hash and video metadata backfill for files not processed by the+current version. A **GPS** toggle beside the type and folder filters narrows the+list to the files whose own metadata states a position, and appears only in a case+that holds some; how many is in its tooltip, not in its label. Those rows carry+one pin glyph — coordinates in the tooltip, not in the title — and clicking it+flies the map there.## Map@@ -109,9 +139,9 @@ The `…` button beside the filter opens the same set at full width, with previesearch across title, note, place and provider, and three sorts. It is a modal, soit 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.+Editing a place or a capture (**Edit** on any row) sets its title, note, relation+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, referenceimage) float top-left. **View** — fullscreen, OSM labels, saved work — continues@@ -127,6 +157,15 @@ fit directly in the card; additional posts expand in place, and selecting oneopens its draft in Geo Report. Hovering a card, a tree row or a search resultlights the others.+A card also holds the point's relations. The Saved index carries their count only,+so a stack of five marks is never five requests: a lone mark opens its relations+straight away — clicking a place to see which photos claim it is the point of the+gesture — and a stack waits to be asked. A point enrichment proposed from a file's+metadata is marked `suggested` in both the card and the tree, so a camera's reading+never passes for analyst work. The Save-place dialog carries the matching write:+one **Relate to…** field says why the point is being saved while the analyst still+knows.+## Geo ProofA proof is composed of panels: case images, each carrying its source. Two thingsdiff --git a/frontend/e2e/app.fixture.js b/frontend/e2e/app.fixture.jsindex 953ff9f..d611add 100644--- a/frontend/e2e/app.fixture.js+++ b/frontend/e2e/app.fixture.js@@ -58,6 +58,13 @@ const settings = {month: '2026-07',};+// The relation vocabulary as engine/links.py serves it (ONTOLOGY §3).+const relationTypes = [+ { type: 'located-at', label: 'was shot at', from_types: ['capture', 'media'], to_types: ['place'], manual: true },+ { type: 'depicts', label: 'shows', from_types: ['capture', 'media'], to_types: ['place'], manual: true },+ { type: 'same-image-as', label: 'is the same picture as', from_types: ['media'], to_types: ['media'], manual: false },+];+const providers = [{id: 'esri-world-imagery',label: 'Esri World Imagery',@@ -91,6 +98,10 @@ export async function installAppFixture(page, options = {}) {const savedIndexDelays = options.savedIndexDelays ?? {};const proofIndexDelays = options.proofIndexDelays ?? {};const fixtureDrafts = options.drafts ?? {};+ // Relations, keyed by entity id: what the bounded chain endpoint answers for+ // the row whose relations a surface asked for.+ const fixtureChains = options.chains ?? {};+ const linkWrites = [];await page.addInitScript((caseId) => {localStorage.setItem('azimut:lastCase', caseId);@@ -126,6 +137,7 @@ export async function installAppFixture(page, options = {}) {}if (path === '/api/settings') return json(route, settings);if (path === '/api/templates') return json(route, { proof: [], post: [] });+ if (path === '/api/cases/relation-types') return json(route, relationTypes);if (path === '/api/cases') {return json(route, fixtureCases.map((item) => ({ entity_count: 1, ...item })));}@@ -151,7 +163,28 @@ export async function installAppFixture(page, options = {}) {return json(route, { items: [], next_cursor: null });}if (caseId && path === `/api/cases/${caseId}/search-grids`) return json(route, []);+ const chainMatch = caseId && path.match(new RegExp(`^/api/cases/${caseId}/entities/(.+)/chain$`));+ if (chainMatch) {+ const chain = fixtureChains[chainMatch[1]];+ return json(route, chain ?? { entity: null, sources: [], lost: [], dependents: [], relations: [], empty: true });+ }+ const linkMatch = caseId && path.match(new RegExp(`^/api/cases/${caseId}/links(?:/(.+))?$`));+ if (linkMatch && request.method() !== 'GET') {+ linkWrites.push({+ method: request.method(),+ id: linkMatch[1] ?? null,+ body: request.method() === 'DELETE' ? null : request.postDataJSON(),+ });+ return json(route, request.method() === 'DELETE' ? { status: 'deleted' } : { id: 'link-new' });+ }if (path === `/api/cases/${CASE_ID}/media`) return json(route, media);+ // One media file with everything its sidecar holds. The browse index leaves+ // enrichment's metadata dumps out, so the Details panel reads a file at a time.+ if (path === `/api/cases/${CASE_ID}/media/item`) {+ const wanted = url.searchParams.get('path');+ const found = media.find((item) => item.path === wanted);+ return found ? json(route, found) : route.fulfill({ status: 404, body: '{}' });+ }// 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.@@ -204,6 +237,7 @@ export async function installAppFixture(page, options = {}) {return {captures,proofSaves,+ linkWrites,expectNoUnexpectedRequests: () => expect(unexpected).toEqual([]),};}diff --git a/frontend/e2e/saved-relations.spec.js b/frontend/e2e/saved-relations.spec.jsnew file mode 100644index 0000000..6766019--- /dev/null+++ b/frontend/e2e/saved-relations.spec.js@@ -0,0 +1,143 @@+import { test, expect } from '@playwright/test';+import { CASE_ID, installAppFixture } from './app.fixture.js';++/**+ * Relations on the map, in a real Leaflet popup.+ *+ * The popup is the one surface where a click has somewhere else to go: Leaflet+ * closes a popup when a click reaches the map, and the card's own controls edit+ * only the card. Rendering it server-side cannot tell us whether that holds, so+ * these run in the browser.+ */++const point = {+ lat: 48.8584,+ lon: 2.2945,+ geo: { state: 'ok', country_code: 'fr', country: 'France' },+ continent: 'Europe',+ country_en: 'France',+};++const photo = { id: 'media-1', type: 'media', label: 'roadside photo', attrs: { path: 'media/panel.svg' } };++/** Two places at one point, so the marks collapse into a single counted mark. */+const stack = [+ {+ id: 'place-1',+ key: 'place-1',+ kind: 'place',+ title: 'checkpoint north',+ fetched_at: '2026-07-24T09:00:00Z',+ relations: 1,+ status: 'suggested',+ ...point,+ },+ {+ id: 'place-2',+ key: 'place-2',+ kind: 'place',+ title: 'checkpoint south',+ fetched_at: '2026-07-24T08:00:00Z',+ relations: 0,+ status: 'confirmed',+ ...point,+ },+];++const suggestedChain = {+ entity: { id: 'place-1', type: 'place', label: 'checkpoint north', attrs: point },+ sources: [],+ lost: [],+ dependents: [],+ relations: [+ {+ entity: photo,+ direction: 'in',+ link: {+ id: 'link-1',+ from: 'media-1',+ to: 'place-1',+ type: 'located-at',+ provenance: { by: 'enrich', at: '2026-07-24T09:00:00Z', status: 'suggested' },+ },+ },+ ],+ empty: false,+};++test('opens a stacked row’s relations without closing the card', async ({ page }) => {+ const fixture = await installAppFixture(page, {+ savedIndex: stack,+ chains: { 'place-1': suggestedChain },+ });++ await page.goto('/#satellite');+ await expect(page.locator('.map')).toHaveClass(/leaflet-container/);+ await page.getByRole('button', { name: 'Show saved work on the map' }).click();+ await page.locator('.saved-mark').click();++ const popup = page.locator('.saved-popup');+ await expect(popup.getByText('2 saved here')).toBeVisible();+ // a stack waits to be asked: five marks must not mean five fetches+ await expect(popup.getByText('roadside photo')).toHaveCount(0);++ await popup.getByRole('button', { name: '1 relation' }).click();++ await expect(popup).toBeVisible();+ // the card fetches its edges behind the click, so give that read its own window+ await expect(popup.getByText('roadside photo')).toBeVisible({ timeout: 15000 });+ await expect(popup.locator('select')).toHaveValue('located-at');+ fixture.expectNoUnexpectedRequests();+});++test('corrects the reading of a relation in place, and takes one back', async ({ page }) => {+ const fixture = await installAppFixture(page, {+ savedIndex: [stack[0]],+ chains: { 'place-1': suggestedChain },+ });++ await page.goto('/#satellite');+ await expect(page.locator('.map')).toHaveClass(/leaflet-container/);+ await page.getByRole('button', { name: 'Show saved work on the map' }).click();+ await page.locator('.saved-mark').click();++ const popup = page.locator('.saved-popup');+ await expect(popup.getByText('roadside photo')).toBeVisible({ timeout: 15000 });++ // the wrong verb is corrected on the same edge, not deleted and restated+ await popup.locator('select').selectOption('depicts');+ await expect(popup).toBeVisible();++ await popup.getByTitle('Dismiss this relation').click();++ expect(fixture.linkWrites).toEqual([+ { method: 'PATCH', id: 'link-1', body: { type: 'depicts' } },+ { method: 'DELETE', id: 'link-1', body: null },+ ]);+ fixture.expectNoUnexpectedRequests();+});++test('settles a suggested relation from the card, which survives the click', async ({ page }) => {+ const fixture = await installAppFixture(page, {+ savedIndex: [stack[0]],+ chains: { 'place-1': suggestedChain },+ });++ await page.goto('/#satellite');+ await expect(page.locator('.map')).toHaveClass(/leaflet-container/);+ await page.getByRole('button', { name: 'Show saved work on the map' }).click();+ await page.locator('.saved-mark').click();++ const popup = page.locator('.saved-popup');+ // a lone mark opens its relations straight away+ await expect(popup.getByText('roadside photo')).toBeVisible({ timeout: 15000 });+ await expect(popup.getByText('suggested')).toBeVisible();++ await popup.getByTitle('Confirm this relation').click();++ await expect(popup).toBeVisible();+ expect(fixture.linkWrites).toEqual([+ { method: 'PATCH', id: 'link-1', body: { status: 'confirmed' } },+ ]);+ fixture.expectNoUnexpectedRequests();+});diff --git a/frontend/src/components/EntityDetails.svelte b/frontend/src/components/EntityDetails.svelteindex efe73ab..35c5b9d 100644--- a/frontend/src/components/EntityDetails.svelte+++ b/frontend/src/components/EntityDetails.svelte@@ -15,10 +15,14 @@import { buildTree, flattenPaths, folderOf } from '../lib/folderTree.js';import { assignFolder as fileEntity } from '../lib/filing.js';import { DEPENDS_ON } from '../lib/chain.js';+ import { loadRelationTypes, relatableTypes, saveRelation } from '../lib/relations.svelte.js';import { openEntity, gotoCapture, ENTITY_TOOL } from '../lib/navigate.js';+ import { pollWhile } from '../lib/poll.js';import Icon from './Icon.svelte';import ConfirmDialog from './ConfirmDialog.svelte';import FolderSelect from './FolderSelect.svelte';+ import RelationList from './RelationList.svelte';+ import RelationPicker from './RelationPicker.svelte';let { entityId, onclose, ondeleted } = $props();@@ -102,28 +106,72 @@resolve(e, firstSeed);});- async function resolve(e, seedFields) {- const endpoint = e.type === 'media' ? 'media' : e.type === 'capture' ? 'satellite' : null;- if (!endpoint || !e.attrs?.path) {+ /** The file behind an entity, with everything the sidecar holds.+ *+ * A media file is read one at a time: the metadata dumps this panel shows+ * (EXIF, video fields) are hundreds of rows each and are deliberately kept out+ * of the browse index, so asking for the whole list would neither carry them+ * nor be cheap. A capture still comes off the satellite list, which is small+ * and has no per-item read.+ *+ * ``quiet`` re-reads without the loading banner: the enrichment poll below+ * calls this every 1.5s, and flashing "Loading…" at someone reading the panel+ * would look like a fault rather than a background job finishing. */+ async function resolve(e, seedFields, quiet = false) {+ const path = e.attrs?.path;+ if (!path || (e.type !== 'media' && e.type !== 'capture')) {infoData = null;return;}- infoLoading = true;+ const cid = caseState.current.id;+ if (!quiet) infoLoading = true;try {- const list = await api.get(`/api/cases/${caseState.current.id}/${endpoint}`);+ const found =+ e.type === 'media'+ ? await api.get(`/api/cases/${cid}/media/item?path=${encodeURIComponent(path)}`)+ : (await api.get(`/api/cases/${cid}/satellite`)).find((m) => m.path === path);if (seededId !== e.id) return; // selection moved on mid-fetch- infoData = list.find((m) => m.path === e.attrs.path) ?? null;+ infoData = found ?? null;if (infoData && seedFields) {infoTitle = infoData.title ?? e.label ?? '';infoNotes = infoData.notes ?? infoNotes;}} catch {- infoData = null;+ // a failed quiet re-read keeps what is on screen: the panel is being read,+ // and blanking it because one poll missed would lose the analyst's place+ if (!quiet) infoData = null;} finally {infoLoading = false;}}+ // Enrichment runs in a job, so a file opened moments after its import has no+ // metadata to show yet. The Media Library's own poll covers the modal it hosts,+ // but this body also lives in the case sidebar, where nothing else is watching:+ // import, switch to Satellite, open the file from the sidebar, and the EXIF+ // section would sit empty until something unrelated reloaded the case. The file+ // itself reports the job's state, so poll on that and stop when it settles.+ const enriching = $derived(+ infoData?.enrich_state === 'queued' || infoData?.enrich_state === 'running'+ );++ $effect(() => {+ if (!enriching || !entity) return;+ return pollWhile(() => enriching, () => resolve(entity, false, true), 1500);+ });++ // A relation stated here rides along with Save, like the title and the notes:+ // the panel's model is "edit the fields, press Save", and a second commit+ // button beside it would be one gesture too many.+ let pendingRelation = $state(null);+ loadRelationTypes();+ const canRelate = $derived(!!entity && relatableTypes(entity.type).length > 0);++ $effect(() => {+ currentId; // a different entity means a different subject+ pendingRelation = null;+ });+async function saveInfo() {if (!entity || infoSaving) return;infoSaving = true;@@ -145,6 +193,10 @@if ((infoFolder.trim() || '') !== (folderOf(entity) ?? '')) {await fileEntity(cid, entity, infoFolder.trim());}+ if (pendingRelation) {+ await saveRelation(cid, entity.id, pendingRelation);+ pendingRelation = null;+ }await reloadCase();toast('Saved', 'ok', 1600);} catch (e) {@@ -208,6 +260,11 @@if (bytes >= 1 << 10) return (bytes / (1 << 10)).toFixed(0) + ' KB';return bytes + ' B';}++ function formatCoords(gps) {+ if (gps?.lat == null || gps?.lon == null) return '';+ return `${Number(gps.lat).toFixed(6)}, ${Number(gps.lon).toFixed(6)}`;+ }</script>{#if entity}@@ -307,8 +364,42 @@{/if}</div>+ {#if infoData?.kind === 'image' && (infoData.taken_at || infoData.gps || Object.keys(infoData.exif ?? {}).length)}+ <details class="metadata-details">+ <summary>EXIF metadata <span>{Object.keys(infoData.exif ?? {}).length}</span></summary>+ <div class="exif-rows">+ {#if infoData.taken_at}+ <div class="info-row"><span class="info-k">Captured</span><span class="mono">{infoData.taken_at}</span></div>+ {/if}+ {#if infoData.gps}+ <div class="info-row"><span class="info-k">GPS</span><span class="mono">{formatCoords(infoData.gps)}</span></div>+ {/if}+ {#each Object.entries(infoData.exif ?? {}) as [key, value] (key)}+ <div class="info-row"><span class="info-k">{key}</span><span class="exif-value">{value}</span></div>+ {/each}+ </div>+ </details>+ {/if}++ {#if infoData?.kind === 'video' && Object.keys(infoData.video_metadata ?? {}).length}+ <details class="metadata-details">+ <summary>Video metadata <span>{Object.keys(infoData.video_metadata).length}</span></summary>+ <div class="exif-rows">+ {#if infoData.taken_at}+ <div class="info-row"><span class="info-k">Captured</span><span class="mono">{infoData.taken_at}</span></div>+ {/if}+ {#if infoData.gps}+ <div class="info-row"><span class="info-k">GPS</span><span class="mono">{formatCoords(infoData.gps)}</span></div>+ {/if}+ {#each Object.entries(infoData.video_metadata) as [key, value] (key)}+ <div class="info-row"><span class="info-k">{key}</span><span class="exif-value">{value}</span></div>+ {/each}+ </div>+ </details>+ {/if}+<!-- derivation chain: click a row to walk to that entity's details -->- {#if chain && !chain.empty}+ {#if chain && (chain.sources.length || chain.lost.length || chain.dependents.length)}<div class="chain">{#if chain.sources.length || chain.lost.length}<div class="chain-h">Made from</div>@@ -349,6 +440,21 @@</div>{/if}+ <!-- relations: what this entity says about the world, not how it was made -->+ {#if canRelate}+ <div class="chain">+ <div class="chain-h">Relations</div>+ <RelationList+ caseId={caseState.current.id}+ relations={chain?.relations ?? []}+ subjectType={entity.type}+ onwalk={(target) => (walkedId = target.id)}+ onchanged={reloadCase}+ />+ <RelationPicker subjectType={entity.type} bind:value={pendingRelation} />+ </div>+ {/if}+{#if EDITABLE.has(entity.type)}<label class="modal-label" for="ed-notes">Notes</label><textarea id="ed-notes" class="textarea" rows="3" bind:value={infoNotes} placeholder="Add observations, links, context…"></textarea>@@ -496,6 +602,36 @@max-height: 8.5em;overflow-y: auto;}+ .metadata-details {+ margin-top: 12px;+ border-top: 1px solid var(--border);+ padding-top: 8px;+ }+ .metadata-details summary {+ cursor: pointer;+ color: var(--text-2);+ font-size: var(--fs-sm);+ font-weight: 600;+ }+ .metadata-details summary span {+ color: var(--text-3);+ font-size: var(--fs-xs);+ font-weight: 400;+ }+ .exif-rows {+ display: flex;+ flex-direction: column;+ gap: 6px;+ margin-top: 8px;+ }+ .exif-rows .info-k {+ min-width: 120px;+ overflow-wrap: anywhere;+ }+ .exif-value {+ min-width: 0;+ overflow-wrap: anywhere;+ }.textarea {width: 100%;resize: vertical;diff --git a/frontend/src/components/EntityDetails.test.js b/frontend/src/components/EntityDetails.test.jsindex 525e239..fda5ca1 100644--- a/frontend/src/components/EntityDetails.test.js+++ b/frontend/src/components/EntityDetails.test.js@@ -11,3 +11,83 @@ describe('capture details', () => {expect(source).toContain('target="_blank" rel="noreferrer"');});});++describe('import enrichment details', () => {+ it('keeps parsed image metadata in a collapsed EXIF section', () => {+ expect(source).toContain('<details class="metadata-details">');+ expect(source).toContain('<summary>EXIF metadata');+ expect(source).toContain('{infoData.taken_at}');+ expect(source).toContain('formatCoords(infoData.gps)');+ expect(source).toContain('{#each Object.entries(infoData.exif ?? {}) as [key, value] (key)}');+ });++ it('uses the same collapsed section for local video probe metadata', () => {+ expect(source).toContain('<summary>Video metadata');+ expect(source).toContain('Object.keys(infoData.video_metadata ?? {}).length');+ expect(source).toContain(+ '{#each Object.entries(infoData.video_metadata) as [key, value] (key)}'+ );+ });++ it('renders relations through the shared list, walking the panel in place', () => {+ expect(source).toContain('relations={chain?.relations ?? []}');+ expect(source).toContain('onwalk={(target) => (walkedId = target.id)}');+ expect(source).toContain('onchanged={reloadCase}');+ });++ it('separates relations from the derivation chain, which has its own rule', () => {+ // a relation says something about the world; the chain says how a file was+ // made and decides what a delete destroys+ expect(source).toContain(+ '{#if chain && (chain.sources.length || chain.lost.length || chain.dependents.length)}'+ );+ expect(source).toContain('{#if canRelate}');+ expect(source).toContain('relatableTypes(entity.type).length > 0');+ });++ it('files a stated relation with Save rather than adding a second commit button', () => {+ expect(source).toContain('<RelationPicker subjectType={entity.type} bind:value={pendingRelation} />');+ expect(source).toContain('if (pendingRelation) {');+ expect(source).toContain('await saveRelation(cid, entity.id, pendingRelation);');+ });++ it('drops a pending relation when the panel walks to another entity', () => {+ expect(source).toContain('currentId; // a different entity means a different subject');+ expect(source).toContain('pendingRelation = null;');+ });+});++describe('reading the file behind an entity', () => {+ it('reads one media file, not the whole case, to show its metadata', () => {+ // the EXIF and video dumps this panel renders are hundreds of rows each and+ // are deliberately absent from the browse index, so the list would neither+ // carry them nor be cheap to fetch+ expect(source).toContain('/media/item?path=${encodeURIComponent(path)}');+ expect(source).not.toContain('const list = await api.get(');+ });++ it('still reads a capture off the satellite list, which has no per-item read', () => {+ expect(source).toContain("(await api.get(`/api/cases/${cid}/satellite`)).find((m) => m.path === path)");+ });++ it('drops the panel data when the entity names no file', () => {+ expect(source).toContain("if (!path || (e.type !== 'media' && e.type !== 'capture'))");+ });+});++describe('metadata arriving after the panel opened', () => {+ it('polls the file while its enrichment job is still running', () => {+ // Enrichment runs in a job, so a file opened moments after its import has no+ // metadata yet. The Media Library's poll covers the modal it hosts, but this+ // body also lives in the case sidebar, where nothing else is watching.+ expect(source).toContain("infoData?.enrich_state === 'queued' || infoData?.enrich_state === 'running'");+ expect(source).toContain('return pollWhile(() => enriching, () => resolve(entity, false, true), 1500);');+ });++ it('re-reads quietly, so a background job finishing does not look like a fault', () => {+ expect(source).toContain('async function resolve(e, seedFields, quiet = false)');+ expect(source).toContain('if (!quiet) infoLoading = true;');+ // and a poll that missed keeps what is on screen rather than blanking it+ expect(source).toContain('if (!quiet) infoData = null;');+ });+});diff --git a/frontend/src/components/RelationList.svelte b/frontend/src/components/RelationList.sveltenew file mode 100644index 0000000..b959d4e--- /dev/null+++ b/frontend/src/components/RelationList.svelte@@ -0,0 +1,312 @@+<script>+ /**+ * The non-chain edges of one entity (ONTOLOGY §3), one row each.+ *+ * A relation says something about the world — this photo was shot there, these+ * two files are the same picture — where the derivation chain says how a file+ * was made. Import enrichment proposes them from a file's own metadata, so most+ * rows start `suggested` and carry the two clicks that settle them: confirm+ * turns a machine's reading into a finding, dismiss drops the edge.+ *+ * One body, three homes — the Details panel, the map popup and (next) the case+ * board all render this, so the vocabulary and the gestures stay identical+ * wherever a relation appears.+ */+ import { api } from '../lib/api.js';+ import { toast } from '../lib/state.svelte.js';+ import { loadRelationTypes, relationOptions, relationVerb } from '../lib/relations.svelte.js';+ import { openEntity } from '../lib/navigate.js';+ import Icon from './Icon.svelte';++ let {+ caseId,+ relations = [],+ subjectType = null, // the type these relations are about; enables restating+ onwalk = null, // given, a row walks the host to that entity in place+ onchanged, // a relation was settled or restated: the host reloads what it reads+ max = 6, // rows past this hide behind one "+ n more" click+ } = $props();++ /** Where a row leads. Hosts that can show the entity in place say so; the rest+ * open it in its own tool. Either way the row says "Open …" before the click,+ * because a click that silently swaps the whole workspace reads as a bug. */+ const walk = (entity) => (onwalk ? onwalk(entity) : openEntity(entity));++ const ENTITY_ICON = {+ media: 'media', capture: 'satellite', place: 'pin', proof: 'proof',+ post: 'post', 'inspect-session': 'inspect', note: 'note', bookmark: 'link',+ };++ loadRelationTypes();++ let expanded = $state(false);+ let busyId = $state(null);++ /**+ * A row control acts on its own relation, and nothing above it should treat the+ * click as its own. That matters most in a map popup: Leaflet decides a click+ * was "on the map" by walking up from the event target to find the popup+ * container, and these controls replace themselves, so their button can already+ * be detached by the time the event bubbles — the card would close under the+ * analyst. Stopping inside the handler rather than on a wrapper, because Svelte+ * delegates these clicks to the app root: an ancestor that stopped them would+ * silence the buttons instead of protecting them.+ */+ function own(handler) {+ return (event) => {+ event.stopPropagation();+ handler();+ };+ }++ // Suggestions first: they are the only rows that need a decision, and a case+ // with forty confirmed relations must not bury the three awaiting review.+ const ordered = $derived(+ [...relations].sort(+ (a, b) => Number(isSuggested(b)) - Number(isSuggested(a))+ )+ );+ const shown = $derived(expanded ? ordered : ordered.slice(0, max));+ const hidden = $derived(Math.max(0, ordered.length - shown.length));++ function isSuggested(relation) {+ return relation.link?.provenance?.status === 'suggested';+ }++ /** A place carries its own point, so its row can offer the map. */+ function placePoint(entity) {+ const lat = Number(entity?.attrs?.lat);+ const lon = Number(entity?.attrs?.lon);+ if (entity?.type !== 'place' || !Number.isFinite(lat) || !Number.isFinite(lon)) return null;+ return `${lat.toFixed(6)}, ${lon.toFixed(6)}`;+ }++ /** The other readings the vocabulary allows for this pair, running the same way+ * round as the edge already does — reversing it would be a different relation,+ * not a correction. Empty for a machine's claim, which is not the analyst's to+ * reword, and empty when the pair has only one reading. */+ function verbOptions(relation) {+ if (!subjectType) return [];+ const options = relationOptions(subjectType, relation.entity.type).filter(+ (option) => option.direction === relation.direction+ );+ return options.length > 1 ? options : [];+ }++ async function restate(link, type) {+ if (busyId || type === link.type) return;+ busyId = link.id;+ try {+ await api.patch(`/api/cases/${caseId}/links/${link.id}`, { type });+ toast('Relation updated', 'ok', 1600);+ await onchanged?.();+ } catch (e) {+ toast(e.message, 'danger');+ } finally {+ busyId = null;+ }+ }++ async function confirm(link) {+ if (busyId) return;+ busyId = link.id;+ try {+ await api.patch(`/api/cases/${caseId}/links/${link.id}`, { status: 'confirmed' });+ toast('Relation confirmed', 'ok', 1600);+ await onchanged?.();+ } catch (e) {+ toast(e.message, 'danger');+ } finally {+ busyId = null;+ }+ }++ /** Drop the edge. The same gesture whichever status it had, because a relation+ * is a statement and taking it back is the only way to correct one — the+ * wording differs so it reads as "not that" on a proposal and "no longer+ * true" on something the analyst had already accepted. */+ async function remove(link, suggested) {+ if (busyId) return;+ busyId = link.id;+ try {+ await api.del(`/api/cases/${caseId}/links/${link.id}`);+ toast(suggested ? 'Relation dismissed' : 'Relation removed', 'info', 1600);+ await onchanged?.();+ } catch (e) {+ toast(e.message, 'danger');+ } finally {+ busyId = null;+ }+ }+</script>++{#if ordered.length}+ <div class="relations">+ {#each shown as relation (relation.link.id)}+ {@const point = placePoint(relation.entity)}+ {@const suggested = isSuggested(relation)}+ {@const verbs = verbOptions(relation)}+ <div class="relation" class:suggested class:busy={busyId === relation.link.id}>+ <button+ class="subject"+ onclick={own(() => walk(relation.entity))}+ title={`Open ${relation.entity.label}${point ? ` · ${point}` : ''}`}+ >+ <Icon name={ENTITY_ICON[relation.entity.type] ?? 'file'} size={12} />+ <span class="label">{relation.entity.label}</span>+ {#if !verbs.length}+ <span class="verb">+ {relation.direction === 'in' ? '← ' : ''}{relationVerb(relation.link.type)}+ </span>+ {/if}+ </button>+ <div class="acts">+ {#if verbs.length}+ <!-- the reading is corrected in place: same edge, same id, right verb -->+ <select+ class="select verb-select"+ value={relation.link.type}+ title="What this relation states"+ disabled={busyId === relation.link.id}+ onchange={(event) => restate(relation.link, event.currentTarget.value)}+ >+ {#each verbs as option (option.type)}+ <option value={option.type}>{option.label}</option>+ {/each}+ </select>+ {/if}+ {#if point}+ <button+ class="btn btn-ghost btn-sm act"+ title={`Show ${point} on the map`}+ onclick={own(() => openEntity(relation.entity))}+ >+ <Icon name="crosshair" size={12} />+ </button>+ {/if}+ {#if suggested}+ <button+ class="btn btn-ghost btn-sm act ok"+ title="Confirm this relation"+ disabled={busyId === relation.link.id}+ onclick={own(() => confirm(relation.link))}+ >+ <Icon name="check" size={12} />+ </button>+ {/if}+ <button+ class="btn btn-ghost btn-sm act no"+ title={suggested ? 'Dismiss this relation' : 'Remove this relation'}+ disabled={busyId === relation.link.id}+ onclick={own(() => remove(relation.link, suggested))}+ >+ <Icon name="x" size={12} />+ </button>+ </div>+ </div>+ {/each}+ {#if hidden}+ <button class="more" onclick={own(() => (expanded = true))}>+ {hidden} more</button>+ {/if}+ </div>+{/if}++<style>+ .relations {+ display: flex;+ flex-direction: column;+ gap: 2px;+ min-width: 0;+ }+ .relation {+ display: flex;+ align-items: center;+ gap: 2px;+ min-width: 0;+ border-radius: var(--r-sm);+ }+ .relation.busy {+ opacity: 0.5;+ }+ /* a machine's reading, not a finding: one hairline is enough to say so */+ .relation.suggested .subject {+ border-left: 2px solid color-mix(in srgb, var(--accent) 55%, transparent);+ }+ .subject {+ display: flex;+ align-items: center;+ gap: 7px;+ flex: 1;+ min-width: 0;+ padding: 5px 6px;+ border: 0;+ border-radius: var(--r-sm);+ background: transparent;+ color: var(--text-2);+ font: inherit;+ font-size: var(--fs-sm);+ text-align: left;+ }+ button.subject {+ cursor: pointer;+ }+ button.subject:hover {+ background: var(--bg-2);+ color: var(--text-1);+ }+ .label {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .verb {+ flex-shrink: 0;+ margin-left: auto;+ font-size: 10px;+ padding: 1px 5px;+ border-radius: 999px;+ background: var(--bg-2);+ color: var(--text-3);+ white-space: nowrap;+ }+ /* the row's own actions stay quiet until the row is under the pointer */+ .acts {+ display: flex;+ flex: 0 0 auto;+ gap: 1px;+ opacity: 0.55;+ }+ .relation:hover .acts,+ .relation:focus-within .acts {+ opacity: 1;+ }+ .act {+ padding-inline: 5px;+ }+ .verb-select {+ flex: 0 0 auto;+ width: auto;+ max-width: 128px;+ padding: 1px 4px;+ font-size: 10px;+ color: var(--text-3);+ }+ .act.ok:hover {+ color: var(--ok, #46a758);+ }+ .act.no:hover {+ color: var(--danger, #e5484d);+ }+ .more {+ align-self: flex-start;+ padding: 2px 6px;+ border: 0;+ background: none;+ color: var(--accent);+ font-size: var(--fs-xs);+ cursor: pointer;+ }+ .more:hover {+ text-decoration: underline;+ }+</style>diff --git a/frontend/src/components/RelationList.test.js b/frontend/src/components/RelationList.test.jsnew file mode 100644index 0000000..89f3b40--- /dev/null+++ b/frontend/src/components/RelationList.test.js@@ -0,0 +1,109 @@+import { describe, expect, it } from 'vitest';+import { readFileSync } from 'node:fs';++const source = readFileSync(new URL('./RelationList.svelte', import.meta.url), 'utf8');++describe('RelationList', () => {+ it('is the one body every surface renders relations through', () => {+ // the case sidebar, the Media info modal, the map popup — and next the case+ // board. A second copy is how the vocabulary and the gestures drift apart.+ const hosts = ['EntityDetails.svelte', '../tools/satellite/SavedPopup.svelte'];+ for (const host of hosts) {+ const body = readFileSync(new URL(host, import.meta.url), 'utf8');+ expect(body).toContain('RelationList');+ // no host keeps its own confirm/dismiss call+ expect(body).not.toContain("{ status: 'confirmed' }");+ }+ });++ it('names an edge from the shared vocabulary, never by its type slug', () => {+ expect(source).toContain("from '../lib/relations.svelte.js'");+ expect(source).toContain('relationVerb(relation.link.type)');+ });++ it('offers confirm only on a suggestion', () => {+ expect(source).toContain("relation.link?.provenance?.status === 'suggested'");+ expect(source).toContain("api.patch(`/api/cases/${caseId}/links/${link.id}`, { status: 'confirmed' })");+ expect(source).toContain('{#if suggested}');+ expect(source).toContain('title="Confirm this relation"');+ expect(source).toContain('await onchanged?.()');+ });++ it('lets any relation be taken back, whatever its status', () => {+ // a relation is a statement; correcting one means removing the edge, and a+ // confirmed relation the analyst stated by hand is the likeliest mistake+ expect(source).toContain('api.del(`/api/cases/${caseId}/links/${link.id}`)');+ expect(source).toContain("title={suggested ? 'Dismiss this relation' : 'Remove this relation'}");+ expect(source).toContain("toast(suggested ? 'Relation dismissed' : 'Relation removed'");+ // the remove button sits outside the suggested-only branch+ const removeAt = source.indexOf('onclick={own(() => remove(relation.link, suggested))}');+ const branchEnd = source.indexOf('{/if}', source.indexOf('{#if suggested}'));+ expect(removeAt).toBeGreaterThan(branchEnd);+ });++ it('corrects a wrong reading on the same edge, without deleting it', () => {+ // a relation stays editable: same id, same provenance, right verb+ expect(source).toContain("api.patch(`/api/cases/${caseId}/links/${link.id}`, { type })");+ expect(source).toContain('function verbOptions(relation)');+ expect(source).toContain("option.direction === relation.direction");+ expect(source).toContain('return options.length > 1 ? options : [];');+ // no subject type means no restating: the alternatives cannot be worked out+ expect(source).toContain('if (!subjectType) return [];');+ });++ it('is given the subject type by every host, so restating works everywhere', () => {+ const hosts = {+ 'EntityDetails.svelte': 'subjectType={entity.type}',+ '../tools/satellite/SavedPopup.svelte': "subjectType={row.kind === 'place' ? 'place' : 'capture'}",+ '../tools/Satellite.svelte': 'subjectType="place"',+ };+ for (const [host, expected] of Object.entries(hosts)) {+ const body = readFileSync(new URL(host, import.meta.url), 'utf8');+ expect(body).toContain(expected);+ }+ });++ it('keeps its clicks to itself, inside each handler', () => {+ // In a Leaflet popup, a click that looks like it reached the map closes the+ // card. These controls replace themselves, so their button can be detached by+ // the time the event bubbles and Leaflet's walk up to the popup container+ // finds nothing. It has to be stopped *in* the handler: Svelte delegates these+ // clicks to the app root, so an ancestor that stopped them would silence the+ // buttons instead of shielding them.+ expect(source).toContain('function own(handler)');+ expect(source).toContain('event.stopPropagation();');+ for (const wired of [+ 'onclick={own(() => walk(relation.entity))}',+ 'onclick={own(() => confirm(relation.link))}',+ 'onclick={own(() => remove(relation.link, suggested))}',+ 'onclick={own(() => (expanded = true))}',+ ]) {+ expect(source).toContain(wired);+ }+ // no host wraps the list in a click-swallowing ancestor+ const popup = readFileSync(new URL('../tools/satellite/SavedPopup.svelte', import.meta.url), 'utf8');+ expect(popup).not.toContain('use:insideCard');+ });++ it('puts the rows awaiting a decision first', () => {+ expect(source).toContain('Number(isSuggested(b)) - Number(isSuggested(a))');+ });++ it('caps a long list behind one click rather than growing the panel', () => {+ expect(source).toContain('max = 6');+ expect(source).toContain('expanded ? ordered : ordered.slice(0, max)');+ expect(source).toContain('+ {hidden} more');+ });++ it('offers the map for a neighbour that carries its own point', () => {+ // confirming "shot here" without seeing where is signing blind+ expect(source).toContain("entity?.type !== 'place'");+ expect(source).toContain('${lat.toFixed(6)}, ${lon.toFixed(6)}');+ expect(source).toContain('title={`Show ${point} on the map`}');+ expect(source).toContain('onclick={own(() => openEntity(relation.entity))}');+ });++ it('keeps the coordinates in the tooltip so a row stays one line', () => {+ expect(source).toContain('title={`Open ${relation.entity.label}${point ? ` · ${point}` : \'\'}`}');+ });+});diff --git a/frontend/src/components/RelationPicker.svelte b/frontend/src/components/RelationPicker.sveltenew file mode 100644index 0000000..2914131--- /dev/null+++ b/frontend/src/components/RelationPicker.svelte@@ -0,0 +1,211 @@+<script>+ /**+ * State one relation by hand: pick the other entity, then how it reads.+ *+ * A collected value rather than an action, because the subject often does not+ * exist yet — the Satellite save gate lets the analyst say "this photo was shot+ * here" while filling in a place the case has never held. The host files the+ * choice with `saveRelation` once it has both ends.+ *+ * The searchable list is bounded (the catalog endpoint, one short page), and+ * only the entity types the vocabulary accepts for this subject are offered.+ */+ import { api } from '../lib/api.js';+ import { buildCatalogQuery } from '../lib/catalog.js';+ import { caseState } from '../lib/state.svelte.js';+ import { loadRelationTypes, relatableTypes, relationOptions } from '../lib/relations.svelte.js';+ import Icon from './Icon.svelte';+ import SearchInput from './SearchInput.svelte';++ let {+ subjectType, // entity type the relation is being stated about+ value = $bindable(null), // { entityId, label, entityType, type, direction } | null+ } = $props();++ const PAGE = 8; // a short page: this is a picker, not a browser+ const ENTITY_ICON = {+ media: 'media', capture: 'satellite', place: 'pin', proof: 'proof',+ post: 'post', 'inspect-session': 'inspect', note: 'note', bookmark: 'link',+ };++ loadRelationTypes();++ let query = $state('');+ let results = $state([]);+ let open = $state(false);+ let searching = $state(false);+ let seq = 0;++ const types = $derived(relatableTypes(subjectType));+ // The chosen entity decides which verbs are available: a place accepts "was+ // shot at" from a photo, and nothing at all from another place.+ const options = $derived(value ? relationOptions(subjectType, value.entityType) : []);++ $effect(() => {+ const caseId = caseState.current?.id;+ const wanted = types;+ const term = query.trim();+ if (!open || !caseId || !wanted.length) return;+ const mine = ++seq;+ searching = true;+ api+ .get(buildCatalogQuery(caseId, { types: wanted, query: term, limit: PAGE }))+ .then((page) => {+ if (mine !== seq) return; // a newer keystroke already answered+ results = page.items ?? [];+ })+ .catch(() => {+ if (mine === seq) results = [];+ })+ .finally(() => {+ if (mine === seq) searching = false;+ });+ });++ function choose(entity) {+ const [first] = relationOptions(subjectType, entity.type);+ if (!first) return; // the vocabulary has no reading for this pair+ value = {+ entityId: entity.id,+ label: entity.label,+ entityType: entity.type,+ type: first.type,+ direction: first.direction,+ };+ open = false;+ query = '';+ }++ function setType(event) {+ const picked = options.find((o) => o.type === event.currentTarget.value);+ if (picked) value = { ...value, type: picked.type, direction: picked.direction };+ }+</script>++{#if types.length}+ <div class="picker">+ {#if value}+ <div class="chosen">+ <Icon name={ENTITY_ICON[value.entityType] ?? 'file'} size={13} />+ <span class="chosen-label" title={value.label}>{value.label}</span>+ {#if options.length > 1}+ <select class="select verb-select" value={value.type} onchange={setType}>+ {#each options as option (option.type)}+ <option value={option.type}>{option.label}</option>+ {/each}+ </select>+ {:else}+ <span class="verb">{options[0]?.label ?? value.type}</span>+ {/if}+ <button class="btn btn-ghost btn-sm" title="Remove this relation" onclick={() => (value = null)}>+ <Icon name="x" size={12} />+ </button>+ </div>+ {:else if open}+ <SearchInput bind:value={query} placeholder="Search the case…" width="100%" />+ <div class="results">+ {#each results as entity (entity.id)}+ <button class="result" onclick={() => choose(entity)}>+ <Icon name={ENTITY_ICON[entity.type] ?? 'file'} size={12} />+ <span class="result-label">{entity.label}</span>+ <span class="result-type">{entity.type}</span>+ </button>+ {/each}+ {#if !results.length}+ <p class="hint">{searching ? 'Searching…' : 'Nothing to relate here yet.'}</p>+ {/if}+ </div>+ {:else}+ <button class="btn btn-sm add" onclick={() => (open = true)}>+ <Icon name="link" size={13} /> Relate to…+ </button>+ {/if}+ </div>+{/if}++<style>+ .picker {+ display: flex;+ flex-direction: column;+ gap: 6px;+ min-width: 0;+ }+ .add {+ align-self: flex-start;+ }+ .chosen {+ display: flex;+ align-items: center;+ gap: 7px;+ min-width: 0;+ padding: 4px 6px;+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ background: var(--bg-2);+ font-size: var(--fs-sm);+ color: var(--text-2);+ }+ .chosen-label {+ flex: 1;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .verb {+ flex-shrink: 0;+ font-size: 10px;+ padding: 1px 5px;+ border-radius: 999px;+ background: var(--bg-3);+ color: var(--text-3);+ }+ .verb-select {+ flex: 0 0 auto;+ max-width: 150px;+ font-size: var(--fs-xs);+ }+ .results {+ display: flex;+ flex-direction: column;+ gap: 1px;+ max-height: 168px;+ overflow-y: auto;+ }+ .result {+ display: flex;+ align-items: center;+ gap: 7px;+ min-width: 0;+ padding: 5px 6px;+ border: 0;+ border-radius: var(--r-sm);+ background: transparent;+ color: var(--text-2);+ font: inherit;+ font-size: var(--fs-sm);+ text-align: left;+ cursor: pointer;+ }+ .result:hover {+ background: var(--bg-2);+ color: var(--text-1);+ }+ .result-label {+ flex: 1;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .result-type {+ flex-shrink: 0;+ font-size: 10px;+ color: var(--text-3);+ }+ .hint {+ margin: 2px 0;+ font-size: var(--fs-xs);+ color: var(--text-3);+ }+</style>diff --git a/frontend/src/components/RelationPicker.test.js b/frontend/src/components/RelationPicker.test.jsnew file mode 100644index 0000000..e16dc58--- /dev/null+++ b/frontend/src/components/RelationPicker.test.js@@ -0,0 +1,36 @@+import { describe, expect, it } from 'vitest';+import { readFileSync } from 'node:fs';++const source = readFileSync(new URL('./RelationPicker.svelte', import.meta.url), 'utf8');++describe('RelationPicker', () => {+ it('collects a choice instead of filing it, because the subject may not exist yet', () => {+ // the Satellite save gate states "this photo was shot here" while filling in+ // a place the case has never held+ expect(source).toContain('value = $bindable(null)');+ expect(source).not.toContain('api.post');+ expect(source).toContain('entityId: entity.id');+ expect(source).toContain('direction: first.direction');+ });++ it('searches only the entity types the vocabulary accepts for this subject', () => {+ expect(source).toContain('relatableTypes(subjectType)');+ expect(source).toContain('buildCatalogQuery(caseId, { types: wanted, query: term, limit: PAGE })');+ expect(source).toContain('const PAGE = 8');+ });++ it('drops a stale page rather than letting it overwrite a newer keystroke', () => {+ expect(source).toContain('const mine = ++seq');+ expect(source).toContain('if (mine !== seq) return;');+ });++ it('lets the analyst pick the reading when the pair has more than one', () => {+ expect(source).toContain('relationOptions(subjectType, value.entityType)');+ expect(source).toContain('{#if options.length > 1}');+ expect(source).toContain('{option.label}');+ });++ it('shows nothing at all when the subject can hold no relation', () => {+ expect(source).toContain('{#if types.length}');+ });+});diff --git a/frontend/src/lib/mediaFilter.js b/frontend/src/lib/mediaFilter.jsindex e3ebffe..ff7ae8d 100644--- a/frontend/src/lib/mediaFilter.js+++ b/frontend/src/lib/mediaFilter.js@@ -59,7 +59,15 @@ export const SORTS = [*/export function visibleMedia(items,- { hasCase = true, catMatch = null, folderFilter = null, query = '', sort = 'newest', direction } = {}+ {+ hasCase = true,+ catMatch = null,+ folderFilter = null,+ gpsOnly = false,+ query = '',+ sort = 'newest',+ direction,+ } = {}) {if (!hasCase) return [];return sortItems(@@ -67,6 +75,7 @@ export function visibleMedia((i) =>(!catMatch || catMatch(i)) &&(!folderFilter || i.folder === folderFilter) &&+ (!gpsOnly || hasPosition(i)) &&matchesQuery(i, query)),sort,@@ -74,6 +83,19 @@ export function visibleMedia();}+/** The position a file's own metadata states, or null. Enrichment writes it from+ * image EXIF or a video's container tags; both land on the same field. */+export function mediaPoint(item) {+ const lat = Number(item?.gps?.lat);+ const lon = Number(item?.gps?.lon);+ if (!Number.isFinite(lat) || !Number.isFinite(lon)) return null;+ return { lat, lon };+}++export function hasPosition(item) {+ return mediaPoint(item) !== null;+}+/** 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.diff --git a/frontend/src/lib/mediaFilter.test.js b/frontend/src/lib/mediaFilter.test.jsindex f15ed95..cb68092 100644--- a/frontend/src/lib/mediaFilter.test.js+++ b/frontend/src/lib/mediaFilter.test.js@@ -5,6 +5,8 @@ import {isSatelliteMedia,mediaDisplayKind,matchesQuery,+ mediaPoint,+ hasPosition,sortItems,visibleMedia,} from './mediaFilter.js';@@ -186,3 +188,35 @@ describe('hasMediaForFilters', () => {expect(hasMediaForFilters(items, { folderFilter: 'sources' })).toBe(true);});});++describe('mediaPoint', () => {+ it('reads the position a file states about itself, whatever wrote it', () => {+ // EXIF for an image, container tags for a video: enrichment lands both here+ expect(mediaPoint({ gps: { lat: 48.8583, lon: 2.2945 } })).toEqual({ lat: 48.8583, lon: 2.2945 });+ expect(mediaPoint({ kind: 'video', gps: { lat: -33.86, lon: 151.21 } })).toEqual({+ lat: -33.86,+ lon: 151.21,+ });+ });++ it('refuses a point the map could not place', () => {+ expect(mediaPoint({})).toBeNull();+ expect(mediaPoint({ gps: null })).toBeNull();+ expect(mediaPoint({ gps: { lat: 48.0 } })).toBeNull();+ expect(mediaPoint({ gps: { lat: 'north', lon: 'east' } })).toBeNull();+ expect(hasPosition({ gps: { lat: 0, lon: 0 } })).toBe(true); // enrichment already dropped 0,0+ });+});++describe('visibleMedia — position filter', () => {+ const located = item({ filename: 'gps.jpg', gps: { lat: 1, lon: 2 } });+ const bare = item({ filename: 'plain.jpg' });++ it('keeps only the files that state one, and composes with the other filters', () => {+ expect(visibleMedia([located, bare], { gpsOnly: true }).map((i) => i.filename)).toEqual([+ 'gps.jpg',+ ]);+ expect(visibleMedia([located, bare], { gpsOnly: false }).length).toBe(2);+ expect(visibleMedia([located, bare], { gpsOnly: true, query: 'plain' })).toEqual([]);+ });+});diff --git a/frontend/src/lib/mediaQuery.js b/frontend/src/lib/mediaQuery.jsindex ac93892..b54790d 100644--- a/frontend/src/lib/mediaQuery.js+++ b/frontend/src/lib/mediaQuery.js@@ -3,13 +3,14 @@* distinct from an unset folder. Mirrors `buildCatalogQuery` in catalog.js. */export function buildMediaQuery(caseId,- { q, kind, category, folder, sort, direction, limit, cursor } = {}+ { q, kind, category, folder, gps, 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 (gps) params.set('gps', 'true');if (sort) params.set('sort', sort);if (direction) params.set('direction', direction);if (limit != null) params.set('limit', String(limit));diff --git a/frontend/src/lib/mediaQuery.test.js b/frontend/src/lib/mediaQuery.test.jsindex 58bf313..db4a686 100644--- a/frontend/src/lib/mediaQuery.test.js+++ b/frontend/src/lib/mediaQuery.test.js@@ -27,3 +27,13 @@ describe('buildMediaQuery', () => {expect(buildMediaQuery('c1', { folder: '' })).toBe('/api/cases/c1/media/page?folder=');});});++describe('buildMediaQuery — position filter', () => {+ it('asks for only the located files when the filter is on', () => {+ expect(buildMediaQuery('c1', { gps: true })).toBe('/api/cases/c1/media/page?gps=true');+ });++ it('says nothing when it is off, so the default page is unfiltered', () => {+ expect(buildMediaQuery('c1', { gps: false })).toBe('/api/cases/c1/media/page');+ });+});diff --git a/frontend/src/lib/navigate.js b/frontend/src/lib/navigate.jsindex aa41648..d9ae52a 100644--- a/frontend/src/lib/navigate.js+++ b/frontend/src/lib/navigate.js@@ -96,6 +96,19 @@ export function openNotebook(noteId = null) {uiState.tool = 'notebook';}+/**+ * Fly the Satellite map to a bare point.+ *+ * For a position a file states about itself rather than one the case has filed:+ * the map is where "is this plausible?" gets answered, and enrichment's proposed+ * place is already waiting there as a mark.+ */+export function gotoPoint(lat, lon) {+ if (!Number.isFinite(lat) || !Number.isFinite(lon)) return;+ uiState.gotoCoords = { lat, lon };+ uiState.tool = 'satellite';+}+/** Fly the Satellite map to a capture's recorded coordinates (its marker). */export function gotoCapture(entity) {const lat = Number(entity.attrs?.lat);diff --git a/frontend/src/lib/navigate.test.js b/frontend/src/lib/navigate.test.jsindex 200b8ab..f27e66d 100644--- a/frontend/src/lib/navigate.test.js+++ b/frontend/src/lib/navigate.test.js@@ -1,6 +1,6 @@import { beforeEach, describe, expect, it, vi } from 'vitest';import { uiState } from './state.svelte.js';-import { openEntity } from './navigate.js';+import { gotoPoint, openEntity } from './navigate.js';beforeEach(() => {uiState.tool = 'media';@@ -31,3 +31,19 @@ describe('openEntity', () => {});});});++describe('gotoPoint', () => {+ it('flies the map to a position a file states about itself', () => {+ // no entity to open: the point comes off a sidecar, and the map is where+ // "is this plausible?" gets answered+ gotoPoint(48.8583, 2.2945);+ expect(uiState.tool).toBe('satellite');+ expect(uiState.gotoCoords).toEqual({ lat: 48.8583, lon: 2.2945 });+ });++ it('ignores a point it could not place', () => {+ uiState.gotoCoords = null;+ gotoPoint(Number('north'), 2.2945);+ expect(uiState.gotoCoords).toBeNull();+ });+});diff --git a/frontend/src/lib/relations.svelte.js b/frontend/src/lib/relations.svelte.jsnew file mode 100644index 0000000..d38caef--- /dev/null+++ b/frontend/src/lib/relations.svelte.js@@ -0,0 +1,84 @@+/**+ * The relation vocabulary (ONTOLOGY §3), fetched once and shared.+ *+ * The backend owns it: which non-chain edges exist, how each one reads in words,+ * what entity types either end accepts, and whether an analyst may state it at+ * all. Every surface that shows or creates a relation reads this registry, so+ * adding a type is one edit in `engine/links.py` rather than one per screen.+ *+ * Loaded lazily on the first surface that needs it and kept for the session —+ * the vocabulary is code, not case data, so it never changes under an open tab.+ */+import { api } from './api.js';++const registry = $state({ types: [] });+let pending = null;++/**+ * Fetch the vocabulary once. Safe to call from every component that needs it —+ * the session loads it at startup and each surface asks again on mount, which is+ * what makes a failed read recoverable: it is dropped rather than cached, so the+ * next surface retries instead of inheriting an empty vocabulary for good. Until+ * one succeeds, rows name an edge by its type and the picker stays empty: a+ * degraded label, never a broken panel.+ */+export function loadRelationTypes() {+ pending ??= api+ .get('/api/cases/relation-types')+ .then((types) => {+ registry.types = Array.isArray(types) ? types : [];+ })+ .catch(() => {+ pending = null;+ });+ return pending;+}++/** How a link type reads in words, or the raw type until the registry lands. */+export function relationVerb(type) {+ return registry.types.find((entry) => entry.type === type)?.label ?? type;+}++/**+ * The relations an analyst may state between a subject and another entity.+ *+ * The vocabulary is directed — a photo is shot at a place, never the reverse — so+ * each option records which end the subject sits on: `out` when the subject is+ * the `from`, `in` when it is the `to`. Callers never guess the order.+ */+export function relationOptions(subjectType, otherType) {+ const options = [];+ for (const entry of registry.types) {+ if (!entry.manual) continue;+ if (entry.from_types.includes(subjectType) && entry.to_types.includes(otherType)) {+ options.push({ type: entry.type, label: entry.label, direction: 'out' });+ } else if (entry.from_types.includes(otherType) && entry.to_types.includes(subjectType)) {+ options.push({ type: entry.type, label: entry.label, direction: 'in' });+ }+ }+ return options;+}++/** Entity types that can sit at the other end of a manual relation with this one. */+export function relatableTypes(subjectType) {+ const types = new Set();+ for (const entry of registry.types) {+ if (!entry.manual) continue;+ if (entry.from_types.includes(subjectType)) entry.to_types.forEach((t) => types.add(t));+ if (entry.to_types.includes(subjectType)) entry.from_types.forEach((t) => types.add(t));+ }+ return [...types];+}++/**+ * File one collected choice against a subject that now exists.+ *+ * Split from the picker because a relation is often chosen before its subject is+ * saved: the Satellite save gate lets the analyst say "this photo was shot here"+ * while filling in a place the case does not hold yet.+ */+export function saveRelation(caseId, subjectId, choice) {+ const [from_id, to_id] =+ choice.direction === 'out' ? [subjectId, choice.entityId] : [choice.entityId, subjectId];+ return api.post(`/api/cases/${caseId}/links`, { from_id, to_id, type: choice.type });+}diff --git a/frontend/src/lib/relations.test.js b/frontend/src/lib/relations.test.jsnew file mode 100644index 0000000..ed3dd9c--- /dev/null+++ b/frontend/src/lib/relations.test.js@@ -0,0 +1,137 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+// This instance is never given a registry, so it is also the "before the fetch+// lands" case: every surface renders against an empty vocabulary at first paint.+import { relationOptions as coldOptions, relationVerb as coldVerb } from './relations.svelte.js';++const get = vi.fn();+const post = vi.fn();+vi.mock('./api.js', () => ({ api: { get: (...a) => get(...a), post: (...a) => post(...a) } }));++const VOCABULARY = [+ {+ type: 'located-at',+ label: 'was shot at',+ from_types: ['capture', 'media'],+ to_types: ['place'],+ manual: true,+ },+ {+ type: 'depicts',+ label: 'shows',+ from_types: ['capture', 'media'],+ to_types: ['place'],+ manual: true,+ },+ {+ type: 'same-image-as',+ label: 'is the same picture as',+ from_types: ['media'],+ to_types: ['media'],+ manual: false,+ },+];++let relations;++beforeEach(async () => {+ vi.resetModules();+ get.mockReset();+ post.mockReset();+ get.mockResolvedValue(VOCABULARY);+ relations = await import('./relations.svelte.js');+});++describe('the relation vocabulary', () => {+ it('is fetched once however many surfaces ask for it', async () => {+ await Promise.all([+ relations.loadRelationTypes(),+ relations.loadRelationTypes(),+ relations.loadRelationTypes(),+ ]);+ expect(get).toHaveBeenCalledTimes(1);+ expect(get).toHaveBeenCalledWith('/api/cases/relation-types');+ });++ it('leaves a surface usable before the fetch lands', () => {+ expect(coldVerb('located-at')).toBe('located-at');+ expect(coldOptions('place', 'media')).toEqual([]);+ });++ it('names an edge in words once the registry is in', async () => {+ await relations.loadRelationTypes();+ expect(relations.relationVerb('located-at')).toBe('was shot at');+ expect(relations.relationVerb('same-image-as')).toBe('is the same picture as');+ expect(relations.relationVerb('invented-by-hand')).toBe('invented-by-hand');+ });++ it('leaves the panel usable when the registry cannot be read', async () => {+ vi.resetModules();+ get.mockRejectedValue(new Error('offline'));+ const degraded = await import('./relations.svelte.js');+ await degraded.loadRelationTypes();+ expect(degraded.relationVerb('located-at')).toBe('located-at');+ expect(degraded.relationOptions('place', 'media')).toEqual([]);+ });+});++describe('relationOptions', () => {+ beforeEach(() => relations.loadRelationTypes());++ it('records which end the subject sits on, because the vocabulary is directed', () => {+ // from a place: the photo is the subject of the edge, the place its object+ expect(relations.relationOptions('place', 'media')).toEqual([+ { type: 'located-at', label: 'was shot at', direction: 'in' },+ { type: 'depicts', label: 'shows', direction: 'in' },+ ]);+ // from the photo, the same two edges run outward+ expect(relations.relationOptions('media', 'place').map((o) => o.direction)).toEqual([+ 'out',+ 'out',+ ]);+ });++ it('never offers a machine-only relation', () => {+ expect(relations.relationOptions('media', 'media')).toEqual([]);+ });++ it('offers nothing for a pair the ontology has no reading for', () => {+ expect(relations.relationOptions('place', 'place')).toEqual([]);+ expect(relations.relationOptions('post', 'place')).toEqual([]);+ });+});++describe('relatableTypes', () => {+ beforeEach(() => relations.loadRelationTypes());++ it('lists what can sit at the other end, so a picker searches only those', () => {+ expect(relations.relatableTypes('place').sort()).toEqual(['capture', 'media']);+ expect(relations.relatableTypes('media')).toEqual(['place']);+ expect(relations.relatableTypes('post')).toEqual([]);+ });+});++describe('saveRelation', () => {+ it('files the endpoints in the order the link type requires', async () => {+ await relations.saveRelation('case-1', 'e_place', {+ entityId: 'e_photo',+ type: 'located-at',+ direction: 'in',+ });+ expect(post).toHaveBeenCalledWith('/api/cases/case-1/links', {+ from_id: 'e_photo',+ to_id: 'e_place',+ type: 'located-at',+ });++ await relations.saveRelation('case-1', 'e_photo', {+ entityId: 'e_place',+ type: 'located-at',+ direction: 'out',+ });+ expect(post).toHaveBeenLastCalledWith('/api/cases/case-1/links', {+ from_id: 'e_photo',+ to_id: 'e_place',+ type: 'located-at',+ });+ });+});diff --git a/frontend/src/lib/state.svelte.js b/frontend/src/lib/state.svelte.jsindex f73d4b4..1bed83f 100644--- a/frontend/src/lib/state.svelte.js+++ b/frontend/src/lib/state.svelte.js@@ -10,6 +10,7 @@ import { formatCoords as renderCoords } from './coords.js';import { loadWidth, saveWidth, clampWidth } from './sidebar.js';import { loadTheme, saveTheme, applyTheme } from './theme.js';import { shouldShowUpdate } from './appUpdate.js';+import { loadRelationTypes } from './relations.svelte.js';/*** App-wide display preferences (Settings → Preferences), mirrored from@@ -249,6 +250,10 @@ export async function initSession() {// in the wrong format; a settings read failure is never fatal to a sessionawait loadPrefs().catch(() => {});await loadTemplates().catch(() => {});+ // The relation vocabulary is code, not case data, and several surfaces name an+ // edge with it on their first paint. Reading it here means no relation row ever+ // renders a type slug it would replace a moment later.+ await loadRelationTypes().catch(() => {});await refreshCaseList();let lastId = null;try {diff --git a/frontend/src/tools/MediaLibrary.svelte b/frontend/src/tools/MediaLibrary.svelteindex 988f08b..befbf21 100644--- a/frontend/src/tools/MediaLibrary.svelte+++ b/frontend/src/tools/MediaLibrary.svelte@@ -10,9 +10,11 @@isGenericImage,isSatelliteMedia,mediaDisplayKind,+ mediaPoint,visibleMedia,SORTS,} from '../lib/mediaFilter.js';+ import { gotoPoint } from '../lib/navigate.js';import Icon from '../components/Icon.svelte';import SearchInput from '../components/SearchInput.svelte';import Modal from '../components/Modal.svelte';@@ -33,6 +35,7 @@q: query,category: catFilter,folder: folderFilter,+ gps: gpsOnly,sort,direction: sortDirection,limit: PAGE,@@ -92,6 +95,15 @@// --- folder filter (user-defined folders) ---let folderFilter = $state(null); // null = All+ // --- position filter (independent of type and folder) ---+ // The one filter a geolocation case asks for constantly: which files told us+ // where they were taken. Offered only when the case holds some, so it never+ // adds a dead control to a case of screenshots.+ let gpsOnly = $state(false);+ const gpsCount = $derived(+ pl.facets?.gps_count ?? items.filter((i) => mediaPoint(i)).length+ );+// --- free-text search + sort ---let query = $state('');let sort = $state('name');@@ -105,10 +117,10 @@{ id: 'added', label: 'Added' },];const browseFiltersActive = $derived(- query.length > 0 || catFilter !== null || folderFilter !== null+ query.length > 0 || catFilter !== null || folderFilter !== null || gpsOnly);const filtersActive = $derived(- query.length > 0 || catFilter !== null || folderFilter !== null || sort !== 'name' || sortDirection !== 'asc'+ browseFiltersActive || sort !== 'name' || sortDirection !== 'asc');const showBrowseBar = $derived(items.length > 0 || browseFiltersActive);@@ -129,6 +141,7 @@hasCase: !!caseState.current,catMatch,folderFilter,+ gpsOnly,query,sort,direction: sortDirection,@@ -183,10 +196,31 @@reloadIfServerBacked();}+ function toggleGpsOnly() {+ gpsOnly = !gpsOnly;+ reloadIfServerBacked();+ }++ /** The stated position, spelled out. Lives in the tooltip rather than in the+ * row: a filename is what the analyst reads a list by. */+ function pointLabel(item) {+ const point = mediaPoint(item);+ return point ? `${point.lat.toFixed(6)}, ${point.lon.toFixed(6)}` : '';+ }++ // The map is where a claimed position gets judged, and enrichment's proposed+ // place is already waiting there as a mark.+ function showOnMap(item, event) {+ event?.stopPropagation(); // the thumbnail behind this opens the lightbox+ const point = mediaPoint(item);+ if (point) gotoPoint(point.lat, point.lon);+ }+function resetFilters() {query = '';catFilter = null;folderFilter = null;+ gpsOnly = false;sort = 'name';sortDirection = 'asc';headerSort = null;@@ -236,6 +270,9 @@const thumbsPending = $derived(items.some((i) => i.thumb_state === 'queued' || i.thumb_state === 'running'));+ const enrichmentPending = $derived(+ items.some((i) => i.enrich_state === 'queued' || i.enrich_state === 'running')+ );$effect(() => {const id = caseState.current?.id;@@ -303,6 +340,17 @@return pollWhile(() => thumbsPending, () => refresh(), 1500);});+ // Enrichment changes both the media sidecar and the Suggestions graph. Poll+ // both views until the worker settles, but only while Media is visible.+ $effect(() => {+ if (!enrichmentPending || uiState.tool !== 'media' || !caseState.current) return;+ return pollWhile(+ () => enrichmentPending,+ () => Promise.all([refresh(), reloadCase()]),+ 1500+ );+ });+// Queue (re)generation: a single failed thumbnail (path given) or every// missing/failed one across the case. The worker drains the queue; the poll// above reflects each result as it lands.@@ -331,6 +379,23 @@}}+ // Queue enrichment for media imported by an older version. The worker drains+ // the queue; Details and Suggestions update as each image lands.+ async function enrichMedia() {+ const id = caseState.current?.id;+ if (!id) return;+ try {+ const { queued } = await api.post(`/api/cases/${id}/media/enrich`, {});+ await refresh();+ toast(+ queued ? `Enriching ${queued} file${queued > 1 ? 's' : ''}` : 'Nothing left to enrich',+ queued ? 'info' : 'ok'+ );+ } catch (e) {+ toast(e.message, 'danger');+ }+ }+async function importFiles(fileList) {const files = [...fileList];if (!files.length) return;@@ -568,6 +633,14 @@><Icon name="reset" size={15} /> Thumbnails</button>+ <button+ class="btn"+ onclick={enrichMedia}+ title="Read image EXIF, hashes and video metadata locally"+ disabled={!items.length}+ >+ <Icon name="search" size={15} /> Enrich+ </button><inputtype="file"multiple@@ -619,6 +692,19 @@{/each}</select>+ {#if gpsCount || gpsOnly}+ <button+ class="btn btn-sm gps-filter"+ class:on={gpsOnly}+ type="button"+ aria-pressed={gpsOnly}+ title={`Show only the ${gpsCount} file${gpsCount > 1 ? 's' : ''} whose own metadata states a position`}+ onclick={toggleGpsOnly}+ >+ <Icon name="pin" size={13} /> GPS+ </button>+ {/if}+<!-- user-defined folders (independent facet) -->{#if folders.length}<span class="bar-sep"></span>@@ -745,6 +831,15 @@<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}`}>+ {#if mediaPoint(item)}+ <button+ class="btn btn-ghost btn-sm"+ title={`Metadata says ${pointLabel(item)} — show it on the map`}+ onclick={() => showOnMap(item)}+ >+ <Icon name="pin" size={14} />+ </button>+ {/if}<button class="btn btn-ghost btn-sm" title="Info / Edit notes" onclick={() => openInfo(item)}><Icon name="note" size={14} /></button>@@ -823,6 +918,16 @@<Icon name={KIND_ICONS[mediaDisplayKind(item)] ?? 'file'} size={34} />{/if}<span class="kind badge">{mediaDisplayKind(item)}</span>+ {#if mediaPoint(item)}+ <button+ class="gps-badge badge"+ title={`Metadata says ${pointLabel(item)} — show it on the map`}+ aria-label={`Show ${pointLabel(item)} on the map`}+ onclick={(e) => showOnMap(item, e)}+ >+ <Icon name="pin" size={11} />+ </button>+ {/if}{#if item.folder}<span class="folder-badge badge"><Icon name="folder" size={10} />{item.folder}@@ -1129,6 +1234,14 @@padding: 4px 8px;flex-shrink: 0;}+ .gps-filter {+ flex-shrink: 0;+ white-space: nowrap;+ }+ .gps-filter.on {+ border-color: var(--accent);+ color: var(--accent);+ }.reset-filters {margin-left: auto;white-space: nowrap;@@ -1291,6 +1404,23 @@background: rgba(16, 16, 16, 0.75);backdrop-filter: blur(4px);}+ /* a stated position, as one glyph: the coordinates are in the tooltip, and the+ badge is the way to the map rather than a second line of text */+ .gps-badge {+ position: absolute;+ top: 8px;+ right: 8px;+ padding: 3px 5px;+ border: 0;+ background: rgba(16, 16, 16, 0.75);+ backdrop-filter: blur(4px);+ color: var(--accent);+ cursor: pointer;+ }+ .gps-badge:hover {+ color: var(--accent-text, #fff);+ background: var(--accent);+ }.folder-badge {position: absolute;bottom: 6px;@@ -1337,6 +1467,24 @@gap: 2px;padding: 4px 8px 8px;}+ /* Cards only — a list row shares this class and must stay on one line. A card+ clips its overflow, so a button row that does not fit loses its last button,+ and the last one is Delete. Wrapping costs a few pixels of card height; a+ delete button that is there but unclickable costs trust. */+ .grid .actions {+ flex-wrap: wrap;+ }+ /* Small cards are 150px wide and hold the same five actions a large one does:+ at the default padding that is 184px of buttons inside 150px of card. Tighten+ the buttons rather than drop an action — every one of them is the only way to+ reach what it does from this view. */+ .grid.compact .actions {+ gap: 1px;+ padding-inline: 6px;+ }+ .grid.compact .actions .btn {+ padding-inline: 4px;+ }.del {margin-left: auto;}@@ -1344,15 +1492,33 @@.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;+ shifts every sortable heading out of alignment.++ So the actions cell is a fixed width, and it is computed rather than typed:+ one ghost icon button is a 14px glyph plus 8px of padding and a 1px border+ on each side, and the widest row holds six of them — GPS pin, info, open,+ inspect, proof, delete. A literal here goes stale the next time a tool earns+ a row action, and the symptom is the delete button quietly clipped off the+ end of the row. */+ --media-action: 32px;+ --media-action-gap: 2px;+ /* the six buttons plus slack. Sized to the exact sum, the cell fits only+ until a sub-pixel of rounding says otherwise, and then Delete — which+ `margin-left: auto` holds at the right edge — is the one that goes. The+ slack is also where that auto margin lives, so the row still reads as+ "actions, then delete". */+ --media-actions: calc(6 * var(--media-action) + 5 * var(--media-action-gap) + 10px);+ --media-columns: 54px minmax(180px, 1fr) 90px 82px minmax(100px, 0.45fr) 132px+ var(--media-actions);padding: 6px 20px 18px;}.media-row {display: grid;grid-template-columns: var(--media-columns);align-items: center;- min-width: 790px;+ /* the sum of the columns above, so the row scrolls rather than crushing its+ last cell when the panel is narrow */+ min-width: calc(624px + var(--media-actions));min-height: 54px;gap: 10px;padding: 5px 8px;@@ -1448,7 +1614,14 @@display: flex;align-items: center;min-width: 0;- gap: 2px;+ gap: var(--media-action-gap);+ /* a row is one line. The cell is sized to hold every button, so wrapping here+ would only ever mean the width calculation is wrong — and it would hide the+ error by dropping Delete onto a second line instead of showing it. */+ flex-wrap: nowrap;+ }+ .media-col-actions > * {+ flex: 0 0 auto;}.media-row:not(.media-head) .media-col-actions {opacity: 0.72;diff --git a/frontend/src/tools/MediaLibrary.test.js b/frontend/src/tools/MediaLibrary.test.jsindex 722cc97..f24d461 100644--- a/frontend/src/tools/MediaLibrary.test.js+++ b/frontend/src/tools/MediaLibrary.test.js@@ -65,6 +65,57 @@ describe('Media Library thumbnail states', () => {});});+describe('Media Library enrichment', () => {+ it('offers an explicit local backfill instead of running one on mount', () => {+ expect(source).toContain('async function enrichMedia()');+ expect(source).toContain('await api.post(`/api/cases/${id}/media/enrich`, {})');+ expect(source).toContain('title="Read image EXIF, hashes and video metadata locally"');+ expect(source).toContain('<Icon name="search" size={15} /> Enrich');+ });++ it('polls media and Suggestions while enrichment is running', () => {+ expect(source).toContain("i.enrich_state === 'queued' || i.enrich_state === 'running'");+ expect(source).toContain(+ "if (!enrichmentPending || uiState.tool !== 'media' || !caseState.current) return;"+ );+ expect(source).toContain('() => Promise.all([refresh(), reloadCase()])');+ expect(source).toContain('await refresh();');+ });+});++describe('Media Library positions', () => {+ it('filters on the position server-side, so it holds over a paged case', () => {+ expect(source).toContain('gps: gpsOnly');+ expect(source).toContain('function toggleGpsOnly()');+ expect(source).toContain('reloadIfServerBacked();');+ // ...and client-side too, for the case that fits one page+ expect(source).toContain('gpsOnly,');+ });++ it('counts the located files from the server facet, not from the loaded page', () => {+ expect(source).toContain('pl.facets?.gps_count ?? items.filter((i) => mediaPoint(i)).length');+ });++ it('hides the filter entirely in a case where nothing carries a position', () => {+ expect(source).toContain('{#if gpsCount || gpsOnly}');+ });++ it('marks a located row with one glyph and keeps the coordinates in the tooltip', () => {+ // the row is read by its filename; coordinates belong in the tooltip and on+ // the map, not appended to every title+ expect(source).toContain('function pointLabel(item)');+ expect(source).toContain('title={`Metadata says ${pointLabel(item)} — show it on the map`}');+ expect(source).toContain('<Icon name="pin" size={11} />');+ expect(source).not.toContain('{pointLabel(item)}<');+ });++ it('sends a stated position to the map without disturbing the thumbnail', () => {+ expect(source).toContain('function showOnMap(item, event)');+ expect(source).toContain('event?.stopPropagation();');+ expect(source).toContain('gotoPoint(point.lat, point.lon)');+ });+});+describe('Media Library bounded loading', () => {it('browses via the bounded /media/page endpoint, not the unbounded list', () => {expect(source).toContain('createPagedList');@@ -147,9 +198,16 @@ describe('Media Library browse controls', () => {});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;');+ // still one fixed grid — an `auto` actions column is empty in the header and+ // wide in a data row, which shifts every sortable heading out of alignment.+ // The actions width is computed from the button metrics rather than typed;+ // the literal it replaced fitted exactly five buttons and clipped the sixth.+ expect(source).toContain(+ '--media-columns: 54px minmax(180px, 1fr) 90px 82px minmax(100px, 0.45fr) 132px'+ );expect(source).toContain('grid-template-columns: var(--media-columns);');expect(source).not.toContain('132px auto;');+ expect(source).not.toContain('132px 168px;');});it('uses one folder dropdown and keeps its default unfiltered', () => {@@ -181,7 +239,7 @@ describe('Media Library browse controls', () => {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("query = '';\n catFilter = null;\n folderFilter = null;\n gpsOnly = false;\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');@@ -224,3 +282,37 @@ describe('Media Library gated-download cookie affordance', () => {expect(source).toContain('disabled={authPrompt.busy || chromiumBlocked}');});});++describe('row and card actions fit', () => {+ const source = readFileSync(new URL('./MediaLibrary.svelte', import.meta.url), 'utf8');++ it('sizes the list actions cell from the widest row, not from a literal', () => {+ // six at its widest: GPS pin, info, open, inspect, proof, delete. A typed+ // width goes stale the next time a tool earns a row action, and the symptom+ // is Delete clipped off the end of the row.+ expect(source).toContain('--media-action: 32px');+ expect(source).toContain(+ '--media-actions: calc(6 * var(--media-action) + 5 * var(--media-action-gap) + 10px)'+ );+ // sized to the exact sum, the cell fits only until a sub-pixel of rounding+ // says otherwise, and then Delete wraps to a line of its own+ expect(source).toContain('flex-wrap: nowrap;');+ expect(source).toContain('var(--media-actions);');+ expect(source).toContain('min-width: calc(624px + var(--media-actions));');+ // and the cell's own gap is the one the width was computed from+ expect(source).toContain('gap: var(--media-action-gap);');+ });++ it('keeps every card action reachable in the 150px small view', () => {+ // the card clips its overflow, so a row that does not fit loses its last+ // button — Delete+ expect(source).toContain('.grid.compact .actions .btn {');+ expect(source).toContain('padding-inline: 4px;');+ });++ it('lets a card wrap without letting a list row wrap', () => {+ // both share the `actions` class; only the card may take a second line+ expect(source).toContain('.grid .actions {\n flex-wrap: wrap;');+ expect(source).not.toMatch(/\n \.actions \{[^}]*flex-wrap: wrap/);+ });+});diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelteindex 7e10869..2e0734f 100644--- a/frontend/src/tools/Satellite.svelte+++ b/frontend/src/tools/Satellite.svelte@@ -14,6 +14,8 @@import { clampSize, scaledCapture } from '../lib/captureSize.js';import { panelWidth } from '../lib/panelWidth.js';import { assignFolder } from '../lib/filing.js';+ import { saveRelation } from '../lib/relations.svelte.js';+ import { openEntity } from '../lib/navigate.js';import { isRegistered, sourceRect, frameFitsView } from '../lib/screenCrop.js';import { extensionVersion, captureTab, onActivated } from '../lib/extBridge.js';import {@@ -54,6 +56,8 @@import FolderBrowser from '../components/FolderBrowser.svelte';import ConfirmDialog from '../components/ConfirmDialog.svelte';import FolderSelect from '../components/FolderSelect.svelte';+ import RelationList from '../components/RelationList.svelte';+ import RelationPicker from '../components/RelationPicker.svelte';import RefViewer from './RefViewer.svelte';import MapToolCluster from './satellite/MapToolCluster.svelte';import GridSearchPanel from './satellite/GridSearchPanel.svelte';@@ -2645,6 +2649,7 @@lon: displayCoords.lon,zoom: center.zoom,bearing,+ relation: null, // collected by the gate, filed once the place exists};}@@ -2658,7 +2663,23 @@lon: Number(row.lon),zoom: row.zoom,bearing: row.bearing,+ relation: null,+ relations: [],};+ loadPlaceRelations(row.id);+ }++ /** The relations a place already holds, from the bounded chain endpoint. The+ * dialog edits everything else about the point, so hiding them here would make+ * it the one surface where a relation can be added but never taken back. */+ async function loadPlaceRelations(placeId) {+ if (!placeId) return;+ try {+ const chain = await api.get(`/api/cases/${caseState.current.id}/entities/${placeId}/chain`);+ if (placeModal?.id === placeId) placeModal.relations = chain?.relations ?? [];+ } catch {+ if (placeModal?.id === placeId) placeModal.relations = [];+ }}function placeCoordsLabel(m) {@@ -2670,16 +2691,19 @@placeSaving = true;try {const m = placeModal;+ let caseId = caseState.current.id;+ let placeId = m.id;if (m.id) {// edit existing place: retitle + set/clear the noteconst title = m.title.trim() || placeCoordsLabel(m);- await api.patch(`/api/cases/${caseState.current.id}/entities/${m.id}`, {+ await api.patch(`/api/cases/${caseId}/entities/${m.id}`, {label: title,attrs: { notes: m.notes.trim(), folder: m.folder ?? '' },});} else {const c = await ensureCase();- await api.post(`/api/cases/${c.id}/satellite/place`, {+ caseId = c.id;+ const entity = await api.post(`/api/cases/${c.id}/satellite/place`, {lat: m.lat,lon: m.lon,zoom: m.zoom,@@ -2688,7 +2712,11 @@notes: m.notes,folder: m.folder,});+ placeId = entity.id;}+ // The relation is filed last: it needs a place that exists, and saving the+ // point is worth keeping even if the edge is refused.+ if (m.relation && placeId) await saveRelation(caseId, placeId, m.relation);placeModal = null;await reloadCase();toast('Place saved', 'ok', 1600);@@ -2748,6 +2776,7 @@onproof={sendToComposer}onpost={openLinkedPost}onshowproofs={() => (savedKind = 'proofs')}+ onrefresh={reloadCase}/>{/if}@@ -3402,6 +3431,24 @@</div></div><hr style="border:none;border-top:1px solid var(--border);margin:12px 0" />+ <!-- what this point already claims, and why it is being saved — said while+ the analyst still knows: the photo it geolocates, the video whose+ metadata pointed here -->+ <span style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin-bottom:5px">Relations</span>+ {#if placeModal.relations?.length}+ <RelationList+ caseId={caseState.current.id}+ relations={placeModal.relations}+ subjectType="place"+ onwalk={(entity) => { placeModal = null; openEntity(entity); }}+ onchanged={async () => {+ await loadPlaceRelations(placeModal?.id);+ await reloadCase();+ }}+ />+ {/if}+ <RelationPicker subjectType="place" bind:value={placeModal.relation} />+ <hr style="border:none;border-top:1px solid var(--border);margin:12px 0" /><label for="place-notes" style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin-bottom:5px">Notes</label><textareaid="place-notes"diff --git a/frontend/src/tools/satellite/SavedOverlay.svelte b/frontend/src/tools/satellite/SavedOverlay.svelteindex 4f40263..90dd553 100644--- a/frontend/src/tools/satellite/SavedOverlay.svelte+++ b/frontend/src/tools/satellite/SavedOverlay.svelte@@ -7,6 +7,7 @@import L from 'leaflet';import { paths } from '../../components/Icon.svelte';import { groupSavedMarkers, markerPrecision } from '../../lib/savedMarkers.js';+ import { openEntity } from '../../lib/navigate.js';import SavedPopup from './SavedPopup.svelte';let {@@ -21,6 +22,7 @@onproof,onpost,onshowproofs,+ onrefresh,} = $props();const GLYPH = { place: 'pin', capture: 'satellite', screenshot: 'screen', proof: 'proof' };@@ -88,6 +90,14 @@map.closePopup();onshowproofs?.();},+ // opening a related media leaves the map, so close the card first — the+ // same gesture as every other row here, rather than a popup that+ // vanishes without saying it would+ onentity: (entity) => {+ map.closePopup();+ openEntity(entity);+ },+ onrefresh: () => onrefresh?.(),},});return host;@@ -101,11 +111,59 @@return () => map.off('zoomend', sync);});+ // Is a card open? Rebuilding the layer destroys it, and the card is a surface+ // the analyst works in — settling relations, reading a stack. So a refreshed+ // index waits for the card to close rather than pulling it out from under them.+ let popupOpen = $state(false);+ $effect(() => {+ if (!map) return;+ const opened = () => (popupOpen = true);+ const closed = () => (popupOpen = false);+ map.on('popupopen', opened);+ map.on('popupclose', closed);+ return () => {+ map.off('popupopen', opened);+ map.off('popupclose', closed);+ };+ });++ // The group is replaced by `rebuild` and torn down when the overlay itself goes+ // away — deliberately not through the data effect's cleanup, which Svelte runs+ // before every re-run, including one that decides to defer.+ let group = null;+ let builtFor = null; // the case the current layer was built for+$effect(() => {if (!map) return;- const marks = groupSavedMarkers(items, markerPrecision(zoom));+ return () => {+ group?.remove();+ group = null;+ elements = new Map();+ if (mounted) {+ unmount(mounted);+ mounted = null;+ }+ };+ });++ $effect(() => {+ const rows = items;+ const cid = caseId;+ const precision = markerPrecision(zoom);+ const held = popupOpen; // tracked, so closing the card applies what waited+ if (!map) return;+ // A different case is never deferred: leaving another case's marks on the map+ // would be worse than closing a card.+ if (held && builtFor === cid) return;+ builtFor = cid;+ rebuild(rows, precision);+ });++ function rebuild(rows, precision) {+ const marks = groupSavedMarkers(rows, precision);const next = new Map();- const group = L.layerGroup(+ group?.remove();+ group = L.layerGroup(marks.map((mark) => {const marker = L.marker([mark.lat, mark.lon], {icon: icon(mark),@@ -131,15 +189,7 @@})).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 itdiff --git a/frontend/src/tools/satellite/SavedPopup.svelte b/frontend/src/tools/satellite/SavedPopup.svelteindex 503cf9e..8954ec9 100644--- a/frontend/src/tools/satellite/SavedPopup.svelte+++ b/frontend/src/tools/satellite/SavedPopup.svelte@@ -9,6 +9,9 @@* the ground rather than of your clicks.*/import Icon from '../../components/Icon.svelte';+ import RelationList from '../../components/RelationList.svelte';+ import { api } from '../../lib/api.js';+ import { toast } from '../../lib/state.svelte.js';import { postTarget } from '../../lib/post.js';import { stackOrder } from '../../lib/savedMarkers.js';@@ -22,6 +25,8 @@onproof,onpost,onshowproofs,+ onentity, // a related entity was picked: leave for its own tool+ onrefresh, // a relation was settled: sync the other surfaces} = $props();const GLYPH = { place: 'pin', capture: 'satellite', screenshot: 'screen', proof: 'proof' };@@ -51,6 +56,62 @@const here = $derived(ordered[0]);const day = (stamp) => (stamp ? String(stamp).slice(0, 10) : null);+++ // Relations: the saved index carries the count, never the edges — it is loaded+ // whole on case open. The edges come from the bounded chain endpoint, per row,+ // and only for a row whose relations are on screen. A single mark opens them+ // straight away (clicking a place to see which photos claim it is the point of+ // the gesture); a stack waits to be asked, so five marks are not five fetches.+ //+ // Settling one reloads this row's edges, then asks the host to sync the rest —+ // confirming a proposed relation confirms its point, which the Suggestions list+ // shows too. The refreshed index cannot rebuild the layer under an open card+ // (SavedOverlay defers that), so the count reads the loaded list meanwhile.+ let openRows = $state([]);+ let relationsByRow = $state({});+ const relationCount = (row) =>+ relationsByRow[rowKey(row)]?.length ?? Number(row.relations ?? 0);+ const relationsShown = (row) => openRows.includes(rowKey(row));++ $effect(() => {+ const only = ordered.length === 1 ? ordered[0] : null;+ // guarded on "already open": this effect writes the state it reads, so+ // without it the row would be fetched a second time on the re-run+ if (!only || !relationCount(only) || relationsShown(only)) return;+ showRelations(null, only);+ });++ async function loadRelations(row) {+ if (!caseId || !row.id) return;+ try {+ const chain = await api.get(`/api/cases/${caseId}/entities/${row.id}/chain`);+ relationsByRow = { ...relationsByRow, [rowKey(row)]: chain?.relations ?? [] };+ } catch (e) {+ // A read that failed is not an answer: caching it as an empty list would+ // have the card claim this point holds no relations. Fold the row back so+ // the count still says there are some, and a second click retries.+ openRows = openRows.filter((key) => key !== rowKey(row));+ toast(`Could not read the relations: ${e.message}`, 'danger', 5000);+ }+ }++ function showRelations(event, row) {+ // Leaflet decides whether a click was "on the map" by walking up from the+ // event target to find the popup container. This control replaces itself with+ // the loaded list, so by then the clicked button can already be detached from+ // the document — the walk finds nothing and the map closes the card under us.+ // Keeping the event inside the card is what makes that impossible.+ event?.stopPropagation();+ if (!relationsShown(row)) openRows = [...openRows, rowKey(row)];+ loadRelations(row);+ }++ async function relationSettled(row) {+ await loadRelations(row);+ await onrefresh?.();+ }+</script><div class="pop">@@ -85,6 +146,9 @@<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}+ {#if row.status === 'suggested'}+ <span class="proposed" title="Proposed from a file's own metadata">suggested</span>+ {/if}</p><p class="meta">{#if row.imagery_date}<span>Imagery {row.imagery_date}</span>{/if}@@ -100,6 +164,29 @@</p>{/if}{#if row.notes}<p class="note">{row.notes}</p>{/if}+ {#if relationCount(row)}+ <section class="relations">+ {#if relationsShown(row)}+ <p class="rel-heading">+ <Icon name="link" size={11} />+ {relationCount(row) === 1 ? 'Relation' : `Relations · ${relationCount(row)}`}+ </p>+ <RelationList+ {caseId}+ relations={relationsByRow[rowKey(row)] ?? []}+ subjectType={row.kind === 'place' ? 'place' : 'capture'}+ max={3}+ onwalk={(entity) => onentity?.(entity)}+ onchanged={() => relationSettled(row)}+ />+ {:else}+ <button type="button" class="link" onclick={(event) => showRelations(event, row)}>+ <Icon name="link" size={11} />+ {relationCount(row)} relation{relationCount(row) > 1 ? 's' : ''}+ </button>+ {/if}+ </section>+ {/if}{#if rowPosts.length}<section class="linked-posts"><p class="post-heading">@@ -297,11 +384,25 @@color: var(--text-2);overflow-wrap: anywhere;}- .linked-posts {+ .proposed {+ padding: 0 4px;+ border-radius: 999px;+ background: color-mix(in srgb, var(--accent) 16%, transparent);+ color: color-mix(in srgb, var(--accent) 85%, var(--text-2));+ font-size: 9px;+ }+ /* the dot separator the meta line inserts between its bits would read as part+ of the chip, so this one stands on its own */+ .meta > .proposed::before {+ content: none;+ }+ .linked-posts,+ .relations {margin-top: 4px;padding-top: 5px;border-top: 1px solid var(--border);}+ .rel-heading,.post-heading {display: flex;align-items: center;diff --git a/frontend/src/tools/satellite/SavedPopup.test.js b/frontend/src/tools/satellite/SavedPopup.test.jsindex 5f72b29..a9166fa 100644--- a/frontend/src/tools/satellite/SavedPopup.test.js+++ b/frontend/src/tools/satellite/SavedPopup.test.js@@ -183,3 +183,66 @@ describe('SavedOverlay popup wiring', () => {expect(overlay).toContain('row.key ?? row.id');});});++describe('SavedPopup relations', () => {+ const related = { ...place, relations: 2 };++ it('offers a stack of points its relations without fetching any of them', () => {+ // the saved index carries a count; five marks must not mean five requests+ const body = at([related, capture]);+ expect(body).toContain('2 relations');+ expect(body).not.toContain('Relations · 2');+ });++ it('says nothing at all about a point that has none', () => {+ expect(at([place])).not.toContain('relation');+ });++ it('marks a point enrichment proposed, so it cannot pass for analyst work', () => {+ expect(at([{ ...place, status: 'suggested' }])).toContain('suggested');+ expect(at([place])).not.toContain('suggested');+ });++ it('loads the edges from the bounded chain endpoint, not from the index', () => {+ const source = readFileSync(new URL('./SavedPopup.svelte', import.meta.url), 'utf8');+ expect(source).toContain('api.get(`/api/cases/${caseId}/entities/${row.id}/chain`)');+ expect(source).toContain('relationsByRow = { ...relationsByRow, [rowKey(row)]: chain?.relations ?? [] }');+ // a single mark opens them straight away: clicking a place to see which+ // photos claim it is the whole point of the gesture+ expect(source).toContain('const only = ordered.length === 1 ? ordered[0] : null;');+ // the auto-open effect writes the state it reads, so it guards on "already+ // open" rather than fetching the row twice+ expect(source).toContain('if (!only || !relationCount(only) || relationsShown(only)) return;');+ // the toggle keeps its click inside the card, or Leaflet closes it+ expect(source).toContain('event?.stopPropagation();');+ });++ it('syncs the other surfaces without the layer taking the card down', () => {+ // confirming a proposed relation confirms its point, which the Suggestions+ // list shows too — so the host reloads. The overlay defers rebuilding the+ // marker layer while a card is open, and the count reads the loaded list+ // meanwhile rather than the index it just invalidated.+ const source = readFileSync(new URL('./SavedPopup.svelte', import.meta.url), 'utf8');+ expect(source).toContain('await onrefresh?.()');+ expect(source).toContain('relationsByRow[rowKey(row)]?.length ?? Number(row.relations ?? 0)');+ expect(overlay).toContain('if (held && builtFor === cid) return;');+ expect(overlay).toContain("map.on('popupopen', opened)");+ // the layer's teardown is not the data effect's cleanup, which Svelte runs+ // before every re-run — including one that decides to defer+ expect(overlay).toContain('function rebuild(rows, precision)');+ });++ it('never caches a failed read as "this point has no relations"', () => {+ const source = readFileSync(new URL('./SavedPopup.svelte', import.meta.url), 'utf8');+ expect(source).toContain('openRows = openRows.filter((key) => key !== rowKey(row));');+ expect(source).toContain('Could not read the relations');+ });++ it('leaves for a related entity’s own tool by closing the card first', () => {+ // every other row in this card closes it before navigating; a popup that+ // vanishes without saying it would reads as a bug+ expect(overlay).toContain('onentity: (entity) => {');+ expect(overlay).toContain('map.closePopup();');+ expect(overlay).toContain('openEntity(entity);');+ });+});diff --git a/frontend/src/tools/satellite/SavedRow.svelte b/frontend/src/tools/satellite/SavedRow.svelteindex 053d3f8..1894136 100644--- a/frontend/src/tools/satellite/SavedRow.svelte+++ b/frontend/src/tools/satellite/SavedRow.svelte@@ -89,6 +89,10 @@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}+ <!-- a point enrichment proposed from a file's metadata, not analyst work -->+ {#if row.status === 'suggested'}+ <span class="proposed" title="Proposed from a file's own metadata">suggested</span>+ {/if}</span>{#if row.notes}<span class="note">{row.notes}</span>{/if}</span>@@ -250,6 +254,14 @@margin-right: 6px;color: var(--border-strong);}+ .proposed {+ flex-shrink: 0;+ padding: 0 4px;+ border-radius: 999px;+ background: color-mix(in srgb, var(--accent) 16%, transparent);+ color: color-mix(in srgb, var(--accent) 85%, var(--text-2));+ font-size: 9px;+ }.note {font-size: var(--fs-xs);color: var(--text-2);diff --git a/src/azimut/api/cases.py b/src/azimut/api/cases.pyindex 8a6bd84..848b536 100644--- a/src/azimut/api/cases.py+++ b/src/azimut/api/cases.py@@ -160,6 +160,19 @@ class EntityPatch(BaseModel):status: EntityStatus | None = None+class LinkIn(BaseModel):+ # `from`/`to` are the link's own field names, but `from` is a Python keyword;+ # the request spells them out rather than aliasing around it.+ from_id: str = Field(min_length=1, max_length=64)+ to_id: str = Field(min_length=1, max_length=64)+ type: str = Field(min_length=1, max_length=40)+++class LinkPatch(BaseModel):+ status: EntityStatus | None = None+ type: str | None = Field(default=None, min_length=1, max_length=40)++class FolderIn(BaseModel):name: str = Field(min_length=1, max_length=120)@@ -185,6 +198,27 @@ def create_scratch() -> dict[str, Any]:return {"id": case.id, **case.overview()}[email protected]("/relation-types")+def relation_types() -> list[dict[str, Any]]:+ """The relation vocabulary (ONTOLOGY §3): how each type reads in words, the+ entity types each end accepts, and whether an analyst may state it.++ Every surface reads this instead of keeping its own copy — the picker offers+ the ``manual`` ones, the relation rows use ``label`` to name an edge. Declared+ above ``/{case_id}`` so the literal path wins.+ """+ return [+ {+ "type": entry.type,+ "label": entry.label,+ "from_types": sorted(entry.from_types),+ "to_types": sorted(entry.to_types),+ "manual": entry.manual,+ }+ for entry in link_engine.RELATION_TYPES+ ]++@router.get("/{case_id}")def read_case(case_id: str) -> dict[str, Any]:case = get_case(case_id)@@ -321,11 +355,65 @@ def update_entity(case_id: str, entity_id: str, body: EntityPatch) -> dict[str,case = get_case(case_id)patch = {k: v for k, v in body.model_dump().items() if v is not None}try:- return case.update_entity(entity_id, patch)+ entity = case.update_entity(entity_id, patch)+ if body.status == "confirmed":+ link_engine.confirm_incident_relations(case, entity_id)+ return entityexcept CaseError as exc:raise HTTPException(status_code=404, detail=str(exc)) from exc[email protected]("/{case_id}/links")+def create_link(case_id: str, body: LinkIn) -> dict[str, Any]:+ """State one relation by hand. Confirmed, and only from the registry."""+ try:+ return link_engine.add_relation(+ get_case(case_id), body.from_id, body.to_id, body.type, by="user"+ )+ except CaseError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc++[email protected]("/{case_id}/links/{link_id}")+def update_link(case_id: str, link_id: str, body: LinkPatch) -> dict[str, Any]:+ """Confirm a suggestion, or correct which relation an edge states.++ Restating the type goes through the vocabulary, so a 400 means the ontology+ has no such reading for those two entities; a missing link is a 404.+ """+ if body.status is None and body.type is None:+ raise HTTPException(status_code=400, detail="nothing to update")+ case = get_case(case_id)+ try:+ link = case.get_link(link_id)+ if link is None:+ raise HTTPException(status_code=404, detail=f"link '{link_id}' not found")+ if body.type is not None and body.type != link["type"]:+ link = link_engine.set_relation_type(case, link_id, body.type)+ if body.status == "confirmed":+ link = link_engine.confirm_relation(case, link_id)+ elif body.status is not None:+ link = case.update_link(link_id, {"status": body.status})+ return link+ except CaseError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc++[email protected]("/{case_id}/links/{link_id}")+def remove_link(case_id: str, link_id: str) -> dict[str, str]:+ """Take back one relation. Dismissing a proposal and retracting a confirmed+ statement are the same gesture; a derivation is neither, and is refused with a+ 400 rather than dropped without its tombstone."""+ case = get_case(case_id)+ if case.get_link(link_id) is None:+ raise HTTPException(status_code=404, detail=f"link '{link_id}' not found")+ try:+ link_engine.remove_relation(case, link_id)+ except CaseError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ return {"status": "deleted"}++@router.get("/{case_id}/entities/{entity_id}/dependents")def entity_dependents(case_id: str, entity_id: str) -> dict[str, Any]:"""What deleting this entity would take with it, and what it would scar.@@ -346,9 +434,8 @@ def entity_dependents(case_id: str, entity_id: str) -> dict[str, Any]:@router.get("/{case_id}/entities/{entity_id}/chain")def entity_chain(case_id: str, entity_id: str) -> dict[str, Any]:- """One entity plus its derivation chain (sources, dependents, lost sources),- read from its incident links only — the Details panel's relations without- shipping the whole graph (Step 5)."""+ """One entity plus its derivation chain and direct relations, read from its+ incident links only without shipping the whole graph."""case = get_case(case_id)chain = link_engine.chain_of(case, entity_id)if chain is None:diff --git a/src/azimut/api/media.py b/src/azimut/api/media.pyindex ffe79e7..cf7afe7 100644--- a/src/azimut/api/media.py+++ b/src/azimut/api/media.py@@ -8,6 +8,7 @@ from fastapi import APIRouter, HTTPException, UploadFilefrom pydantic import BaseModel, Field, HttpUrlfrom .. import config, jobs+from ..engine import enrich as enrich_enginefrom ..engine import media as media_enginefrom ..engine import thumbnails as thumbnail_enginefrom ..workspace import Case, CaseError@@ -40,31 +41,48 @@ class ThumbRegenIn(BaseModel):path: str | None = None+class EnrichIn(BaseModel):+ path: str | None = None++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`` when- the cached file is present, ``queued``/``running``/``failed`` from its- thumbnail job while the worker is on it, else ``none`` (no thumbnail, e.g. an- audio file, or one pruned from the cache). A referenced-but-missing thumbnail- (evicted by the budget) is reported as absent so the grid falls back cleanly.+ """Tag each media item with the background states the UI polls.++ ``thumb_state`` is ``ready`` when the cached file is present,+ ``queued``/``running``/``failed`` from its thumbnail job, else ``none``.+ ``enrich_state`` follows the enrichment job and is ``ready`` once the current+ enrichment version has landed. A referenced-but-missing thumbnail (evicted+ by the budget) is reported as absent so the grid falls back cleanly."""- jobs_by_path = {j["key"]: j for j in case.list_jobs(kind=thumbnail_engine.THUMB_KIND)}+ thumb_jobs = {j["key"]: j for j in case.list_jobs(kind=thumbnail_engine.THUMB_KIND)}+ enrich_jobs = {j["key"]: j for j in case.list_jobs(kind=enrich_engine.ENRICH_KIND)}for item in items:thumb = item.get("thumbnail")if thumb and case.resolve_inside(thumb).exists():item["thumb_state"] = "ready"- continue- item["thumbnail"] = None- if item.get("kind") not in thumbnail_engine.THUMBNAILED_KINDS:- item["thumb_state"] = "none"else:- job = jobs_by_path.get(item["path"])- item["thumb_state"] = (- job["state"] if job and job["state"] in ("queued", "running", "failed") else "none"- )+ item["thumbnail"] = None+ if item.get("kind") not in thumbnail_engine.THUMBNAILED_KINDS:+ item["thumb_state"] = "none"+ else:+ job = thumb_jobs.get(item["path"])+ item["thumb_state"] = (+ job["state"]+ if job and job["state"] in ("queued", "running", "failed")+ else "none"+ )++ enrich_job = enrich_jobs.get(item["path"])+ if enrich_job and enrich_job["state"] in ("queued", "running", "failed"):+ item["enrich_state"] = enrich_job["state"]+ elif item.get("enrich_version") == enrich_engine.ENRICH_VERSION:+ item["enrich_state"] = "ready"+ else:+ item["enrich_state"] = "none"return items@@ -81,6 +99,7 @@ def page_media(kind: str | None = None,category: str | None = None,folder: str | None = None,+ gps: bool = False,sort: str = "newest",direction: str | None = None,limit: int = 200,@@ -90,7 +109,8 @@ def page_media((Media Library, Files). Small cases return one page with a null``next_cursor``, so the client filters in memory with no further calls; alarge case pages via ``cursor`` and searches server-side via ``q``.- ``facets`` counts the whole filtered set so category/folder controls stay+ ``gps=true`` keeps only the files whose metadata states a position.+ ``facets`` counts the whole filtered set so category/folder/GPS controls stayaccurate. The unbounded ``GET .../media`` stays for consumers that need thefull index (pickers, satellite crops, derivation)."""case = get_case(case_id)@@ -101,6 +121,7 @@ def page_media(kind=kind,category=category,folder=folder,+ gps=gps,sort=sort,direction=direction,limit=limit,@@ -110,6 +131,28 @@ def page_media(return result[email protected]("/cases/{case_id}/media/item")+def read_media_item(case_id: str, path: str) -> dict[str, Any]:+ """One media file, read from its sidecar — the whole record, enrichment's full+ metadata dumps included.++ The browse index leaves those dumps out on purpose (they are hundreds of rows+ per file, and the listings are read 200 at a time), so this is where a surface+ that shows one file gets them. ``entity_id`` comes off the index row rather+ than a graph lookup, so opening one file never scans the case.+ """+ case = get_case(case_id)+ try:+ item = media_engine.read_item(case, path)+ except CaseError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ if item is None:+ raise HTTPException(status_code=404, detail=f"no media at {path!r}")+ indexed = case.media_items_by_paths([path])+ entity_id = indexed[0].get("entity_id") if indexed else None+ return with_thumb_state(case, [{**item, "entity_id": entity_id}])[0]++@router.post("/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."""@@ -144,6 +187,41 @@ def regenerate_thumbnails(case_id: str, body: ThumbRegenIn) -> dict[str, int]:return {"queued": len(targets)}[email protected]("/cases/{case_id}/media/enrich")+def enrich_media(case_id: str, body: EnrichIn) -> dict[str, int]:+ """Queue local image and video enrichment.++ With a ``path`` this re-reads that one item. Without one it queues images+ that have not reached the current enrichment version, including media from+ older Azimut releases. Merely opening a case never starts this backfill.++ ``queued`` counts jobs the queue actually took, not items considered: naming a+ path whose kind carries no enrichment (an audio file, a PDF) queues nothing,+ and reporting one would have the toast announce work that will never run.+ """+ case = get_case(case_id)+ items = media_engine.list_media(case)+ if body.path is not None:+ targets = [item for item in items if item["path"] == body.path]+ else:+ targets = [+ item+ for item in items+ if item.get("kind") in enrich_engine.ENRICHED_KINDS+ and item.get("enrich_version") != enrich_engine.ENRICH_VERSION+ ]+ queued = 0+ for item in targets:+ if enrich_engine.on_register(+ case,+ item["path"],+ item.get("kind", ""),+ item.get("entity_id") or "",+ ):+ queued += 1+ return {"queued": queued}++@router.post("/cases/{case_id}/media/upload")async def upload(case_id: str, file: UploadFile) -> dict[str, Any]:case = get_case(case_id)diff --git a/src/azimut/engine/enrich.py b/src/azimut/engine/enrich.pynew file mode 100644index 0000000..4862960--- /dev/null+++ b/src/azimut/engine/enrich.py@@ -0,0 +1,509 @@+"""Import enrichment: what a file says about itself, read locally in a job.++- **Image EXIF** — every readable main, EXIF, GPS, interoperability, maker-note+ and thumbnail IFD field, with GPS and capture time parsed for suggestions.+- **Image dHash** — a 64-bit pixel fingerprint, so a resized or requantised copy+ of a picture already in the case still lands within a few bits of the original.+- **Video metadata** — ffprobe's container, stream and arbitrary tag fields,+ including parsed ISO 6709 GPS and creation time when the file carries them.++Nothing here decides anything. Results are written to the media sidecar and+proposed to the graph with ``status="suggested"`` (ONTOLOGY §4): a camera's own+metadata is a claim, and a claim the analyst has not looked at is not a fact.+"""++from __future__ import annotations++import json+import re+import subprocess+from datetime import datetime, timezone+from pathlib import Path+from typing import TYPE_CHECKING, Any++import numpy as np+from PIL import ExifTags, Image++from . import ffmpeg as ffmpeg_engine+from . import links as link_engine+from . import workqueue++if TYPE_CHECKING:+ from ..workspace import Case as CaseType++#: Image EXIF/dHash and video container metadata are local, bounded reads. Audio+#: and generic files carry no enrichment workflow yet.+ENRICHED_KINDS = frozenset({"image", "video"})++#: EXIF IFD pointers (EXIF 2.3 §4.6.3).+_GPS_IFD = 0x8825+_EXIF_IFD = 0x8769+_MAKER_NOTE_IFD = 0x927C+_INTEROP_IFD = 0xA005+_THUMBNAIL_IFD = -1+_DATETIME_ORIGINAL = 36867++# EXIF is attacker-controlled input. Keep every readable tag, but bound both+# the tag count and each rendered value before it reaches a sidecar and the UI.+EXIF_TAG_CAP = 256+EXIF_VALUE_CAP = 512+VIDEO_FIELD_CAP = 512++_ISO6709 = re.compile(r"^\s*([+-]\d{2}(?:\.\d+)?)([+-]\d{3}(?:\.\d+)?)")++#: dHash grid: an 8x9 grayscale reduction gives 8x8 = 64 comparison bits.+_HASH_SIDE = 8++#: Hamming distance at or below which two hashes are proposed as the same+#: picture. 10/64 tolerates rescaling and JPEG requantisation while keeping+#: unrelated photographs apart.+DHASH_MATCH = 10+ENRICH_VERSION = 2++#: How many of the case's existing hashes one job compares against, newest+#: first. The scan is a linear read of the media index, so it is bounded rather+#: than left to grow with the case; past this, a near-duplicate simply is not+#: proposed. Exact-byte duplicates never reach here — ``media._register``+#: dedupes on SHA-256 first.+DHASH_SCAN_CAP = 5000++#: Link types this module proposes, from the shared registry. Neither is a chain+#: type, so neither cascades a delete nor leaves a tombstone: a suggestion the+#: analyst never looked at must not decide what a delete destroys.+LOCATED_AT = link_engine.LOCATED_AT+SAME_IMAGE_AS = link_engine.SAME_IMAGE_AS+++def _decimal(dms: Any, ref: Any) -> float | None:+ """One EXIF coordinate: (degrees, minutes, seconds) rationals plus a N/S/E/W+ reference, folded into a signed decimal degree."""+ try:+ degrees, minutes, seconds = (float(part) for part in tuple(dms)[:3])+ except (TypeError, ValueError, ZeroDivisionError):+ return None+ value = degrees + minutes / 60 + seconds / 3600+ if str(ref).strip().upper() in ("S", "W"):+ value = -value+ return value+++def _gps(exif: Image.Exif) -> dict[str, float] | None:+ """The image's GPS point, or None when it has none, when the pair is+ incomplete, when it is out of range, or when it is exactly (0, 0) — Null+ Island is overwhelmingly a zeroed field rather than a photograph taken in the+ Gulf of Guinea."""+ try:+ gps = exif.get_ifd(_GPS_IFD)+ except Exception:+ return None+ if not gps:+ return None+ lat = _decimal(gps.get(2), gps.get(1))+ lon = _decimal(gps.get(4), gps.get(3))+ if lat is None or lon is None:+ return None+ if not (-90 <= lat <= 90) or not (-180 <= lon <= 180):+ return None+ if lat == 0 and lon == 0:+ return None+ return {"lat": lat, "lon": lon}+++def _taken_at(exif: Image.Exif) -> str | None:+ """DateTimeOriginal as an ISO string. No timezone is appended: EXIF records+ the camera's own clock with no offset, and stamping a ``Z`` on it would claim+ a UTC the file never asserted."""+ try:+ raw = exif.get_ifd(_EXIF_IFD).get(_DATETIME_ORIGINAL)+ except Exception:+ return None+ if not raw:+ return None+ try:+ parsed = datetime.strptime(str(raw).strip(), "%Y:%m:%d %H:%M:%S")+ except ValueError:+ return None+ return parsed.strftime("%Y-%m-%dT%H:%M:%S")+++def _display_value(value: Any) -> str:+ """A bounded, JSON-safe rendering of one EXIF value.++ The cap is applied while building the string, not after: a maker note is a+ megabyte of bytes and a lens table is thousands of rationals, and rendering+ either one in full before slicing it to 512 characters would do all the work+ the cap exists to avoid.+ """+ if isinstance(value, bytes):+ decoded = value[: EXIF_VALUE_CAP + 1].rstrip(b"\x00").decode("utf-8", errors="replace")+ if not decoded.isprintable(): # a binary blob: report its size instead+ return f"{len(value)} bytes"+ return decoded[:EXIF_VALUE_CAP] + ("…" if len(value) > EXIF_VALUE_CAP else "")+ if isinstance(value, (tuple, list)):+ parts: list[str] = []+ length = 0+ for part in value:+ parts.append(str(part))+ length += len(parts[-1]) + 2+ if length > EXIF_VALUE_CAP:+ break+ text = ", ".join(parts)+ else:+ text = str(value)+ return text[:EXIF_VALUE_CAP] + ("…" if len(text) > EXIF_VALUE_CAP else "")+++def exif_metadata(path: Path) -> dict[str, str]:+ """Every readable EXIF tag, flattened into display-ready key/value rows.++ Pillow keeps GPS and camera tags in nested IFDs. Expand those rather than+ exposing their numeric pointers, and prefix duplicate names only when one+ would otherwise overwrite another. The bounded strings can be stored in a+ media sidecar and rendered without re-opening the image.+ """+ try:+ with Image.open(path) as img:+ exif = img.getexif()+ if not exif:+ return {}++ rows: dict[str, str] = {}++ def add(name: str, value: Any, prefix: str = "") -> None:+ if len(rows) >= EXIF_TAG_CAP:+ return+ key = name if name not in rows else f"{prefix}{name}"+ if key in rows:+ return+ rows[key] = _display_value(value)++ for tag_id, value in exif.items():+ if tag_id in (_GPS_IFD, _EXIF_IFD):+ continue+ add(ExifTags.TAGS.get(tag_id, str(tag_id)), value, "Image ")++ def read_ifd(ifd: int) -> dict[int, Any]:+ try:+ return exif.get_ifd(ifd)+ except Exception:+ return {}++ interop_names = {+ int(member): member.name+ for member in getattr(ExifTags, "Interop", ())+ }+ ifd_specs: tuple[tuple[int, dict[int, str], str], ...] = (+ (_EXIF_IFD, ExifTags.TAGS, "EXIF "),+ (_GPS_IFD, ExifTags.GPSTAGS, "GPS "),+ (_INTEROP_IFD, interop_names, "Interop "),+ (_MAKER_NOTE_IFD, {}, "Maker note "),+ (_THUMBNAIL_IFD, ExifTags.TAGS, "Thumbnail "),+ )++ for ifd, names, prefix in ifd_specs:+ for tag_id, value in read_ifd(ifd).items():+ add(names.get(tag_id, str(tag_id)), value, prefix)++ return rows+ except Exception:+ return {}+++def exif_facts(path: Path) -> dict[str, Any]:+ """The GPS point and capture date an image carries. Missing, unreadable or+ implausible values are left out rather than reported as empty: this feeds+ suggestions, and a suggestion of nothing is noise."""+ try:+ with Image.open(path) as img:+ exif = img.getexif()+ except Exception: # unreadable file, decode clamp, no EXIF block at all+ return {}+ facts: dict[str, Any] = {}+ gps = _gps(exif)+ if gps:+ facts["gps"] = gps+ taken = _taken_at(exif)+ if taken:+ facts["taken_at"] = taken+ return facts+++def _flatten_video(prefix: str, value: Any, rows: dict[str, str]) -> None:+ """Flatten ffprobe JSON without assuming today's container tag vocabulary."""+ if len(rows) >= VIDEO_FIELD_CAP:+ return+ if isinstance(value, dict):+ for key, nested in value.items():+ clean_key = str(key).replace("_", " ")[:120]+ label = f"{prefix} · {clean_key}" if prefix else clean_key+ _flatten_video(label, nested, rows)+ return+ if isinstance(value, list):+ for index, nested in enumerate(value):+ _flatten_video(f"{prefix} {index}", nested, rows)+ return+ rows[prefix] = _display_value(value)+++def _video_gps(data: dict[str, Any]) -> dict[str, float] | None:+ """A QuickTime/MP4 ISO 6709 location tag, or a decimal GPS pair."""+ tags: list[tuple[str, Any]] = []+ format_data = data.get("format")+ if isinstance(format_data, dict) and isinstance(format_data.get("tags"), dict):+ tags.extend(format_data["tags"].items())+ for stream in data.get("streams", []):+ if isinstance(stream, dict) and isinstance(stream.get("tags"), dict):+ tags.extend(stream["tags"].items())++ for key, raw in tags:+ folded = str(key).casefold()+ if "location" not in folded and "gps" not in folded:+ continue+ text = str(raw).strip()+ match = _ISO6709.match(text)+ if match:+ lat, lon = float(match.group(1)), float(match.group(2))+ if -90 <= lat <= 90 and -180 <= lon <= 180 and (lat != 0 or lon != 0):+ return {"lat": lat, "lon": lon}+ parts = [part.strip() for part in text.split(",", 1)]+ if len(parts) == 2:+ try:+ lat, lon = float(parts[0]), float(parts[1])+ except ValueError:+ continue+ if -90 <= lat <= 90 and -180 <= lon <= 180 and (lat != 0 or lon != 0):+ return {"lat": lat, "lon": lon}+ return None+++def video_facts(path: Path) -> dict[str, Any] | None:+ """All ffprobe container/stream metadata, plus parsed GPS and capture time.++ ``None`` means the probe never ran — ffprobe is missing, or it died or timed+ out — so no enrichment version is stamped and the backfill will try this file+ again. An unreadable video returns an empty dict instead: ffprobe did look and+ the file exposed no trustworthy metadata, which is an answer, and re-reading it+ on every backfill would never produce a different one.+ """+ probe = ffmpeg_engine.ffprobe_path()+ if probe is None:+ return None+ try:+ proc = subprocess.run(+ [+ probe,+ "-v",+ "error",+ "-print_format",+ "json",+ "-show_format",+ "-show_streams",+ str(path),+ ],+ capture_output=True,+ timeout=30,+ )+ except (OSError, subprocess.TimeoutExpired):+ return None # the probe never finished: transient, so let it be retried+ if proc.returncode != 0:+ return {}+ try:+ data = json.loads(proc.stdout or b"{}")+ except (TypeError, ValueError):+ return {}+ if not isinstance(data, dict):+ return {}++ rows: dict[str, str] = {}+ _flatten_video("", data, rows)+ facts: dict[str, Any] = {"video_metadata": rows} if rows else {}+ gps = _video_gps(data)+ if gps:+ facts["gps"] = gps++ format_data = data.get("format")+ tags = format_data.get("tags") if isinstance(format_data, dict) else {}+ taken_at = tags.get("creation_time") if isinstance(tags, dict) else None+ if not taken_at:+ for stream in data.get("streams", []):+ stream_tags = stream.get("tags") if isinstance(stream, dict) else None+ if isinstance(stream_tags, dict) and stream_tags.get("creation_time"):+ taken_at = stream_tags["creation_time"]+ break+ if taken_at:+ facts["taken_at"] = str(taken_at)+ return facts+++def dhash(path: Path) -> str:+ """A 64-bit difference hash of the image, as 16 hex characters.++ The picture is reduced to a 9x8 grayscale grid and each pixel is compared+ with its right-hand neighbour: what survives is the gradient structure, which+ is what stays the same across a resize or a re-encode.+ """+ with Image.open(path) as img:+ gray = img.convert("L").resize((_HASH_SIDE + 1, _HASH_SIDE), Image.Resampling.BILINEAR)+ pixels = np.asarray(gray, dtype=np.int16)+ brighter = pixels[:, 1:] > pixels[:, :-1]+ return str(np.packbits(brighter.flatten()).tobytes().hex())+++def hamming(a: str, b: str) -> int:+ """Bit distance between two dHashes. A mismatched length means one of them+ came from a different generator, so nothing is comparable: report the maximum."""+ if len(a) != len(b):+ return _HASH_SIDE * _HASH_SIDE+ return bin(int(a, 16) ^ int(b, 16)).count("1")+++# -- the enrich job ---------------------------------------------------------++#: Job kind for the durable queue. Enrichment is queued, never inline: an import+#: must stay as fast as the copy it performs.+ENRICH_KIND = "enrich"+++def _now() -> str:+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+++def on_register(case: "CaseType", rel_media: str, kind: str, entity_id: str) -> bool:+ """Queue enrichment for a freshly imported item. Keyed on the media path, so+ a re-import or a backfill never stacks duplicates.++ Returns whether a job was queued, so a caller counting work (the Enrich+ button's backfill) reports what the queue took rather than what it offered.+ """+ if kind not in ENRICHED_KINDS:+ return False+ workqueue.enqueue(+ case,+ ENRICH_KIND,+ key=rel_media,+ payload={"path": rel_media, "entity_id": entity_id},+ )+ return True+++def _suggest_place(case: "CaseType", entity_id: str, gps: dict[str, float]) -> None:+ """Propose the media's own coordinates as a place, and point the media at it.++ Places are deduplicated on a rounded coordinate key (about 1 m), so a roll+ of photographs from one spot proposes one place rather than forty. The key+ is an attribute of the places enrichment mints; a place the analyst pinned+ by hand has none and is left alone, because merging the two is a judgement+ the Suggestions panel exists to let them make.+ """+ from . import satellite as satellite_engine++ key = f"{gps['lat']:.5f},{gps['lon']:.5f}"+ place = case.find_entity(attr="enrich_coord_key", value=key)+ if place is None:+ place = satellite_engine.save_place(+ case,+ gps["lat"],+ gps["lon"],+ by="enrich",+ extra_attrs={"enrich_coord_key": key},+ status="suggested",+ )+ case.add_link(+ entity_id,+ place["id"],+ LOCATED_AT,+ by="enrich",+ status="suggested",+ unique=True,+ )+++def _suggest_same_image(case: "CaseType", entity_id: str, rel: str, digest: str) -> None:+ """Propose the case's other pictures of the same scene.++ Bounded on purpose (``DHASH_SCAN_CAP``): this runs inside a job on every+ import, and an unbounded scan would grow with the case until an import of+ one photo reads the whole media index.++ Each match's entity comes off the index row it was already read from. A+ per-match graph lookup would be a full scan of the entities table, and a+ burst of near-identical photographs is exactly the case that produces many+ matches at once.+ """+ for item in case.list_media_items()[:DHASH_SCAN_CAP]:+ other = item.get("dhash")+ path = item.get("path")+ if not other or path == rel:+ continue+ if hamming(digest, other) > DHASH_MATCH:+ continue+ match_id = item.get("entity_id")+ if not match_id:+ continue+ case.add_link(+ entity_id,+ match_id,+ SAME_IMAGE_AS,+ by="enrich",+ status="suggested",+ unique=True,+ )+++def _handle(case: "CaseType", job: dict[str, Any]) -> None:+ """Run one enrichment job: read the file's own claims, record them on the+ sidecar. A media file that is gone cancels the job."""+ from . import media as media_engine++ rel = job["payload"].get("path")+ item = media_engine.read_item(case, rel) if rel else None+ if item is None:+ raise workqueue.JobCancelled(f"media gone: {rel}")+ path = case.resolve_inside(rel)+ if not path.exists():+ raise workqueue.JobCancelled(f"media gone: {rel}")++ # Has this file been through a completed enrichment before? Re-reading it+ # refreshes the facts, but it must not re-propose edges: dropping a suggestion+ # is how an analyst says "not that", and an Enrich click that resurrected every+ # dismissal would make the gesture unusable. Media from an older release has no+ # version stamp, so a first backfill still gets its suggestions.+ first_pass = item.get("enrich_version") is None++ facts: dict[str, Any] = {"enriched_at": _now()}+ if item.get("kind") == "video":+ video = video_facts(path)+ if video is None:+ facts["video_probe"] = "unavailable"+ else:+ facts["enrich_version"] = ENRICH_VERSION+ facts.update(video)+ else:+ facts["enrich_version"] = ENRICH_VERSION+ facts.update(exif_facts(path))+ metadata = exif_metadata(path)+ if metadata:+ facts["exif"] = metadata+ try:+ facts["dhash"] = dhash(path)+ except Exception: # unreadable pixels: the EXIF still stands on its own+ pass+ media_engine.merge_item(case, rel, facts)++ # The facts are recorded either way; the graph only hears about them as+ # proposals (ONTOLOGY §4). A missing entity id means this media predates the+ # link — the sidecar still gains its facts.+ if not first_pass:+ return+ entity_id = job["payload"].get("entity_id") or (+ case.find_entity(attr="path", value=rel) or {}+ ).get("id")+ if not entity_id:+ return+ if facts.get("gps"):+ _suggest_place(case, entity_id, facts["gps"])+ if facts.get("dhash"):+ _suggest_same_image(case, entity_id, rel, facts["dhash"])+++workqueue.register(ENRICH_KIND, _handle)diff --git a/src/azimut/engine/links.py b/src/azimut/engine/links.pyindex 99cd77c..9b219b9 100644--- a/src/azimut/engine/links.py+++ b/src/azimut/engine/links.py@@ -24,10 +24,16 @@ The test a new tool applies: *delete the target — is anything usable left in mfile?* Yes → ``derived-from``. No → ``depends-on``. Emitted at save time with``status: "confirmed"``: a derivation is a mechanical fact of the analyst's ownclick, not a tool's guess (ONTOLOGY §4).++Everything else is a **relation**: a statement about the world rather than about+how a file was made. ``RELATION_TYPES`` below is the registry the UI offers and+the API validates against, so one vocabulary serves the Details panel, the map+and the case board rather than one per tool."""from __future__ import annotations+from dataclasses import dataclassfrom datetime import datetime, timezonefrom typing import Any@@ -47,6 +53,188 @@ TOMBSTONE_TYPES = (DERIVED_FROM,)#: ``attrs`` key holding the tombstones. Additive — schema stays 0.LOST = "lost_sources"+# -- relations: the non-chain edges (ONTOLOGY §3) -----------------------------+#+# A relation says something about the world — this photo was shot there, these+# two files are the same picture — where a chain edge says something about how a+# file was produced. Nothing here cascades a delete or leaves a tombstone:+# removing either endpoint just drops the edge.++LOCATED_AT = "located-at"+SAME_IMAGE_AS = "same-image-as"+DEPICTS = "depicts"+++@dataclass(frozen=True)+class RelationType:+ """One relation the vocabulary knows, and what it may join.++ ``from_types``/``to_types`` are the entity types each end accepts, so the+ picker can only offer edges the ontology has a reading for and the API can+ refuse the rest. ``label`` completes the sentence *"<from> … <to>"* and is+ what every surface displays instead of the type slug. ``manual`` is whether+ an analyst may state it: some relations are only ever a machine's claim.+ """++ type: str+ label: str+ from_types: frozenset[str]+ to_types: frozenset[str]+ manual: bool = True+++#: The relation vocabulary, in menu order. Deliberately not every type in the+#: ONTOLOGY §3 table: a type reaches this tuple once an entity type exists at both+#: ends, so nothing is offered that cannot be filed.+RELATION_TYPES: tuple[RelationType, ...] = (+ RelationType(+ LOCATED_AT,+ "was shot at",+ from_types=frozenset({"media", "capture"}),+ to_types=frozenset({"place"}),+ ),+ RelationType(+ DEPICTS,+ "shows",+ from_types=frozenset({"media", "capture"}),+ to_types=frozenset({"place"}),+ ),+ # Enrichment's own claim: two files whose perceptual hashes are within+ # DHASH_MATCH bits. Named here so the UI can say it in words, never offered+ # by hand — a person comparing two pictures is not measuring a hash.+ RelationType(+ SAME_IMAGE_AS,+ "is the same picture as",+ from_types=frozenset({"media"}),+ to_types=frozenset({"media"}),+ manual=False,+ ),+)+++def relation_type(type_: str) -> RelationType | None:+ """The registry entry for a relation type, or None if it has no reading."""+ return next((entry for entry in RELATION_TYPES if entry.type == type_), None)+++def add_relation(+ case: CaseRepository, from_id: str, to_id: str, type_: str, *, by: str+) -> dict[str, Any]:+ """State one relation between two entities, as the analyst's own claim.++ ``status`` is always ``confirmed``: a suggestion is what a tool proposes for+ review (ONTOLOGY §4), so an analyst clicking "relate these" would have+ nothing left to review. Chain types are refused — a derivation is recorded by+ the save that produced it, never asserted after the fact — and so is any pair+ the registry has no reading for. Repeats are idempotent rather than stacked.+ """+ spec = _statable(type_)+ if from_id == to_id:+ raise CaseError("an entity cannot relate to itself")+ _check_endpoints(case, spec, from_id, to_id)+ return case.add_link(from_id, to_id, type_, by=by, unique=True)+++def set_relation_type(case: CaseRepository, link_id: str, type_: str) -> dict[str, Any]:+ """Correct which relation an existing edge states.++ The same two entities, a different reading — "shows this place" where the+ analyst first said "was shot at" — so it is one edge corrected rather than a+ delete and a re-statement, and the wrong reading leaves no trace. Same+ validation as stating one, plus a refusal to collapse onto a relation the pair+ already holds.+ """+ spec = _statable(type_)+ link = case.get_link(link_id)+ if link is None:+ raise CaseError(f"link '{link_id}' not found")+ _statable(link["type"]) # a machine's claim is not the analyst's to reword+ _check_endpoints(case, spec, link["from"], link["to"])+ twin = any(+ other["id"] != link_id+ and other["from"] == link["from"]+ and other["to"] == link["to"]+ and other["type"] == type_+ for other in case.links_of(link["from"])+ )+ if twin:+ raise CaseError("those two already hold that relation")+ return case.update_link(link_id, {"type": type_})+++def confirm_relation(case: CaseRepository, link_id: str) -> dict[str, Any]:+ """Accept a proposed relation, and with it the entities it joins.++ The two halves of an enrichment suggestion are one claim: "this file was shot+ at this point" cannot be true while the point itself is still only proposed.+ So confirming the edge confirms whichever endpoint is still `suggested` — the+ mirror of confirming an entity, which confirms its incident suggestions+ (api/cases.update_entity). Without both directions the Suggestions list and+ the relation rows disagree about the same click.+ """+ link = case.get_link(link_id)+ if link is None:+ raise CaseError(f"link '{link_id}' not found")+ for endpoint in (link["from"], link["to"]):+ entity = case.get_entity(endpoint)+ if entity is not None and entity["provenance"]["status"] == "suggested":+ case.update_entity(endpoint, {"status": "confirmed"})+ return case.update_link(link_id, {"status": "confirmed"})+++def remove_relation(case: CaseRepository, link_id: str) -> None:+ """Take back one relation.++ Chain edges are refused here as they are everywhere else in this module: a+ derivation is recorded by the save that produced it, and dropping one behind+ the delete path would lose it without the tombstone `losses` relies on+ (``TOMBSTONE_TYPES``). A relation, by contrast, is a statement, and taking a+ statement back is the only way to correct one.+ """+ link = case.get_link(link_id)+ if link is None:+ raise CaseError(f"link '{link_id}' not found")+ if link["type"] in CHAIN_TYPES:+ raise CaseError(f"'{link['type']}' is a derivation, not a relation to take back")+ case.remove_link(link_id)+++def confirm_incident_relations(case: CaseRepository, entity_id: str) -> None:+ """Accept the suggestions hanging off an entity the analyst just confirmed.++ The mirror of :func:`confirm_relation`, and it has to carry the same+ invariant: an edge is confirmed together with the entity at its far end, or+ the map still chips a point "suggested" while the relation row beside it reads+ as a finding. One hop only — accepting a photo's own point is a reading of+ that photo, not a licence to accept whatever that point was separately+ proposed to be.+ """+ for link in case.links_of(entity_id):+ if link["provenance"]["status"] != "suggested":+ continue+ far = link["to"] if link["from"] == entity_id else link["from"]+ neighbour = case.get_entity(far)+ if neighbour is not None and neighbour["provenance"]["status"] == "suggested":+ case.update_entity(far, {"status": "confirmed"})+ case.update_link(link["id"], {"status": "confirmed"})+++def _statable(type_: str) -> RelationType:+ spec = relation_type(type_)+ if spec is None or not spec.manual:+ raise CaseError(f"'{type_}' is not a relation the analyst can state")+ return spec+++def _check_endpoints(+ case: CaseRepository, spec: RelationType, from_id: str, to_id: str+) -> None:+ source, target = _entity(case, from_id), _entity(case, to_id)+ if source["type"] not in spec.from_types:+ raise CaseError(f"a {source['type']} cannot be the subject of '{spec.type}'")+ if target["type"] not in spec.to_types:+ raise CaseError(f"a {target['type']} cannot be the object of '{spec.type}'")+def _now() -> str:return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")@@ -186,22 +374,33 @@ def losses(case: CaseRepository, doomed_ids: set[str]) -> dict[str, list[dict[stdef chain_of(case: CaseRepository, entity_id: str) -> dict[str, Any] | None:- """One entity's derivation chain (ONTOLOGY §3), for the Details panel.+ """One entity's derivation chain and direct relations, for Details.Mirrors the frontend ``chainOf``: its direct ``sources`` (outgoing``derived-from`` / ``depends-on`` edges), its direct ``dependents`` (the- incoming ones), and the tombstoned ``lost_sources`` it still carries. Reads- only the edges incident to this entity (``links_of``) plus each neighbour, so- it never materialises the whole graph. Returns ``None`` if the entity is- gone.+ incoming ones), direct non-chain ``relations``, and the tombstoned+ ``lost_sources`` it still carries. Reads only the edges incident to this+ entity (``links_of``) plus each neighbour, so it never materialises the whole+ graph. Returns ``None`` if the entity is gone."""entity = case.get_entity(entity_id)if entity is None:return Nonesources: list[dict[str, Any]] = []dependents: list[dict[str, Any]] = []+ relations: list[dict[str, Any]] = []for link in case.links_of(entity_id):if link["type"] not in CHAIN_TYPES:+ neighbour_id = link["to"] if link["from"] == entity_id else link["from"]+ neighbour = case.get_entity(neighbour_id)+ if neighbour is not None:+ relations.append(+ {+ "entity": neighbour,+ "link": link,+ "direction": "out" if link["from"] == entity_id else "in",+ }+ )continueif link["from"] == entity_id:neighbour = case.get_entity(link["to"])@@ -217,7 +416,8 @@ def chain_of(case: CaseRepository, entity_id: str) -> dict[str, Any] | None:"sources": sources,"lost": lost,"dependents": dependents,- "empty": not sources and not lost and not dependents,+ "relations": relations,+ "empty": not sources and not lost and not dependents and not relations,}diff --git a/src/azimut/engine/media.py b/src/azimut/engine/media.pyindex 5ddc0c3..df81639 100644--- a/src/azimut/engine/media.py+++ b/src/azimut/engine/media.py@@ -21,6 +21,7 @@ from PIL import Imagefrom .. import configfrom ..workspace import Case, ensure_dir+from . import enrich as enrich_enginefrom . import ffmpeg as ffmpeg_enginefrom . import links as link_enginefrom . import thumbnails as thumbnail_engine@@ -161,10 +162,28 @@ def _sidecar_path(media_path: Path) -> Path:return media_path.with_name(media_path.name + SIDECAR_SUFFIX)+#: Prefix and suffix of the scratch file a sidecar write goes through. Named so+#: it can be recognised again: `finally` clears it on any failure this process+#: sees, but a power cut between the write and the rename leaves one behind, and+#: whatever walks a case's files has to know it is debris rather than content+#: (`Case._holds_content`).+SIDECAR_TMP_PREFIX = "."+SIDECAR_TMP_SUFFIX = ".tmp"++def _write_sidecar(media_path: Path, data: dict[str, Any]) -> None:- _sidecar_path(media_path).write_text(- json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"+ sidecar = _sidecar_path(media_path)+ temporary = sidecar.with_name(+ f"{SIDECAR_TMP_PREFIX}{sidecar.name}.{uuid.uuid4().hex}{SIDECAR_TMP_SUFFIX}")+ try:+ temporary.write_text(+ json.dumps(data, indent=2, ensure_ascii=False) + "\n",+ encoding="utf-8",+ )+ temporary.replace(sidecar)+ finally:+ temporary.unlink(missing_ok=True)def _source_paths(source: dict[str, Any]) -> list[str]:@@ -251,6 +270,9 @@ def _register()indexed = {**sidecar, "path": rel_path}case.upsert_media_item(indexed, entity_id=entity["id"])+ # Enrichment runs after the sidecar and index row exist: the handler reads+ # the item back, and the worker can claim the job the moment it is queued.+ enrich_engine.on_register(case, rel_path, kind, 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(@@ -695,28 +717,43 @@ def download_url(return result+def merge_item(case: Case, rel_path: str, patch: dict[str, Any]) -> dict[str, Any] | None:+ """Merge ``patch`` into a media item's sidecar and mirror it onto the index+ row. Returns the merged item, or None when the sidecar is gone.++ Held under the case lock: several background handlers patch different fields+ of the same sidecar (a thumbnail path, then enrichment facts), and an+ unguarded read-modify-write would drop whichever landed first.+ """+ with case.lock:+ media_path = case.resolve_inside(rel_path)+ sidecar = _sidecar_path(media_path)+ if not sidecar.exists():+ return None+ data = json.loads(sidecar.read_text(encoding="utf-8"))+ data.update(patch)+ _write_sidecar(media_path, data)+ indexed = {**data, "path": rel_path}+ case.upsert_media_item(indexed)+ return indexed++def set_thumbnail(case: Case, rel_path: str, thumb_rel: str | None) -> None:"""Record (or clear) a media item's thumbnail path in its sidecar. Thethumbnail worker calls this once it finishes a queued (e.g. video) render, sothe next media listing reports the thumbnail as ready."""- media_path = case.resolve_inside(rel_path)- sidecar = _sidecar_path(media_path)- if not sidecar.exists():- return- data = json.loads(sidecar.read_text(encoding="utf-8"))- data["thumbnail"] = thumb_rel- _write_sidecar(media_path, data)- case.upsert_media_item({**data, "path": rel_path})+ merge_item(case, rel_path, {"thumbnail": thumb_rel})def read_item(case: Case, rel_path: str) -> dict[str, Any] | None:- media_path = case.resolve_inside(rel_path)- sidecar = _sidecar_path(media_path)- if not sidecar.exists():- return None- data = json.loads(sidecar.read_text(encoding="utf-8"))- data["path"] = rel_path- return data+ with case.lock:+ media_path = case.resolve_inside(rel_path)+ sidecar = _sidecar_path(media_path)+ if not sidecar.exists():+ return None+ data = json.loads(sidecar.read_text(encoding="utf-8"))+ data["path"] = rel_path+ return datadef list_media(case: Case) -> list[dict[str, Any]]:@@ -725,44 +762,52 @@ def list_media(case: Case) -> list[dict[str, Any]]:def update_media(case: Case, rel_path: str, patch: dict[str, Any]) -> dict[str, Any]:"""Update mutable sidecar fields (notes, folder, title) and mirror them onto- the media entity so the case sidebar stays in sync."""- media_path = case.resolve_inside(rel_path)- sidecar = _sidecar_path(media_path)- if not sidecar.exists():- raise ValueError(f"no sidecar found for {rel_path!r}")-- data = json.loads(sidecar.read_text(encoding="utf-8"))- for key in ("notes", "folder", "title"):- if key in patch:- val = patch[key]- if val is None or val == "":- data.pop(key, None)- else:- data[key] = str(val)-- _write_sidecar(media_path, data)-- # mirror onto the media entity (label mirrors the title; folder/notes attrs)- entity = case.find_entity(attr="path", value=rel_path)- if entity:- entity_patch: dict[str, Any] = {}- if "title" in patch:- # a cleared title falls back to the filename, like a fresh import —- # the sidebar label must never freeze on a title that no longer exists- entity_patch["label"] = str(patch["title"] or "") or media_path.name- attrs: dict[str, Any] = {}- if "folder" in patch:- attrs["folder"] = patch["folder"] or ""- if "notes" in patch:- attrs["notes"] = patch["notes"] or ""- if attrs:- entity_patch["attrs"] = attrs- if entity_patch:- case.update_entity(entity["id"], entity_patch)-- indexed = {**data, "path": rel_path}- case.upsert_media_item(indexed, entity_id=entity["id"] if entity else None)- return indexed+ the media entity so the case sidebar stays in sync.++ Under the case lock, like every other sidecar write: the Save gate names an+ item immediately after filing it, while the enrichment job queued by that+ same filing may already be writing the file's own facts to the same sidecar.+ Unguarded, whichever finished second dropped the other's fields — and the one+ users noticed was the name they had just typed.+ """+ with case.lock:+ media_path = case.resolve_inside(rel_path)+ sidecar = _sidecar_path(media_path)+ if not sidecar.exists():+ raise ValueError(f"no sidecar found for {rel_path!r}")++ data = json.loads(sidecar.read_text(encoding="utf-8"))+ for key in ("notes", "folder", "title"):+ if key in patch:+ val = patch[key]+ if val is None or val == "":+ data.pop(key, None)+ else:+ data[key] = str(val)++ _write_sidecar(media_path, data)++ # mirror onto the media entity (label mirrors the title; folder/notes attrs)+ entity = case.find_entity(attr="path", value=rel_path)+ if entity:+ entity_patch: dict[str, Any] = {}+ if "title" in patch:+ # a cleared title falls back to the filename, like a fresh import —+ # the sidebar label must never freeze on a title that no longer exists+ entity_patch["label"] = str(patch["title"] or "") or media_path.name+ attrs: dict[str, Any] = {}+ if "folder" in patch:+ attrs["folder"] = patch["folder"] or ""+ if "notes" in patch:+ attrs["notes"] = patch["notes"] or ""+ if attrs:+ entity_patch["attrs"] = attrs+ if entity_patch:+ case.update_entity(entity["id"], entity_patch)++ 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:diff --git a/src/azimut/engine/satellite.py b/src/azimut/engine/satellite.pyindex 5930a0d..70f9523 100644--- a/src/azimut/engine/satellite.py+++ b/src/azimut/engine/satellite.py@@ -21,6 +21,7 @@ from __future__ import annotationsfrom datetime import datetime, timezonefrom typing import Any+from ..repository import EntityStatusfrom ..workspace import Casefrom . import continentsfrom . import coords as coords_engine@@ -59,6 +60,7 @@ def save_place(title: str | None = None,by: str = "satellite",extra_attrs: dict[str, Any] | None = None,+ status: EntityStatus = "confirmed",) -> dict[str, Any]:"""Register a point as a navigable ``place`` — no image, no download.@@ -68,6 +70,10 @@ def save_place(same way whatever route wrote them. The caller resolves the geographyafterwards (``locate_on_save``); ``extra_attrs`` carries whatever only oneof them has, such as the extension's source URL.++ ``status`` is how a place the analyst has not seen yet enters the case:+ import enrichment proposes one from a photo's EXIF as ``suggested`` (a+ camera's claim, not a finding), and the map's own pin stays ``confirmed``."""attrs: dict[str, Any] = {"coords": coords_label(lat, lon, "dd"),@@ -79,7 +85,7 @@ def save_place(}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")+ return case.add_entity("place", label, attrs=attrs, by=by, status=status)def is_capture(item: dict[str, Any]) -> bool:@@ -167,7 +173,11 @@ def _saved_when(entity: dict[str, Any], capture: dict[str, Any] | None) -> str:def _saved_row(- case: Case, entity: dict[str, Any], capture: dict[str, Any] | None, proofs: int = 0+ case: Case,+ entity: dict[str, Any],+ capture: dict[str, Any] | None,+ proofs: int = 0,+ relations: int = 0,) -> dict[str, Any]:attrs = entity.get("attrs") or {}source = capture or {}@@ -218,6 +228,13 @@ def _saved_row(# once, so a worked row is marked rather than doubled by a proof# marker landing on the capture it composes."proofs": proofs,+ # how many relations (non-chain edges) touch this point, so the popup can+ # offer to load them without the index carrying the edges themselves.+ "relations": relations,+ # `suggested` means a tool proposed this point and nobody has looked yet —+ # enrichment mints one per GPS-tagged file. The tree and the popup mark+ # those rather than letting them read as the analyst's own work.+ "status": (entity.get("provenance") or {}).get("status") or "confirmed",}@@ -225,21 +242,32 @@ 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.+ nothing else: no media rows, no derivation, no edges. Work that hangs off a+ point is a count (proofs, relations) rather than a list, so 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. The popup loads the edges themselves from the+ bounded chain endpoint when it opens."""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+ # two grouped queries for the whole case rather than one per row: this list# is read on case open and must not walk the graph row by rowworked = case.count_dependents(link_type=links.DERIVED_FROM, from_type="proof")+ related = case.count_incident_links(exclude_types=list(links.CHAIN_TYPES))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 Noneif 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)))+ rows.append(+ _saved_row(+ case,+ entity,+ capture,+ worked.get(entity["id"], 0),+ related.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 shuffledorder = {row["id"]: i for i, row in enumerate(rows)}diff --git a/src/azimut/engine/thumbnails.py b/src/azimut/engine/thumbnails.pyindex fe9a36d..fb10e13 100644--- a/src/azimut/engine/thumbnails.py+++ b/src/azimut/engine/thumbnails.py@@ -12,9 +12,10 @@ to the original file. This module owns their whole lifecycle.then renamed into `.thumbs/` — a reader never sees a half-written thumbnail, andthe Windows rename rules are respected.- **Cheap image thumbnails run inline** for instant feedback; the **CPU-heavy- path (ffmpeg video frames) goes through the durable per-case `jobs` queue** and- is drained by a single worker, so several imports never spawn several ffmpegs at- once. A failed inline render is enqueued for the worker to retry.+ path (ffmpeg video frames) goes through the durable per-case `jobs` queue**+ drained by the shared single worker (`engine/workqueue.py`), so several imports+ never spawn several ffmpegs at once. A failed inline render is enqueued for the+ worker to retry.- **Recovery**: a job left `running` by a crashed process is reclaimed on caseopen (`Case.recover_jobs`), so work resumes instead of stalling.- **Budget**: `prune_cache` evicts least-recently-used thumbnails past a size@@ -25,8 +26,6 @@ from __future__ import annotationsimport jsonimport subprocess-import threading-import timeimport uuidfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any@@ -35,6 +34,7 @@ from PIL import Imagefrom ..workspace import ensure_dirfrom . import ffmpeg as ffmpeg_engine+from . import workqueueif TYPE_CHECKING:from ..workspace import Case as CaseType@@ -142,9 +142,7 @@ def generate(case: "CaseType", rel_media: str, sha256: str, kind: str) -> str |def enqueue(case: "CaseType", rel_media: str) -> dict[str, Any]:"""Queue a thumbnail job for one media file and wake the worker. Keyed on themedia path, so re-enqueue (a retry or a regenerate) never stacks duplicates."""- job = case.enqueue_job(THUMB_KIND, key=rel_media, payload={"path": rel_media})- wake(case)- return job+ return workqueue.enqueue(case, THUMB_KIND, key=rel_media, payload={"path": rel_media})def on_register(case: "CaseType", rel_media: str, sha256: str, kind: str) -> str | None:@@ -164,102 +162,33 @@ def on_register(case: "CaseType", rel_media: str, sha256: str, kind: str) -> strreturn None-# -- durable worker --------------------------------------------------------+# -- the enqueued (CPU-heavy) path -----------------------------------------#-# One background worker across all cases: a single daemon thread drains queued-# thumbnail jobs one at a time, so ffmpeg (CPU-heavy) never runs several at once-# — the doc's "default to one CPU-heavy worker". Work only ever starts from a-# user action (an import, a regenerate) or crash recovery, never from merely-# opening a case or tab.+# Video frames go through the shared durable queue (engine/workqueue.py) so+# ffmpeg never runs several instances at once. This module supplies the handler;+# the queue owns the thread and the settlement.-_worker_lock = threading.Lock()-_pending: dict[str, "CaseType"] = {}-_worker_running = False-# When False, `wake` does not start the background thread — the queue is drained-# explicitly instead (tests, and any caller that wants deterministic draining).-start_workers = True+def _handle(case: "CaseType", job: dict[str, Any]) -> None:+ """Run one thumbnail job: render the file and record it on the sidecar.--def _process_one(case: "CaseType", job: dict[str, Any]) -> None:- """Run one claimed thumbnail job: render the file, update its sidecar, and- settle the job. A missing media file cancels the job (nothing to render); any- other failure is recorded and retried until the attempt budget is spent."""+ A missing media file cancels the job (nothing to render); a render failure is+ retried by the queue until the attempt budget is spent.+ """from . import media as media_enginerel = job["payload"].get("path")item = media_engine.read_item(case, rel) if rel else Noneif item is None: # the media (or its sidecar) is gone — nothing to do- case.cancel_job(job["id"])- return+ raise workqueue.JobCancelled(f"media gone: {rel}")try:thumb_rel = generate(case, rel, item.get("sha256", ""), item.get("kind", ""))except ThumbnailError as exc:- case.fail_job(job["id"], str(exc))- return+ raise workqueue.JobFailed(str(exc)) from excmedia_engine.set_thumbnail(case, rel, thumb_rel)- case.complete_job(job["id"])---def drain(case: "CaseType") -> int:- """Process every queued thumbnail job for one case, one at a time, in the- calling thread. Returns how many jobs were handled. Synchronous and- deterministic — the worker loop and the tests both call it."""- handled = 0- while True:- job = case.claim_job(kinds=[THUMB_KIND])- if job is None:- return handled- _process_one(case, job)- handled += 1---def _run_loop() -> None:- global _worker_running- while True:- with _worker_lock:- if not _pending:- _worker_running = False- return- case_id, case = next(iter(_pending.items()))- try:- drain(case)- except Exception: # a worker must never die on one case's failure- pass- with _worker_lock:- _pending.pop(case_id, None)---def wake(case: "CaseType") -> None:- """Ensure the single background worker is draining ``case``'s queue. Registers- the case and starts the worker thread if it isn't already running; a no-op if- the case is already pending."""- global _worker_running- if not start_workers:- return- with _worker_lock:- _pending[case.id] = case- if _worker_running:- return- _worker_running = True- threading.Thread(target=_run_loop, name="thumbnail-worker", daemon=True).start()---def wait_until_idle(timeout: float = 5.0) -> bool:- """Wait for the shared worker to finish its current queue, if any.-- This is mainly useful for orderly shutdown and deterministic callers that- need to remove a case directory after queuing work. It never interrupts an- active render; ``False`` means the caller's timeout elapsed first.- """- deadline = time.monotonic() + timeout- while time.monotonic() < deadline:- with _worker_lock:- if not _worker_running:- return True- time.sleep(0.01)- with _worker_lock:- return not _worker_running+++workqueue.register(THUMB_KIND, _handle)# -- cache maintenance -----------------------------------------------------diff --git a/src/azimut/engine/workqueue.py b/src/azimut/engine/workqueue.pynew file mode 100644index 0000000..43bf546--- /dev/null+++ b/src/azimut/engine/workqueue.py@@ -0,0 +1,161 @@+"""The durable background work queue (doc "Thumbnail and background-job model"),+generalised beyond thumbnails.++Each case owns a `jobs` table; this module is the single consumer of it. A job+kind registers one handler, and **one** worker thread drains one case at a time+across every kind. That single-worker rule is not just about CPU (ffmpeg must not+run several times at once) — it is also what serialises handlers that write the+same media sidecar. Do not widen it to a pool without giving those writes their+own locking.++Settlement is central, so a handler only decides *what happened*:++- returns normally -> the job is `ready`+- raises `JobCancelled` -> the work no longer applies (its media is gone); the+ job is dropped without burning the retry budget on something that cannot+ succeed+- raises `JobFailed`, or anything unexpected -> the job is recorded failed and+ retried until its attempt budget is spent++Work only ever starts from a user action (an import, a regenerate, a backfill)+or from crash recovery — never from merely opening a case or a tab.+"""++from __future__ import annotations++import threading+import time+from typing import TYPE_CHECKING, Any, Callable++if TYPE_CHECKING:+ from ..workspace import Case as CaseType++Handler = Callable[["CaseType", dict[str, Any]], None]++#: kind -> handler. Producers register at import time (see engine/thumbnails.py+#: and engine/enrich.py); a kind with no handler is a job nothing can run, so it+#: is cancelled rather than retried.+HANDLERS: dict[str, Handler] = {}+++class JobCancelled(Exception):+ """The job's subject is gone or no longer applies. Drop it."""+++class JobFailed(Exception):+ """The job failed this time and deserves another attempt."""+++def register(kind: str, handler: Handler) -> None:+ HANDLERS[kind] = handler+++def enqueue(+ case: "CaseType",+ kind: str,+ *,+ key: str | None = None,+ payload: dict[str, Any] | None = None,+) -> dict[str, Any]:+ """Queue one job and wake the worker. A ``key`` makes the enqueue idempotent:+ re-queueing the same (kind, key) returns the pending job instead of stacking+ a duplicate."""+ job = case.enqueue_job(kind, key=key, payload=payload or {})+ wake(case)+ return job+++def has_queued(case: "CaseType") -> bool:+ """True when the case has work waiting, of any kind."""+ return bool(case.list_jobs(state="queued"))+++def _settle(case: "CaseType", job: dict[str, Any]) -> None:+ handler = HANDLERS.get(job["kind"])+ if handler is None:+ case.cancel_job(job["id"])+ return+ try:+ handler(case, job)+ except JobCancelled:+ case.cancel_job(job["id"])+ except JobFailed as exc:+ case.fail_job(job["id"], str(exc))+ except Exception as exc: # a handler bug must not stall the queue+ case.fail_job(job["id"], f"{type(exc).__name__}: {exc}")+ else:+ case.complete_job(job["id"])+++def drain(case: "CaseType") -> int:+ """Process every queued job for one case, one at a time, in the calling+ thread. Returns how many jobs were handled. Synchronous and deterministic —+ the worker loop and the tests both call it."""+ handled = 0+ while True:+ job = case.claim_job()+ if job is None:+ return handled+ _settle(case, job)+ handled += 1+++# -- the single background worker -----------------------------------------++_worker_lock = threading.Lock()+_pending: dict[str, "CaseType"] = {}+_worker_running = False++# When False, `wake` does not start the background thread — the queue is drained+# explicitly instead (tests, and any caller that wants deterministic draining).+start_workers = True+++def _run_loop() -> None:+ global _worker_running+ while True:+ with _worker_lock:+ if not _pending:+ _worker_running = False+ return+ case_id, case = next(iter(_pending.items()))+ try:+ drain(case)+ except Exception: # a worker must never die on one case's failure+ pass+ with _worker_lock:+ _pending.pop(case_id, None)+++def wake(case: "CaseType") -> None:+ """Ensure the single background worker is draining ``case``'s queue. A no-op+ if the case is already pending."""+ global _worker_running+ if not start_workers:+ return+ with _worker_lock:+ _pending[case.id] = case+ if _worker_running:+ return+ _worker_running = True+ threading.Thread(target=_run_loop, name="azimut-worker", daemon=True).start()+++def wait_until_idle(timeout: float = 5.0) -> bool:+ """Wait for the shared worker to finish its current queue, if any.++ Useful for orderly shutdown and for callers that need to move a case+ directory after queuing work. It never interrupts active work; ``False``+ means the caller's timeout elapsed first.+ """+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ with _worker_lock:+ if not _worker_running:+ return True+ time.sleep(0.01)+ # One last look: the worker may have finished during the final sleep, and+ # reporting a timeout for work that is actually done would have the caller+ # refuse to move a case directory it is now free to move.+ with _worker_lock:+ return not _worker_runningdiff --git a/src/azimut/repository.py b/src/azimut/repository.pyindex 7557cf4..dc828e7 100644--- a/src/azimut/repository.py+++ b/src/azimut/repository.py@@ -86,6 +86,11 @@ class CaseRepository(Protocol):def list_links(self) -> list[dict[str, Any]]:...+ def get_link(self, link_id: str) -> dict[str, Any] | None:+ """One edge by id, or None. The single-row read behind editing a relation,+ so correcting one never walks the graph."""+ ...+def links_of(self, entity_id: str) -> list[dict[str, Any]]:"""Every link incident to ``entity_id`` (either endpoint), in stableorder. The bounded neighbour read behind the derivation chain — reads only@@ -104,6 +109,17 @@ class CaseRepository(Protocol):"""...+ def count_incident_links(self, *, exclude_types: list[str]) -> dict[str, int]:+ """``{entity_id: n}`` — links incident to each entity in either+ direction, skipping ``exclude_types``, in one grouped query.++ The bulk "does this row have relations?" read. Callers own the+ vocabulary: passing the chain types leaves exactly the relations, which+ is what the derivation chain excludes too. Entities with none are absent+ rather than present with a zero.+ """+ ...+def get_entity(self, entity_id: str) -> dict[str, Any] | None:...@@ -135,12 +151,16 @@ class CaseRepository(Protocol):kind: str | None = None,category: str | None = None,folder: str | None = None,+ gps: bool = False,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."""+ """Filter, sort and page media without scanning sidecar files.++ ``gps`` keeps only the items whose own metadata states a position.+ """...# -- entity mutations --------------------------------------------------@@ -188,6 +208,10 @@ class CaseRepository(Protocol):) -> list[dict[str, Any]]:...+ def update_link(self, link_id: str, patch: dict[str, Any]) -> dict[str, Any]:+ """Set a link's ``status`` and/or ``type``, keeping its id and provenance."""+ ...+def remove_link(self, link_id: str) -> None:...diff --git a/src/azimut/server.py b/src/azimut/server.pyindex 10f98d1..2dc0db4 100644--- a/src/azimut/server.py+++ b/src/azimut/server.py@@ -63,9 +63,9 @@ def install_local_guard(app: FastAPI) -> None:def _recover_jobs() -> None:"""On startup, return jobs a crashed process left ``running`` to the queue and- wake the worker for any case with pending thumbnail work. A `running` row+ wake the worker for any case that still has pending work. A `running` rownothing owns would otherwise stall forever; recovery resumes it."""- from .engine import thumbnails+ from .engine import workqueuefrom .workspace import Casefor row in Case.list_all():@@ -74,8 +74,8 @@ def _recover_jobs() -> None:case.recover_jobs()except Exception:continue- if any(j["state"] == "queued" for j in case.list_jobs(kind=thumbnails.THUMB_KIND)):- thumbnails.wake(case)+ if workqueue.has_queued(case):+ workqueue.wake(case)def create_app() -> FastAPI:diff --git a/src/azimut/sqlite_backend.py b/src/azimut/sqlite_backend.pyindex d8ea346..52b2da4 100644--- a/src/azimut/sqlite_backend.py+++ b/src/azimut/sqlite_backend.py@@ -41,7 +41,11 @@ if TYPE_CHECKING:# 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 5 adds `has_gps` to that index. The coordinates themselves travel in+# `item_json` and need no column; presence does, because filtering "only the+# files that carry a position" has to happen in SQL over the whole case rather+# than in the page the client already holds.+SQLITE_SCHEMA = 5_SCHEMA = """CREATE TABLE meta (@@ -102,7 +106,8 @@ CREATE TABLE media_items (search_text TEXT NOT NULL,source_type TEXT,source_op TEXT,- imagery_mode TEXT+ imagery_mode TEXT,+ has_gps INTEGER NOT NULL DEFAULT 0);CREATE INDEX idx_entities_type ON entities(type);CREATE INDEX idx_entities_status ON entities(prov_status);@@ -118,6 +123,7 @@ 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);+CREATE INDEX idx_media_gps ON media_items(has_gps);"""# Job lifecycle (doc "Job states"): a fresh job is `queued`; the worker claims it@@ -214,6 +220,20 @@ def _migrate_3_to_4(conn: sqlite3.Connection) -> None:conn.execute("CREATE INDEX idx_media_source ON media_items(source_type)")+def _migrate_4_to_5(conn: sqlite3.Connection) -> None:+ """Add ``media_items.has_gps`` and backfill it from each indexed item.++ The sidecar JSON is already in the row, so this reads no files: a case+ enriched before the column existed gains its GPS filter on open, and one that+ was never enriched simply has every flag at zero.+ """+ conn.execute("ALTER TABLE media_items ADD COLUMN has_gps INTEGER NOT NULL DEFAULT 0")+ for row in conn.execute("SELECT path, item_json FROM media_items").fetchall():+ if _has_gps(json.loads(row["item_json"])):+ conn.execute("UPDATE media_items SET has_gps = 1 WHERE path = ?", (row["path"],))+ conn.execute("CREATE INDEX idx_media_gps ON media_items(has_gps)")++# 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.@@ -221,6 +241,7 @@ _SQLITE_MIGRATIONS: dict[int, Callable[[sqlite3.Connection], None]] = {1: _migrate_1_to_2,2: _migrate_2_to_3,3: _migrate_3_to_4,+ 4: _migrate_4_to_5,}_MEDIA_CATEGORIES = (@@ -247,9 +268,38 @@ _MEDIA_CATEGORY_SQL = {}+def _has_gps(item: dict[str, Any]) -> bool:+ """Whether an indexed media item carries a usable position.++ Enrichment writes ``gps`` as ``{lat, lon}`` when a file's own metadata states+ one (engine/enrich.py). Anything else — absent, half-filled, non-numeric —+ counts as no position, so the filter can never offer a row it cannot place.+ """+ gps = item.get("gps")+ if not isinstance(gps, dict):+ return False+ try:+ float(gps["lat"]), float(gps["lon"])+ except (KeyError, TypeError, ValueError):+ return False+ return True+++#: Sidecar fields the browse index deliberately does not mirror. Enrichment's+#: full metadata dumps (engine/enrich.py) are hundreds of rows per file, and this+#: index is read 200 items at a time by the grid and whole by the pickers — one+#: fat field would multiply every one of those responses by ten. They stay in the+#: sidecar, which is the file-level record, and reach the UI one file at a time+#: through ``GET .../media/item``. Parsed facts (``gps``, ``taken_at``,+#: ``dhash``) are small and stay indexed.+_UNINDEXED_MEDIA_FIELDS = ("exif", "video_metadata")++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))+ for field_name in _UNINDEXED_MEDIA_FIELDS:+ clean.pop(field_name, None)source = clean.get("source")if not isinstance(source, dict):source = {}@@ -302,6 +352,7 @@ def _normalise_media_item(item: dict[str, Any]) -> tuple[dict[str, Any], tuple[Asource.get("type"),source.get("op"),source.get("imagery_mode"),+ int(_has_gps(clean)),)@@ -580,6 +631,11 @@ class SqliteCase:with self._connect() as conn:return [self._link(r) for r in conn.execute("SELECT * FROM links ORDER BY rowid")]+ def get_link(self, link_id: str) -> dict[str, Any] | None:+ with self._connect() as conn:+ row = conn.execute("SELECT * FROM links WHERE id = ?", (link_id,)).fetchone()+ return self._link(row) if row is not None else None+def links_of(self, entity_id: str) -> list[dict[str, Any]]:with self._connect() as conn:rows = conn.execute(@@ -599,6 +655,22 @@ class SqliteCase:).fetchall()return {r["to_id"]: int(r["n"]) for r in rows}+ def count_incident_links(self, *, exclude_types: list[str]) -> dict[str, int]:+ skipped = list(dict.fromkeys(exclude_types))+ where = ""+ if skipped:+ where = f" WHERE type NOT IN ({', '.join('?' * len(skipped))})"+ with self._connect() as conn:+ rows = conn.execute(+ "SELECT id, COUNT(*) AS n FROM ("+ f" SELECT from_id AS id FROM links{where}"+ " UNION ALL"+ f" SELECT to_id AS id FROM links{where}"+ ") GROUP BY id",+ (*skipped, *skipped),+ ).fetchall()+ return {r["id"]: int(r["n"]) for r in rows}+def page_entities(self,*,@@ -735,8 +807,9 @@ class SqliteCase: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(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"+ " size, added_at, search_text, source_type, source_op, imagery_mode,"+ " has_gps"+ ") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"" ON CONFLICT(path) DO UPDATE SET"" entity_id = COALESCE(excluded.entity_id, media_items.entity_id),"" item_json = excluded.item_json,"@@ -744,7 +817,8 @@ class SqliteCase:" 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",+ " source_op = excluded.source_op, imagery_mode = excluded.imagery_mode,"+ " has_gps = excluded.has_gps",(values[0], entity_id, *values[1:]),)@@ -764,12 +838,18 @@ class SqliteCase:@staticmethoddef _media_item(row: sqlite3.Row) -> dict[str, Any]:- return json.loads(row["item_json"])+ """One browse item, with the media entity it belongs to.++ ``entity_id`` is the column, not a sidecar field: the row already holds+ the link, so a caller that needs the entity behind a path reads it here+ instead of scanning the graph for an attribute match.+ """+ return {**json.loads(row["item_json"]), "entity_id": row["entity_id"]}def list_media_items(self) -> list[dict[str, Any]]:with self._connect() as conn:rows = conn.execute(- "SELECT item_json FROM media_items"+ "SELECT item_json, entity_id FROM media_items"" ORDER BY added_at DESC, path COLLATE NOCASE").fetchall()return [self._media_item(row) for row in rows]@@ -783,7 +863,7 @@ class SqliteCase:placeholders = ", ".join("?" for _ in unique)with self._connect() as conn:rows = conn.execute(- f"SELECT item_json FROM media_items WHERE path IN ({placeholders})",+ f"SELECT item_json, entity_id FROM media_items WHERE path IN ({placeholders})",unique,).fetchall()by_path = {@@ -798,6 +878,7 @@ class SqliteCase:kind: str | None = None,category: str | None = None,folder: str | None = None,+ gps: bool = False,sort: str = "newest",direction: str | None = None,limit: int = 200,@@ -818,10 +899,16 @@ class SqliteCase:base_where.append("search_text LIKE ? ESCAPE '\\'")base_params.append(_like_contains(term))+ # Category and GPS are two independent refinements of that base. Each+ # one's own facet count leaves itself out and applies the other, so a+ # chooser always reports what clicking it would actually yield.+ category_sql = _MEDIA_CATEGORY_SQL.get(category or "")selected_where = list(base_where)selected_params = list(base_params)- if category in _MEDIA_CATEGORY_SQL:- selected_where.append(_MEDIA_CATEGORY_SQL[category])+ if category_sql:+ selected_where.append(category_sql)+ if gps:+ selected_where.append("has_gps = 1")def clause(parts: list[str]) -> str:return (" WHERE " + " AND ".join(parts)) if parts else ""@@ -849,7 +936,7 @@ class SqliteCase:).fetchone()[0])rows = conn.execute(- f"SELECT item_json FROM media_items{selected_clause}"+ f"SELECT item_json, entity_id FROM media_items{selected_clause}"f" ORDER BY {order_col} {order}, path COLLATE NOCASE {order}"" LIMIT ? OFFSET ?",[*selected_params, limit, offset],@@ -872,16 +959,24 @@ class SqliteCase:).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.+ # selected, so its counts exclude the current category but keep the+ # rest of the filter, GPS included.+ gps_scope = [*base_where, "has_gps = 1"] if gps else base_wherecategory_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]])}",+ f"SELECT COUNT(*) FROM media_items{clause([*gps_scope, _MEDIA_CATEGORY_SQL[key]])}",base_params,).fetchone()[0])+ gps_count = int(+ conn.execute(+ "SELECT COUNT(*) FROM media_items"+ f"{clause([*base_where, *([category_sql] if category_sql else []), 'has_gps = 1'])}",+ base_params,+ ).fetchone()[0]+ )next_offset = offset + len(rows)return {@@ -892,6 +987,7 @@ class SqliteCase:"kind_counts": kind_counts,"folder_counts": folder_counts,"category_counts": category_counts,+ "gps_count": gps_count,},}@@ -1103,6 +1199,33 @@ class SqliteCase:return self._write(op)+ def update_link(self, link_id: str, patch: dict[str, Any]) -> dict[str, Any]:+ """Update a link's status or type without rebuilding the edge.++ Restating the type keeps the edge's id and provenance: the two entities+ were always related, only the reading was wrong. Which types may be+ restated is the vocabulary's call (``engine/links.py``), not the store's.+ """++ def op(conn: sqlite3.Connection) -> dict[str, Any]:+ row = conn.execute("SELECT * FROM links WHERE id = ?", (link_id,)).fetchone()+ if row is None:+ raise CaseError(f"link '{link_id}' not found")+ status = patch.get("status")+ if status not in ("confirmed", "suggested"):+ status = row["prov_status"]+ type_ = patch.get("type") or row["type"]+ conn.execute(+ "UPDATE links SET prov_status = ?, type = ? WHERE id = ?",+ (status, type_, link_id),+ )+ self._touch(conn)+ updated = conn.execute("SELECT * FROM links WHERE id = ?", (link_id,)).fetchone()+ assert updated is not None+ return self._link(updated)++ return self._write(op)+def remove_link(self, link_id: str) -> None:def op(conn: sqlite3.Connection) -> None:cur = conn.execute("DELETE FROM links WHERE id = ?", (link_id,))diff --git a/src/azimut/workspace.py b/src/azimut/workspace.pyindex 2dbfa03..7a70eaa 100644--- a/src/azimut/workspace.py+++ b/src/azimut/workspace.py@@ -190,6 +190,15 @@ class Case:# Resolved lazily from the manifest on first graph access, then cached.self._sqlite_cache: Any = _UNSET+ @property+ def lock(self) -> threading.RLock:+ """The per-case reentrant lock guarding read-modify-write of the case's+ files. Public because the media sidecars need the same serialisation the+ case database already gets: two background handlers can patch different+ fields of one sidecar, and an unguarded read-modify-write loses one of+ them."""+ return self._lock+@propertydef _sqlite(self) -> "SqliteCase | None":"""The SQLite graph backend if this case is on the sqlite storage@@ -333,6 +342,28 @@ class Case:if not dst.exists():shutil.copy2(self.json_path, dst)+ @staticmethod+ def _holds_content(path: Path) -> bool:+ """Whether a case directory holds any file the analyst would miss.++ Debris does not count. A sidecar write goes through a scratch file it+ renames into place (``engine/media._write_sidecar``); a power cut in that+ window strands one, and treating it as content would keep an otherwise+ empty scratch case alive forever.+ """+ for sub in CASE_SUBDIRS:+ directory = path / sub+ if not directory.is_dir():+ continue+ for candidate in directory.rglob("*"):+ if not candidate.is_file():+ continue+ name = candidate.name+ if name.startswith(".") and name.endswith(".tmp"):+ continue+ return True+ return False+@classmethoddef cleanup_scratch(cls, max_age_days: int = SCRATCH_MAX_AGE_DAYS) -> int:"""Delete scratch cases that hold nothing and haven't been touched in@@ -366,12 +397,7 @@ class Case:continueif when.replace(tzinfo=timezone.utc).timestamp() > cutoff:continue- if any(- p.is_file()- for sub in CASE_SUBDIRS- if (path / sub).is_dir()- for p in (path / sub).rglob("*")- ):+ if cls._holds_content(path):continuetry:case.delete()@@ -529,6 +555,7 @@ class Case:kind: str | None = None,category: str | None = None,folder: str | None = None,+ gps: bool = False,sort: str = "newest",direction: str | None = None,limit: int = 200,@@ -539,18 +566,25 @@ class Case:kind=kind,category=category,folder=folder,+ gps=gps,sort=sort,direction=direction,limit=limit,offset=offset,)+ def get_link(self, link_id: str) -> dict[str, Any] | None:+ return self._graph().get_link(link_id)+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 count_incident_links(self, *, exclude_types: list[str]) -> dict[str, int]:+ return self._graph().count_incident_links(exclude_types=exclude_types)+def get_entity(self, entity_id: str) -> dict[str, Any] | None:return self._graph().get_entity(entity_id)@@ -647,6 +681,26 @@ class Case:data["name"] = nameself._write_json(data)+ @staticmethod+ def _settle_background_work() -> None:+ """Let the shared worker finish before this case's directory moves.++ Background jobs write inside the case folder — a thumbnail, and+ enrichment's sidecar — and a directory cannot be moved or removed from+ under a thread writing into it: POSIX raises ``Directory not empty`` when+ a file appears between the walk and the ``rmdir``, and Windows refuses+ outright while a handle is open. Enrichment made the window wide enough to+ hit, since reading EXIF or probing a video takes far longer than writing a+ thumbnail.++ Bounded, and it never interrupts work in flight. Nothing re-wakes the+ worker for a case afterwards, because the only thing that queues work is a+ request against that case — and this one is on its way out.+ """+ from .engine import workqueue++ workqueue.wait_until_idle()+def promote(self, name: str) -> "Case":"""Move a scratch case into cases/ under a proper name (spec §3.3)."""if not self.is_scratch:@@ -656,12 +710,14 @@ class Case:if dest.exists():raise CaseError(f"case '{slug}' already exists")dest.parent.mkdir(parents=True, exist_ok=True)+ self._settle_background_work()shutil.move(str(self.path), str(dest))promoted = Case(dest)promoted.rename(name)return promoteddef delete(self) -> None:+ self._settle_background_work()shutil.rmtree(self.path)# -- entities & links (spec §5) -----------------------------------------@@ -730,6 +786,9 @@ class Case:"""return self._graph().sync_links(from_id, type_, to_ids, by=by, status=status)+ def update_link(self, link_id: str, patch: dict[str, Any]) -> dict[str, Any]:+ return self._graph().update_link(link_id, patch)+def remove_link(self, link_id: str) -> None:self._graph().remove_link(link_id)diff --git a/tests/conftest.py b/tests/conftest.pyindex 321c9f0..1838aab 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -19,12 +19,29 @@ def offline_reverse_geocode(monkeypatch):monkeypatch.setattr(geo, "reverse_geocode", lambda lat, lon, timeout=8, language=None: None)+def _let_the_worker_finish() -> None:+ """Wait for the shared background worker before a throwaway workspace is+ removed.++ Importing media queues enrichment, so a test that never mentions jobs can+ still leave the worker mid-write when its temp directory goes — which on+ POSIX surfaces as a "directory not empty" teardown error and on Windows as a+ locked file. This is the same orderly-shutdown wait the app itself performs.+ """+ from azimut.engine import workqueue++ workqueue.wait_until_idle(timeout=10)++@pytest.fixture()def tmp_workspace(monkeypatch):"""A throwaway workspace root — for engine tests that read/write settings."""with tempfile.TemporaryDirectory() as home:monkeypatch.setenv("AZIMUT_HOME", home)- yield home+ try:+ yield home+ finally:+ _let_the_worker_finish()@pytest.fixture()@@ -36,5 +53,8 @@ def client(monkeypatch):# base_url is a loopback host so the app's own Host guard (server.py# install_local_guard) lets requests through, as a real browser would.- with TestClient(create_app(), base_url="http://127.0.0.1") as c:- yield c+ try:+ with TestClient(create_app(), base_url="http://127.0.0.1") as c:+ yield c+ finally:+ _let_the_worker_finish()diff --git a/tests/test_cases_api.py b/tests/test_cases_api.pyindex 7374af4..4b56946 100644--- a/tests/test_cases_api.py+++ b/tests/test_cases_api.py@@ -497,3 +497,21 @@ def test_cleanup_scratch_reaps_only_old_empty_sessions(tmp_workspace):assert with_entity.path.exists()assert with_file.path.exists()assert empty_new.path.exists()+++def test_cleanup_scratch_treats_a_stranded_sidecar_temp_file_as_debris(tmp_workspace):+ """A sidecar write renames a scratch file into place. A power cut in that window+ strands one, and counting it as content would keep an empty scratch session+ alive forever — the exact accumulation cleanup exists to stop."""+ import json as jsonlib++ from azimut.workspace import Case++ stranded = Case.create("Scratch session", scratch=True)+ (stranded.path / "media" / ".shot.png.azimut.json.deadbeef.tmp").write_bytes(b"{}")+ data = jsonlib.loads(stranded.json_path.read_text(encoding="utf-8"))+ data["updated_at"] = "2000-01-01T00:00:00Z"+ stranded.json_path.write_text(jsonlib.dumps(data), encoding="utf-8")++ assert Case.cleanup_scratch() == 1+ assert not stranded.path.exists()diff --git a/tests/test_enrich.py b/tests/test_enrich.pynew file mode 100644index 0000000..d7e996b--- /dev/null+++ b/tests/test_enrich.py@@ -0,0 +1,462 @@+"""Import enrichment: what a local image or video file says about itself.++Everything here is pixels and bytes on disk. The no-network assertion is not+decoration — enrichment runs on every import, and reaching out on any of them+would break the local-first rule the whole app is built on.+"""++from __future__ import annotations++import socket+from fractions import Fraction+from pathlib import Path+from types import SimpleNamespace++import pytest+from PIL import Image++from azimut.engine import enrich++[email protected](autouse=True)+def no_network(monkeypatch):+ """Any socket created inside this module is a bug."""++ def explode(*args, **kwargs):+ raise AssertionError("enrichment must not touch the network")++ monkeypatch.setattr(socket, "socket", explode)+ monkeypatch.setattr(socket, "create_connection", explode)+++def _image(tmp_path: Path, name="shot.jpg", size=(64, 48), exif: Image.Exif | None = None) -> Path:+ path = tmp_path / name+ img = Image.new("RGB", size)+ for x in range(size[0]): # a horizontal ramp, so the hash is not all zeros+ for y in range(size[1]):+ img.putpixel((x, y), (x * 4 % 256, y * 4 % 256, 40))+ img.save(path, "JPEG", exif=exif if exif is not None else Image.Exif())+ return path+++def _exif_with_gps(lat_dms, lat_ref, lon_dms, lon_ref, taken=None) -> Image.Exif:+ exif = Image.Exif()+ gps = {+ 1: lat_ref,+ 2: tuple(Fraction(v).limit_denominator() for v in lat_dms),+ 3: lon_ref,+ 4: tuple(Fraction(v).limit_denominator() for v in lon_dms),+ }+ exif.get_ifd(0x8825).update(gps)+ if taken:+ exif.get_ifd(0x8769)[36867] = taken+ return exif+++def test_exif_facts_converts_dms_to_signed_decimal(tmp_path):+ exif = _exif_with_gps((48, 51, 30.0), "N", (2, 21, 3.0), "E", "2023:06:11 14:22:31")+ facts = enrich.exif_facts(_image(tmp_path, exif=exif))++ assert facts["gps"]["lat"] == pytest.approx(48.858333, abs=1e-5)+ assert facts["gps"]["lon"] == pytest.approx(2.350833, abs=1e-5)+ assert facts["taken_at"] == "2023-06-11T14:22:31"+++def test_exif_facts_applies_the_southern_and_western_hemisphere_refs(tmp_path):+ exif = _exif_with_gps((33, 51, 54.0), "S", (151, 12, 36.0), "W")+ facts = enrich.exif_facts(_image(tmp_path, exif=exif))++ assert facts["gps"]["lat"] < 0+ assert facts["gps"]["lon"] < 0+++def test_exif_facts_returns_nothing_for_an_image_without_exif(tmp_path):+ assert enrich.exif_facts(_image(tmp_path)) == {}+++def test_exif_facts_drops_out_of_range_and_null_island_coordinates(tmp_path):+ out_of_range = _exif_with_gps((99, 0, 0.0), "N", (0, 0, 0.0), "E")+ assert "gps" not in enrich.exif_facts(_image(tmp_path, "a.jpg", exif=out_of_range))++ null_island = _exif_with_gps((0, 0, 0.0), "N", (0, 0, 0.0), "E")+ assert "gps" not in enrich.exif_facts(_image(tmp_path, "b.jpg", exif=null_island))+++def test_exif_facts_survives_a_malformed_date(tmp_path):+ exif = _exif_with_gps((1, 0, 0.0), "N", (1, 0, 0.0), "E", "not a date")+ facts = enrich.exif_facts(_image(tmp_path, exif=exif))+ assert "taken_at" not in facts+ assert facts["gps"]["lat"] == pytest.approx(1.0)+++def test_exif_metadata_keeps_camera_and_nested_gps_tags_for_details(tmp_path):+ exif = _exif_with_gps((48, 51, 30.0), "N", (2, 21, 3.0), "E", "2023:06:11 14:22:31")+ exif[271] = "Camera maker"+ exif[272] = "Camera model"+ exif[65000] = "A future tag"++ rows = enrich.exif_metadata(_image(tmp_path, exif=exif))++ assert rows["Make"] == "Camera maker"+ assert rows["Model"] == "Camera model"+ assert rows["DateTimeOriginal"] == "2023:06:11 14:22:31"+ assert rows["GPSLatitudeRef"] == "N"+ assert "48.0" in rows["GPSLatitude"]+ assert rows["65000"] == "A future tag"+++def test_dhash_is_16_hex_chars_and_stable(tmp_path):+ path = _image(tmp_path)+ digest = enrich.dhash(path)+ assert len(digest) == 16+ assert int(digest, 16) >= 0+ assert enrich.dhash(path) == digest+++def test_dhash_matches_the_same_picture_at_a_different_size(tmp_path):+ original = _image(tmp_path, "big.jpg", size=(400, 300))+ with Image.open(original) as img:+ img.resize((120, 90)).save(tmp_path / "small.jpg", "JPEG")++ assert enrich.hamming(enrich.dhash(original), enrich.dhash(tmp_path / "small.jpg")) <= enrich.DHASH_MATCH+++def test_dhash_separates_two_different_pictures(tmp_path):+ ramp = _image(tmp_path, "ramp.jpg")+ flat = tmp_path / "flat.jpg"+ Image.new("RGB", (64, 48), (10, 200, 90)).save(flat, "JPEG")++ assert enrich.hamming(enrich.dhash(ramp), enrich.dhash(flat)) > enrich.DHASH_MATCH+++def test_importing_an_image_queues_enrichment_and_lands_the_facts(tmp_workspace, monkeypatch, tmp_path):+ from azimut.engine import media as media_engine+ from azimut.engine import workqueue+ from azimut.workspace import Case++ monkeypatch.setattr(workqueue, "start_workers", False)+ case = Case.create("Enrich")+ exif = _exif_with_gps((48, 51, 30.0), "N", (2, 21, 3.0), "E", "2023:06:11 14:22:31")+ source = _image(tmp_path, exif=exif)++ with source.open("rb") as fh:+ result = media_engine.import_stream(case, "shot.jpg", fh)+ rel = result["item"]["path"]++ assert [j["kind"] for j in case.list_jobs(state="queued")].count(enrich.ENRICH_KIND) == 1+ workqueue.drain(case)++ item = media_engine.read_item(case, rel)+ assert item["gps"]["lat"] == pytest.approx(48.858333, abs=1e-5)+ assert item["gps"]["lon"] == pytest.approx(2.350833, abs=1e-5)+ assert item["taken_at"] == "2023-06-11T14:22:31"+ assert len(item["dhash"]) == 16+ assert item["enriched_at"]+ assert item["enrich_version"] == enrich.ENRICH_VERSION+ assert item["exif"]["DateTimeOriginal"] == "2023:06:11 14:22:31"+++def test_enrichment_is_recorded_even_when_the_image_carries_nothing(tmp_workspace, monkeypatch, tmp_path):+ from azimut.engine import media as media_engine+ from azimut.engine import workqueue+ from azimut.workspace import Case++ monkeypatch.setattr(workqueue, "start_workers", False)+ case = Case.create("Enrich")+ with _image(tmp_path).open("rb") as fh:+ rel = media_engine.import_stream(case, "plain.jpg", fh)["item"]["path"]++ workqueue.drain(case)++ item = media_engine.read_item(case, rel)+ assert item["enriched_at"] # we looked+ assert "gps" not in item and "taken_at" not in item # and found nothing+ assert item["dhash"] # pixels always hash+++def test_a_deleted_media_cancels_its_enrich_job(tmp_workspace, monkeypatch, tmp_path):+ from azimut.engine import media as media_engine+ from azimut.engine import workqueue+ from azimut.workspace import Case++ monkeypatch.setattr(workqueue, "start_workers", False)+ case = Case.create("Enrich")+ with _image(tmp_path).open("rb") as fh:+ rel = media_engine.import_stream(case, "gone.jpg", fh)["item"]["path"]+ media_path = case.resolve_inside(rel)+ media_path.unlink()+ media_path.with_suffix(media_path.suffix + ".json").unlink(missing_ok=True)++ workqueue.drain(case)++ assert case.list_jobs(kind=enrich.ENRICH_KIND)[0]["state"] == "cancelled"+++def test_video_facts_keep_unknown_tags_and_parse_location(tmp_path, monkeypatch):+ from azimut.engine import ffmpeg as ffmpeg_engine++ payload = b"""{+ "format": {+ "format_name": "mov,mp4",+ "duration": "4.25",+ "tags": {+ "creation_time": "2024-02-03T10:11:12Z",+ "com.apple.quicktime.location.ISO6709": "+48.858300+002.294500+035.0/",+ "future_camera_field": "kept"+ }+ },+ "streams": [{"index": 0, "codec_type": "video", "codec_name": "hevc"}]+ }"""+ seen = []+ monkeypatch.setattr(ffmpeg_engine, "ffprobe_path", lambda: "/local/ffprobe")++ def fake_run(argv, **kwargs):+ seen.append((argv, kwargs))+ return SimpleNamespace(returncode=0, stdout=payload)++ monkeypatch.setattr(enrich.subprocess, "run", fake_run)++ facts = enrich.video_facts(tmp_path / "clip.mov")++ assert seen[0][0][-1] == str(tmp_path / "clip.mov")+ assert seen[0][1] == {"capture_output": True, "timeout": 30}+ assert facts["gps"] == pytest.approx({"lat": 48.8583, "lon": 2.2945})+ assert facts["taken_at"] == "2024-02-03T10:11:12Z"+ assert facts["video_metadata"]["format · tags · future camera field"] == "kept"+ assert facts["video_metadata"]["streams 0 · codec name"] == "hevc"+++def test_a_video_import_queues_enrichment_and_lands_probe_metadata(+ tmp_workspace, monkeypatch+):+ import io++ from azimut.engine import media as media_engine+ from azimut.engine import workqueue+ from azimut.workspace import Case++ monkeypatch.setattr(workqueue, "start_workers", False)+ monkeypatch.setattr(+ enrich,+ "video_facts",+ lambda path: {+ "video_metadata": {"format · format name": "mov,mp4"},+ "gps": {"lat": 48.8583, "lon": 2.2945},+ "taken_at": "2024-02-03T10:11:12Z",+ },+ )+ case = Case.create("Enrich")+ rel = media_engine.import_stream(+ case, "clip.mp4", io.BytesIO(b"not really a video")+ )["item"]["path"]++ assert case.list_jobs(kind=enrich.ENRICH_KIND, state="queued")+ workqueue.drain(case)+ item = media_engine.read_item(case, rel)+ assert item["enrich_version"] == enrich.ENRICH_VERSION+ assert item["video_metadata"]["format · format name"] == "mov,mp4"+ assert item["gps"] == pytest.approx({"lat": 48.8583, "lon": 2.2945})+ media = case.find_entity(attr="path", value=rel)+ links = [link for link in case.links_of(media["id"]) if link["type"] == enrich.LOCATED_AT]+ assert len(links) == 1+ place = case.get_entity(links[0]["to"])+ assert place["type"] == "place"+ assert place["provenance"]["status"] == "suggested"+++def _import_image(case, name, tmp_path, exif=None):+ from azimut.engine import media as media_engine++ src = _image(tmp_path, name, exif=exif) if exif is not None else _image(tmp_path, name)+ with src.open("rb") as fh:+ return media_engine.import_stream(case, name, fh)["item"]["path"]+++def test_gps_becomes_a_suggested_place_linked_to_the_photo(tmp_workspace, monkeypatch, tmp_path):+ from azimut.engine import workqueue+ from azimut.workspace import Case++ monkeypatch.setattr(workqueue, "start_workers", False)+ case = Case.create("Enrich")+ exif = _exif_with_gps((48, 51, 30.0), "N", (2, 21, 3.0), "E")+ rel = _import_image(case, "paris.jpg", tmp_path, exif)+ workqueue.drain(case)++ places = [e for e in case.list_entities() if e["type"] == "place"]+ assert len(places) == 1+ place = places[0]+ assert place["provenance"]["status"] == "suggested"+ assert place["provenance"]["by"] == "enrich"+ assert place["attrs"]["lat"] == pytest.approx(48.858333, abs=1e-5)++ media = case.find_entity(attr="path", value=rel)+ links = [ln for ln in case.links_of(media["id"]) if ln["type"] == enrich.LOCATED_AT]+ assert len(links) == 1+ assert links[0]["to"] == place["id"]+ assert links[0]["provenance"]["status"] == "suggested"+++def test_two_photos_from_the_same_spot_reuse_one_place(tmp_workspace, monkeypatch, tmp_path):+ from azimut.engine import workqueue+ from azimut.workspace import Case++ monkeypatch.setattr(workqueue, "start_workers", False)+ case = Case.create("Enrich")+ exif = _exif_with_gps((48, 51, 30.0), "N", (2, 21, 3.0), "E")+ _import_image(case, "one.jpg", tmp_path, exif)+ workqueue.drain(case)+ _import_image(case, "two.jpg", tmp_path, exif)+ workqueue.drain(case)++ assert len([e for e in case.list_entities() if e["type"] == "place"]) == 1+++def test_draining_twice_does_not_stack_duplicate_suggestions(tmp_workspace, monkeypatch, tmp_path):+ from azimut.engine import workqueue+ from azimut.workspace import Case++ monkeypatch.setattr(workqueue, "start_workers", False)+ case = Case.create("Enrich")+ exif = _exif_with_gps((48, 51, 30.0), "N", (2, 21, 3.0), "E")+ rel = _import_image(case, "again.jpg", tmp_path, exif)+ workqueue.drain(case)+ workqueue.enqueue(case, enrich.ENRICH_KIND, key=rel, payload={"path": rel})+ workqueue.drain(case)++ media = case.find_entity(attr="path", value=rel)+ assert len([ln for ln in case.links_of(media["id"]) if ln["type"] == enrich.LOCATED_AT]) == 1+++def test_a_rescaled_copy_is_suggested_as_the_same_image(tmp_workspace, monkeypatch, tmp_path):+ from azimut.engine import media as media_engine+ from azimut.engine import workqueue+ from azimut.workspace import Case++ monkeypatch.setattr(workqueue, "start_workers", False)+ case = Case.create("Enrich")+ big = _image(tmp_path, "big.jpg", size=(400, 300))+ with Image.open(big) as img:+ img.resize((120, 90)).save(tmp_path / "small.jpg", "JPEG")++ with big.open("rb") as fh:+ first = media_engine.import_stream(case, "big.jpg", fh)["item"]["path"]+ with (tmp_path / "small.jpg").open("rb") as fh:+ second = media_engine.import_stream(case, "small.jpg", fh)["item"]["path"]+ workqueue.drain(case)++ a = case.find_entity(attr="path", value=first)+ b = case.find_entity(attr="path", value=second)+ matches = [ln for ln in case.links_of(b["id"]) if ln["type"] == enrich.SAME_IMAGE_AS]+ assert [ln["to"] for ln in matches] == [a["id"]]+ assert matches[0]["provenance"]["status"] == "suggested"+++def test_unrelated_pictures_are_not_linked(tmp_workspace, monkeypatch, tmp_path):+ from azimut.engine import media as media_engine+ from azimut.engine import workqueue+ from azimut.workspace import Case++ monkeypatch.setattr(workqueue, "start_workers", False)+ case = Case.create("Enrich")+ _import_image(case, "ramp.jpg", tmp_path)+ flat = tmp_path / "flat.jpg"+ Image.new("RGB", (200, 150), (10, 200, 90)).save(flat, "JPEG")+ with flat.open("rb") as fh:+ rel = media_engine.import_stream(case, "flat.jpg", fh)["item"]["path"]+ workqueue.drain(case)++ entity = case.find_entity(attr="path", value=rel)+ assert [ln for ln in case.links_of(entity["id"]) if ln["type"] == enrich.SAME_IMAGE_AS] == []+++def test_a_dismissed_suggestion_does_not_come_back_on_a_re_enrich(tmp_workspace, monkeypatch, tmp_path):+ """Dropping a suggestion is how an analyst says "not that". A re-read refreshes+ the file's facts, but re-proposing what was already settled would make the+ Enrich button undo every triage decision in the case."""+ from azimut.engine import media as media_engine+ from azimut.engine import workqueue+ from azimut.workspace import Case++ monkeypatch.setattr(workqueue, "start_workers", False)+ case = Case.create("Enrich")+ exif = _exif_with_gps((48, 51, 30.0), "N", (2, 21, 3.0), "E")+ rel = _import_image(case, "pin.jpg", tmp_path, exif)+ workqueue.drain(case)++ media = case.find_entity(attr="path", value=rel)+ proposed = [ln for ln in case.links_of(media["id"]) if ln["type"] == enrich.LOCATED_AT]+ assert len(proposed) == 1+ case.remove_link(proposed[0]["id"])++ # the facts are read again — and land again — but the graph is left alone+ media_engine.merge_item(case, rel, {"enriched_at": "", "gps": None})+ enrich.on_register(case, rel, "image", media["id"])+ workqueue.drain(case)++ assert media_engine.read_item(case, rel)["gps"]["lat"] == pytest.approx(48.858333, abs=1e-5)+ assert [ln for ln in case.links_of(media["id"]) if ln["type"] == enrich.LOCATED_AT] == []+++def test_media_from_an_older_release_still_gets_its_suggestions(tmp_workspace, monkeypatch, tmp_path):+ """A file enriched before the version stamp existed has never been proposed+ anything, so the first backfill must still speak up."""+ from azimut.engine import media as media_engine+ from azimut.engine import workqueue+ from azimut.workspace import Case++ monkeypatch.setattr(workqueue, "start_workers", False)+ case = Case.create("Enrich")+ exif = _exif_with_gps((33, 51, 24.0), "S", (151, 12, 55.0), "E")+ rel = _import_image(case, "old.jpg", tmp_path, exif)+ # rewind to what an older release left behind: facts, no version, no edges+ media = case.find_entity(attr="path", value=rel)+ for link in case.links_of(media["id"]):+ case.remove_link(link["id"])+ sidecar = media_engine.read_item(case, rel)+ sidecar.pop("enrich_version", None)+ media_engine._write_sidecar(case.resolve_inside(rel), sidecar)++ enrich.on_register(case, rel, "image", media["id"])+ workqueue.drain(case)++ assert [ln["type"] for ln in case.links_of(media["id"])] == [enrich.LOCATED_AT]+++def test_a_probe_that_never_ran_is_left_for_the_backfill_to_retry(tmp_workspace, monkeypatch, tmp_path):+ """A timed-out or crashed ffprobe is not an answer about the file. Stamping the+ enrichment version on it would take it out of the backfill's reach for good."""+ import subprocess++ from azimut.engine import ffmpeg as ffmpeg_engine++ monkeypatch.setattr(ffmpeg_engine, "ffprobe_path", lambda: "/usr/bin/ffprobe")++ def timeout(*args, **kwargs):+ raise subprocess.TimeoutExpired(cmd="ffprobe", timeout=30)++ monkeypatch.setattr(subprocess, "run", timeout)+ assert enrich.video_facts(tmp_path / "clip.mp4") is None++ # a file ffprobe did read and found nothing in is an answer, and repeating it+ # on every backfill would never produce a different one+ monkeypatch.setattr(+ subprocess, "run", lambda *a, **k: SimpleNamespace(returncode=1, stdout=b"")+ )+ assert enrich.video_facts(tmp_path / "clip.mp4") == {}+++def test_one_exif_value_is_bounded_while_it_is_built(tmp_workspace):+ """The cap exists so a maker note or a lens table never reaches a sidecar in+ full. Rendering the whole thing and then slicing would do all the work the cap+ is there to avoid, so the bound is applied as the string is assembled."""+ huge_list = tuple(range(200_000))+ rendered = enrich._display_value(huge_list)+ assert len(rendered) <= enrich.EXIF_VALUE_CAP + 1+ assert rendered.endswith("…")++ printable = enrich._display_value(b"A" * 5000)+ assert len(printable) <= enrich.EXIF_VALUE_CAP + 1+ # a binary blob is reported by size rather than mangled into replacement chars+ assert enrich._display_value(b"\x00\x01\x02" * 400) == f"{1200} bytes"+ # a short value is untouched+ assert enrich._display_value("Canon EOS 5D") == "Canon EOS 5D"diff --git a/tests/test_links_api.py b/tests/test_links_api.pyindex d93c0a7..633c2d5 100644--- a/tests/test_links_api.py+++ b/tests/test_links_api.py@@ -550,6 +550,63 @@ def test_chain_endpoint_is_empty_for_a_lone_entity(client):assert chain["empty"] is True+def test_chain_endpoint_exposes_and_triages_a_suggested_location_relation(client):+ cid = _new_case(client, "Suggested relation")+ case = Case.open(cid)+ media = case.add_entity("media", "Photo", {"path": "media/photo.jpg"}, by="user")+ place = case.add_entity("place", "Point", by="enrich", status="suggested")+ link = case.add_link(+ media["id"],+ place["id"],+ "located-at",+ by="enrich",+ status="suggested",+ )++ relation = client.get(f"/api/cases/{cid}/entities/{media['id']}/chain").json()[+ "relations"+ ][0]+ assert relation["entity"]["id"] == place["id"]+ assert relation["link"]["id"] == link["id"]+ assert relation["direction"] == "out"++ confirmed = client.patch(+ f"/api/cases/{cid}/links/{link['id']}",+ json={"status": "confirmed"},+ ).json()+ assert confirmed["provenance"]["status"] == "confirmed"++ assert client.delete(f"/api/cases/{cid}/links/{link['id']}").json() == {+ "status": "deleted"+ }+ assert case.links_of(media["id"]) == []+++def test_confirming_a_suggested_place_confirms_its_location_links(client):+ cid = _new_case(client, "Confirm location")+ case = Case.open(cid)+ media = case.add_entity("media", "Photo", {"path": "media/photo.jpg"}, by="user")+ place = case.add_entity("place", "Point", by="enrich", status="suggested")+ link = case.add_link(+ media["id"],+ place["id"],+ "located-at",+ by="enrich",+ status="suggested",+ )++ response = client.patch(+ f"/api/cases/{cid}/entities/{place['id']}",+ json={"status": "confirmed"},+ )++ assert response.json()["provenance"]["status"] == "confirmed"+ confirmed_link = next(+ item for item in case.links_of(place["id"]) if item["id"] == link["id"]+ )+ assert confirmed_link["provenance"]["status"] == "confirmed"++def test_lookup_endpoint_resolves_an_entity_by_attr(client):cid = _new_case(client, "Lookup")a = _upload(client, cid, "a.png")["item"]["path"]@@ -574,3 +631,236 @@ def test_derivation_endpoint_returns_the_closure_and_404s(client):assert len(sub["links"]) == 2 and all(lk["type"] == "derived-from" for lk in sub["links"])assert client.get(f"/api/cases/{cid}/entities/e_nope/derivation").status_code == 404+++# ── relations: the non-chain vocabulary, stated by hand ─────────────────────+++def test_relation_vocabulary_says_how_each_type_reads_and_who_may_state_it(client):+ entries = {row["type"]: row for row in client.get("/api/cases/relation-types").json()}++ assert entries["located-at"]["label"] == "was shot at"+ assert entries["located-at"]["from_types"] == ["capture", "media"]+ assert entries["located-at"]["to_types"] == ["place"]+ assert entries["located-at"]["manual"] is True+ # enrichment's own claim: named so the UI can say it, never offered by hand+ assert entries["same-image-as"]["manual"] is False+++def test_the_analyst_can_state_a_relation_and_it_lands_confirmed(client):+ cid = _new_case(client, "Stated relation")+ case = Case.open(cid)+ media = case.add_entity("media", "Photo", {"path": "media/photo.jpg"}, by="user")+ place = case.add_entity("place", "Checkpoint", {"lat": 48.0, "lon": 37.8}, by="user")++ link = client.post(+ f"/api/cases/{cid}/links",+ json={"from_id": media["id"], "to_id": place["id"], "type": "located-at"},+ ).json()++ assert link["from"] == media["id"] and link["to"] == place["id"]+ # a click is not a guess: there is nothing left for the analyst to review+ assert link["provenance"] == {+ "by": "user",+ "at": link["provenance"]["at"],+ "status": "confirmed",+ }+ # stating it twice is the same one edge, not two+ again = client.post(+ f"/api/cases/{cid}/links",+ json={"from_id": media["id"], "to_id": place["id"], "type": "located-at"},+ ).json()+ assert again["id"] == link["id"]+ assert len(case.links_of(place["id"])) == 1+++def test_a_stated_relation_is_refused_when_the_ontology_has_no_reading(client):+ cid = _new_case(client, "Refused relations")+ case = Case.open(cid)+ media = case.add_entity("media", "Photo", {"path": "media/photo.jpg"}, by="user")+ other = case.add_entity("media", "Other", {"path": "media/other.jpg"}, by="user")+ place = case.add_entity("place", "Checkpoint", {"lat": 48.0, "lon": 37.8}, by="user")++ def post(from_id, to_id, type_):+ return client.post(+ f"/api/cases/{cid}/links",+ json={"from_id": from_id, "to_id": to_id, "type": type_},+ )++ # a derivation records what a save did; it is never asserted after the fact+ assert post(media["id"], place["id"], "derived-from").status_code == 400+ # the wrong way round: a place is not shot at a photo+ assert post(place["id"], media["id"], "located-at").status_code == 400+ # a perceptual-hash match is enrichment's claim, not a person's+ assert post(media["id"], other["id"], "same-image-as").status_code == 400+ # free-typed labels stay valid in stored data, but nothing outside the+ # registry can be minted through the API+ assert post(media["id"], place["id"], "depicts-vaguely").status_code == 400+ assert post(media["id"], media["id"], "located-at").status_code == 400+ assert post(media["id"], "e_ghost", "located-at").status_code == 400++ assert case.links_of(media["id"]) == []+++def test_a_relation_can_be_restated_corrected_and_taken_back(client):+ """Relations are editable for as long as the case is open: a wrong reading is+ corrected on the same edge — same id, same provenance — and any relation can be+ removed, whether a tool proposed it or the analyst stated it."""+ cid = _new_case(client, "Editable relations")+ case = Case.open(cid)+ media = case.add_entity("media", "Photo", {"path": "media/photo.jpg"}, by="user")+ place = case.add_entity("place", "Checkpoint", {"lat": 48.0, "lon": 37.8}, by="user")+ link = client.post(+ f"/api/cases/{cid}/links",+ json={"from_id": media["id"], "to_id": place["id"], "type": "located-at"},+ ).json()++ restated = client.patch(+ f"/api/cases/{cid}/links/{link['id']}", json={"type": "depicts"}+ ).json()+ assert restated["id"] == link["id"] # one edge corrected, not replaced+ assert restated["type"] == "depicts"+ assert restated["provenance"]["at"] == link["provenance"]["at"]++ assert client.delete(f"/api/cases/{cid}/links/{link['id']}").json() == {+ "status": "deleted"+ }+ assert case.links_of(media["id"]) == []+++def test_restating_a_relation_is_refused_outside_the_vocabulary(client):+ cid = _new_case(client, "Refused restatements")+ case = Case.open(cid)+ media = case.add_entity("media", "Photo", {"path": "media/photo.jpg"}, by="user")+ other = case.add_entity("media", "Other", {"path": "media/other.jpg"}, by="user")+ place = case.add_entity("place", "Checkpoint", {"lat": 48.0, "lon": 37.8}, by="user")+ located = case.add_link(media["id"], place["id"], "located-at", by="user")+ depicts = case.add_link(media["id"], place["id"], "depicts", by="user")+ hashed = case.add_link(media["id"], other["id"], "same-image-as", by="enrich")+ derived = case.add_link(media["id"], other["id"], "derived-from", by="user")++ def patch(link_id, body):+ return client.patch(f"/api/cases/{cid}/links/{link_id}", json=body)++ # the pair already holds that reading: two identical edges would say it twice+ assert patch(located["id"], {"type": "depicts"}).status_code == 400+ # a perceptual-hash match is enrichment's claim, not the analyst's to reword+ assert patch(hashed["id"], {"type": "located-at"}).status_code == 400+ # a derivation records what a save did+ assert patch(derived["id"], {"type": "located-at"}).status_code == 400+ # ...and nothing outside the registry can be minted through a restatement+ assert patch(depicts["id"], {"type": "vaguely-near"}).status_code == 400+ assert patch("l_ghost", {"type": "depicts"}).status_code == 404+ assert patch(depicts["id"], {}).status_code == 400 # nothing to update++ assert {item["type"] for item in case.links_of(media["id"])} == {+ "located-at", "depicts", "same-image-as", "derived-from"+ }+++def test_confirming_a_relation_confirms_the_point_it_proposes(client):+ """The two halves of an enrichment suggestion are one claim, so the Suggestions+ list and the relation rows never disagree about the same click: accepting "this+ file was shot at this point" accepts the point too."""+ cid = _new_case(client, "Symmetric confirm")+ case = Case.open(cid)+ media = case.add_entity("media", "Photo", {"path": "media/photo.jpg"}, by="user")+ place = case.add_entity(+ "place", "48.858370, 2.294481", {"lat": 48.85837, "lon": 2.294481},+ by="enrich", status="suggested",+ )+ link = case.add_link(+ media["id"], place["id"], "located-at", by="enrich", status="suggested"+ )++ confirmed = client.patch(+ f"/api/cases/{cid}/links/{link['id']}", json={"status": "confirmed"}+ ).json()++ assert confirmed["provenance"]["status"] == "confirmed"+ assert case.get_entity(place["id"])["provenance"]["status"] == "confirmed"+ # the media was already the analyst's own import: nothing to change there+ assert case.get_entity(media["id"])["provenance"]["status"] == "confirmed"+++def test_dismissing_a_relation_leaves_the_point_it_proposed_alone(client):+ """Dropping the edge is not a verdict on the point. A place can be real while+ one file's claim about it is wrong, and deleting entities behind a dismiss+ would make a one-click triage destructive."""+ cid = _new_case(client, "Dismiss keeps the point")+ case = Case.open(cid)+ media = case.add_entity("media", "Photo", {"path": "media/photo.jpg"}, by="user")+ place = case.add_entity("place", "Point", {"lat": 1.0, "lon": 2.0}, by="enrich", status="suggested")+ link = case.add_link(media["id"], place["id"], "located-at", by="enrich", status="suggested")++ client.delete(f"/api/cases/{cid}/links/{link['id']}")++ assert case.get_entity(place["id"])["provenance"]["status"] == "suggested"+ assert case.links_of(place["id"]) == []+++def test_a_derivation_cannot_be_taken_back_as_if_it_were_a_relation(client):+ """A derivation is recorded by the save that produced it, and deleting one here+ would lose it without the tombstone `losses` reads. The POST and the type+ correction both refuse chain types; the delete has to agree with them."""+ cid = _new_case(client, "Chain is not a relation")+ case = Case.open(cid)+ crop = case.add_entity("media", "Crop", {"path": "media/crop.png"}, by="user")+ source = case.add_entity("media", "Source", {"path": "media/source.png"}, by="user")+ chain = case.add_link(crop["id"], source["id"], "derived-from", by="inspect")++ refused = client.delete(f"/api/cases/{cid}/links/{chain['id']}")++ assert refused.status_code == 400+ assert "derivation" in refused.json()["detail"]+ assert case.get_link(chain["id"]) is not None++ # a link that never existed is still a 404, not a 400+ assert client.delete(f"/api/cases/{cid}/links/l_nope").status_code == 404+++def test_confirming_an_entity_accepts_the_point_its_suggestion_named(client):+ """The two halves of an enrichment suggestion are one claim. Confirming the+ photo cannot leave the place it was proposed at sitting in Suggestions, or the+ map chips a point "suggested" while the relation row beside it reads as a+ finding — the same invariant confirming the edge itself carries."""+ cid = _new_case(client, "Confirm both halves")+ case = Case.open(cid)+ photo = case.add_entity(+ "media", "Photo", {"path": "media/photo.jpg"}, by="enrich", status="suggested"+ )+ place = case.add_entity(+ "place", "Point", {"lat": 1.0, "lon": 2.0}, by="enrich", status="suggested"+ )+ link = case.add_link(photo["id"], place["id"], "located-at", by="enrich", status="suggested")++ client.patch(f"/api/cases/{cid}/entities/{photo['id']}", json={"status": "confirmed"})++ assert case.get_entity(photo["id"])["provenance"]["status"] == "confirmed"+ assert case.get_link(link["id"])["provenance"]["status"] == "confirmed"+ assert case.get_entity(place["id"])["provenance"]["status"] == "confirmed"+++def test_confirming_an_entity_stops_at_one_hop(client):+ """Accepting a photo's own point is a reading of that photo, not a licence to+ accept whatever else that point was separately proposed to be."""+ cid = _new_case(client, "One hop")+ case = Case.open(cid)+ photo = case.add_entity(+ "media", "Photo", {"path": "media/photo.jpg"}, by="enrich", status="suggested"+ )+ place = case.add_entity(+ "place", "Point", {"lat": 1.0, "lon": 2.0}, by="enrich", status="suggested"+ )+ other = case.add_entity(+ "media", "Other", {"path": "media/other.jpg"}, by="enrich", status="suggested"+ )+ case.add_link(photo["id"], place["id"], "located-at", by="enrich", status="suggested")+ far = case.add_link(other["id"], place["id"], "located-at", by="enrich", status="suggested")++ client.patch(f"/api/cases/{cid}/entities/{photo['id']}", json={"status": "confirmed"})++ # the place came along, one hop out; the second photo's own claim did not+ assert case.get_entity(place["id"])["provenance"]["status"] == "confirmed"+ assert case.get_link(far["id"])["provenance"]["status"] == "suggested"+ assert case.get_entity(other["id"])["provenance"]["status"] == "suggested"diff --git a/tests/test_media_api.py b/tests/test_media_api.pyindex ea2dbd2..76eeb45 100644--- a/tests/test_media_api.py+++ b/tests/test_media_api.py@@ -51,13 +51,26 @@ def test_media_list_reports_thumb_state(client):assert item["thumb_state"] == "ready" # image thumbnails render inline+def test_media_list_reports_enrichment_state(client, monkeypatch):+ from azimut.engine import workqueue+ from azimut.workspace import Case++ monkeypatch.setattr(workqueue, "start_workers", False)+ cid = client.post("/api/cases", json={"name": "Enrichment state"}).json()["id"]+ _upload(client, cid, "shot.png", _png_bytes())++ assert client.get(f"/api/cases/{cid}/media").json()[0]["enrich_state"] == "queued"+ workqueue.drain(Case.open(cid))+ assert client.get(f"/api/cases/{cid}/media").json()[0]["enrich_state"] == "ready"++def test_video_thumbnail_is_queued_then_regenerated(client, monkeypatch):- from azimut.engine import thumbnails+ from azimut.engine import thumbnails, workqueuefrom azimut.workspace import Case# drive the queue by hand: disable the background worker, force a rendering# that always succeeds so the test never depends on a real ffmpeg.- monkeypatch.setattr(thumbnails, "start_workers", False)+ monkeypatch.setattr(workqueue, "start_workers", False)monkeypatch.setattr(thumbnails, "_render", lambda mp, out, kind: (out.write_bytes(b"\xff\xd8jpg"), True)[1])@@ -70,15 +83,15 @@ def test_video_thumbnail_is_queued_then_regenerated(client, monkeypatch):item = client.get(f"/api/cases/{cid}/media").json()[0]assert item["thumbnail"] is None and item["thumb_state"] == "queued"- thumbnails.drain(Case.open(cid)) # the worker's work, run synchronously+ workqueue.drain(Case.open(cid)) # the worker's work, run synchronouslyitem = client.get(f"/api/cases/{cid}/media").json()[0]assert item["thumb_state"] == "ready" and item["thumbnail"]def test_regenerate_queues_missing_thumbnails(client, monkeypatch):- from azimut.engine import thumbnails+ from azimut.engine import workqueue- monkeypatch.setattr(thumbnails, "start_workers", False)+ monkeypatch.setattr(workqueue, "start_workers", False)cid = client.post("/api/cases", json={"name": "Regen"}).json()["id"]# an image whose cached thumbnail is then removed (as budget eviction would)item = _upload(client, cid, "shot.png", _png_bytes()).json()["item"]@@ -91,6 +104,44 @@ def test_regenerate_queues_missing_thumbnails(client, monkeypatch):assert client.get(f"/api/cases/{cid}/media").json()[0]["thumb_state"] == "queued"+def test_enrich_backfill_queues_only_items_below_the_current_version(client, monkeypatch):+ from azimut.engine import enrich as enrich_engine+ from azimut.engine import media as media_engine+ from azimut.engine import workqueue+ from azimut.workspace import Case++ monkeypatch.setattr(workqueue, "start_workers", False)+ cid = client.post("/api/cases", json={"name": "Enrich backfill"}).json()["id"]+ rel = _upload(client, cid, "shot.png", _png_bytes()).json()["item"]["path"]+ case = Case.open(cid)++ workqueue.drain(case)+ assert client.post(f"/api/cases/{cid}/media/enrich", json={}).json() == {"queued": 0}++ # Simulate a sidecar written by an older enrichment version.+ media_engine.merge_item(case, rel, {"enrich_version": None})++ assert client.post(f"/api/cases/{cid}/media/enrich", json={}).json() == {"queued": 1}+ queued = case.list_jobs(kind=enrich_engine.ENRICH_KIND, state="queued")+ assert [job["payload"]["path"] for job in queued] == [rel]+++def test_enrich_backfill_can_force_one_known_path(client, monkeypatch):+ from azimut.engine import workqueue+ from azimut.workspace import Case++ monkeypatch.setattr(workqueue, "start_workers", False)+ cid = client.post("/api/cases", json={"name": "Enrich one"}).json()["id"]+ rel = _upload(client, cid, "shot.png", _png_bytes()).json()["item"]["path"]+ case = Case.open(cid)+ workqueue.drain(case)++ response = client.post(f"/api/cases/{cid}/media/enrich", json={"path": rel})++ assert response.json() == {"queued": 1}+ assert case.list_jobs(kind="enrich", state="queued")[0]["payload"]["path"] == rel++def test_listing_carries_category_fields(client):"""The Media Library groups items into facets (Images/Videos/Imports/…) purelyfrom ``kind`` and ``source`` — guard that both survive upload + listing."""@@ -1154,3 +1205,197 @@ def test_download_use_cookies_threads_saved_preference(client, monkeypatch):assert job["status"] == "done"assert seen == [None, {"browser": "firefox"}]+++def test_concurrent_sidecar_merges_do_not_drop_each_other(client, monkeypatch):+ """Two background writers touching one sidecar keep both fields: the merge is+ a read-modify-write under the case lock, not a last-writer-wins overwrite.++ The real worker is off: this is about the lock, not about when enrichment+ happens to land.+ """+ import threading++ from azimut.engine import media as media_engine+ from azimut.engine import workqueue+ from azimut.workspace import Case++ monkeypatch.setattr(workqueue, "start_workers", False)+ cid = client.post("/api/cases", json={"name": "Merge"}).json()["id"]+ rel = _upload(client, cid, "shot.png", _png_bytes()).json()["item"]["path"]+ case = Case.open(cid)++ start = threading.Barrier(2)++ def write(patch):+ start.wait(timeout=5)+ for _ in range(20):+ media_engine.merge_item(case, rel, patch)++ threads = [+ threading.Thread(target=write, args=({"thumbnail": "media/.thumbs/x.jpg"},)),+ threading.Thread(target=write, args=({"dhash": "ff00ff00ff00ff00"},)),+ ]+ for t in threads:+ t.start()+ for t in threads:+ t.join(timeout=10)++ item = media_engine.read_item(case, rel)+ assert item["thumbnail"] == "media/.thumbs/x.jpg"+ assert item["dhash"] == "ff00ff00ff00ff00"+++def test_naming_an_item_survives_the_enrichment_of_the_same_sidecar(client, monkeypatch):+ """The Save gate names an item just after filing it, while the enrichment job+ that filing queued is writing the file's own facts to the same sidecar. Both+ writes have to survive: the regression this guards dropped the typed name.+ """+ import threading++ from azimut.engine import media as media_engine+ from azimut.engine import workqueue+ from azimut.workspace import Case++ monkeypatch.setattr(workqueue, "start_workers", False)+ cid = client.post("/api/cases", json={"name": "Naming"}).json()["id"]+ rel = _upload(client, cid, "shot.png", _png_bytes()).json()["item"]["path"]+ case = Case.open(cid)++ start = threading.Barrier(2)++ def name_it():+ start.wait(timeout=5)+ for _ in range(20):+ media_engine.update_media(case, rel, {"title": "Yard panorama"})++ def enrich_it():+ start.wait(timeout=5)+ for _ in range(20):+ media_engine.merge_item(case, rel, {"dhash": "ff00ff00ff00ff00"})++ threads = [threading.Thread(target=name_it), threading.Thread(target=enrich_it)]+ for t in threads:+ t.start()+ for t in threads:+ t.join(timeout=10)++ item = media_engine.read_item(case, rel)+ assert item["title"] == "Yard panorama"+ assert item["dhash"] == "ff00ff00ff00ff00"+++def test_media_page_filters_and_counts_the_files_that_state_a_position(client):+ """The GPS facet is the browse-time half of import enrichment: a case of four+ hundred files, and the question is which ones told us where they were taken.+ A video's container tags count exactly like an image's EXIF — both land on the+ same sidecar field."""+ from azimut.engine import media as media_engine+ from azimut.workspace import Case++ cid = client.post("/api/cases", json={"name": "Positions"}).json()["id"]+ case = Case.open(cid)+ photo = _upload(client, cid, "photo.png", _png_bytes(color=(9, 0, 0))).json()["item"]+ clip = _upload(client, cid, "clip.png", _png_bytes(color=(10, 0, 0))).json()["item"]+ _upload(client, cid, "plain.png", _png_bytes(color=(11, 0, 0)))++ media_engine.merge_item(case, photo["path"], {"gps": {"lat": 48.8583, "lon": 2.2945}})+ # a video states its position in the container tags, not in EXIF+ media_engine.merge_item(+ case, clip["path"], {"kind": "video", "gps": {"lat": -33.86, "lon": 151.21}}+ )++ everything = client.get(f"/api/cases/{cid}/media/page").json()+ assert everything["total"] == 3+ assert everything["facets"]["gps_count"] == 2++ located = client.get(f"/api/cases/{cid}/media/page", params={"gps": "true"}).json()+ assert located["total"] == 2+ assert {item["path"] for item in located["items"]} == {photo["path"], clip["path"]}+ # the type chooser keeps counting inside the GPS filter, so its numbers say+ # what clicking one would actually give+ assert located["facets"]["category_counts"]["video"] == 1+ assert located["facets"]["category_counts"]["image"] == 1++ # ...and the GPS count follows the selected category the same way+ videos = client.get(+ f"/api/cases/{cid}/media/page", params={"gps": "true", "category": "video"}+ ).json()+ assert videos["total"] == 1+ assert videos["facets"]["gps_count"] == 1+++def test_media_page_ignores_a_half_written_position(client):+ """Enrichment never writes a partial point, but a hand-edited sidecar can hold+ one. A row the map could not place must not be offered as locatable."""+ from azimut.engine import media as media_engine+ from azimut.workspace import Case++ cid = client.post("/api/cases", json={"name": "Half position"}).json()["id"]+ case = Case.open(cid)+ item = _upload(client, cid, "odd.png", _png_bytes(color=(12, 0, 0))).json()["item"]++ for broken in ({"lat": 48.0}, {"lat": 48.0, "lon": None}, {"lat": "north", "lon": "east"}):+ media_engine.merge_item(case, item["path"], {"gps": broken})+ page = client.get(f"/api/cases/{cid}/media/page").json()+ assert page["facets"]["gps_count"] == 0, broken+++def test_the_browse_index_leaves_the_metadata_dumps_to_the_per_item_read(client):+ """Enrichment's full EXIF/video dumps are hundreds of rows per file. The+ listings are read 200 at a time (and whole, by the pickers), so a fat field on+ every row would multiply every one of those responses. They live in the+ sidecar and reach the UI one file at a time."""+ from azimut.engine import media as media_engine+ from azimut.workspace import Case++ cid = client.post("/api/cases", json={"name": "Fat metadata"}).json()["id"]+ case = Case.open(cid)+ item = _upload(client, cid, "shot.png", _png_bytes()).json()["item"]+ exif = {f"Tag{n:03d}": "v" * 64 for n in range(120)}+ media_engine.merge_item(case, item["path"], {"exif": exif, "gps": {"lat": 1.0, "lon": 2.0}})++ page = client.get(f"/api/cases/{cid}/media/page").json()+ listed = client.get(f"/api/cases/{cid}/media").json()+ assert "exif" not in page["items"][0]+ assert "exif" not in listed[0]+ # the parsed facts are small and stay indexed: the grid's pin and the GPS+ # filter both read them off the page+ assert page["items"][0]["gps"] == {"lat": 1.0, "lon": 2.0}+ assert page["facets"]["gps_count"] == 1++ one = client.get(f"/api/cases/{cid}/media/item", params={"path": item["path"]}).json()+ assert one["exif"] == exif+ assert one["path"] == item["path"]+ # the states the UI polls come along, so one read serves the whole panel+ assert one["thumb_state"] == "ready"+ assert one["entity_id"] == graph_read.entities(cid)[0]["id"]+++def test_the_per_item_read_refuses_a_path_outside_the_case(client):+ cid = client.post("/api/cases", json={"name": "Traversal"}).json()["id"]++ assert client.get(f"/api/cases/{cid}/media/item", params={"path": "../../etc/passwd"}).status_code == 400+ assert client.get(f"/api/cases/{cid}/media/item", params={"path": "media/gone.png"}).status_code == 404+++def test_enrich_counts_the_jobs_the_queue_took(client):+ """Naming a file whose kind carries no enrichment queues nothing, and the+ toast must not announce work that will never run."""+ from azimut.engine import workqueue++ cid = client.post("/api/cases", json={"name": "Enrich count"}).json()["id"]+ image = _upload(client, cid, "shot.png", _png_bytes()).json()["item"]+ audio = client.post(+ f"/api/cases/{cid}/media/upload",+ files={"file": ("note.mp3", io.BytesIO(b"ID3\x04\x00\x00\x00\x00\x00\x00"), "audio/mpeg")},+ ).json()["item"]++ assert audio["kind"] not in ("image", "video")+ assert client.post(+ f"/api/cases/{cid}/media/enrich", json={"path": audio["path"]}+ ).json() == {"queued": 0}+ assert client.post(+ f"/api/cases/{cid}/media/enrich", json={"path": image["path"]}+ ).json() == {"queued": 1}+ workqueue.wait_until_idle()diff --git a/tests/test_repository.py b/tests/test_repository.pyindex e02c54f..0200746 100644--- a/tests/test_repository.py+++ b/tests/test_repository.py@@ -72,6 +72,24 @@ def test_add_link_validates_endpoints_and_dedupes(repo):assert len(repo.list_links()) == 1+def test_update_link_changes_suggestion_status_without_rebuilding_edge(repo):+ media = repo.add_entity("media", "Photo", by="user")+ place = repo.add_entity("place", "Point", by="enrich", status="suggested")+ link = repo.add_link(+ media["id"],+ place["id"],+ "located-at",+ by="enrich",+ status="suggested",+ )++ updated = repo.update_link(link["id"], {"status": "confirmed"})++ assert updated["id"] == link["id"]+ assert updated["provenance"]["by"] == "enrich"+ assert updated["provenance"]["status"] == "confirmed"++def test_sync_links_restates_a_source_set(repo):src = repo.add_entity("proof", "P", {"spec": "proofs/p.json"}, by="user")m1 = repo.add_entity("media", "m1", by="user")@@ -375,3 +393,30 @@ def test_prune_drops_only_terminal_jobs(repo):assert repo.prune_jobs() == 1 # the ready one goes, the queued one staysassert [j["id"] for j in repo.list_jobs()] == [live["id"]]+++def test_count_incident_links_groups_relations_in_either_direction(repo):+ """The bulk "has this row relations?" read behind the map popup: the saved+ index is loaded whole on case open, so it carries a count and lets the popup+ fetch the edges. Excluding the chain types leaves exactly what `chain_of`+ reports as relations, which is what keeps the two from disagreeing."""+ photo = repo.add_entity("media", "photo", {"path": "media/x.jpg"}, by="user")+ other = repo.add_entity("media", "other", {"path": "media/y.jpg"}, by="user")+ place = repo.add_entity("place", "point", {"lat": 48.0}, by="user")+ quiet = repo.add_entity("place", "untouched", {"lat": 49.0}, by="user")+ proof = repo.add_entity("proof", "P", {"spec": "proofs/p.json"}, by="user")++ repo.add_link(photo["id"], place["id"], "located-at", by="enrich", status="suggested")+ repo.add_link(photo["id"], other["id"], "same-image-as", by="enrich", status="suggested")+ repo.add_link(proof["id"], photo["id"], "derived-from", by="user") # chain, excluded++ counts = repo.count_incident_links(exclude_types=["derived-from", "depends-on"])++ assert counts[photo["id"]] == 2 # counted at either end+ assert counts[place["id"]] == 1+ assert counts[other["id"]] == 1+ assert quiet["id"] not in counts # untouched rows are absent, not zero+ assert proof["id"] not in counts++ # excluding nothing counts every edge, chain included+ assert repo.count_incident_links(exclude_types=[])[proof["id"]] == 1diff --git a/tests/test_satellite_api.py b/tests/test_satellite_api.pyindex 0e34797..b453743 100644--- a/tests/test_satellite_api.py+++ b/tests/test_satellite_api.py@@ -1071,3 +1071,31 @@ 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 == 422assert client.post(f"/api/cases/{cid}/satellite/locate", params={"limit": 0}).status_code == 422+++def test_index_counts_relations_and_marks_a_proposed_point(client):+ """What the map popup needs to offer relations without the index carrying the+ edges: a count per row, and whether the point is a machine's proposal.+ Enrichment mints one suggested place per GPS-tagged file, so an index that+ could not tell them apart would let a camera's reading pass for analyst work.+ """+ from azimut.workspace import Case++ cid = client.post("/api/cases", json={"name": "Relations index"}).json()["id"]+ case = Case.open(cid)+ photo = case.add_entity("media", "Photo", {"path": "media/photo.jpg"}, by="user")+ proposed = case.add_entity(+ "place", "48.858370, 2.294481", {"lat": 48.85837, "lon": 2.294481},+ by="enrich", status="suggested",+ )+ mine = case.add_entity("place", "Checkpoint", {"lat": 50.4, "lon": 30.5}, by="user")+ case.add_link(photo["id"], proposed["id"], "located-at", by="enrich", status="suggested")++ rows = {row["title"]: row for row in _index(client, cid)}++ assert rows["48.858370, 2.294481"]["relations"] == 1+ assert rows["48.858370, 2.294481"]["status"] == "suggested"+ # a point the analyst pinned by hand carries neither mark+ assert rows["Checkpoint"]["relations"] == 0+ assert rows["Checkpoint"]["status"] == "confirmed"+ assert mine["id"] == rows["Checkpoint"]["id"]diff --git a/tests/test_sqlite_backend.py b/tests/test_sqlite_backend.pyindex 353e2e3..97d25bc 100644--- a/tests/test_sqlite_backend.py+++ b/tests/test_sqlite_backend.py@@ -143,13 +143,14 @@ 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), the jobs table is created (2->3), and- search/media browse indexes arrive in schema 4. A second open applies nothing."""+ column is added and backfilled (1->2), the jobs table is created (2->3),+ search/media browse indexes arrive in schema 4 and the position flag in 5. 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 -> 4 in place+ store = SqliteCase.open(db) # runs 1 -> 2 -> 3 -> 4 -> 5 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"]@@ -158,11 +159,11 @@ 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] == "4"+ assert conn.execute("SELECT value FROM meta WHERE key='schema_version'").fetchone()[0] == "5"applied = {r[0] for r in conn.execute("SELECT version FROM schema_migrations").fetchall()}- assert {2, 3, 4} <= applied+ assert {2, 3, 4, 5} <= appliedcolumns = {row[1] for row in conn.execute("PRAGMA table_info(entities)").fetchall()}@@ -173,12 +174,71 @@ def test_open_upgrades_a_v1_db_through_every_migration(tmp_path):SqliteCase.open(db) # idempotent — the second open applies nothingwith sqlite3.connect(db) as conn:- for version in (2, 3, 4):+ for version in (2, 3, 4, 5):assert conn.execute("SELECT COUNT(*) FROM schema_migrations WHERE version = ?", (version,)).fetchone()[0] == 1+# A schema-4 media index: the browse table as it shipped, before the position+# flag. `media_index_ready` is set because a real v4 case has already backfilled;+# without it, open would rescan the (absent) media folder and clear these rows.+_SCHEMA_V4_MEDIA = """+CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);+CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL);+CREATE TABLE entities (+ id TEXT PRIMARY KEY, type TEXT NOT NULL, label TEXT NOT NULL,+ attrs_json TEXT NOT NULL DEFAULT '{}', folder TEXT,+ search_text TEXT NOT NULL DEFAULT '',+ prov_by TEXT NOT NULL, prov_at TEXT NOT NULL,+ prov_status TEXT NOT NULL DEFAULT 'confirmed', prov_source TEXT+);+CREATE TABLE links (+ id TEXT PRIMARY KEY, from_id TEXT NOT NULL REFERENCES entities(id),+ to_id TEXT NOT NULL REFERENCES entities(id), type TEXT NOT NULL,+ prov_by TEXT NOT NULL, prov_at TEXT NOT NULL,+ prov_status TEXT NOT NULL DEFAULT 'confirmed', prov_source TEXT+);+CREATE TABLE folders (path TEXT PRIMARY KEY);+CREATE TABLE jobs (+ id TEXT PRIMARY KEY, kind TEXT NOT NULL, job_key TEXT,+ state TEXT NOT NULL DEFAULT 'queued', attempts INTEGER NOT NULL DEFAULT 0,+ max_attempts INTEGER NOT NULL DEFAULT 3, payload_json TEXT NOT NULL DEFAULT '{}',+ error TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL+);+CREATE 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+);+INSERT INTO meta(key, value) VALUES('schema_version', '4');+INSERT INTO meta(key, value) VALUES('media_index_ready', '1');+INSERT INTO media_items(path, item_json, filename, kind, name_sort, added_at, search_text)+ VALUES('media/photo.jpg',+ '{"path": "media/photo.jpg", "kind": "image", "gps": {"lat": 48.85, "lon": 2.29}}',+ 'photo.jpg', 'image', 'photo.jpg', '2026-01-01T00:00:00Z', 'photo.jpg');+INSERT INTO media_items(path, item_json, filename, kind, name_sort, added_at, search_text)+ VALUES('media/plain.jpg', '{"path": "media/plain.jpg", "kind": "image"}',+ 'plain.jpg', 'image', 'plain.jpg', '2026-01-02T00:00:00Z', 'plain.jpg');+"""+++def test_open_backfills_the_position_flag_from_already_indexed_items(tmp_path):+ """4 -> 5 reads the sidecar JSON already in the row, so a case enriched before+ the column existed gains its GPS filter on open — no file scan, no re-enrich."""+ db = tmp_path / "case.db"+ with sqlite3.connect(db) as conn:+ conn.executescript(_SCHEMA_V4_MEDIA)++ store = SqliteCase.open(db)++ page = store.page_media_items(gps=True)+ assert [item["path"] for item in page["items"]] == ["media/photo.jpg"]+ assert store.page_media_items()["facets"]["gps_count"] == 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(@@ -405,3 +465,25 @@ def test_convert_a_large_case_is_intact(tmp_workspace, tmp_path):ids = {e["id"] for e in store.list_entities()}for link in store.list_links():assert link["from"] in ids and link["to"] in ids+++def test_a_media_row_carries_the_entity_it_belongs_to(tmp_workspace):+ """The link is already a column. A caller that needs the entity behind a path+ reads it off the row instead of scanning the entities table for an attribute+ match — which is what enrichment does for every near-duplicate it finds."""+ from azimut.workspace import Case++ case = Case.create("Media rows")+ photo = case.add_entity("media", "Photo", attrs={"path": "media/photo.jpg"}, by="test")+ case.upsert_media_item(+ {"path": "media/photo.jpg", "filename": "photo.jpg", "kind": "image"},+ entity_id=photo["id"],+ )+ case.upsert_media_item({"path": "media/loose.jpg", "filename": "loose.jpg", "kind": "image"})++ by_path = {item["path"]: item for item in case.list_media_items()}+ assert by_path["media/photo.jpg"]["entity_id"] == photo["id"]+ # a row nothing filed says so rather than pointing at the wrong entity+ assert by_path["media/loose.jpg"]["entity_id"] is None+ assert case.media_items_by_paths(["media/photo.jpg"])[0]["entity_id"] == photo["id"]+ assert case.page_media_items()["items"][0]["entity_id"] in (photo["id"], None)diff --git a/tests/test_thumbnails.py b/tests/test_thumbnails.pyindex 8a308bd..85e9b8e 100644--- a/tests/test_thumbnails.py+++ b/tests/test_thumbnails.py@@ -18,7 +18,7 @@ import pytestfrom PIL import Imagefrom azimut.engine import media as media_engine-from azimut.engine import thumbnails+from azimut.engine import thumbnails, workqueuefrom azimut.workspace import Case@@ -26,7 +26,7 @@ from azimut.workspace import Casedef case(tmp_workspace, monkeypatch):"""A fresh case with the background worker disabled, so tests drain the queueexplicitly and deterministically."""- monkeypatch.setattr(thumbnails, "start_workers", False)+ monkeypatch.setattr(workqueue, "start_workers", False)return Case.create("Thumbs")@@ -73,7 +73,8 @@ def test_drain_generates_the_queued_thumbnail_and_updates_the_sidecar(case, monkmonkeypatch.setattr(thumbnails, "_render", fake_render)item = _register_video(case)["item"]- assert thumbnails.drain(case) == 1+ # The generic queue drains both the thumbnail and video-enrichment jobs.+ assert workqueue.drain(case) == 2job = case.list_jobs(kind=thumbnails.THUMB_KIND)[0]assert job["state"] == "ready"# the sidecar now points at the freshly generated, content-addressed file@@ -86,8 +87,8 @@ def test_a_failing_render_retries_then_fails_without_looping(case, monkeypatch):monkeypatch.setattr(thumbnails, "_render", lambda *a: False) # produces nothing_register_video(case)- handled = thumbnails.drain(case) # claims, fails, requeues, up to the budget- assert handled == 3 # default max_attempts+ handled = workqueue.drain(case) # claims, fails, requeues, up to the budget+ assert handled == 4 # three thumbnail attempts + one video-enrichment jobjob = case.list_jobs(kind=thumbnails.THUMB_KIND)[0]assert job["state"] == "failed" and job["attempts"] == 3@@ -97,7 +98,7 @@ def test_drain_cancels_a_job_whose_media_is_gone(case):(case.subdir("media") / "clip.mp4").unlink()(case.subdir("media") / ("clip.mp4" + media_engine.SIDECAR_SUFFIX)).unlink()- thumbnails.drain(case)+ workqueue.drain(case)assert case.list_jobs(kind=thumbnails.THUMB_KIND)[0]["state"] == "cancelled"@@ -188,7 +189,7 @@ def test_startup_recovers_interrupted_jobs(case, monkeypatch):def test_worker_wakes_and_drains_in_the_background(tmp_workspace, monkeypatch):- monkeypatch.setattr(thumbnails, "start_workers", True)+ monkeypatch.setattr(workqueue, "start_workers", True)def fake_render(media_path, out_path, kind):out_path.write_bytes(b"\xff\xd8\xff\xe0jpeg")@@ -205,4 +206,4 @@ def test_worker_wakes_and_drains_in_the_background(tmp_workspace, monkeypatch):time.sleep(0.05)refreshed = media_engine.read_item(c, item["path"])assert refreshed["thumbnail"] and c.resolve_inside(refreshed["thumbnail"]).exists()- assert thumbnails.wait_until_idle()+ assert workqueue.wait_until_idle()diff --git a/tests/test_workqueue.py b/tests/test_workqueue.pynew file mode 100644index 0000000..7440284--- /dev/null+++ b/tests/test_workqueue.py@@ -0,0 +1,137 @@+"""The generic durable worker: one registry of kind -> handler, one thread, and+central settlement of every claimed job.++The queue is drained explicitly here (`start_workers = False`) so ordering is+deterministic and no background thread outlives a test.+"""++from __future__ import annotations++import threading+import time++import pytest++from azimut.engine import workqueue+from azimut.workspace import Case+++def case(tmp_workspace, monkeypatch):+ monkeypatch.setattr(workqueue, "start_workers", False)+ monkeypatch.setattr(workqueue, "HANDLERS", dict(workqueue.HANDLERS))+ return Case.create("Queue")+++def test_drain_runs_the_handler_registered_for_each_kind(case):+ seen: list[tuple[str, str]] = []+ workqueue.register("alpha", lambda c, job: seen.append(("alpha", job["payload"]["n"])))+ workqueue.register("beta", lambda c, job: seen.append(("beta", job["payload"]["n"])))++ workqueue.enqueue(case, "alpha", payload={"n": "1"})+ workqueue.enqueue(case, "beta", payload={"n": "2"})++ assert workqueue.drain(case) == 2+ assert seen == [("alpha", "1"), ("beta", "2")]+ assert [j["state"] for j in case.list_jobs()] == ["ready", "ready"]+++def test_a_handler_raising_job_cancelled_drops_the_job_without_retrying(case):+ def handler(c, job):+ raise workqueue.JobCancelled("nothing to do")++ workqueue.register("alpha", handler)+ workqueue.enqueue(case, "alpha", payload={})++ assert workqueue.drain(case) == 1+ job = case.list_jobs(kind="alpha")[0]+ assert job["state"] == "cancelled"+ assert job["attempts"] == 1+++def test_a_failing_handler_retries_until_the_attempt_budget_is_spent(case):+ attempts = []++ def handler(c, job):+ attempts.append(job["id"])+ raise workqueue.JobFailed("boom")++ workqueue.register("alpha", handler)+ workqueue.enqueue(case, "alpha", payload={})++ workqueue.drain(case) # claims, fails, requeues, up to the budget+ job = case.list_jobs(kind="alpha")[0]+ assert job["state"] == "failed"+ assert job["error"] == "boom"+ assert len(attempts) == job["max_attempts"]+++def test_a_job_of_an_unknown_kind_is_cancelled_not_left_running(case):+ workqueue.enqueue(case, "gamma", payload={})++ assert workqueue.drain(case) == 1+ assert case.list_jobs(kind="gamma")[0]["state"] == "cancelled"+++def test_has_queued_reports_work_of_any_kind(case):+ workqueue.register("alpha", lambda c, job: None)+ assert workqueue.has_queued(case) is False+ workqueue.enqueue(case, "alpha", payload={})+ assert workqueue.has_queued(case) is True+ workqueue.drain(case)+ assert workqueue.has_queued(case) is False++[email protected]("operation", ["delete", "promote"])+def test_moving_a_case_directory_waits_for_the_background_worker(+ tmp_workspace, monkeypatch, operation+):+ """A job writes inside the case folder, so moving that folder while the worker+ is still in it is how ``Directory not empty`` happens on POSIX and an outright+ refusal happens on Windows.++ This one runs a real worker thread (no ``start_workers = False``): the race is+ the point, and draining by hand would test nothing. Enrichment is what made the+ window wide enough to hit — probing a video takes far longer than writing a+ thumbnail — but the two operations that move a directory are the fix's place,+ not one job kind.+ """+ monkeypatch.setattr(workqueue, "HANDLERS", dict(workqueue.HANDLERS))+ case = Case.create("Doomed", scratch=operation == "promote")+ started = threading.Event()++ def slow(c, job):+ started.set()+ time.sleep(0.3) # wide enough that an un-drained move lands mid-job+ (c.path / "media").mkdir(parents=True, exist_ok=True)+ (c.path / "media" / "late.json").write_text("{}", encoding="utf-8")++ workqueue.register("slow", slow)+ workqueue.enqueue(case, "slow", payload={})+ workqueue.wake(case)+ assert started.wait(2), "the worker never picked the job up"++ if operation == "delete":+ case.delete()+ assert not case.path.exists()+ else:+ moved = case.promote("Promoted")+ # the file the worker wrote travelled with the case rather than being+ # stranded in a half-moved directory+ assert (moved.path / "media" / "late.json").exists()++ # the operation returned only once the worker was out, so nothing is left+ # writing into a path that no longer exists+ assert workqueue.wait_until_idle(timeout=0) is True+++def test_wait_until_idle_looks_once_more_after_the_deadline(case, monkeypatch):+ """A worker that finishes during the final sleep is idle. Reporting a timeout+ for work that is done would have the caller refuse to move a case directory it+ is now free to move."""+ monkeypatch.setattr(workqueue, "_worker_running", False)++ assert workqueue.wait_until_idle(timeout=0) is True++ monkeypatch.setattr(workqueue, "_worker_running", True)+ assert workqueue.wait_until_idle(timeout=0) is False