The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.
JavaScript
Fill Graph and Sheet from the work: proposed links, a Sheet home, folders, and files to geolocate (#98)
OsintMeThat26d04ad62e23
diff --git a/docs/ONTOLOGY.md b/docs/ONTOLOGY.mdindex 40b336b..872b39c 100644--- a/docs/ONTOLOGY.md+++ b/docs/ONTOLOGY.md@@ -580,6 +580,7 @@ a narrowing can only remove a type, never smuggle one in from elsewhere.| `posted` | account → media/bookmark | the account published the content or URL | ✅ || `appears-in` | actor/asset/identifier → image/video media or capture | the entity or a recognizable representation is visible | ✅ || `sited-at` | structure → place | a permanent site, never a dated presence | ✅ |+| `same-site-as` | place → place | the two points belong to one site; proposed for points under 300 m apart | ✅ || `instance-of` | asset → equipment-type | this particular object is one of that model | ✅ || `in-network` | IP/network → network | an address or subnet belongs inside the network | ✅ || `same-image-as` | image media → image media | a machine perceptual-hash match | ✅ |@@ -1044,9 +1045,9 @@ joins and a type by its role, so adding either places it with no edit there:| Lens | Verbs | Derived by | Nodes ||---|---|---|---|-| Everything | all 19 | the whole registry | the case |+| Everything | all 20 | the whole registry | the case || Subjects | `owns`, `part-of`, `member-of`, `associated-with`, `posted`, `appears-in`, `instance-of`, `in-network`, `same-image-as` | an analyst's relation that is not geography | the case |-| Ground | `located-at`, `depicts`, `sited-at` | a relation whose object is a `place` | the case |+| Ground | `located-at`, `depicts`, `sited-at`, `same-site-as` | a relation whose object is a `place` | the case || Statements | `about`, `at`, `cites`, `contradicts` | `action = "claim"` | the case || My work | `derived-from`, `depends-on`, `mentions` | the chain types, plus `action = "mention"` | everything |@@ -1227,7 +1228,7 @@ How it is wired (`engine/links.py`):- **Provenance** (on every entity and link): `by` (tool id: `media-library`,`satellite`, `proof-composer`, `post-composer`, `inspect`, `paste`, `ingest`,- or `user`), `at` (UTC), `status` and optional source URL. It borrows the entity/activity/agent+ `link-finder`, or `user`), `at` (UTC), `status` and optional source URL. It borrows the entity/activity/agentshape of W3C PROV without implementing the full standard.- **Review status** is `confirmed` (analyst-made or analyst-accepted) vs`suggested` (a tool proposed it, awaiting a click). It is not confidence. Import@@ -1242,6 +1243,15 @@ How it is wired (`engine/links.py`):a place can be real while one file's claim about it is wrong. A dismissal sticks,so re-reading a file never re-proposes edges already triaged. Anything still`suggested` is marked as such wherever it appears.+ **The link pass** (`engine/proposals.py`, provenance `link-finder`) proposes the+ rest of what the files already say: the account a post's address names, filed+ `suggested` with its `posted` edge, and `same-site-as` between points under 300 m+ apart, one edge per join so a site of eight points gets seven. It runs after a+ place, a file or a bookmark is filed, and reads each entity once (the manifest's+ `link_pass` mark), so a dropped proposal does not come back. Dropping the last+ proposal of an account it filed takes the account too. A proposal nobody has+ reviewed holds nothing up: a place a proof lets go of is still offered for deletion.+ ✅**A derivation is `confirmed`**: `derived-from`/`depends-on` record what theanalyst's own click just made. `suggested` is for inference — OCR reading a streetname, EXIF proposing a `place`. A relation stated by hand is `confirmed` for thediff --git a/docs/SPEC.md b/docs/SPEC.mdindex 4a7601c..503a622 100644--- a/docs/SPEC.md+++ b/docs/SPEC.md@@ -219,6 +219,12 @@ proof for publication.| ✅ **The Board as an index** | Groups the case by family, people, places and things first with how many events name each and when, the files folded under; Most noted first, Details beside the list, walked with the arrow keys. || ✅ **Every date on a clock** | One Clock chip wherever a date is typed: a day or a time reads on its place's zone, UTC, this computer or any zone in the world, and the Timeline spans that zone's day. || ✅ **Dates in posts, better templates** | A `#date` token carries the proof's date into a post only where a template asks; templates start from a layout, duplicate, preview on the open post with each platform's count, flag a misspelled token and set the default. |+| ✅ **A work folder, and Files that acts** | New files and saved work land in the folder being worked in; folders rename with their items and files; Files and the sidebar act on a right-click, Files filters by type or by what is linked to nothing, and the sidebar also shows the case's to-do lists and recent work. |+| ✅ **Links the case proposes** | Proposes the account a post's address names and joins points under 300 m apart as one site, reviewed in one list from the Graph; a dropped proposal does not come back. |+| ✅ **A Sheet home** | The Sheet tab opens on the recent sheets and the ones the case could start, counted; Close saves and comes back to it; a status chip opens its words. |+| ✅ **Files to geolocate** | One row per imported picture or video, done once a proof answers it, opened from the Sheet home or the Media Library and kept level by Refresh. |+| ✅ **My geolocations by point** | One row per point of every proof, POV or not, with its date, source address and description. |+| ✅ **Where a geolocation sits** | A point named by its coordinates reads as the town it is near on the Graph; a saved proof says which geolocations share its site and what its account posted. |---diff --git a/docs/STORAGE_AND_PERFORMANCE.md b/docs/STORAGE_AND_PERFORMANCE.mdindex 85bb5dc..ef4cf69 100644--- a/docs/STORAGE_AND_PERFORMANCE.md+++ b/docs/STORAGE_AND_PERFORMANCE.md@@ -93,7 +93,7 @@ for a case to fit under it on Windows, and names it as a warning elsewhere.<case>/ # the analyst's: Azimut writes nothing here but azimut/README.txt # which half of the folder is whoseazimut/- case.json # small manifest: name, dates, storage format, schema and to-do lists+ case.json # small manifest: name, dates, storage format, schema, to-do lists, work folder, link-pass marknotes.md # case-wide Markdown notenotes/ # note bodies, named after their title, filed as in the notebookmedia/ # imported, downloaded and derived media@@ -138,7 +138,8 @@ names that keep a case's longest path inside Windows' 260-character limit.new directory level or a raised cap breaks it.`case.json` is the discovery manifest: name, creation date, and the storage and-schema fields. It no longer holds the graph, so the case switcher can identify a+schema fields, plus two pieces of case metadata that own no files, the to-do lists+and the work folder. It no longer holds the graph, so the case switcher can identify acase without opening its database. `case.db` is the source of truth for mutablestructured state (entities, links, folders, jobs). The files under `media/`,`proofs/`, `sheets/`, `.drafts/`, `.inspect/`, `.collages/`, `.compare/`, `.analysis/`,@@ -200,7 +201,7 @@ carry enough information to detect staleness.| Data | Owner | Notes ||---|---|---|-| Case name and storage version | `case.json` | Small manifest, atomically replaced |+| Case name, storage version, to-do lists, work folder, link-pass mark | `case.json` | Small manifest, atomically replaced; the mark is how far the link pass has read || Entities, links and folders | `case.db` | Transactional and versioned || Entity photo galleries | `case.db` (`entity_images`) | Ordered private photos or Media references, with one primary || Private entity photo bytes | `.data/entity-images/` | Bounded JPEG plus dedicated thumbnail; never indexed as media |@@ -363,7 +364,9 @@ use `.data/rename.json`, so a restart can finish references after the bytes move`folders`: Normalized `/`-separated logical paths for the analyst's organisation. Not- filesystem directories, not semantic links.+ filesystem directories, not semantic links. Every entity write registers the+ folder it carries and its parents, and the list read adds any folder an entity+ sits in, so a folder exists whichever door it came in by.`jobs`: Durable local background work: `id`, `kind`, an optional `job_key`, `state`,diff --git a/docs/UI.md b/docs/UI.mdindex 190ac00..50a36d7 100644--- a/docs/UI.md+++ b/docs/UI.md@@ -442,6 +442,22 @@ single root to expand from. Expansion is the drill-down.sends you opening statements one at a time. It concludes nothing: whether threecitations from one account is a problem is the analyst's to say, and a source with noknown publisher is left out of the claim rather than assumed.+- **The case proposes the links its files already state.** Who posted a file is written in+ its address on X, Telegram, TikTok, YouTube, Instagram, Threads, Bluesky and the+ fediverse, and two points under 300 m apart are usually one site; the case files both as+ proposals (`engine/proposals.py`) after an import, dashed on the drawing, so islands of+ one geolocation each join through their account and their site. **N proposed** in the+ toolbar opens them as one list of sentences — *@BashaReport posted clip.mp4*, *Hangar and+ Runway are one site, 110 m apart* — each with Confirm and Drop, and a line pressed shows+ its node. A dropped proposal does not come back, and dropping the last one of an account+ the case filed takes the account too. On a case filed before this existed the toolbar+ offers **Find links** once; after that every import reads the case again and the count+ is the only news, so the toolbar stays as it was.+- **A point named by its coordinates is drawn by the town it is near.** *96 km N of Al+ Ḩazm* says where `16.982714, 45.053931` is to anybody who does not read coordinates,+ from the offline gazetteer (cities of 15 000 people or more, within 100 km), and the+ exported plate writes the same. The label stays the entity's: the panel shows both and a+ search still matches the digits. A point somebody named keeps its name.- **The legend is the control** for the budget, where the lens is the control for thereading. On a real case one family dwarfs the rest, so leaving `collected` out iswhat spends the budget on the actors, places and statements instead. A handful of@@ -820,9 +836,16 @@ The sidebar defaults to collapsed in Map and open elsewhere. Open state isremembered per workspace for the current session. Reloading restores the defaults.- **Header** — the case name (its id is a tooltip), a **Notes** button opening- `notes.md` in the Notebook, a search field, and one filter chip per entity type- present, counted from the catalog summary. The chips wrap; past the fifth they- fold behind `+N`, and the active one always shows.+ `notes.md` in the Notebook, and three views: **Folders**, **To-do** and+ **Recent**. The choice is remembered across reloads. Folders adds a search field+ and one filter chip per entity type present, counted from the catalog summary.+ The chips wrap; past the fifth they fold behind `+N`, and the active one always+ shows.+- **Views** — the sidebar sits beside whatever tool is open, so it carries what is+ worth having there rather than a second Files. **To-do** is the case's lists from+ Home, one copy shared by both, so a task ticked on the map is ticked on Home.+ **Recent** is the last forty items filed, newest first, read only while it is+ open.- **Body** — one rule: no filter shows the tree, a query or a chip shows a flatresult list. A filtered tree would have to badge folders with per-type countsthe summary cannot give, so the modes are exclusive. Result rows carry their@@ -833,15 +856,22 @@ remembered per workspace for the current session. Reloading restores the defaulta node only when non-empty), the analyst's nested folders, **Unfiled**, then**Trash** when it holds a delete. Trash shows its item count and size; eachgroup can be restored or deleted permanently, and the node can be emptied.- `+ Folder` and `+ Note` sit above the tree.+ `+ Folder` and `+ Note` sit above the tree, with the work folder pinned over+ them when there is one: pressing its name opens the tree down to it, the cross+ stops working there.+- **Right-click** — a folder row offers Rename, New subfolder, New note here, Work+ in this folder and Remove; an item row offers Open, Details, Rename, Move to…,+ Show in Timeline and Move to Unfiled. Renaming needs a field the row has no room+ for, so it opens in the menu itself. A suggestion keeps its two buttons and no+ menu.- **Filing** — drag rows onto a folder, or drop them on Unfiled to unfile.Ctrl/cmd-click and shift-click select several rows first, and the drag carriesall of them; folders are targets, never cargo. The tree scrolls itself when thepointer nears an edge mid-drag, since a native drag swallows the wheel.- Unfiling does not delete data. The **Files** tab presents the same tree with- tiles, multi-select and context actions. It also exposes Trash with the same- restore, permanent-delete and empty actions as the sidebar. Delete sends the- current selection through the standard confirmation.+ Unfiling does not delete data. The **Files** tab (see Sources) presents the+ same tree with tiles, multi-select and context actions. It also exposes Trash+ with the same restore, permanent-delete and empty actions as the sidebar.+ Delete sends the current selection through the standard confirmation.- **Details** — a drawer over the sidebar, closed with the back arrow or Escape, soselecting a row never pushes the case out of view. Every entity uses the same threetabs. **Info** holds identity, declared profile fields, file metadata, notes and@@ -1388,6 +1418,51 @@ for a reload that will never come.## Sources+**Files is the case's file manager.** Everything filed in the case, by folder, as+tiles or a list. Folder counts come from the catalog summary, so a case past its+first page of 200 counts every item. A right-click acts on what was pressed:++- an item, or the selection it is part of — Open; Open in Inspect, Reverse Search+ or Geo Proof for a picture or a video (the Media Library's own list); Rename+ (also F2); Move to…; New folder with the selection; Move to Unfiled; Add event;+ Show in Timeline; Show on map for a capture; Show in folder; Details; Delete;+- a folder — Open, Rename, New subfolder, New note, New bookmark, Import files+ here, Work in this folder, Remove folder;+- empty space — the same additions, into the folder on screen.++Renaming happens in place on the tile, the list row or the tree row: Enter or+leaving the field keeps it, Escape drops it. An item is renamed by the route+Details uses, so a media renames its file. A folder carries its subfolders, its+items and their files: a note's markdown moves with it, and a media's sidecar+and browse index follow. A name another folder already has, ignoring case, is+refused, because two such folders would mirror onto one directory of notes on+Windows and macOS. The toast offers Undo.++Chips under the crumbs narrow the open folder and what is under it by type, and+**Nothing linked yet** keeps what is connected to nothing at all, the Board's+term. Either one turns the view into a flat list, as a search does, asked of the+server past the first page.++**Move to…** is one dialog for Files, the sidebar and the toasts below. It starts+on where the items already are and moves nothing until another folder is picked.++**The work folder.** One folder of the case can be the one being worked in. New+files and saved work land in it when nothing else was chosen: uploads, downloads,+pastes, captures and bookmarks from the extension, Inspect frames, proofs, posts,+sessions, places and Detect pins. Subjects and Claims never do: a person is shared+across every thread of a case, so filing them under one would be a guess. Every+save dialog that picks a folder for something new starts on it and says so, and+picking Unfiled there wins. Where nothing was asked on the way in, the toast names+the folder and offers **Move**. It is set from the crumbs in Files (**Work here**),+a folder's right-click in Files or the sidebar, or the pin on a sidebar folder row.+A case opens Files on it. It is kept in `case.json`, so a bundle carries it; a+rename carries it too, and removing the folder clears it.++**A folder exists whichever door it came in by.** Naming a new folder in a save+dialog used to set it on the item only, so it showed in Files and in no folder+picker. Every write that files an item now registers its folder, and the list+also reads the folders items already sit in, for cases filed before.+The Media Library toolbar keeps its explicit maintenance actions behind a `⋮`beside Import, because both are repairs pressed once in a while and read as astep of importing when they sit next to Download: **Regenerate missing@@ -1411,7 +1486,9 @@ computed with it so the facets never disagree with the list, and toggling it refbecause the loaded page is already the collected subset. It reads how the file**entered the case**, which is not everything true about it: one imported and laterfound identical to an extracted frame stays on the side it came in by. A case holding-nothing but working files says so instead of offering to import. Thumbnail polling follows all pending case jobs, including+nothing but working files says so instead of offering to import. **Worklist**, beside+Import, opens the pictures and videos brought in as the Sheet *Files to geolocate*, built+on the first press and the same one after (Sheet section). Thumbnail polling follows all pending case jobs, includingfiles beyond the loaded page after a case import. Thumbnail failures are scopedto their case, so switching cases always reloads previews even when relativepaths match. Enrichment respects an existing confirmed GPS relation during backfill.@@ -2456,16 +2533,18 @@ Editing a routine opens on the last step, which reads the whole thing back witheach line a way into its step. Both kinds carry a name and a line saying what theyare for, and that line travels with every run they make.-**Where** offers the case's own areas first, as chips in their colours that toggle-in and out of the detection; drawing rectangles, polygons or circles, or taking the-current view as a rectangle, is for ground the case does not watch yet. It prices-the result before anything is fetched: ground area, native tiles, Copernicus-requests and roughly how long. Each date costs two requests a tile, the picture+**Where** offers the case's own areas first, as one list: each group a folded row+with a tick box that takes all its areas in or out, then the ungrouped areas, each+ticked on its own. The areas picked are listed under it. Drawing rectangles,+polygons or circles, or taking the current view as a rectangle, is for ground the+case does not watch yet. It prices the result before anything is fetched: ground+area and native tiles in Where, the Copernicus requests there too once an analyzer+is picked, and roughly how long on the last step. Each date costs two requests a tile, the picturereviewed and the bands measured. A radar vessel sweep adds one for the Sentinel-2 waterclassification it is judged against. One-off drawings stay temporary unless **Save as area** is pressed;-saving a routine promotes its drawings. In **Where**, the same groups select-their current areas in one press, without duplicates, and ungrouped areas stay-available on their own. A selection can be saved as a group; temporary drawings+saving a routine promotes its drawings. A group whose areas are all in reads as+ticked even when they came through another group, and some of them as partly+ticked, so an area is never selected twice. A selection can be saved as a group; temporary drawingsbecome shared areas first. A routine keeps the areas selected when it was saved,so later group edits do not change its scope. An area is grabbed by its edge: dragging insideone pans the map as it would anywhere else, a click on the edge shows its corner@@ -2515,10 +2594,13 @@ A cloudier newest pass is reported as skipped. An unresolved area fails by namewithout stopping the rest. Opening Detect readslocal state only; pass lookups happen only on request or during an explicit run.-**What** picks the analyzer from a list grouped by what it looks for — vessels,+**What** starts with nothing picked, so a detection never runs an analyzer nobody+chose. It picks the analyzer from a list grouped by what it looks for — vessels,fires and burns, water and floods, buildings and earthworks, vegetation and smallmarks, any change — with radar first where it reads the same thing better, and-your own after them. Each built-in says in brackets how far its reading can be+your own after them. The groups start folded, the one holding the pick open, and a+folded group names the analyzer picked in it. The analyzer library folds its built-in+groups the same way. Each built-in says in brackets how far its reading can betrusted, from what calibration showed: *reliable* (the published test, or acontrast few false hits survive), *approximate* (right more often than not, withknown look-alikes) or *rough* (a lead to check). Radar vessels are reliable and@@ -2570,8 +2652,8 @@ passes only flag where to look: the razed-buildings analyzer says so, and theflood one starts at Large, since a flood is fields wide. Without the radar layerthe wizard says where to find it and stops before its dates.-**Small**, **Medium**, **Large** and **All** come first in the What step, above-the analyzers, and set the target size as a whole: floor and ceiling area, cleanup+**Small**, **Medium**, **Large** and **All** come once an analyzer is picked, under+the list, and set the target size as a whole: floor and ceiling area, cleanupand grouping together, since a small target needs no cleanup that would erase it.What the chosen one accepts is written under the buttons in ground terms — a markoutside that band is found and then dropped, which reads as "nothing found" unless@@ -2820,6 +2902,11 @@ unchecked point through the map first**, one at a time: *Use this point* keeps omoves it and goes on to the next. *Later*, offered by Save only, saves the proof andkeeps those points off the case map, where they would read as conclusions; a placealready there stays. To post has no *Later*, since the post publishes the point.+**A save says what the proof just joined**, in one line under the header: *On the same+site as 2 other geolocations · @BashaReport posted 3 other files here*, with **See in the+graph**. It is read from the points and the addresses (`GET /entities/{id}/kin`), so it+answers before the link pass has filed anything, and it goes at the next edit. A proof+that shares nothing draws no line.The exported picture prints them only when asked (Advanced → Show coordinates):unnamed points share one line, a named one takes its own, and the plate grows bywhat it prints. **Show text** switches the credit line off beside it, so a plate@@ -3138,6 +3225,15 @@ carrying its own state and a count; and the half-facts that are too soft to beentities and too valuable to lose. The graph says what the case believes, a sheetsays what it is checking.+- **The tab opens on its home**, the two halves Inspect opens on: the recent sheets,+ newest edit first with the one last open here leading, each with its rows and its+ progress (*8 of 21 done*); and a way in. That way in leads with what the case could start+ now, counted — *Files to geolocate, 21 imported files, 13 without a proof*, *My+ geolocations, 8 proofs* — and opens the one already built rather than a twin, then the+ templates, then a file, a paste or a worklist over a type. Reopening the last sheet by+ itself answered "where was I" and nothing else, and a case with no sheet opened on a+ lecture about what a sheet is for. **Close** in the header saves what was typed and goes+ back to the home.- **The file is the artifact.** `sheets/<name>.csv`, readable in any spreadsheet, writtenwith a byte-order mark so Excel on Windows reads its accents instead of the machine'slegacy codepage, and replaced by **rename rather than in place** so a save that dies@@ -3391,9 +3487,12 @@ says what it is checking.`dd/MM/yyyy` column puts 1 February before 31 January. A date sorts by the moment, astate by its own vocabulary's order, a counting column by the count, and a cell therole cannot read goes to the end rather than into the middle of January.- - A **set of values** draws one chip per value, and clicking one filters on **that- value** — `Buk-M2E, ZU23-2` is two answers, so the filter reads them apart rather than- comparing the whole cell. Whether a cell may hold several is a question with a box for+ - A **set of values** draws one chip per value, and clicking one **opens the column's+ words** to change it, the way a status chip does: a chip reads as the control that+ changes it, and a click on `to do` that filtered the column was the grid answering a+ question nobody asked. Filtering on a value is the heading's funnel, and reads+ `Buk-M2E, ZU23-2` as two answers rather than comparing the whole cell. A chip the app+ wrote, or one naming another row, still filters on the value pressed. Whether a cell may hold several is a question with a box forthe separator under it, rather than one box whose placeholder was the word "no". Thevalue menu counts how many rows hold each, which is what the filter hands back. Reading`2x S-125` as two of `S-125` was offered here once and is gone: it kept a **count inside@@ -3516,15 +3615,31 @@ says what it is checking.- **A sheet can be built out of the proofs the case already holds, and kept level withthem.** The template that fetches and this shape carry almost the same columns and run inopposite directions, so the modal asks which **before** anything else: *one row per- entity* takes a type and its fields, *my geolocations* takes neither. The- outgoing one is one row per proof, carrying the media it rests on, the place it puts on- the map and coordinates read off the graph. Those three columns are the case's and are- read-only; Status, Notes and any column added are the analyst's. It offers no *Build- proofs* button, because the proofs already exist and there is nothing left to fetch.+ entity* takes a type and its fields, *files to geolocate* and *my geolocations* take+ neither. The outgoing one is **one row per point** a proof concludes on, POV or not, so a+ video placed at three spots is three rows: the proof's title, its date as Geo Proof holds+ it (`~` kept), the place, whether the camera stood there, coordinates read off the graph,+ the media it rests on, the address of the post that media came from, and the+ description. Those columns are the case's and are read-only, changed in Geo Proof;+ Status, Notes and any column added are the analyst's. A proof placed nowhere still gets+ its one row. It offers no *Build proofs* button, because the proofs already exist and+ there is nothing left to fetch.+- **Files to geolocate is the same kind of sheet turned the other way**: one row per+ picture or video the analyst imported, never a frame, a capture or a render the app made,+ with its source address, the proof that answers for it however many steps down (a proof+ on a frame answers for the video), and that proof's place. A row starts *done* when a+ proof already answers and *to do* otherwise, so the count is true the day it is built.+ The case's columns are locked, Status and Notes are the analyst's. Refresh files the+ files imported since and moves a row to *done* once a proof answers it, from *to do* or+ *in progress* only: *ruled out* or a word of the analyst's stays. The Media Library's+ **Worklist** opens it, building it on the first press, and a second press opens the same+ one rather than a twin.- **Refresh is a press, never automatic.** A sheet that rewrote itself when it was openedwould move a file under somebody who came to read it, and it would fight the stamp that- keeps two readers of one file from overwriting each other. It files the proofs added- since, restates the columns the case owns, and says what it did.+ keeps two readers of one file from overwriting each other. It files the proofs and the+ points added since, restates the columns the case owns, and says what it did. A row is+ found again by its proof and its place, so a sheet built when this shape was one row+ per proof keeps its rows and its columns, and gains a row per point it lacked.- **It adds and never removes.** A proof deleted since the build keeps its row, its notesand its colour, and answers NO under *In case*. Filtering on that column groups them sothey can be deleted in one gesture — but that is the analyst's call, because the notesdiff --git a/frontend/e2e/app.fixture.js b/frontend/e2e/app.fixture.jsindex 67df3cb..ce23d83 100644--- a/frontend/e2e/app.fixture.js+++ b/frontend/e2e/app.fixture.js@@ -747,6 +747,15 @@ export async function installAppFixture(page, options = {}) {const captures = [];const placeWrites = [];const proofSaves = [];+ const kinReads = [];+ const proposalRuns = [];+ const fixtureProposals = structuredClone(+ options.proposals ?? {+ pending: { accounts: 0, posted: 0, sites: 0 }, items: [], listed: 0, radius: 300,+ // Read already, as a case is once anything was imported: the toolbar stays as it was.+ through: '2026-07-21T00:00:00Z',+ },+ );const fixtureSavedIndex = options.savedIndex ?? savedIndex;// Located files as the Media position reads them (GET /satellite/media).const fixtureMediaIndex = options.mediaIndex ?? [];@@ -2022,12 +2031,36 @@ export async function installAppFixture(page, options = {}) {// composer writes it straight into the header, so dropping it here left// the saved document holding a title the composer never gave it.return json(route, {+ id: 'browser-proof-entity',name: 'browser-proof',title: payload.title,png: 'proofs/browser-proof.png',});}+ // What a saved proof shares with the case, and the links the case proposes by+ // itself. Nothing by default, so a spec that never looks sees an empty answer.+ const kinMatch = path.match(new RegExp(`^/api/cases/${caseId}/entities/([^/]+)/kin$`));+ if (kinMatch) {+ kinReads.push(kinMatch[1]);+ return json(route, options.kin ?? { sites: [], places: [], accounts: [], radius: 300 });+ }+ if (path === `/api/cases/${caseId}/proposals`) {+ if (request.method() === 'POST') proposalRuns.push(Date.now());+ return json(route, {+ ...(request.method() === 'POST' ? { filed: { accounts: 0, posted: 0, sites: 0 } } : {}),+ ...fixtureProposals,+ });+ }+ const dropMatch = path.match(new RegExp(`^/api/cases/${caseId}/proposals/([^/]+)$`));+ if (dropMatch && request.method() === 'DELETE') {+ fixtureProposals.items = fixtureProposals.items.filter((item) => item.id !== dropMatch[1]);+ return json(route, { status: 'deleted', dropped: [], ...fixtureProposals });+ }+ if (path === `/api/cases/${caseId}/sheets/from-case/files`) {+ return json(route, options.filesWorklist ?? { total: 0, answered: 0, sheet: null });+ }+if (path === `/api/cases/${caseId}/sheets` && request.method() === 'GET') {return json(route, {sheets: [...fixtureSheets.values()].map((held) => ({@@ -2135,6 +2168,8 @@ export async function installAppFixture(page, options = {}) {return {captures,+ kinReads,+ proposalRuns,placeWrites,railTiles,referenceTiles,@@ -2238,7 +2273,7 @@ export function repainted(before, after) {export async function openProofWithPanel(page) {await page.goto('/#proof');- await expect(page.getByRole('heading', { name: 'Geo Proof' })).toBeVisible();+ await expect(page.locator('.tool-header').getByRole('button', { name: 'New proof', exact: true })).toBeVisible();await page.getByRole('button', { name: 'New proof' }).first().click();await expect(page.getByRole('heading', { name: 'Create proof' })).toBeVisible();await page.locator('.selectable-pick').click();diff --git a/frontend/e2e/detect-groups.spec.js b/frontend/e2e/detect-groups.spec.jsindex abb4793..7b4287b 100644--- a/frontend/e2e/detect-groups.spec.js+++ b/frontend/e2e/detect-groups.spec.js@@ -44,8 +44,8 @@ test('Areas groups fold and search, while Where keeps ungrouped areas available'const where = dock.getByRole('region', { name: 'Where to look' });await expect(where).toContainText('Ungrouped');await expect(where.getByRole('button', { name: 'River' })).toBeVisible();- await where.getByRole('button', { name: 'Use Ports' }).click();- await where.getByRole('button', { name: 'Use Priority' }).click();+ await where.getByRole('checkbox', { name: 'Use Ports' }).click();+ await expect(where.getByRole('checkbox', { name: 'Use Priority' })).toHaveAttribute('aria-checked', 'true');await expect(where.locator('.area-row')).toHaveCount(1);await where.getByRole('button', { name: 'River' }).click();await expect(where.locator('.area-row')).toHaveCount(2);diff --git a/frontend/e2e/detect.spec.js b/frontend/e2e/detect.spec.jsindex 8f8a188..23dca7f 100644--- a/frontend/e2e/detect.spec.js+++ b/frontend/e2e/detect.spec.js@@ -95,6 +95,13 @@ async function openDetect(page, withRun = false, withRoutine = false, twoRuns =return { errors, calls, prefs };}+/** What starts with nothing picked and every category folded: open the first, take its first analyzer. */+async function pickAnalyzer(page) {+ const step = page.getByRole('region', { name: 'What to look for' });+ await step.locator('.fold').first().click();+ await step.getByRole('radio').first().click();+}+async function typeWhenDay(page, button, field, value) {await page.getByRole('button', { name: button, exact: true }).click();const details = page.locator('.manual-date');@@ -163,6 +170,7 @@ test('clicking a Detect date opens a calendar of passes and previews the chosenawait page.getByRole('button', { name: 'New one pass', exact: true }).click();await page.getByRole('button', { name: 'North site', exact: true }).click();await page.getByRole('button', { name: 'Next: What' }).click();+ await pickAnalyzer(page);await page.getByRole('button', { name: 'Next: When' }).click();await page.getByRole('button', { name: 'Date A', exact: true }).click();const calendar = page.getByRole('group', { name: 'A pass calendar' });@@ -188,6 +196,7 @@ test('each area opens its own A and B calendars with its pass list below', asyncawait page.getByRole('button', { name: 'North site', exact: true }).click();await page.getByRole('button', { name: 'Second site', exact: true }).click();await page.getByRole('button', { name: 'Next: What' }).click();+ await pickAnalyzer(page);await page.getByRole('button', { name: 'Next: When' }).click();const first = page.getByRole('region', { name: 'Dates for North site' });const second = page.getByRole('region', { name: 'Dates for Second site' });@@ -239,6 +248,7 @@ test('landing, dock rail and the When step fit the existing map workspace', asynawait page.getByRole('button', { name: 'New one pass', exact: true }).click();await page.getByRole('button', { name: 'North site', exact: true }).click();await page.getByRole('button', { name: 'Next: What' }).click();+ await pickAnalyzer(page);await page.getByRole('button', { name: 'Next: When' }).click();// A and B are asked in the step itself, B the newest pass until a day is chosenawait expect(page.getByRole('heading', { name: 'Which two images' })).toBeVisible();@@ -287,6 +297,7 @@ test('Detect menus fit the dock at its minimum and maximum widths', async ({ pagawait page.getByRole('button', { name: 'North site', exact: true }).click();for (const next of ['Next: What', 'Next: When']) {await expect.poll(() => dock.evaluate((node) => node.scrollWidth - node.clientWidth)).toBeLessThanOrEqual(2);+ if (next === 'Next: When') await pickAnalyzer(page);await page.getByRole('button', { name: next }).click();}await expect.poll(() => dock.evaluate((node) => node.scrollWidth - node.clientWidth)).toBeLessThanOrEqual(2);@@ -300,7 +311,7 @@ test('Detect menus fit the dock at its minimum and maximum widths', async ({ pagexpect(errors).toEqual([]);});-test('the size is asked before the analyzers, and a pair months apart warns about shadows', async ({ page }) => {+test('the size is asked once an analyzer is picked, and a pair months apart warns about shadows', async ({ page }) => {const { errors, calls } = await openDetect(page);await page.getByRole('button', { name: 'New detection', exact: true }).click();await page.getByRole('button', { name: 'New one pass', exact: true }).click();@@ -308,14 +319,15 @@ test('the size is asked before the analyzers, and a pair months apart warns abouawait page.getByRole('button', { name: 'Next: What' }).click();const step = page.getByRole('region', { name: 'What to look for' });const sizes = step.getByRole('group', { name: 'Target size' });+ await expect(sizes).toHaveCount(0);+ await expect(page.getByRole('button', { name: 'Next: When' })).toBeDisabled();+ await pickAnalyzer(page);await expect(sizes).toHaveCount(1);await expect(sizes.getByRole('button', { name: 'All', exact: true })).toHaveAttribute('aria-pressed', 'true');- const [above, list] = [await sizes.boundingBox(), await step.getByRole('radiogroup', { name: 'Analyzer' }).boundingBox()];- expect(above.y + above.height).toBeLessThanOrEqual(list.y);- const cloud = step.getByLabel('Maximum cloud cover');- const cloudBox = await cloud.boundingBox();- expect(cloudBox.y).toBeGreaterThanOrEqual(above.y + above.height);- expect(cloudBox.y + cloudBox.height).toBeLessThanOrEqual(list.y);+ const [list, below] = [await step.getByRole('radiogroup', { name: 'Analyzer' }).boundingBox(), await sizes.boundingBox()];+ expect(list.y + list.height).toBeLessThanOrEqual(below.y);+ const cloudBox = await step.getByLabel('Maximum cloud cover').boundingBox();+ expect(cloudBox.y).toBeGreaterThanOrEqual(below.y + below.height);await page.screenshot({ path: test.info().outputPath('detect-what.png') });await page.getByRole('button', { name: 'Next: When' }).click();await typeWhenDay(page, 'Date A', 'Day of A', '21/01/2026');diff --git a/frontend/e2e/files-work-folder.spec.js b/frontend/e2e/files-work-folder.spec.jsnew file mode 100644index 0000000..825f7bd--- /dev/null+++ b/frontend/e2e/files-work-folder.spec.js@@ -0,0 +1,127 @@+import { test, expect } from '@playwright/test';+import { CASE_ID, installAppFixture } from './app.fixture.js';++/**+ * Files and the case sidebar act on a right-click, rename in place, and keep a+ * work folder. The case overview is routed here rather than by the fixture, so a+ * rename or a work folder written by the page is what the next reload reads.+ */+async function caseWithFolders(page, { folders, catalog }) {+ const fixture = await installAppFixture(page, {+ cases: [{ id: CASE_ID, name: 'Browser Test', scratch: false, entities: [], links: [], folders }],+ catalog,+ });+ const state = { folders: [...folders], work_folder: null };+ const writes = [];+ await page.route(`**/api/cases/${CASE_ID}`, (route) =>+ route.fulfill({+ json: {+ id: CASE_ID,+ name: 'Browser Test',+ scratch: false,+ folders: state.folders,+ ...(state.work_folder ? { work_folder: state.work_folder } : {}),+ },+ })+ );+ await page.route(`**/api/cases/${CASE_ID}/folders/rename`, (route) => {+ const body = route.request().postDataJSON();+ writes.push({ rename: body });+ state.folders = state.folders.map((path) =>+ path === body.source || path.startsWith(`${body.source}/`) ? body.target + path.slice(body.source.length) : path+ );+ return route.fulfill({ json: state.folders });+ });+ await page.route(`**/api/cases/${CASE_ID}/work-folder`, (route) => {+ const body = route.request().postDataJSON();+ writes.push({ work: body });+ state.work_folder = body.folder;+ return route.fulfill({ json: { work_folder: body.folder } });+ });+ await page.route(`**/api/cases/${CASE_ID}/todos`, (route) =>+ route.fulfill({ json: { revision: 0, lists: [{ id: 'default', name: 'Tasks', tasks: [] }] } })+ );+ return { fixture, writes };+}++const gate = {+ id: 'gate',+ type: 'place',+ label: 'Gate',+ attrs: { lat: 32.75, lon: 51.86 },+ provenance: { by: 'user', at: '2026-09-30T10:00:00Z', status: 'confirmed' },+};++test('Files renames a folder in place and makes it the work folder', async ({ page }) => {+ const { fixture, writes } = await caseWithFolders(page, { folders: ['Airbase', 'Airbase/North'], catalog: [gate] });+ await page.goto('/#files');++ const grid = page.locator('.grid-pane');+ await grid.locator('.tile.folder', { hasText: 'Airbase' }).click({ button: 'right' });+ const menu = page.getByRole('menu');+ await expect(menu.getByRole('menuitem', { name: 'Rename' })).toBeVisible();+ await expect(menu.getByRole('menuitem', { name: 'Import files here' })).toBeVisible();+ await menu.getByRole('menuitem', { name: 'Rename' }).click();++ const field = grid.getByRole('textbox', { name: 'New name' });+ await expect(field).toHaveValue('Airbase');+ await field.fill('Isfahan');+ await field.press('Enter');+ await expect(grid.locator('.tile.folder', { hasText: 'Isfahan' })).toBeVisible();+ await expect(page.getByText('Renamed to Isfahan')).toBeVisible();+ expect(writes[0]).toEqual({ rename: { source: 'Airbase', target: 'Isfahan' } });++ await grid.locator('.tile.folder', { hasText: 'Isfahan' }).click({ button: 'right' });+ await page.getByRole('menu').getByRole('menuitem', { name: 'Work in this folder' }).click();+ await expect.poll(() => writes.at(-1)).toEqual({ work: { folder: 'Isfahan' } });+ await expect(grid.locator('.tile.folder', { hasText: 'Isfahan' }).locator('.tile-pin')).toBeVisible();+ fixture.expectNoUnexpectedRequests();+});++test('Files offers an item its actions and moves it with Move to…', async ({ page }) => {+ const { fixture } = await caseWithFolders(page, { folders: ['Port'], catalog: [gate] });+ const patches = [];+ await page.route(`**/api/cases/${CASE_ID}/entities/gate`, (route) => {+ patches.push(route.request().postDataJSON());+ return route.fulfill({ json: { ...gate, attrs: { ...gate.attrs, folder: 'Port' } } });+ });+ await page.goto('/#files');++ // an unfiled item sits in Unfiled, not at the root+ await page.locator('.tree-rail .trow', { hasText: 'Unfiled' }).click();+ await page.locator('.grid-pane .tile.entity', { hasText: 'Gate' }).click({ button: 'right' });+ const menu = page.getByRole('menu');+ for (const name of ['Open', 'Rename F2', 'Move to…', 'Add event', 'Show in Timeline', 'Details', 'Delete']) {+ await expect(menu.getByRole('menuitem', { name, exact: true })).toBeVisible();+ }+ await menu.getByRole('menuitem', { name: 'Move to…' }).click();++ const dialog = page.getByRole('dialog', { name: 'Move “Gate”' });+ await dialog.locator('.folder-select .trigger').click();+ await page.locator('.menu .opt', { hasText: 'Port' }).click();+ await dialog.getByRole('button', { name: 'Move', exact: true }).click();+ await expect(dialog).toHaveCount(0);+ expect(patches).toEqual([{ attrs: { folder: 'Port' } }]);+ fixture.expectNoUnexpectedRequests();+});++test('the sidebar switches to the to-do lists and renames a folder from its menu', async ({ page }) => {+ const { fixture, writes } = await caseWithFolders(page, { folders: ['Port'], catalog: [gate] });+ await page.goto('/#files');++ const sidebar = page.locator('aside.sidebar');+ await sidebar.getByRole('tab', { name: 'To-do' }).click();+ await expect(sidebar.getByLabel('New task', { exact: true })).toBeVisible();+ await expect(sidebar.getByPlaceholder('Search this case…')).toHaveCount(0);++ await sidebar.getByRole('tab', { name: 'Folders' }).click();+ await sidebar.locator('.frow', { hasText: 'Port' }).click({ button: 'right' });+ await page.getByRole('menu').getByRole('menuitem', { name: 'Rename' }).click();+ const field = page.getByRole('menu').getByRole('textbox', { name: 'New name' });+ await expect(field).toHaveValue('Port');+ await field.fill('Harbour');+ await field.press('Enter');+ await expect.poll(() => writes.at(-1)).toEqual({ rename: { source: 'Port', target: 'Harbour' } });+ await expect(sidebar.locator('.frow', { hasText: 'Harbour' })).toBeVisible();+ fixture.expectNoUnexpectedRequests();+});diff --git a/frontend/e2e/paste.spec.js b/frontend/e2e/paste.spec.jsindex 078115c..00ef17d 100644--- a/frontend/e2e/paste.spec.js+++ b/frontend/e2e/paste.spec.js@@ -184,7 +184,7 @@ test('a paste in Proof stays the composer\'s own', async ({ page }) => {await page.getByRole('button', { name: 'Compose', exact: true }).click();await page.getByRole('button', { name: 'Geo Proof', exact: true }).click();- await expect(page.getByRole('heading', { name: 'Geo Proof' })).toBeVisible();+ await expect(page.locator('.tool-header').getByRole('button', { name: 'New proof', exact: true })).toBeVisible();await page.getByRole('button', { name: 'New proof' }).first().click();await expect(page.getByRole('heading', { name: 'Create proof' })).toBeVisible();await page.locator('.selectable-pick').click();diff --git a/frontend/e2e/proof-kin.spec.js b/frontend/e2e/proof-kin.spec.jsnew file mode 100644index 0000000..1680388--- /dev/null+++ b/frontend/e2e/proof-kin.spec.js@@ -0,0 +1,46 @@+import { test, expect } from '@playwright/test';+import { installAppFixture, openProofWithPanel } from './app.fixture.js';++/**+ * What a geolocation shares with the case, said where the analyst is the moment the proof+ * is saved: other geolocations on its site, what its account posted. One line, gone at the+ * next edit, and one press to the graph.+ */+test('a saved proof says what it shares with the case and opens it in the graph', async ({ page }) => {+ const fixture = await installAppFixture(page, {+ // The saved proof is found again, as the case would: otherwise the composer reads it+ // as deleted elsewhere and the document as unsaved.+ lookupEntities: { 'proofs/.meta/browser-proof.json': { id: 'browser-proof-entity' } },+ kin: {+ sites: ['proof-2', 'proof-3'],+ places: ['place-2', 'place-3'],+ radius: 300,+ accounts: [{ label: '@BashaReport', id: null, files: 3 }],+ },+ });+ await openProofWithPanel(page);++ await page.getByRole('button', { name: 'Save proof', exact: true }).click();+ await expect.poll(() => fixture.proofSaves.length).toBe(1);++ const line = page.locator('.kin');+ await expect(line).toContainText('On the same site as 2 other geolocations');+ await expect(line).toContainText('@BashaReport posted 3 other files here');+ expect(fixture.kinReads).toEqual(['browser-proof-entity']);++ await line.getByRole('button', { name: 'See in the graph' }).click();+ await expect(page.locator('.tabstrip').getByRole('button', { name: 'Graph' })).toHaveAttribute('aria-current', /.+/);+});++test('a proof that shares nothing says nothing', async ({ page }) => {+ const fixture = await installAppFixture(page, {+ lookupEntities: { 'proofs/.meta/browser-proof.json': { id: 'browser-proof-entity' } },+ });+ await openProofWithPanel(page);++ await page.getByRole('button', { name: 'Save proof', exact: true }).click();+ await expect.poll(() => fixture.kinReads.length).toBe(1);++ await expect(page.locator('.kin')).toHaveCount(0);+ fixture.expectNoUnexpectedRequests();+});diff --git a/frontend/e2e/report-buttons.spec.js b/frontend/e2e/report-buttons.spec.jsindex 89ff641..29e7408 100644--- a/frontend/e2e/report-buttons.spec.js+++ b/frontend/e2e/report-buttons.spec.js@@ -18,7 +18,7 @@ for (const theme of ['dark', 'light']) {const fixture = await installAppFixture(page);await page.addInitScript((value) => localStorage.setItem('azimut:theme', value), theme);await page.goto('/#proof');- await expect(page.getByRole('heading', { name: 'Geo Proof' })).toBeVisible({ timeout: 15_000 });+ await expect(page.locator('.tool-header').getByRole('button', { name: 'New proof', exact: true })).toBeVisible({ timeout: 15_000 });const header = page.locator('.tool-header');const saveProof = header.getByRole('button', { name: 'Save proof', exact: true });@@ -43,7 +43,8 @@ for (const theme of ['dark', 'light']) {const publishHover = await buttonStyle(toPost);await page.getByRole('button', { name: 'Geo Report', exact: true }).click();- await expect(page.getByRole('heading', { name: 'Geo Report' })).toBeVisible();+ await expect(page.getByRole('button', { name: 'Save as draft', exact: true })).toBeVisible();+ await expect(page.locator('.tabstrip').getByRole('button', { name: 'Geo Report', exact: true })).toHaveAttribute('aria-current', 'page');await page.mouse.move(0, 0);const actions = header.locator('.head-actions');const draft = actions.getByRole('button', { name: 'Save as draft', exact: true });diff --git a/frontend/e2e/saved-media.spec.js b/frontend/e2e/saved-media.spec.jsindex aae3522..67ebbaf 100644--- a/frontend/e2e/saved-media.spec.js+++ b/frontend/e2e/saved-media.spec.js@@ -98,7 +98,7 @@ test('opens the proof a file was placed by', async ({ page }) => {await page.locator('.saved-mark').click();await page.keyboard.press('ArrowRight');await panel(page).getByRole('button', { name: 'Roofline' }).click();- await expect(page.getByRole('heading', { name: 'Geo Proof' })).toBeVisible();+ await expect(page.locator('.tool-header').getByRole('button', { name: 'New proof', exact: true })).toBeVisible();await expect(page).toHaveURL(/#proof/);});diff --git a/frontend/e2e/sheet.spec.js b/frontend/e2e/sheet.spec.jsindex c649cb6..b9edd47 100644--- a/frontend/e2e/sheet.spec.js+++ b/frontend/e2e/sheet.spec.js@@ -27,6 +27,8 @@ const SHEETS = [async function openSheet(page) {await page.goto('/#sheet');await expect(page.getByRole('heading', { name: 'Sheet', exact: true })).toBeVisible();+ // The tab lands on its home; a sheet is opened from its recent list.+ await page.locator('.home .sheet').first().click();await expect(page.getByRole('grid', { name: 'Sheet rows' })).toBeVisible();}@@ -226,7 +228,49 @@ test('the empty case says what a sheet is for', async ({ page }) => {await installAppFixture(page, { sheets: [] });await page.goto('/#sheet');- await expect(page.getByText('No sheet in this case.')).toBeVisible();- await expect(page.getByText('A worklist that counts what is left')).toBeVisible();- await expect(page.getByRole('button', { name: 'New sheet' })).toBeVisible();+ await expect(page.getByText('No sheet in this case yet.')).toBeVisible();+ await expect(page.getByText(/A worklist that counts what is left/)).toBeVisible();+ await expect(page.getByRole('button', { name: /Verification worklist/ })).toBeVisible();+ await expect(page.getByRole('button', { name: 'Paste a table' })).toBeVisible();+});++/**+ * The tab's home: what is being worked on, and what the case could start. Close takes a+ * sheet back to it, and whatever was typed reaches the file first.+ */+test('lands on the home and closes back to it, saving what was typed', async ({ page }) => {+ const fixture = await installAppFixture(page, {+ sheets: SHEETS,+ filesWorklist: { total: 21, answered: 8, sheet: null },+ });+ await page.goto('/#sheet');+ await expect(page.getByRole('heading', { name: 'Recent sheets' })).toBeVisible();+ await expect(page.getByText('21 imported files, 13 without a proof')).toBeVisible();+ await expect(page.getByRole('grid', { name: 'Sheet rows' })).toHaveCount(0);++ await page.locator('.home .sheet').first().click();+ await expect(page.getByRole('grid', { name: 'Sheet rows' })).toBeVisible();+ await typeInto(page, 0, 3, 'checked twice');+ await page.getByRole('button', { name: 'Close', exact: true }).click();++ await expect(page.getByRole('heading', { name: 'Recent sheets' })).toBeVisible();+ await expect.poll(() => fixture.sheetOnDisk('sheet-1').rows[0][3]).toBe('checked twice');+ fixture.expectNoUnexpectedRequests();+});++test('a status chip opens its words instead of filtering the column', async ({ page }) => {+ await installAppFixture(page, {+ sheets: [['Worklist', ['Subject', 'Status'], [+ ['Quai sud', 'to do'],+ ['Pont nord', 'done'],+ ], { roles: { Status: { kind: 'state', values: ['to do', 'in progress', 'done', 'ruled out'] } } }]],+ });+ await openSheet(page);++ await cell(page, 0, 2).locator('.cell-chip').click();++ await expect(page.locator('.offers')).toBeVisible();+ await expect(page.locator('.offers').getByRole('button', { name: 'in progress' })).toBeVisible();+ // Both rows still on screen: nothing was filtered.+ await expect(page.locator('.rows:not(.ghost) .row')).toHaveCount(2);});diff --git a/frontend/e2e/timeline.spec.js b/frontend/e2e/timeline.spec.jsindex ae6e301..3e5dc63 100644--- a/frontend/e2e/timeline.spec.js+++ b/frontend/e2e/timeline.spec.js@@ -900,7 +900,14 @@ test('starts a media correction from the captured date', async ({ page }) => {});test('expands dense events in place and can collapse them again', async ({ page }) => {- await openTimeline(page);+ // Lanes share the axis's height, so a crowd only folds into a `+n` once it outgrows+ // what the axis can hold: a few more marks than the shared timelineItems carry.+ const crowd = Array.from({ length: 40 }, (_, index) => ({+ ...timelineItem('dense-0'),+ id: `temporal:claim:crowd-${index}`, owner_id: `crowd-${index}`,+ label: `Gate camera ${index + 1} records the same arrival window`,+ }));+ await openTimeline(page, { timelineItems: [...timelineItems, ...crowd] });const cluster = page.locator('.timeline-cluster').first();await expect(cluster).toBeVisible();const before = await page.locator('.timeline-event.statement').count();diff --git a/frontend/src/App.svelte b/frontend/src/App.svelteindex afb37f1..838d426 100644--- a/frontend/src/App.svelte+++ b/frontend/src/App.svelte@@ -11,6 +11,7 @@checkForUpdatesOnStart,toggleTheme,} from './lib/state.svelte.js';+ import { api } from './lib/api.js';import { updateBadges } from './lib/staleness.js';import { startEvents, onEvent } from './lib/events.js';import {@@ -38,6 +39,8 @@import DetectActivity from './components/DetectActivity.svelte';import WorkspaceStopped from './components/WorkspaceStopped.svelte';import NoteBar from './components/NoteBar.svelte';+ import MoveDialog from './components/MoveDialog.svelte';+ import { filedToast, workFolder } from './lib/folders.js';import { isNoteKey } from './lib/noteHere.svelte.js';import { readStatus, stoppedBecause } from './lib/workspace.js';import { analysisSearch, leaveAnalysisView } from './lib/analysisSearch.svelte.js';@@ -244,18 +247,30 @@// the capture extension files screenshots while this tab just sits here, and// they must show up without a reload. Refresh only what the nudge names.startEvents();- onEvent('capture', (ev) => {- toast(`Capture filed from ${ev.site}: ${ev.title}`, 'ok', 5000);- if (caseState.current?.id === ev.case_id) reloadCase();- });- onEvent('bookmark', (ev) => {- toast(`Bookmark saved: ${ev.title}`, 'ok', 5000);- if (caseState.current?.id === ev.case_id) reloadCase();- });- onEvent('place', (ev) => {- toast(`Place saved from ${ev.site}: ${ev.title}`, 'ok', 5000);- if (caseState.current?.id === ev.case_id) reloadCase();- });+ // Filed from another window, so the toast is where the analyst hears which+ // folder it landed in, with Move when the work folder took it.+ async function filedFromExtension(ev, lead, fallback) {+ if (caseState.current?.id !== ev.case_id) return toast(fallback, 'ok', 5000);+ await reloadCase();+ let entity = null;+ if (workFolder()) {+ try {+ entity = ev.entity_id+ ? (await api.get(`/api/cases/${ev.case_id}/entities/${ev.entity_id}/chain`)).entity+ : (await api.get(`/api/cases/${ev.case_id}/entities/lookup?attr=path&value=${encodeURIComponent(ev.path)}`)).entity;+ } catch {+ /* the toast still says it was filed */+ }+ }+ filedToast(lead, [entity], { fallback, timeout: 5000 });+ }+ onEvent('capture', (ev) =>+ filedFromExtension(ev, `“${ev.title}” filed from ${ev.site}`, `Capture filed from ${ev.site}: ${ev.title}`)+ );+ onEvent('bookmark', (ev) => filedFromExtension(ev, `Bookmark “${ev.title}” saved`, `Bookmark saved: ${ev.title}`));+ onEvent('place', (ev) =>+ filedFromExtension(ev, `“${ev.title}” saved from ${ev.site}`, `Place saved from ${ev.site}: ${ev.title}`)+ );// The case's saved work, moved from another window onto it: a second app tab,// or the map panel the extension draws over someone else's map. Silent, unlike// the three above — the analyst did this themselves, just not here — and the@@ -383,6 +398,7 @@<buttonclass="tab-btn"class:active={uiState.tool === toolId}+ aria-current={uiState.tool === toolId ? 'page' : undefined}onclick={() => (uiState.tool = toolId)}>{toolLabel(toolId)}@@ -420,6 +436,7 @@<svelte:window onkeydown={onGlobalKey} /><NoteBar />+<MoveDialog /><Toasts />{#if workspaceStopped}diff --git a/frontend/src/App.test.js b/frontend/src/App.test.jsindex 9df0be3..bc41767 100644--- a/frontend/src/App.test.js+++ b/frontend/src/App.test.js@@ -52,3 +52,11 @@ describe('Add event, from every tool', () => {expect(markup).toContain('<NoteBar />');});});++describe('the tab strip', () => {+ it('names the open tool on its tab, since Geo Proof and Geo Report carry no title of their own', () => {+ expect(markup).toContain("aria-current={uiState.tool === toolId ? 'page' : undefined}");+ expect(readFileSync(new URL('./tools/ProofComposer.svelte', import.meta.url), 'utf8')).not.toContain('<h2>Geo Proof</h2>');+ expect(readFileSync(new URL('./tools/PostComposer.svelte', import.meta.url), 'utf8')).not.toContain('<h2>Geo Report</h2>');+ });+});diff --git a/frontend/src/app.css b/frontend/src/app.cssindex d97ee20..cd96d94 100644--- a/frontend/src/app.css+++ b/frontend/src/app.css@@ -559,9 +559,9 @@ a:hover {font-size: var(--fs-sm);color: var(--text-3);}-/* The name of what the tool is editing, next to the tool's own title. Inspect,- the Proof Composer and the Post Composer all name their work this way, and- the name is the filename it saves under. */+/* The name of what the tool is editing. Inspect, the Proof Composer and the+ Post Composer all name their work this way, and the name is the filename it+ saves under. */.tool-header .title-input {width: min(320px, 26vw);font-weight: 600;diff --git a/frontend/src/components/CaseSidebar.svelte b/frontend/src/components/CaseSidebar.svelteindex a4bda6f..f98688c 100644--- a/frontend/src/components/CaseSidebar.svelte+++ b/frontend/src/components/CaseSidebar.svelte@@ -9,14 +9,23 @@setSidebarWidth,persistSidebarWidth,} from '../lib/state.svelte.js';- import { DEFAULT_W } from '../lib/sidebar.js';+ import { DEFAULT_W, saveSidebarView } from '../lib/sidebar.js';import { buildTree, flattenPaths } from '../lib/folderTree.js';import { buildCatalogQuery, settleCatalogSummary } from '../lib/catalog.js';import { createPagedList } from '../lib/pagedList.svelte.js';import { filterEntities, isFiltering, typeChips } from '../lib/sidebarSearch.js';- import { assignFolder as fileEntity, assignFolderBatch } from '../lib/filing.js';+ import { assignFolder as fileEntity, assignFolderBatch, renameEntity } from '../lib/filing.js';import { createNote } from '../lib/notes.js';- import { openEntity, openNotebook } from '../lib/navigate.js';+ import { openEntity, openInTimeline, openNotebook } from '../lib/navigate.js';+ import {+ ancestorsOf,+ leafOf,+ removeFolder,+ removeFolderPrompt,+ renameFolder,+ renamedPath,+ setWorkFolder,+ } from '../lib/folders.js';import { emptyTrash, purgeGroup, readTrash, restoreGroup, undoAction } from '../lib/trash.js';import Icon from './Icon.svelte';import Modal from './Modal.svelte';@@ -26,6 +35,7 @@import SidebarTree from './sidebar/SidebarTree.svelte';import SidebarResults from './sidebar/SidebarResults.svelte';import DetailsDrawer from './sidebar/DetailsDrawer.svelte';+ import CaseTodos from '../tools/overview/CaseTodos.svelte';// ── bounded catalog loading (docs/STORAGE_AND_PERFORMANCE.md, Step 5) ───────// The sidebar no longer holds the whole graph. It builds the folder tree from@@ -376,28 +386,123 @@}function askDeleteFolder(path) {- const prefix = path + '/';- const subs = allFolders.filter((f) => f.startsWith(prefix)).length;confirmState = {- title: 'Remove this folder?',- message: subs- ? `“${path}” and its ${subs} subfolder(s) will be removed from My work.`- : `“${path}” will be removed from My work.`,- detail: 'Items inside are unfiled. No files are deleted.',- confirmLabel: 'Remove folder',- tone: 'default',- icon: 'folderMinus',+ ...removeFolderPrompt(path, allFolders),// The backend unfiles every entity under the removed subtree, so this// does not enumerate the graph — it just drops the folder and refreshes.- action: async () => {- await api.del(- `/api/cases/${caseState.current.id}/folders?name=${encodeURIComponent(path)}`- );- await reloadCase();- },+ action: () => removeFolder(caseState.current.id, path),};}+ // ── the work folder ───────────────────────────────────────────────────────+ // Pinned above the tree, so the folder new files land in is always in view, and+ // one press away from being opened.+ const working = $derived(caseState.current?.work_folder ?? null);+ async function toggleWorkFolder(path) {+ try {+ await setWorkFolder(caseState.current.id, working === path ? null : path);+ } catch (e) {+ toast(e.message, 'danger');+ }+ }+ function revealWorkFolder() {+ if (!working) return;+ for (const path of ancestorsOf(working)) {+ if (!expanded[path]) {+ expanded[path] = true;+ loadFolder(path);+ }+ }+ }++ // ── views: folders, to-do, recent ─────────────────────────────────────────+ const view = $derived(uiState.sidebarView);+ function setView(next) {+ uiState.sidebarView = next;+ saveSidebarView(next);+ }+ // What was filed last, read only while the view is open, and again after any+ // write so a save in another tool shows up here.+ const RECENT = 40;+ let recent = $state({ items: [], loading: false });+ $effect(() => {+ const id = caseState.current?.id;+ void caseState.rev;+ if (view !== 'recent' || !id) return;+ untrack(() => loadRecent(id));+ });+ async function loadRecent(id) {+ recent.loading = true;+ try {+ const page = await api.get(buildCatalogQuery(id, { status: 'confirmed', limit: RECENT, order: '-created' }));+ if (caseState.current?.id === id) recent.items = page.items ?? [];+ } catch {+ if (caseState.current?.id === id) recent.items = [];+ } finally {+ recent.loading = false;+ }+ }++ // ── right-click ───────────────────────────────────────────────────────────+ // A short menu on a folder or an item: what the row's hover buttons do, plus+ // renaming, which needs a field the row has no room for. The field opens in+ // the menu itself.+ // menu: { x, y, kind: 'folder', path, mode } | { x, y, kind: 'entity', entity, mode }+ // mode: 'menu' | 'rename' | 'subfolder'+ let menu = $state(null);+ let menuText = $state('');+ const MENU_W = 220;+ const MENU_H = 280;+ function placeMenu(ev) {+ return {+ x: Math.min(ev.clientX, window.innerWidth - MENU_W - 8),+ y: Math.min(ev.clientY, Math.max(8, window.innerHeight - MENU_H - 8)),+ };+ }+ function openFolderMenu(ev, path) {+ menu = { ...placeMenu(ev), kind: 'folder', path, mode: 'menu' };+ }+ function openEntityMenu(ev, entity) {+ menu = { ...placeMenu(ev), kind: 'entity', entity, mode: 'menu' };+ }+ function menuField(mode) {+ menuText = mode === 'rename' ? (menu.kind === 'folder' ? leafOf(menu.path) : menu.entity.label) : '';+ menu = { ...menu, mode };+ }+ function menuRun(fn) {+ const held = menu;+ menu = null;+ fn(held);+ }+ async function submitMenuField() {+ const held = menu;+ const text = menuText.trim();+ menu = null;+ if (!held || !text) return;+ const caseId = caseState.current.id;+ try {+ if (held.mode === 'subfolder') {+ await createFolder(`${held.path}/${text}`);+ } else if (held.kind === 'folder') {+ if (text.includes('/')) {+ toast('A folder name cannot hold a slash', 'warn');+ return;+ }+ const target = renamedPath(held.path, text);+ if (target) await renameFolder(caseId, held.path, target);+ } else if (text !== held.entity.label) {+ await renameEntity(caseId, held.entity, text);+ await reloadCase();+ }+ } catch (e) {+ toast(e.message, 'danger');+ }+ }+ function focusSelect(node) {+ node.focus();+ node.select();+ }+// ── details drawer (docs/UI.md §Case sidebar) ─────────────────────────────// The editor body lives in EntityDetails.svelte (shared with the Media// Library modal). It opens over the sidebar instead of growing under the@@ -513,8 +618,10 @@{chips}total={summary?.total ?? 0}resultCount={filtering ? resultRows.length : null}+ {view}onnotes={() => openNotebook()}onselecttype={(t) => (typeFilter = t)}+ onview={setView}/><!-- the drag handlers here only auto-scroll; the drop targets are the@@ -528,7 +635,22 @@ondrop={() => setEdgeScroll(0)}onwheel={onBodyWheel}>- {#if filtering}+ {#if view === 'todo'}+ <div class="todo-view">+ <CaseTodos caseId={caseState.current.id} compact />+ </div>+ {:else if view === 'recent'}+ <SidebarResults+ rows={recent.items}+ caseId={caseState.current.id}+ loading={recent.loading}+ empty="Nothing filed yet."+ onactivate={onEntityActivate}+ oninfo={openInfo}+ onunfile={askRemoveFromMyWork}+ onmenu={openEntityMenu}+ />+ {:else if filtering}<SidebarResultsrows={resultRows}caseId={caseState.current.id}@@ -538,8 +660,29 @@onactivate={onEntityActivate}oninfo={openInfo}onunfile={askRemoveFromMyWork}+ onmenu={openEntityMenu}/>{:else}+ {#if working}+ <div class="work-line">+ <Icon name="pushpin" size={13} />+ <button+ class="work-name"+ title="New files and saved work land in this folder. Press to show it."+ onclick={revealWorkFolder}+ >+ {working}+ </button>+ <button+ class="work-stop"+ title="Stop working in this folder"+ aria-label="Stop working in this folder"+ onclick={() => toggleWorkFolder(working)}+ >+ <Icon name="x" size={12} />+ </button>+ </div>+ {/if}<div class="actions"><button class="act-btn" onclick={() => (newFolderOpen = !newFolderOpen)}><Icon name="plus" size={12} /><Icon name="folder" size={13} /><span>Folder</span>@@ -582,6 +725,10 @@onmoresuggested={() => loadSuggested(true)}oncreatefolder={createFolder}onremovefolder={askDeleteFolder}+ workFolder={working}+ onworkfolder={toggleWorkFolder}+ onfoldermenu={openFolderMenu}+ onentitymenu={openEntityMenu}onfile={onFileDrop}onactivate={onEntityActivate}oninfo={openInfo}@@ -605,6 +752,78 @@{/if}</aside>+<!-- right-click menu on a folder or an item -->+{#if menu}+ <div+ class="menu-backdrop"+ role="presentation"+ onpointerdown={() => (menu = null)}+ oncontextmenu={(e) => { e.preventDefault(); menu = null; }}+ ></div>+ <div+ class="menu card"+ role="menu"+ tabindex="-1"+ style="left:{menu.x}px; top:{menu.y}px"+ onkeydown={(e) => e.key === 'Escape' && (menu = null)}+ >+ <div class="menu-head">{menu.kind === 'folder' ? leafOf(menu.path) : menu.entity.label}</div>+ {#if menu.mode !== 'menu'}+ <form class="menu-field" onsubmit={(e) => { e.preventDefault(); submitMenuField(); }}>+ <input+ class="input"+ aria-label={menu.mode === 'subfolder' ? 'Subfolder name' : 'New name'}+ placeholder={menu.mode === 'subfolder' ? 'Subfolder…' : 'Name…'}+ bind:value={menuText}+ use:focusSelect+ />+ <button class="btn btn-primary btn-sm" type="submit" disabled={!menuText.trim()}>+ {menu.mode === 'subfolder' ? 'Create' : 'Rename'}+ </button>+ </form>+ {:else if menu.kind === 'folder'}+ <button class="menu-item" role="menuitem" onclick={() => menuField('rename')}>+ <Icon name="edit" size={13} /> Rename+ </button>+ <button class="menu-item" role="menuitem" onclick={() => menuField('subfolder')}>+ <Icon name="folder" size={13} /> New subfolder+ </button>+ <button class="menu-item" role="menuitem" onclick={() => menuRun((m) => (noteModal = { title: '', folder: m.path }))}>+ <Icon name="note" size={13} /> New note here+ </button>+ <button class="menu-item" role="menuitem" onclick={() => menuRun((m) => toggleWorkFolder(m.path))}>+ <Icon name="pushpin" size={13} /> {working === menu.path ? 'Stop working here' : 'Work in this folder'}+ </button>+ <div class="menu-sep"></div>+ <button class="menu-item danger" role="menuitem" onclick={() => menuRun((m) => askDeleteFolder(m.path))}>+ <Icon name="folderMinus" size={13} /> Remove folder+ </button>+ {:else}+ <button class="menu-item" role="menuitem" onclick={() => menuRun((m) => onEntityActivate(m.entity))}>+ <Icon name="external" size={13} /> Open+ </button>+ <button class="menu-item" role="menuitem" onclick={() => menuRun((m) => openInfo(m.entity))}>+ <Icon name="info" size={13} /> Details+ </button>+ <button class="menu-item" role="menuitem" onclick={() => menuField('rename')}>+ <Icon name="edit" size={13} /> Rename+ </button>+ <button class="menu-item" role="menuitem" onclick={() => menuRun((m) => (uiState.moving = [m.entity]))}>+ <Icon name="move" size={13} /> Move to…+ </button>+ <button class="menu-item" role="menuitem" onclick={() => menuRun((m) => openInTimeline(m.entity))}>+ <Icon name="clock" size={13} /> Show in Timeline+ </button>+ {#if menu.entity.attrs?.folder}+ <div class="menu-sep"></div>+ <button class="menu-item" role="menuitem" onclick={() => menuRun((m) => askRemoveFromMyWork(m.entity))}>+ <Icon name="folderMinus" size={13} /> Move to Unfiled+ </button>+ {/if}+ {/if}+ </div>+{/if}+<!-- Note create modal -->{#if noteModal}<Modal title="New note" onclose={() => (noteModal = null)} width="580px">@@ -612,7 +831,7 @@<input id="note-title" class="input" placeholder="Note title…" bind:value={noteModal.title} /><span class="modal-label" style="margin-top:10px">Folder (in My work)</span>- <FolderSelect bind:value={noteModal.folder} folders={allFolders} emptyLabel="My work (root)" />+ <FolderSelect bind:value={noteModal.folder} folders={allFolders} emptyLabel="My work (root)" fresh /><div class="modal-row"><div style="flex:1"></div>@@ -693,5 +912,64 @@.new-folder { display: flex; gap: 6px; padding: 2px 8px 8px; }.new-folder .input { flex: 1; font-size: var(--fs-xs); }.modal-label { display: block; font-size: var(--fs-xs); color: var(--text-3); margin: 8px 0 4px; }+ .todo-view { padding: 4px 8px 12px; }+ .work-line {+ display: flex;+ align-items: center;+ gap: 6px;+ margin: 0 8px 6px;+ padding: 5px 8px;+ border: 1px solid var(--accent);+ border-radius: var(--r-sm);+ background: var(--accent-soft);+ color: var(--accent);+ font-size: var(--fs-xs);+ }+ .work-name {+ flex: 1;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ color: var(--text-1);+ font-weight: 600;+ text-align: left;+ }+ .work-stop { display: flex; color: var(--text-3); padding: 2px; border-radius: 4px; }+ .work-stop:hover { color: var(--text-1); }+ .menu-backdrop { position: fixed; inset: 0; z-index: 940; }+ .menu {+ position: fixed;+ z-index: 950;+ width: 220px;+ padding: 6px;+ box-shadow: var(--shadow-2);+ }+ .menu-head {+ margin: 2px 4px 6px;+ color: var(--text-3);+ font-size: var(--fs-xs);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .menu-item {+ display: flex;+ align-items: center;+ gap: 8px;+ width: 100%;+ padding: 6px 8px;+ border-radius: var(--r-sm);+ color: var(--text-1);+ font-size: var(--fs-sm);+ text-align: left;+ }+ .menu-item:hover { background: var(--bg-2); }+ .menu-item > :global(svg) { color: var(--text-3); flex-shrink: 0; }+ .menu-item.danger { color: var(--danger, #e5484d); }+ .menu-item.danger > :global(svg) { color: inherit; }+ .menu-sep { height: 1px; margin: 5px 2px; background: var(--border); }+ .menu-field { display: flex; gap: 6px; }+ .menu-field .input { flex: 1; min-width: 0; font-size: var(--fs-sm); }.modal-row { display: flex; align-items: center; gap: 8px; margin-top: 14px; }</style>diff --git a/frontend/src/components/CaseSidebar.test.js b/frontend/src/components/CaseSidebar.test.jsindex 05e545c..d96f6e1 100644--- a/frontend/src/components/CaseSidebar.test.js+++ b/frontend/src/components/CaseSidebar.test.js@@ -77,7 +77,7 @@ describe('trash node', () => {describe('browse vs. results', () => {it('shows the tree until something is filtered, then a flat list', () => {expect(shell).toContain('const filtering = $derived(isFiltering({ query, type: typeFilter }))');- expect(shell).toContain('{#if filtering}');+ expect(shell).toContain('{:else if filtering}');expect(shell).toContain('<SidebarResults');expect(shell).toContain('{:else}');expect(shell).toContain('<SidebarTree');@@ -104,9 +104,11 @@ describe('browse vs. results', () => {});it('never collapses what the analyst opened: `expanded` is untouched by a search', () => {- // the only writes are the declaration, the case reset, a toggle and a create+ // the only writes are the declaration, the case reset, a toggle, a create and+ // showing the work folder, which only ever opensconst writes = shell.match(/expanded(\[[^\]]+\])? =/g) ?? [];- expect(writes).toHaveLength(4);+ expect(writes).toHaveLength(5);+ expect(shell).toContain('if (!expanded[path]) {\n expanded[path] = true;');});it('says so plainly when nothing matches', () => {@@ -236,3 +238,58 @@ describe('details drawer', () => {expect(drawer).toContain("import EntityDetails from '../EntityDetails.svelte'");});});++describe('views', () => {+ it('switches between folders, to-do and recent, and remembers the choice', () => {+ expect(header).toContain("{ id: 'folders', label: 'Folders'");+ expect(header).toContain("{ id: 'todo', label: 'To-do'");+ expect(header).toContain("{ id: 'recent', label: 'Recent'");+ expect(shell).toContain('saveSidebarView(next)');+ });++ it('keeps search and the type chips to the folder view', () => {+ expect(header).toContain("{#if view === 'folders'}");+ });++ it('shows the case to-do lists Home shows, from the same copy', () => {+ expect(shell).toContain('<CaseTodos caseId={caseState.current.id} compact />');+ });++ it('reads what was filed last only while that view is open', () => {+ expect(shell).toContain("if (view !== 'recent' || !id) return;");+ expect(shell).toContain("order: '-created'");+ });+});++describe('work folder', () => {+ it('pins it above the tree and on its row', () => {+ expect(shell).toContain('class="work-line"');+ expect(tree).toContain('{#if workFolder === node.path}');+ expect(tree).toContain('onworkfolder(node.path)');+ });++ it('toggles it through the shared folder actions', () => {+ expect(shell).toContain('await setWorkFolder(caseState.current.id, working === path ? null : path)');+ });+});++describe('right-click', () => {+ it('opens a menu on folder rows and on entity rows, never on a suggestion', () => {+ expect(tree).toContain('onfoldermenu(e, node.path)');+ expect(tree).toContain('onmenu={onentitymenu}');+ expect(row).toContain('if (!onmenu || suggested) return;');+ });++ it('renames a folder or an item through the routes Files uses', () => {+ expect(shell).toContain('await renameFolder(caseId, held.path, target)');+ expect(shell).toContain('await renameEntity(caseId, held.entity, text)');+ });++ it('removes a folder with the same prompt as Files', () => {+ expect(shell).toContain('...removeFolderPrompt(path, allFolders)');+ });++ it('moves an item with the shared Move dialog', () => {+ expect(shell).toContain('uiState.moving = [m.entity]');+ });+});diff --git a/frontend/src/components/EntitySummary.svelte b/frontend/src/components/EntitySummary.svelteindex ebdfbf2..063e031 100644--- a/frontend/src/components/EntitySummary.svelte+++ b/frontend/src/components/EntitySummary.svelte@@ -12,7 +12,8 @@* One read per entity shown (`/catalog/events`), refreshed with the case.*/import { tick } from 'svelte';- import { caseState, uiState } from '../lib/state.svelte.js';+ import { caseState } from '../lib/state.svelte.js';+ import { openInTimeline } from '../lib/navigate.js';import { fetchEventRows } from '../lib/catalog.js';import { entityFamily, entityLabel } from '../lib/entityTypes.svelte.js';import { entityIcon } from '../lib/entityIcon.js';@@ -85,15 +86,7 @@});function openTimeline() {- uiState.timelineFocus = {- entityId: entity.id,- entityLabel: entity.label,- entityType: entity.type,- entityAttrs: entity.attrs ?? {},- itemId: null,- producedHere: false,- };- uiState.tool = 'timeline';+ openInTimeline(entity);onclose?.();}</script>diff --git a/frontend/src/components/EntityTime.svelte b/frontend/src/components/EntityTime.svelteindex f0a2935..30311d1 100644--- a/frontend/src/components/EntityTime.svelte+++ b/frontend/src/components/EntityTime.svelte@@ -2,7 +2,8 @@/** Entity-scoped temporal history. Mounted only while the Time tab is open. */import { api } from '../lib/api.js';import { changeInterval, formatTemporalValue, temporalKindLabel } from '../lib/timeline.js';- import { reloadCase, toast, uiState } from '../lib/state.svelte.js';+ import { reloadCase, toast } from '../lib/state.svelte.js';+ import { openInTimeline } from '../lib/navigate.js';import Icon from './Icon.svelte';import TemporalClaimEditor from './TemporalClaimEditor.svelte';@@ -100,15 +101,7 @@}function openTimeline(item = null) {- uiState.timelineFocus = {- entityId: entity.id,- entityLabel: entity.label,- entityType: entity.type,- entityAttrs: entity.attrs ?? {},- itemId: item?.id ?? null,- producedHere: item?.produced_here === true,- };- uiState.tool = 'timeline';+ openInTimeline(entity, item);onclose?.();}diff --git a/frontend/src/components/EntityTime.test.js b/frontend/src/components/EntityTime.test.jsindex ef5d55c..07f10ab 100644--- a/frontend/src/components/EntityTime.test.js+++ b/frontend/src/components/EntityTime.test.js@@ -37,10 +37,8 @@ describe('entity Time tab', () => {});it('hands the visible entity scope to the global Timeline', () => {- expect(source).toContain('uiState.timelineFocus = {\n entityId: entity.id,\n entityLabel: entity.label,');- // a working file says so, or a Media track holding them back would hide the row- expect(source).toContain('producedHere: item?.produced_here === true,');- expect(source).toContain("uiState.tool = 'timeline'");+ // lib/navigate.js builds the focus, tested there+ expect(source).toContain('openInTimeline(entity, item);');});it('opens an existing assessment in an explicit inline editor', () => {diff --git a/frontend/src/components/FolderSelect.svelte b/frontend/src/components/FolderSelect.svelteindex 8cdab7f..e2da9d8 100644--- a/frontend/src/components/FolderSelect.svelte+++ b/frontend/src/components/FolderSelect.svelte@@ -1,18 +1,31 @@<script>+ import { untrack } from 'svelte';import Icon from './Icon.svelte';import { buildTree, flattenPaths } from '../lib/folderTree.js';import { portal } from '../lib/fullscreen.js';+ import { workFolder } from '../lib/folders.js';// A folder picker that only lets you choose an existing My-work folder or// deliberately create a new one — no free-typing a stray path by accident.+ //+ // `fresh` says it picks where something new goes: it then starts on the case's+ // work folder, which is what the server would have filed it in anyway. Picking+ // the empty row still sends no folder, and that choice wins.let {value = $bindable(''),folders = [],emptyLabel = 'No folder',allowCreate = true,+ fresh = false,id = undefined,} = $props();+ const working = $derived(workFolder());+ // Once, when the picker opens on a new item; later changes are the analyst's.+ untrack(() => {+ if (fresh && !value && workFolder()) value = workFolder();+ });+let open = $state(false);let creating = $state(false);let newName = $state('');@@ -77,6 +90,7 @@><Icon name={value ? 'folder' : 'folderMinus'} size={14} /><span class="cur" class:none={!value}>{value || emptyLabel}</span>+ {#if value && value === working}<span class="tag">Work folder</span>{/if}<Icon name="chevronDown" size={14} /></button>@@ -101,6 +115,7 @@><Icon name="folder" size={14} /><span class="grow">{o.name}</span>+ {#if o.path === working}<span class="tag">Work folder</span>{/if}{#if value === o.path}<Icon name="check" size={14} />{/if}</button>{/each}@@ -162,6 +177,16 @@.cur.none {color: var(--text-3);}+ .tag {+ flex-shrink: 0;+ padding: 0 6px;+ border-radius: var(--r-sm);+ background: var(--accent-soft);+ color: var(--accent);+ font-size: var(--fs-xs);+ font-weight: 600;+ white-space: nowrap;+ }/* Portaled to <body>, so they sit above the modal overlay (z-index 900). */.backdrop {position: fixed;diff --git a/frontend/src/components/Icon.svelte b/frontend/src/components/Icon.svelteindex 67487c3..4e39eeb 100644--- a/frontend/src/components/Icon.svelte+++ b/frontend/src/components/Icon.svelte@@ -159,7 +159,7 @@flame: 'M12 3c3.2 3.4 5 6 5 8.6a5 5 0 0 1-10 0c0-1.6.6-3 1.9-4.3.1 1.2.6 2 1.4 2.6C10 7.6 10.6 5.3 12 3Z',// The guide, wherever it is asked for. A question mark rather than a book: the// press means "what is this tab", not "open a document".- help: 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18Zm-2.3 6.4a2.3 2.3 0 0 1 4.5.7c0 1.5-2.2 2-2.2 3.4M12 16.7h.01',+ help: 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18ZM9.1 9.6a2.9 2.9 0 1 1 4.2 2.6c-.8.4-1.3 1-1.3 1.9v.4M12 16.3a.8.8 0 1 0 0 1.6.8.8 0 1 0 0-1.6Z',keyboard: 'M3 7h18a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V8a1 1 0 0 1 1-1Zm3.5 3.2h.01m3.2 0h.01m3.2 0h.01m3.2 0h.01M8 13.8h8',};</script>diff --git a/frontend/src/components/MoveDialog.render.test.js b/frontend/src/components/MoveDialog.render.test.jsnew file mode 100644index 0000000..756fa9a--- /dev/null+++ b/frontend/src/components/MoveDialog.render.test.js@@ -0,0 +1,71 @@+// @vitest-environment happy-dom+import { afterEach, describe, expect, it, vi } from 'vitest';+import { flushSync, mount, unmount } from 'svelte';++const { patch, get } = vi.hoisted(() => ({ patch: vi.fn(async () => ({})), get: vi.fn() }));+vi.mock('../lib/api.js', () => ({ api: { patch, get } }));++const { caseState, uiState } = await import('../lib/state.svelte.js');+const { default: MoveDialog } = await import('./MoveDialog.svelte');++let live = null;+let target = null;++async function settle() {+ for (let i = 0; i < 20; i++) await Promise.resolve();+ flushSync();+}++function show(entities) {+ caseState.current = { id: 'c1', name: 'Case', folders: ['Port', 'Port/Docks', 'Airbase'] };+ get.mockImplementation(async () => ({ ...caseState.current }));+ uiState.moving = entities;+ target = document.createElement('div');+ document.body.append(target);+ live = mount(MoveDialog, { target });+ flushSync();+}++const dialog = () => document.querySelector('[role="dialog"]');+const button = (label) => [...dialog().querySelectorAll('button')].find((b) => b.textContent.trim() === label);+const option = (label) => [...document.querySelectorAll('.menu .opt')].find((b) => b.textContent.trim().startsWith(label));++afterEach(() => {+ if (live) unmount(live);+ live = null;+ target?.remove();+ uiState.moving = null;+ patch.mockClear();+});++describe('Move to…', () => {+ it('opens on where the items already are, and only moves to somewhere else', () => {+ show([{ id: 'p1', type: 'place', label: 'Gate', attrs: { folder: 'Port' } }]);+ expect(dialog().getAttribute('aria-label')).toBe('Move “Gate”');+ expect(dialog().textContent).toContain('Port');+ expect(button('Move').disabled).toBe(true);+ });++ it('files every item the way the sidebar does, then closes', async () => {+ show([+ { id: 'p1', type: 'place', label: 'Gate', attrs: { folder: 'Port' } },+ { id: 'm1', type: 'media', label: 'Shot', attrs: { path: 'media/shot.png', folder: 'Airbase' } },+ ]);+ expect(dialog().getAttribute('aria-label')).toBe('Move 2 items');+ dialog().querySelector('.folder-select .trigger').click();+ flushSync();+ option('Docks').click();+ flushSync();+ button('Move').click();+ await settle();+ expect(patch).toHaveBeenCalledWith('/api/cases/c1/entities/p1', { attrs: { folder: 'Port/Docks' } });+ expect(patch).toHaveBeenCalledWith('/api/cases/c1/media', { path: 'media/shot.png', folder: 'Port/Docks' });+ expect(uiState.moving).toBeNull();+ expect(uiState.toasts.at(-1).message).toBe('Moved 2 items to Port/Docks');+ });++ it('shows nothing while there is nothing to move', () => {+ show(null);+ expect(dialog()).toBeNull();+ });+});diff --git a/frontend/src/components/MoveDialog.svelte b/frontend/src/components/MoveDialog.sveltenew file mode 100644index 0000000..13a2542--- /dev/null+++ b/frontend/src/components/MoveDialog.svelte@@ -0,0 +1,76 @@+<script>+ /**+ * Move to…: refile what `uiState.moving` names into one folder. Mounted once,+ * so Files, the sidebar and a toast that filed something into the work folder+ * all open the same dialog.+ */+ import { caseState, reloadCase, toast, uiState } from '../lib/state.svelte.js';+ import { assignFolderBatch } from '../lib/filing.js';+ import { folderOf } from '../lib/folderTree.js';+ import Modal from './Modal.svelte';+ import FolderSelect from './FolderSelect.svelte';++ const items = $derived(uiState.moving ?? []);+ // Where they already are, when they share one folder: the picker starts there.+ const shared = $derived.by(() => {+ const folders = new Set(items.map((e) => folderOf(e) ?? ''));+ return folders.size === 1 ? [...folders][0] : '';+ });+ let folder = $state('');+ let busy = $state(false);+ let openedOn = null;+ $effect(() => {+ if (uiState.moving !== openedOn) {+ openedOn = uiState.moving;+ folder = shared;+ }+ });++ const title = $derived(+ items.length === 1 ? `Move “${items[0].label}”` : `Move ${items.length} items`+ );++ function close() {+ if (!busy) uiState.moving = null;+ }++ async function move() {+ const caseId = caseState.current?.id;+ if (!caseId || busy) return;+ busy = true;+ try {+ await assignFolderBatch(caseId, items, folder);+ await reloadCase();+ toast(+ `Moved ${items.length === 1 ? `“${items[0].label}”` : `${items.length} items`} to ${folder || 'Unfiled'}`,+ 'ok',+ 2200+ );+ uiState.moving = null;+ } catch (e) {+ toast(e.message, 'danger');+ } finally {+ busy = false;+ }+ }+</script>++{#if items.length && caseState.current}+ <Modal {title} onclose={close} width="420px">+ <span class="label">Folder</span>+ <FolderSelect bind:value={folder} folders={caseState.current.folders ?? []} emptyLabel="Unfiled" />+ <div class="row">+ <div class="grow"></div>+ <button class="btn" onclick={close} disabled={busy}>Cancel</button>+ <button class="btn btn-primary" onclick={move} disabled={busy || folder === shared}>+ {busy ? 'Moving…' : 'Move'}+ </button>+ </div>+ </Modal>+{/if}++<style>+ .label { display: block; font-size: var(--fs-xs); color: var(--text-3); margin: 2px 0 6px; }+ .row { display: flex; align-items: center; gap: 8px; margin-top: 14px; }+ .grow { flex: 1; }+</style>diff --git a/frontend/src/components/PasteDialog.svelte b/frontend/src/components/PasteDialog.svelteindex 91f3390..ba76451 100644--- a/frontend/src/components/PasteDialog.svelte+++ b/frontend/src/components/PasteDialog.svelte@@ -98,7 +98,7 @@{#if asks('folder')}<span class="modal-label" style="margin-top:10px">Folder (in My work)</span>- <FolderSelect bind:value={values.folder} {folders} emptyLabel="My work (root)" />+ <FolderSelect bind:value={values.folder} {folders} emptyLabel="My work (root)" fresh />{/if}{#if asks('source')}diff --git a/frontend/src/components/ProposalReview.render.test.js b/frontend/src/components/ProposalReview.render.test.jsnew file mode 100644index 0000000..d0a39fa--- /dev/null+++ b/frontend/src/components/ProposalReview.render.test.js@@ -0,0 +1,139 @@+// @vitest-environment happy-dom+/**+ * The review of the links the case proposed by itself: a pass on a press, one line per+ * proposal, and Confirm or Drop on each, which is the whole of what it does.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { flushSync, mount, unmount } from 'svelte';++const get = vi.fn();+const post = vi.fn();+const patch = vi.fn(async () => ({}));+const del = vi.fn();+vi.mock('../lib/api.js', () => ({ api: { get, post, patch, del } }));++const toast = vi.fn();+const reloadCase = vi.fn(async () => {});+const uiState = { openGraphEntity: null };+vi.mock('../lib/state.svelte.js', async () => {+ const { caseState } = await import('./views.fixture.svelte.js');+ return { caseState, toast, uiState, reloadCase };+});++const { default: ProposalReview } = await import('./ProposalReview.svelte');++const NONE = {+ pending: { accounts: 0, posted: 0, sites: 0 }, items: [], listed: 0, radius: 300, through: null,+};+const ITEMS = [+ {+ id: 'l_post', type: 'posted',+ from: { id: 'e_acc', label: '@BashaReport', type: 'account' },+ to: { id: 'e_clip', label: 'clip.mp4', type: 'media' },+ },+ {+ id: 'l_site', type: 'same-site-as', metres: 110,+ from: { id: 'e_a', label: 'Hangar', type: 'place' },+ to: { id: 'e_b', label: 'Runway', type: 'place' },+ },+];+const SOME = {+ pending: { accounts: 1, posted: 1, sites: 1 }, items: ITEMS, listed: 2, radius: 300,+ through: '2026-10-01T10:00:00Z',+};++let live = null;+let target = null;++async function settle() {+ for (let index = 0; index < 10; index += 1) await Promise.resolve();+ flushSync();+}++async function open() {+ target = document.createElement('div');+ document.body.append(target);+ live = mount(ProposalReview, { target, props: { caseId: 'case-a' } });+ await settle();+}++const button = (label) =>+ [...target.querySelectorAll('button')].find((node) => node.textContent.trim().startsWith(label));++beforeEach(() => {+ vi.clearAllMocks();+ uiState.openGraphEntity = null;+});++afterEach(() => {+ if (live) unmount(live);+ live = null;+ document.body.innerHTML = '';+});++describe('the proposed links', () => {+ it('offers a pass on a case never read, and opens on what it found', async () => {+ get.mockResolvedValue(NONE);+ post.mockResolvedValue({ filed: { accounts: 1, posted: 1, sites: 1 }, ...SOME });+ await open();++ button('Find links').click();+ await settle();++ expect(post).toHaveBeenCalledWith('/api/cases/case-a/proposals', {});+ expect(toast).toHaveBeenCalledWith('Proposed 1 account, 1 posted link, 1 same-site link.');+ expect(reloadCase).toHaveBeenCalled();+ const lines = [...target.querySelectorAll('.say')].map((node) => node.textContent.trim());+ expect(lines).toEqual([+ '@BashaReport posted clip.mp4',+ 'Hangar and Runway are one site, 110 m apart',+ ]);+ });++ it('stays out of the toolbar once the case was read and nothing waits', async () => {+ get.mockResolvedValue({ ...NONE, through: '2026-10-01T10:00:00Z' });+ await open();++ expect(target.querySelectorAll('button')).toHaveLength(0);+ });++ it('counts what waits and confirms one through the ordinary link patch', async () => {+ get.mockResolvedValue(SOME);+ await open();+ expect(button('2 proposed')).toBeDefined();++ button('2 proposed').click();+ flushSync();+ get.mockResolvedValue({ ...NONE, pending: { accounts: 0, posted: 0, sites: 1 }, items: [ITEMS[1]], listed: 1 });+ button('Confirm').click();+ await settle();++ expect(patch).toHaveBeenCalledWith('/api/cases/case-a/links/l_post', { status: 'confirmed' });+ expect(target.querySelectorAll('.say')).toHaveLength(1);+ });++ it('drops one and takes the answer the server gives back', async () => {+ get.mockResolvedValue(SOME);+ del.mockResolvedValue({ ...NONE, pending: { accounts: 0, posted: 0, sites: 1 }, items: [ITEMS[1]], listed: 1 });+ await open();+ button('2 proposed').click();+ flushSync();++ button('Drop').click();+ await settle();++ expect(del).toHaveBeenCalledWith('/api/cases/case-a/proposals/l_post');+ expect(target.querySelectorAll('.say')).toHaveLength(1);+ });++ it('shows a line in the graph when it is pressed', async () => {+ get.mockResolvedValue(SOME);+ await open();+ button('2 proposed').click();+ flushSync();++ target.querySelectorAll('.say')[1].click();++ expect(uiState.openGraphEntity).toBe('e_b');+ });+});diff --git a/frontend/src/components/ProposalReview.svelte b/frontend/src/components/ProposalReview.sveltenew file mode 100644index 0000000..59b4698--- /dev/null+++ b/frontend/src/components/ProposalReview.svelte@@ -0,0 +1,165 @@+<script>+ /**+ * The links the case proposed by itself, read and settled in one list.+ *+ * Who posted a file is written in its address, and two points a few hundred metres+ * apart are usually one site, so the case files those as proposals+ * (`engine/proposals.py`) instead of waiting for somebody to type them. This is where+ * they are confirmed or dropped, one line each, without hunting dashed edges across a+ * drawing. A dropped proposal does not come back.+ *+ * The pass runs by itself after an import; **Find links** runs it now, which is what a+ * case filed before this existed needs once. It is offered only until the case has been+ * read, since after that every import reads it again and the count is the only news.+ */+ import Icon from './Icon.svelte';+ import { api } from '../lib/api.js';+ import { closeOnOutsidePointer } from '../lib/dismiss.js';+ import { filedWords, proposalSentence, waitingCount } from '../lib/proposalReview.js';+ import { caseState, reloadCase, toast, uiState } from '../lib/state.svelte.js';++ let { caseId } = $props();++ let data = $state(null);+ let open = $state(false);+ let busy = $state(false);+ let box = $state(null);++ $effect(() => {+ const id = caseId;+ void caseState.rev;+ if (!id) return;+ let live = true;+ api+ .get(`/api/cases/${id}/proposals`)+ .then((answer) => live && (data = answer))+ .catch(() => live && (data = null));+ return () => (live = false);+ });++ $effect(() => (open && box ? closeOnOutsidePointer(box, () => (open = false)) : undefined));++ const waiting = $derived(waitingCount(data?.pending));+ /** Never read for links yet: a case filed before the pass existed. */+ const unread = $derived(Boolean(data) && !data.through);++ async function look() {+ if (busy || !caseId) return;+ busy = true;+ try {+ const answer = await api.post(`/api/cases/${caseId}/proposals`, {});+ data = answer;+ toast(filedWords(answer.filed));+ if (waitingCount(answer.pending)) open = true;+ await reloadCase();+ } catch (error) {+ toast(error.message || 'The case could not be read for links.', 'error');+ } finally {+ busy = false;+ }+ }++ async function confirm(item) {+ if (busy) return;+ busy = true;+ try {+ await api.patch(`/api/cases/${caseId}/links/${item.id}`, { status: 'confirmed' });+ data = await api.get(`/api/cases/${caseId}/proposals`);+ await reloadCase();+ } catch (error) {+ toast(error.message || 'This link could not be confirmed.', 'error');+ } finally {+ busy = false;+ }+ }++ async function drop(item) {+ if (busy) return;+ busy = true;+ try {+ data = await api.del(`/api/cases/${caseId}/proposals/${item.id}`);+ await reloadCase();+ } catch (error) {+ toast(error.message || 'This link could not be dropped.', 'error');+ } finally {+ busy = false;+ }+ }++ function show(item) {+ uiState.openGraphEntity = item.to.id;+ }+</script>++<div class="review" bind:this={box}>+ {#if waiting}+ <button class="count proposed" class:on={open} aria-expanded={open}+ title="Links the case proposed by itself, to confirm or drop"+ onclick={() => (open = !open)}>+ {waiting} proposed+ </button>+ {:else if unread}+ <button class="btn btn-ghost btn-sm" disabled={busy || !caseId} onclick={look}+ title="Read who posted each file and which points share a site">+ <Icon name="link" size={13} /> {busy ? 'Looking' : 'Find links'}+ </button>+ {/if}++ {#if open}+ <div class="panel card" role="dialog" aria-label="Proposed links">+ <div class="head">+ <strong>Proposed links</strong>+ <button class="btn btn-ghost btn-xs" disabled={busy} onclick={look}>Look again</button>+ </div>+ <p class="note">+ Who posted a file, read off its address, and points under {data?.radius ?? 300} m+ apart. Confirm what holds and drop the rest.+ </p>+ <ul>+ {#each data?.items ?? [] as item (item.id)}+ <li>+ <button class="say" onclick={() => show(item)} title="Show it in the graph">+ {proposalSentence(item)}+ </button>+ <button class="btn btn-ghost btn-xs" disabled={busy} onclick={() => confirm(item)}>+ Confirm+ </button>+ <button class="btn btn-ghost btn-xs" disabled={busy} onclick={() => drop(item)}>+ Drop+ </button>+ </li>+ {:else}+ <li class="note">Nothing left to review.</li>+ {/each}+ </ul>+ {#if waiting > (data?.listed ?? 0)}+ <p class="note">The first {data.listed} of {waiting}. Settling these brings up the rest.</p>+ {/if}+ </div>+ {/if}+</div>++<style>+ .review { position: relative; display: inline-flex; }+ .count {+ font-size: var(--fs-xs); padding: 2px 8px; border-radius: 999px;+ border: 1px solid var(--accent); color: var(--accent); background: var(--accent-soft);+ }+ .count.on { background: var(--accent); color: var(--bg-1); }+ .panel {+ position: absolute; top: calc(100% + 6px); right: 0; z-index: 40;+ width: min(460px, 90vw); max-height: 60vh; overflow: auto; padding: 10px 12px;+ display: flex; flex-direction: column; gap: 6px;+ }+ .head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }+ .head strong { font-size: var(--fs-sm); }+ ul { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; }+ li { display: flex; align-items: center; gap: 4px; }+ .say {+ flex: 1; min-width: 0; text-align: left; padding: 3px 4px; border-radius: var(--r-sm);+ color: var(--text-1); font-size: var(--fs-xs);+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;+ }+ .say:hover { background: var(--bg-2); }+ .note { color: var(--text-3); font-size: var(--fs-xs); line-height: 1.5; margin: 0; }+</style>diff --git a/frontend/src/components/SheetFromCase.svelte b/frontend/src/components/SheetFromCase.svelteindex a46a83f..01b4a63 100644--- a/frontend/src/components/SheetFromCase.svelte+++ b/frontend/src/components/SheetFromCase.svelte@@ -16,9 +16,12 @@* what they came from, so editing them and promoting them again updates those entities* rather than minting twins.*- * **My geolocations** takes neither: its shape is fixed, one row per proof with- * the media it rests on and the place it puts on the map. That fixed shape is what lets it+ * **My geolocations** takes neither: its shape is fixed, one row per point a proof+ * concludes on, with the media it rests on and what Geo Proof says about it. That fixed shape is what lets it* be kept level with the case afterwards, which the other one cannot be.+ *+ * **Files to geolocate** is the same kind of fixed shape turned the other way: one row+ * per picture or video the analyst imported, done once a proof answers for it.*/import Icon from './Icon.svelte';import { api } from '../lib/api.js';@@ -33,6 +36,7 @@let shape = $state('generic');let counts = $state([]);+ let files = $state(null);let type = $state('');let fields = $state([]);let title = $state('');@@ -53,6 +57,10 @@if (!type && counts.length) type = counts[0].id;}).catch(() => {});+ api+ .get(`/api/cases/${caseId}/sheets/from-case/files`)+ .then((answer) => live && (files = answer))+ .catch(() => {});return () => (live = false);});@@ -67,17 +75,22 @@$effect(() => {if (touched) return;if (proofs) title = 'My geolocations';+ else if (filesShape) title = 'Files to geolocate';else if (type) title = `${entityLabel(type)} to check`;});const proofs = $derived(shape === 'proofs');+ const filesShape = $derived(shape === 'files');+ const fixed = $derived(proofs || filesShape);const available = $derived(entityFields(type).filter((field) => field.kind !== 'geojson'));- // The proofs shape counts proofs, whatever type the other branch is sitting on.+ // The fixed shapes count what they are made of, whatever type the other branch is on.const held = $derived(- counts.find((entry) => entry.id === (proofs ? 'proof' : type))?.count ?? 0,+ filesShape+ ? (files?.total ?? 0)+ : (counts.find((entry) => entry.id === (proofs ? 'proof' : type))?.count ?? 0),);const taken = $derived(Math.min(held, MAX_ROWS));- const ready = $derived(Boolean((proofs || type) && title.trim() && held));+ const ready = $derived(Boolean((fixed || type) && title.trim() && held));function toggle(key) {fields = fields.includes(key) ? fields.filter((entry) => entry !== key) : [...fields, key];@@ -87,17 +100,21 @@<div class="from-case"><p class="label">What the sheet is</p><div class="shapes">- <button class="shape" class:on={!proofs} onclick={() => (shape = 'generic')}>+ <button class="shape" class:on={!fixed} onclick={() => (shape = 'generic')}><strong>One row per entity</strong><small>a worklist over a type you choose</small></button>+ <button class="shape" class:on={filesShape} onclick={() => (shape = 'files')}>+ <strong>Files to geolocate</strong>+ <small>one row per imported picture or video</small>+ </button><button class="shape" class:on={proofs} onclick={() => (shape = 'proofs')}><strong>My geolocations</strong>- <small>one row per proof, kept level with the case</small>+ <small>one row per point of every proof, POV included</small></button></div>- {#if !proofs}+ {#if !fixed}<p class="label">What is in it</p>{#if counts.length}<div class="types">@@ -119,7 +136,7 @@oninput={() => (touched = true)} /></label>- {#if !proofs && available.length}+ {#if !fixed && available.length}<p class="label">And which fields get a column. None is fine if the sheet only carries your own.</p>@@ -136,10 +153,18 @@<p class="says" class:none={!ready}>{#if !held}- {proofs ? 'This case holds no proofs yet.' : 'This case holds nothing of that type.'}+ {proofs+ ? 'This case holds no proofs yet.'+ : filesShape+ ? 'No picture or video was imported into this case yet.'+ : 'This case holds nothing of that type.'}+ {:else if filesShape}+ <strong>{taken}</strong> {taken === 1 ? 'row' : 'rows'}, one per imported picture or+ video, {files?.answered ?? 0} already with a proof.+ {#if held > MAX_ROWS}<span>Only the first {MAX_ROWS} by name.</span>{/if}{:else if proofs}- <strong>{taken}</strong> {taken === 1 ? 'row' : 'rows'}, one per proof, with its source- media, its place and its coordinates.+ One row per point of {taken} {taken === 1 ? 'proof' : 'proofs'}, POV or not, with the+ date, the place, its coordinates, the source and the description.{#if held > MAX_ROWS}<span>Only the first {MAX_ROWS} by name.</span>{/if}{:else}<strong>{taken}</strong> {taken === 1 ? 'row' : 'rows'}, one per@@ -148,7 +173,10 @@{/if}</p><p class="note">- {#if proofs}+ {#if filesShape && files?.sheet}+ This case already has this worklist. Its Refresh brings it level, and building here+ makes a second one.+ {:else if fixed}The case writes those columns and Refresh keeps them level with it. Status, Notes and anycolumn you add are yours.{:else}@@ -171,7 +199,7 @@.from-case { display: flex; flex-direction: column; min-height: 0; }.label { color: var(--text-3); font-size: var(--fs-xs); margin: 12px 0 5px; line-height: 1.5; }.label:first-child { margin-top: 0; }- .shapes { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 6px; }+ .shapes { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; }.shape {display: flex; flex-direction: column; gap: 2px; padding: 8px 10px; text-align: left;border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--bg-2);diff --git a/frontend/src/components/SheetFromProofs.render.test.js b/frontend/src/components/SheetFromProofs.render.test.jsindex a18eb9a..f3235c6 100644--- a/frontend/src/components/SheetFromProofs.render.test.js+++ b/frontend/src/components/SheetFromProofs.render.test.js@@ -97,8 +97,25 @@ describe('choosing what the sheet is', () => {const target = open({ caseId: 'c1', onmake, onclose: vi.fn() });await settle();press(target, 'My geolocations');- expect(flat(target)).toContain('12 rows, one per proof');- expect(flat(target)).toContain('its source media, its place and its coordinates');+ expect(flat(target)).toContain('One row per point of 12 proofs, POV or not');+ expect(flat(target)).toContain('the date, the place, its coordinates, the source');+ });++ it('offers the files worklist with how many a proof already answers', async () => {+ const fallback = get.getMockImplementation();+ get.mockImplementation((path) =>+ path.endsWith('/sheets/from-case/files')+ ? Promise.resolve({ total: 21, answered: 8, sheet: null })+ : fallback(path),+ );+ const target = open({ caseId: 'c1', onmake, onclose: vi.fn() });+ await settle();+ press(target, 'Files to geolocate');+ expect(flat(target)).toContain('21 rows, one per imported picture or video, 8 already with a proof');+ press(target, 'Build the sheet');+ expect(onmake).toHaveBeenLastCalledWith(+ expect.objectContaining({ title: 'Files to geolocate', shape: 'files' }),+ );});it('names the sheet after the shape until the analyst says otherwise', async () => {diff --git a/frontend/src/components/SheetHome.svelte b/frontend/src/components/SheetHome.sveltenew file mode 100644index 0000000..8f9e0c5--- /dev/null+++ b/frontend/src/components/SheetHome.svelte@@ -0,0 +1,205 @@+<script>+ /**+ * What the Sheet tab opens on: the sheets being worked on, and the ones this case could+ * start now. The same two halves Inspect opens on, recent work and a way in, so a tab is+ * never a blank grid or a lecture on what a sheet is.+ *+ * The case's own proposals lead the "start" half, counted (`lib/sheetHome.js`): the files+ * imported and not yet placed are a worklist the analyst would otherwise build by hand.+ */+ import Icon from './Icon.svelte';+ import { api } from '../lib/api.js';+ import { timeAgo } from '../lib/analysisViews.js';+ import { caseProposals, progressWords, recentSheets } from '../lib/sheetHome.js';+ import { SHEET_TEMPLATES } from '../lib/sheetTemplates.js';+ import { caseState } from '../lib/state.svelte.js';++ let {+ caseId,+ sheets = [],+ last = null,+ busy = false,+ onopen,+ onbuild,+ ontemplate,+ onimport,+ onpaste,+ onfromcase,+ } = $props();++ let files = $state(null);+ let proofs = $state(0);+ let term = $state('');++ // Asked again whenever the case reloads, since an import or a proof elsewhere changes+ // both answers. Read only: offering a worklist must not build it.+ $effect(() => {+ const id = caseId;+ void caseState.rev;+ if (!id) return;+ let live = true;+ api+ .get(`/api/cases/${id}/sheets/from-case/files`)+ .then((answer) => live && (files = answer))+ .catch(() => live && (files = null));+ api+ .get(`/api/cases/${id}/catalog/summary`)+ .then((answer) => live && (proofs = answer.by_type?.proof ?? 0))+ .catch(() => live && (proofs = 0));+ return () => (live = false);+ });++ const ordered = $derived(recentSheets(sheets, last));+ const shown = $derived(+ term.trim()+ ? ordered.filter((sheet) =>+ String(sheet.title ?? '').toLowerCase().includes(term.trim().toLowerCase()),+ )+ : ordered,+ );+ const proposals = $derived(caseProposals({ files, proofs, sheets }));++ function startShape(proposal) {+ if (proposal.open) onopen(proposal.open);+ else onbuild({ title: proposal.title, shape: proposal.shape });+ }+</script>++<div class="home">+ <section class="col recent">+ <div class="head">+ <h3>Recent sheets</h3>+ <p>A sheet is a CSV in the case folder. Status, notes and colours are kept with it.</p>+ </div>+ {#if sheets.length > 8}+ <input class="input find" bind:value={term} placeholder="Find a sheet"+ aria-label="Find a sheet" />+ {/if}+ {#if sheets.length}+ <ul class="sheets">+ {#each shown as sheet (sheet.id)}+ <li>+ <button class="sheet" onclick={() => onopen(sheet.id)}>+ <Icon name={sheet.shape === 'files' ? 'video' : sheet.shape === 'proofs' ? 'proof' : 'table'}+ size={15} />+ <span class="name">{sheet.title}</span>+ {#if sheet.id === last}<em class="tag">Last open</em>{/if}+ <small>+ {sheet.rows} {sheet.rows === 1 ? 'row' : 'rows'}{#if progressWords(sheet.progress)}+ · {progressWords(sheet.progress)}{/if}{#if sheet.modified_at}+ · {timeAgo(sheet.modified_at)}{/if}+ </small>+ </button>+ </li>+ {:else}+ <li class="note">No match.</li>+ {/each}+ </ul>+ {:else}+ <p class="note">No sheet in this case yet.</p>+ {/if}+ </section>++ <section class="col start">+ <div class="head">+ <h3>Start a sheet</h3>+ <p>A worklist that counts what is left, or a grid that compares candidates.</p>+ </div>++ {#if proposals.length}+ <p class="label">From this case</p>+ <div class="cards">+ {#each proposals as proposal (proposal.shape)}+ <button class="card proposal" disabled={busy} onclick={() => startShape(proposal)}>+ <span class="card-title">+ <Icon name={proposal.shape === 'files' ? 'video' : 'proof'} size={14} />+ {proposal.title}+ </span>+ <small>{proposal.detail}</small>+ <small class="hint">{proposal.hint}</small>+ <span class="go">{proposal.open ? 'Open' : 'Build'}</span>+ </button>+ {/each}+ </div>+ {/if}++ <p class="label">From a template</p>+ <div class="cards">+ {#each SHEET_TEMPLATES as entry (entry.id)}+ <button class="card" onclick={() => ontemplate(entry.id)}>+ <span class="card-title">{entry.label}</span>+ <small>{entry.hint}</small>+ </button>+ {/each}+ </div>++ <p class="label">From a table</p>+ <div class="row-actions">+ <label class="btn btn-sm">+ <Icon name="upload" size={13} /> Import a file+ <input type="file" accept=".csv,.tsv,.xlsx,text/csv,text/plain" hidden+ onchange={(event) => { onimport(event.currentTarget.files); event.currentTarget.value = ''; }} />+ </label>+ <button class="btn btn-sm" onclick={onpaste}>+ <Icon name="copy" size={13} /> Paste a table+ </button>+ <button class="btn btn-sm" onclick={onfromcase}>+ <Icon name="graph" size={13} /> From the case+ </button>+ </div>+ </section>+</div>++<style>+ .home {+ flex: 1; min-height: 0; overflow: auto;+ display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);+ gap: 28px; max-width: 1240px; width: 100%; margin: 0 auto; padding: 24px 20px;+ align-content: start;+ }+ @media (max-width: 900px) { .home { grid-template-columns: minmax(0, 1fr); } }+ .col { display: flex; flex-direction: column; gap: 10px; min-width: 0; }+ .head h3 { font-size: var(--fs-md); font-weight: 700; margin: 0 0 4px; }+ .head p { margin: 0; color: var(--text-3); font-size: var(--fs-sm); line-height: 1.5; }+ .find { max-width: 320px; }+ .sheets { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; }+ .sheet {+ width: 100%; display: grid; grid-template-columns: auto minmax(0, 1fr) auto;+ grid-template-areas: 'icon name tag' 'icon meta meta';+ align-items: center; column-gap: 10px; row-gap: 2px; padding: 8px 10px; text-align: left;+ border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--bg-2);+ color: var(--text-1);+ }+ .sheet:hover { border-color: var(--border-strong); }+ .sheet :global(svg) { grid-area: icon; color: var(--text-3); }+ .sheet .name {+ grid-area: name; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;+ font-size: var(--fs-sm); font-weight: 600;+ }+ .sheet .tag {+ grid-area: tag; font-style: normal; font-size: var(--fs-xs); color: var(--accent);+ }+ .sheet small { grid-area: meta; color: var(--text-3); font-size: var(--fs-xs); }+ .label { color: var(--text-3); font-size: var(--fs-xs); margin: 8px 0 0; }+ .cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(210px, 1fr)); gap: 6px; }+ .card {+ display: flex; flex-direction: column; gap: 3px; padding: 9px 11px; text-align: left;+ border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--bg-2);+ position: relative;+ }+ .card:hover:not(:disabled) { border-color: var(--border-strong); }+ .card.proposal { border-color: var(--accent); background: var(--accent-soft); }+ .card-title {+ display: inline-flex; align-items: center; gap: 6px;+ color: var(--text-1); font-size: var(--fs-sm); font-weight: 600;+ }+ .proposal .card-title { color: var(--accent); }+ .card small { color: var(--text-3); font-size: var(--fs-xs); line-height: 1.4; }+ .proposal small:first-of-type { color: var(--text-2); }+ .go {+ position: absolute; top: 8px; right: 10px; font-size: var(--fs-xs); color: var(--accent);+ font-weight: 600;+ }+ .row-actions { display: flex; flex-wrap: wrap; gap: 6px; }+ .note { color: var(--text-3); font-size: var(--fs-sm); }+</style>diff --git a/frontend/src/components/sidebar/EntityRow.svelte b/frontend/src/components/sidebar/EntityRow.svelteindex bdfa2d4..80253c8 100644--- a/frontend/src/components/sidebar/EntityRow.svelte+++ b/frontend/src/components/sidebar/EntityRow.svelte@@ -22,6 +22,8 @@ondismiss = () => {},ondragstart = () => {},ondragend = () => {},+ /** Right-click: `(event, entity)`. A suggestion has its own two buttons instead. */+ onmenu = null,} = $props();const isClickable = $derived(@@ -45,6 +47,11 @@role={isClickable ? 'button' : undefined}tabindex={isClickable ? 0 : undefined}onkeydown={(ev) => ev.key === 'Enter' && onactivate(entity, ev)}+ oncontextmenu={(ev) => {+ if (!onmenu || suggested) return;+ ev.preventDefault();+ onmenu(ev, entity);+ }}>{#if !suggested}<Icon name="grip" size={13} />{/if}{#if entity.thumb}diff --git a/frontend/src/components/sidebar/SidebarHeader.svelte b/frontend/src/components/sidebar/SidebarHeader.svelteindex b6c8bbe..fa1c2dc 100644--- a/frontend/src/components/sidebar/SidebarHeader.svelte+++ b/frontend/src/components/sidebar/SidebarHeader.svelte@@ -1,5 +1,6 @@<script>- // Zone 1: identity, search, type chips. Fixed — it never scrolls away.+ // Zone 1: identity, the view switch, then search and type chips for the folder+ // view. Fixed — it never scrolls away.import Icon from '../Icon.svelte';import SearchInput from '../SearchInput.svelte';@@ -11,10 +12,20 @@chips = [],total = 0,resultCount = null,+ view = 'folders',onnotes = () => {},onselecttype = () => {},+ onview = () => {},} = $props();+ // Three readings of one case beside whatever tool is open: its folders, what is+ // left to do, and what was filed last.+ const VIEWS = [+ { id: 'folders', label: 'Folders', icon: 'folder' },+ { id: 'todo', label: 'To-do', icon: 'check' },+ { id: 'recent', label: 'Recent', icon: 'clock' },+ ];+// A case with a dozen entity types would push its rarest chips off a single// line, so the row wraps and only the busiest few show until "+N" is pressed.// The active chip is always in view, even when it sits past the cut.@@ -38,6 +49,21 @@</button></div>+ <div class="views" role="tablist" aria-label="Sidebar view">+ {#each VIEWS as v (v.id)}+ <button+ class="view"+ class:active={view === v.id}+ role="tab"+ aria-selected={view === v.id}+ onclick={() => onview(v.id)}+ >+ <Icon name={v.icon} size={13} /> {v.label}+ </button>+ {/each}+ </div>++ {#if view === 'folders'}<SearchInputbind:value={query}placeholder="Search this case…"@@ -66,6 +92,7 @@{/if}</div>{/if}+ {/if}</div><style>@@ -127,4 +154,20 @@background: var(--accent-soft);}.n { font-weight: 600; }+ .views {+ display: flex;+ gap: 2px;+ margin: -4px -4px 0;+ }+ .view {+ display: flex;+ align-items: center;+ gap: 5px;+ padding: 6px 8px;+ color: var(--text-3);+ font-size: var(--fs-xs);+ font-weight: 600;+ }+ .view:hover { color: var(--text-1); }+ .view.active { color: var(--text-1); box-shadow: inset 0 -2px 0 var(--accent); }</style>diff --git a/frontend/src/components/sidebar/SidebarResults.svelte b/frontend/src/components/sidebar/SidebarResults.svelteindex 7456750..8cdee64 100644--- a/frontend/src/components/sidebar/SidebarResults.svelte+++ b/frontend/src/components/sidebar/SidebarResults.svelte@@ -1,7 +1,7 @@<script>// Zone 2, results mode: a flat list, whatever the filing. Each row carries its// folder as meta, which answers "where is this filed?" without expanding a- // single node.+ // single node. The Recent view is the same list, newest first.import { resultMeta } from '../../lib/sidebarSearch.js';import EntityRow from './EntityRow.svelte';@@ -14,12 +14,14 @@onactivate = () => {},oninfo = () => {},onunfile = () => {},+ onmenu = null,+ empty = 'No match in this case.',} = $props();</script><div class="results">{#each rows as e (e.id)}- <EntityRow entity={e} {caseId} meta={resultMeta(e)} {onactivate} {oninfo} {onunfile} />+ <EntityRow entity={e} {caseId} meta={resultMeta(e)} {onactivate} {oninfo} {onunfile} {onmenu} />{/each}{#if hasMore}@@ -27,7 +29,7 @@{/if}{#if rows.length === 0 && !loading}- <div class="none">No match in this case.</div>+ <div class="none">{empty}</div>{/if}</div>diff --git a/frontend/src/components/sidebar/SidebarTree.svelte b/frontend/src/components/sidebar/SidebarTree.svelteindex 2b09f85..6c6ef06 100644--- a/frontend/src/components/sidebar/SidebarTree.svelte+++ b/frontend/src/components/sidebar/SidebarTree.svelte@@ -27,6 +27,12 @@onmoresuggested = () => {},oncreatefolder = () => {},onremovefolder = () => {},+ /** The case's work folder, marked with its pin. */+ workFolder = null,+ onworkfolder = () => {},+ /** Right-click on a folder row or an entity row: `(event, path)` / `(event, entity)`. */+ onfoldermenu = () => {},+ onentitymenu = () => {},onfile = () => {},onactivate = () => {},oninfo = () => {},@@ -195,6 +201,7 @@onactivate={onRowClick}{oninfo}{onunfile}+ onmenu={onentitymenu}/>{/each}{#if !unfiled.done}@@ -277,11 +284,27 @@ondrop={(e) => onDropFolder(e, node.path)}onclick={() => ontoggle(node.path)}onkeydown={(e) => e.key === 'Enter' && ontoggle(node.path)}+ oncontextmenu={(e) => { e.preventDefault(); onfoldermenu(e, node.path); }}><Icon name={isExpanded(node.path) ? 'chevronDown' : 'chevronRight'} size={12} /><Icon name={isExpanded(node.path) ? 'folderOpen' : 'folder'} size={13} /><span class="fname">{node.name}</span>+ {#if workFolder === node.path}+ <span class="pin" title="Work folder: new files and saved work land here"><Icon name="pushpin" size={12} /></span>+ {/if}<span class="fcount">{subtreeCountFrom(node, byFolder)}</span>+ {#if workFolder !== node.path}+ <span+ class="fact"+ role="button"+ tabindex="0"+ title="Work in this folder: new files and saved work land here"+ onclick={(e) => { e.stopPropagation(); onworkfolder(node.path); }}+ onkeydown={(e) => e.key === 'Enter' && (e.stopPropagation(), onworkfolder(node.path))}+ >+ <Icon name="pushpin" size={12} />+ </span>+ {/if}<spanclass="fact"role="button"@@ -339,6 +362,7 @@onactivate={onRowClick}{oninfo}{onunfile}+ onmenu={onentitymenu}/>{/each}{#if !sec.done}@@ -378,6 +402,7 @@.fact { opacity: 0; color: var(--text-3); display: flex; padding: 2px; border-radius: 4px; flex-shrink: 0; }.fact:hover { color: var(--text-1); }.fdel:hover { color: var(--danger, #e55); }+ .pin { display: flex; color: var(--accent); flex-shrink: 0; }.frow:hover .fact { opacity: 1; }.trash-head { display: flex; align-items: center; position: relative; }.trash-toggle { padding-right: 34px; }diff --git a/frontend/src/lib/filing.js b/frontend/src/lib/filing.jsindex 89eb82e..a157a7c 100644--- a/frontend/src/lib/filing.js+++ b/frontend/src/lib/filing.js@@ -22,3 +22,20 @@ export async function assignFolder(caseId, entity, folder) {export async function assignFolderBatch(caseId, entities, folder) {for (const entity of entities) await assignFolder(caseId, entity, folder);}++/**+ * Rename an entity the way Details does. A media or a capture is its file, so+ * the name goes through its own route and renames the file on disk; a note,+ * a proof or a session follows its label on the server.+ */+export async function renameEntity(caseId, entity, name) {+ const title = (name ?? '').trim();+ if (!title) return;+ if (entity.type === 'capture' && entity.attrs?.path) {+ await api.patch(`/api/cases/${caseId}/satellite`, { path: entity.attrs.path, title });+ } else if (entity.type === 'media' && entity.attrs?.path) {+ await api.patch(`/api/cases/${caseId}/media`, { path: entity.attrs.path, title });+ } else {+ await api.patch(`/api/cases/${caseId}/entities/${entity.id}`, { label: title });+ }+}diff --git a/frontend/src/lib/filing.test.js b/frontend/src/lib/filing.test.jsindex 27f5e34..1c3ed98 100644--- a/frontend/src/lib/filing.test.js+++ b/frontend/src/lib/filing.test.js@@ -1,6 +1,6 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import { api } from './api.js';-import { assignFolder, assignFolderBatch } from './filing.js';+import { assignFolder, assignFolderBatch, renameEntity } from './filing.js';vi.mock('./api.js', () => ({ api: { patch: vi.fn(async () => ({})) } }));@@ -56,3 +56,25 @@ describe('assignFolderBatch', () => {});});});++describe('renameEntity', () => {+ it('renames a media through its own route, which renames the file', async () => {+ await renameEntity('case-1', media, ' Gate at dawn ');+ expect(api.patch).toHaveBeenCalledWith('/api/cases/case-1/media', { path: 'media/a.jpg', title: 'Gate at dawn' });+ });++ it('renames a capture through the satellite route, as Details does', async () => {+ await renameEntity('case-1', capture, 'North pier');+ expect(api.patch).toHaveBeenCalledWith('/api/cases/case-1/satellite', { path: 'media/cap.png', title: 'North pier' });+ });++ it('renames anything else by its label, which moves a note or a proof file server-side', async () => {+ await renameEntity('case-1', note, 'Summary');+ expect(api.patch).toHaveBeenCalledWith('/api/cases/case-1/entities/n1', { label: 'Summary' });+ });++ it('does nothing for an empty name', async () => {+ await renameEntity('case-1', note, ' ');+ expect(api.patch).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/lib/folders.js b/frontend/src/lib/folders.jsnew file mode 100644index 0000000..97bbec1--- /dev/null+++ b/frontend/src/lib/folders.js@@ -0,0 +1,103 @@+/**+ * Folder actions shared by Files and the case sidebar: renaming a folder,+ * removing one, and the case's work folder. One wording and one Undo, whichever+ * of the two surfaces the analyst pressed them in.+ *+ * Each call reloads the case: the folder list, the sidebar's counts and every+ * picker read it from there.+ */+import { api } from './api.js';+import { caseState, reloadCase, toast, uiState } from './state.svelte.js';++export const leafOf = (path) => (path ?? '').split('/').pop();+export const parentOf = (path) => (path ?? '').split('/').slice(0, -1).join('/');++/** The folder new files and saved work land in, or null. */+export const workFolder = () => caseState.current?.work_folder ?? null;++/** The path and every folder above it, outermost first. */+export function ancestorsOf(path) {+ const segments = (path ?? '').split('/').filter(Boolean);+ return segments.map((_, i) => segments.slice(0, i + 1).join('/'));+}++/** True when `path` is `root` or sits under it. */+export const inSubtree = (path, root) => Boolean(path) && (path === root || path.startsWith(`${root}/`));++/**+ * Where a folder goes when its own name changes to `name`: same parent, new last+ * segment. Null when the name cannot be one segment, or does not change anything.+ */+export function renamedPath(path, name) {+ const leaf = (name ?? '').trim();+ if (!leaf || leaf.includes('/')) return null;+ const parent = parentOf(path);+ const target = parent ? `${parent}/${leaf}` : leaf;+ return target === path ? null : target;+}++/** Rename `source` to `target`, offering the way back on the toast. */+export async function renameFolder(caseId, source, target) {+ await api.post(`/api/cases/${caseId}/folders/rename`, { source, target });+ await reloadCase();+ toast(`Renamed to ${leafOf(target)}`, 'ok', 6000, {+ label: 'Undo',+ onClick: async () => {+ try {+ await api.post(`/api/cases/${caseId}/folders/rename`, { source: target, target: source });+ await reloadCase();+ } catch (e) {+ toast(e.message, 'danger');+ }+ },+ });+}++/** Drop a folder and its subfolders. Its items are unfiled by the server. */+export async function removeFolder(caseId, path) {+ await api.del(`/api/cases/${caseId}/folders?name=${encodeURIComponent(path)}`);+ await reloadCase();+}++/** Work in `folder`, or stop with null. */+export async function setWorkFolder(caseId, folder) {+ await api.put(`/api/cases/${caseId}/work-folder`, { folder: folder || null });+ await reloadCase();+}++/** The confirmation both surfaces show before removing a folder. */+export function removeFolderPrompt(path, folders) {+ const subs = folders.filter((f) => f.startsWith(`${path}/`)).length;+ return {+ title: 'Remove this folder?',+ message: subs+ ? `“${leafOf(path)}” and its ${subs} subfolder${subs === 1 ? '' : 's'} will be removed.`+ : `“${leafOf(path)}” will be removed.`,+ detail: 'Items inside are unfiled. No files are deleted.',+ confirmLabel: 'Remove folder',+ tone: 'default',+ icon: 'folderMinus',+ };+}++/**+ * Say that something was filed, and where, when the work folder took it.+ *+ * Nothing was asked on the way in (an upload, a download, a quick place, the+ * extension), so the toast is the one place the analyst hears which folder it+ * went to, and its Move is the way out when it was filed for another thread.+ * `lead` reads before the folder ("2 files filed"); `fallback` is the message+ * when no work folder was involved. A toast that already offers something+ * (`action`) keeps it and names the folder in its words only.+ */+export function filedToast(lead, entities, { fallback = lead, action = null, timeout = 3800 } = {}) {+ const folder = workFolder();+ const filed = (entities ?? []).filter(Boolean);+ if (!folder || !filed.length || !filed.every((e) => e.attrs?.folder === folder)) {+ return toast(fallback, 'ok', action ? Math.max(timeout, 6000) : timeout, action);+ }+ return toast(`${lead} in ${leafOf(folder)}`, 'ok', 7000, action ?? {+ label: 'Move',+ onClick: () => (uiState.moving = filed),+ });+}diff --git a/frontend/src/lib/folders.test.js b/frontend/src/lib/folders.test.jsnew file mode 100644index 0000000..267c5cb--- /dev/null+++ b/frontend/src/lib/folders.test.js@@ -0,0 +1,123 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const post = vi.fn().mockResolvedValue([]);+const put = vi.fn().mockResolvedValue({});+const del = vi.fn().mockResolvedValue([]);+const get = vi.fn();+vi.mock('./api.js', () => ({+ api: {+ post: (...a) => post(...a),+ put: (...a) => put(...a),+ del: (...a) => del(...a),+ get: (...a) => get(...a),+ },+}));++const { caseState, uiState } = await import('./state.svelte.js');+const folders = await import('./folders.js');+const {+ ancestorsOf, filedToast, inSubtree, leafOf, parentOf, removeFolder, removeFolderPrompt,+ renameFolder, renamedPath, setWorkFolder, workFolder,+} = folders;++beforeEach(() => {+ post.mockClear();+ put.mockClear();+ del.mockClear();+ caseState.current = { id: 'c1', name: 'Case', folders: [], work_folder: null };+ get.mockImplementation(async () => ({ ...caseState.current }));+ uiState.toasts = [];+ uiState.moving = null;+});++describe('paths', () => {+ it('names a folder by its last segment and finds its parent', () => {+ expect(leafOf('Airbase/North')).toBe('North');+ expect(parentOf('Airbase/North')).toBe('Airbase');+ expect(parentOf('Airbase')).toBe('');+ expect(ancestorsOf('A/B/C')).toEqual(['A', 'A/B', 'A/B/C']);+ });++ it('tells a subfolder from a folder that only starts with the same letters', () => {+ expect(inSubtree('Air/North', 'Air')).toBe(true);+ expect(inSubtree('Air', 'Air')).toBe(true);+ expect(inSubtree('Airbase', 'Air')).toBe(false);+ expect(inSubtree('', 'Air')).toBe(false);+ });++ it('renames in place: same parent, one new segment, and nothing when unchanged', () => {+ expect(renamedPath('Airbase/North', ' Hangars ')).toBe('Airbase/Hangars');+ expect(renamedPath('Airbase', 'Isfahan')).toBe('Isfahan');+ expect(renamedPath('Airbase', 'Airbase')).toBeNull();+ expect(renamedPath('Airbase', ' ')).toBeNull();+ expect(renamedPath('Airbase', 'a/b')).toBeNull();+ });+});++describe('folder actions', () => {+ it('renames, then offers the way back on the toast', async () => {+ await renameFolder('c1', 'Airbase', 'Isfahan');+ expect(post).toHaveBeenCalledWith('/api/cases/c1/folders/rename', { source: 'Airbase', target: 'Isfahan' });+ const toast = uiState.toasts.at(-1);+ expect(toast.message).toBe('Renamed to Isfahan');+ await toast.action.onClick();+ expect(post).toHaveBeenLastCalledWith('/api/cases/c1/folders/rename', { source: 'Isfahan', target: 'Airbase' });+ });++ it('removes a folder through the server and reloads the case', async () => {+ await removeFolder('c1', 'Air base');+ expect(del).toHaveBeenCalledWith('/api/cases/c1/folders?name=Air%20base');+ expect(get).toHaveBeenCalledWith('/api/cases/c1');+ });++ it('asks before removing, counting the subfolders that go with it', () => {+ const prompt = removeFolderPrompt('Air', ['Air', 'Air/N', 'Air/S', 'Airbase']);+ expect(prompt.message).toBe('“Air” and its 2 subfolders will be removed.');+ expect(prompt.detail).toBe('Items inside are unfiled. No files are deleted.');+ expect(removeFolderPrompt('Airbase', ['Airbase']).message).toBe('“Airbase” will be removed.');+ });++ it('sets the work folder, and clears it with an empty one', async () => {+ await setWorkFolder('c1', 'Airbase');+ expect(put).toHaveBeenLastCalledWith('/api/cases/c1/work-folder', { folder: 'Airbase' });+ await setWorkFolder('c1', '');+ expect(put).toHaveBeenLastCalledWith('/api/cases/c1/work-folder', { folder: null });+ });++ it('reads the work folder off the open case', () => {+ expect(workFolder()).toBeNull();+ caseState.current = { ...caseState.current, work_folder: 'Airbase' };+ expect(workFolder()).toBe('Airbase');+ });+});++describe('filedToast', () => {+ const filed = { id: 'e1', attrs: { folder: 'Air/North' } };++ it('says the plain thing when no work folder took it', () => {+ filedToast('2 files filed', [filed], { fallback: '2 files added to the case' });+ expect(uiState.toasts.at(-1)).toMatchObject({ message: '2 files added to the case', action: null });+ });++ it('names the work folder and offers Move when it took everything', () => {+ caseState.current = { ...caseState.current, work_folder: 'Air/North' };+ filedToast('2 files filed', [filed, { id: 'e2', attrs: { folder: 'Air/North' } }]);+ const toast = uiState.toasts.at(-1);+ expect(toast.message).toBe('2 files filed in North');+ toast.action.onClick();+ expect(uiState.moving.map((e) => e.id)).toEqual(['e1', 'e2']);+ });++ it('does not claim the work folder for what landed elsewhere', () => {+ caseState.current = { ...caseState.current, work_folder: 'Air/North' };+ filedToast('Image filed', [{ id: 'e3', attrs: { folder: '' } }], { fallback: 'Image added to the case' });+ expect(uiState.toasts.at(-1).message).toBe('Image added to the case');+ });++ it('keeps an offer the toast already makes', () => {+ caseState.current = { ...caseState.current, work_folder: 'Air/North' };+ const offer = { label: 'Set source', onClick: () => {} };+ filedToast('1 file filed', [filed], { action: offer });+ expect(uiState.toasts.at(-1)).toMatchObject({ message: '1 file filed in North', action: offer });+ });+});diff --git a/frontend/src/lib/graphPlate.js b/frontend/src/lib/graphPlate.jsindex 8c9eede..57626c2 100644--- a/frontend/src/lib/graphPlate.js+++ b/frontend/src/lib/graphPlate.js@@ -145,7 +145,7 @@ export function graphDrawing({// A proposal is drawn as one everywhere it appears (ONTOLOGY §4)....(data.status === 'suggested' ? { dash: '3 3' } : {}),}));- names.push(svgText(shortLabel(data.label ?? node.id), {+ names.push(svgText(shortLabel(data.caption ?? data.label ?? node.id), {// Konva places a text box by its top; SVG by its baseline, hence the drop.x: at.x, y: at.y + radius + 14, size: 11, anchor: 'middle',fill: PLATE_COLOURS.label, halo: 3,diff --git a/frontend/src/lib/graphPlate.test.js b/frontend/src/lib/graphPlate.test.jsindex 8c01ae4..daee800 100644--- a/frontend/src/lib/graphPlate.test.js+++ b/frontend/src/lib/graphPlate.test.js@@ -68,6 +68,16 @@ describe('serialising the graph', () => {expect(body).not.toContain('White pickup with a very long name indeed');});+ it('writes a point named by its coordinates by the town the drawing names it', () => {+ const nodes = NODES.map((node) =>+ node.id === 'e_quay' ? { ...node, label: '16.98, 45.05', caption: '96 km N of Al Hazm' } : node,+ );+ const { body } = graphDrawing(scene({ byId: new Map(nodes.map((node) => [node.id, node])) }));++ expect(body).toContain('96 km N of Al Hazm');+ expect(body).not.toContain('16.98, 45.05');+ });+it('haloes the names and the verbs, which is what makes them readable on the lines', () => {const { body } = graphDrawing(scene());// The canvas does the same with `fillAfterStrokeEnabled`; without it every namediff --git a/frontend/src/lib/guide.js b/frontend/src/lib/guide.jsindex 854f92a..6bdb10e 100644--- a/frontend/src/lib/guide.js+++ b/frontend/src/lib/guide.js@@ -314,6 +314,10 @@ export const GUIDE = [label: 'Draw these N hands over the question',text: 'The Graph receives the filter rather than the rows it matched, so the drawing answers at any case size and stays live as the case changes.',},+ {+ label: 'The case proposes the links its files state',+ text: 'Who posted a file, read off its address, and points under 300 m apart are filed as proposals. N proposed in the Graph lists them to confirm or drop.',+ },{label: 'The Graph never writes to the case',text: 'Expanding, hiding, folding and dragging are your picture. Undo reaches all of them and reaches nothing the case holds.',@@ -332,7 +336,7 @@ export const GUIDE = [},{label: 'Sheet works on real CSV files',- text: 'The sheets the case holds, in a grid. A declared sheet can be promoted into entities, places and dated claims, read as a plan first.',+ text: 'The tab opens on the recent sheets and the ones the case could start, like Files to geolocate. A declared sheet can be promoted into entities, places and dated claims, read as a plan first.',},],},diff --git a/frontend/src/lib/mediaImport.js b/frontend/src/lib/mediaImport.jsnew file mode 100644index 0000000..7a6cadd--- /dev/null+++ b/frontend/src/lib/mediaImport.js@@ -0,0 +1,32 @@+/**+ * Upload a batch of files into the case, one request each, so one refusal does+ * not lose the rest. Shared by the Media Library's Import and Files' Import here.+ *+ * Does not reload the case or toast: the caller says what landed, and where.+ */+import { api } from './api.js';++/** `{ landed, filed, duplicates, failed }`: paths, their entities, the count of+ * bytes the case already held, and `{ name, message }` for each refusal. */+export async function uploadFiles(caseId, files, sourceUrl = '') {+ const landed = [];+ const filed = [];+ const failed = [];+ let duplicates = 0;+ for (const file of files) {+ const form = new FormData();+ form.append('file', file);+ if (sourceUrl) form.append('source_url', sourceUrl);+ try {+ const res = await api.post(`/api/cases/${caseId}/media/upload`, form);+ if (res.duplicate) duplicates++;+ else if (res.item?.path) {+ landed.push(res.item.path);+ filed.push(res.entity);+ }+ } catch (e) {+ failed.push({ name: file.name, message: e.message });+ }+ }+ return { landed, filed, duplicates, failed };+}diff --git a/frontend/src/lib/mediaImport.test.js b/frontend/src/lib/mediaImport.test.jsnew file mode 100644index 0000000..acd3262--- /dev/null+++ b/frontend/src/lib/mediaImport.test.js@@ -0,0 +1,43 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const post = vi.fn();+vi.mock('./api.js', () => ({ api: { post: (...a) => post(...a) } }));++const { uploadFiles } = await import('./mediaImport.js');++const file = (name) => new File(['x'], name, { type: 'image/png' });++beforeEach(() => post.mockReset());++describe('uploadFiles', () => {+ it('sends the stated origin with every file of the batch', async () => {+ post.mockResolvedValue({ duplicate: false, item: { path: 'media/a.png' }, entity: { id: 'e1' } });+ await uploadFiles('c1', [file('a.png'), file('b.png')], 'https://example.org/thread');+ expect(post).toHaveBeenCalledTimes(2);+ for (const [url, form] of post.mock.calls) {+ expect(url).toBe('/api/cases/c1/media/upload');+ expect(form.get('source_url')).toBe('https://example.org/thread');+ }+ });++ it('sends no origin when none was stated', async () => {+ post.mockResolvedValue({ duplicate: false, item: { path: 'media/a.png' }, entity: { id: 'e1' } });+ await uploadFiles('c1', [file('a.png')]);+ expect(post.mock.calls[0][1].has('source_url')).toBe(false);+ });++ it('keeps going past a refusal and says what landed, what was known, what failed', async () => {+ post+ .mockResolvedValueOnce({ duplicate: false, item: { path: 'media/a.png' }, entity: { id: 'e1' } })+ .mockResolvedValueOnce({ duplicate: true, item: { path: 'media/old.png' }, entity: { id: 'e0' } })+ .mockRejectedValueOnce(new Error('too large'))+ .mockResolvedValueOnce({ duplicate: false, item: { path: 'media/d.png' }, entity: { id: 'e4' } });+ const result = await uploadFiles('c1', ['a', 'b', 'c', 'd'].map((n) => file(`${n}.png`)));+ expect(result).toEqual({+ landed: ['media/a.png', 'media/d.png'],+ filed: [{ id: 'e1' }, { id: 'e4' }],+ duplicates: 1,+ failed: [{ name: 'c.png', message: 'too large' }],+ });+ });+});diff --git a/frontend/src/lib/navigate.js b/frontend/src/lib/navigate.jsindex d23bf4e..5987c62 100644--- a/frontend/src/lib/navigate.js+++ b/frontend/src/lib/navigate.js@@ -105,6 +105,22 @@ export function openClaim(item) {uiState.tool = 'timeline';}+/**+ * Read an entity on the Timeline: what is dated about it, with `item` (one of its+ * entries) selected when given.+ */+export function openInTimeline(entity, item = null) {+ uiState.timelineFocus = {+ entityId: entity.id,+ entityLabel: entity.label,+ entityType: entity.type,+ entityAttrs: entity.attrs ?? {},+ itemId: item?.id ?? null,+ producedHere: item?.produced_here === true,+ };+ uiState.tool = 'timeline';+}+/** Reopen an artifact in its tool, loading whatever spec/draft it carries. */export function openEntity(entity, resolved = false) {// Places navigate by coordinates, so resolve an old snapshot's id before flying.diff --git a/frontend/src/lib/navigate.test.js b/frontend/src/lib/navigate.test.jsindex 28cd2e3..add0d00 100644--- a/frontend/src/lib/navigate.test.js+++ b/frontend/src/lib/navigate.test.js@@ -5,7 +5,7 @@ const get = vi.fn();vi.mock('./api.js', () => ({ api: { post: (...a) => post(...a), get: (...a) => get(...a) } }));const { caseState, uiState } = await import('./state.svelte.js');-const { gotoCapture, gotoPoint, openComparison, openEntity, openGuide, openInReverseSearch, openMapAt, opensInFileManager } =+const { gotoCapture, gotoPoint, openComparison, openEntity, openGuide, openInReverseSearch, openInTimeline, openMapAt, opensInFileManager } =await import('./navigate.js');beforeEach(() => {@@ -21,6 +21,28 @@ beforeEach(() => {vi.stubGlobal('window', { open: vi.fn() });});+describe('openInTimeline', () => {+ it('scopes the Timeline to the entity and selects the entry it was pressed on', () => {+ const entity = { id: 'm1', label: 'Frame', type: 'media', attrs: { path: 'media/f.png' } };+ openInTimeline(entity, { id: 'event-a', produced_here: true });+ expect(uiState.tool).toBe('timeline');+ expect(uiState.timelineFocus).toEqual({+ entityId: 'm1',+ entityLabel: 'Frame',+ entityType: 'media',+ entityAttrs: { path: 'media/f.png' },+ itemId: 'event-a',+ // a working file says so, or a Media track holding them back would hide the row+ producedHere: true,+ });+ });++ it('opens on the whole entity when no entry is named', () => {+ openInTimeline({ id: 'p1', label: 'Pier', type: 'place' });+ expect(uiState.timelineFocus).toMatchObject({ entityId: 'p1', itemId: null, producedHere: false, entityAttrs: {} });+ });+});+describe('openGuide', () => {it('lands on the section written about the tab the mark was pressed from', () => {openGuide('satellite');diff --git a/frontend/src/lib/openIn.js b/frontend/src/lib/openIn.jsnew file mode 100644index 0000000..708cc85--- /dev/null+++ b/frontend/src/lib/openIn.js@@ -0,0 +1,35 @@+/**+ * The tools a picture or a video can be taken on to, as one list for every menu+ * that offers them: the Media Library's "Open in…" door and Files' right-click.+ * Labels come from `TOOL_LABELS`, keyed by the option's id.+ */+import { uiState } from './state.svelte.js';+import { openInReverseSearch } from './navigate.js';++/** `file` is `{ path, kind, label }`. Anything but a picture or a video has none. */+export function openInOptions(file) {+ if (!file?.path || (file.kind !== 'image' && file.kind !== 'video')) return [];+ return [+ {+ id: 'inspect',+ icon: 'inspect',+ run: () => {+ uiState.inspectPath = file.path;+ uiState.tool = 'inspect';+ },+ },+ { id: 'reverse', icon: 'search', run: () => openInReverseSearch(file) },+ ...(file.kind === 'image'+ ? [+ {+ id: 'proof',+ icon: 'proof',+ run: () => {+ if (!uiState.composeQueue.includes(file.path)) uiState.composeQueue.push(file.path);+ uiState.tool = 'proof';+ },+ },+ ]+ : []),+ ];+}diff --git a/frontend/src/lib/proposalReview.js b/frontend/src/lib/proposalReview.jsnew file mode 100644index 0000000..dbba58a--- /dev/null+++ b/frontend/src/lib/proposalReview.js@@ -0,0 +1,52 @@+/**+ * The words the proposal review reads in (`components/ProposalReview.svelte`).+ *+ * A proposal is shown as the sentence it stands for, so a line reads the way the graph+ * would say it: who posted what, which two points are one site and how far apart.+ */++/** How many proposals are waiting: the edges, since an account waits on its edges. */+export function waitingCount(pending) {+ return (pending?.posted ?? 0) + (pending?.sites ?? 0);+}++/** One proposal as a sentence. */+export function proposalSentence(item) {+ if (item?.type === 'posted') return `${item.from.label} posted ${item.to.label}`;+ if (item?.type === 'same-site-as') {+ const apart = Number.isFinite(item.metres) ? `, ${item.metres} m apart` : '';+ return `${item.from.label} and ${item.to.label} are one site${apart}`;+ }+ return `${item?.from?.label ?? ''} → ${item?.to?.label ?? ''}`;+}++/** What one pass filed, as the toast says it. */+export function filedWords(filed) {+ const parts = [];+ if (filed?.accounts) parts.push(`${filed.accounts} ${filed.accounts === 1 ? 'account' : 'accounts'}`);+ if (filed?.posted) parts.push(`${filed.posted} posted ${filed.posted === 1 ? 'link' : 'links'}`);+ if (filed?.sites) parts.push(`${filed.sites} same-site ${filed.sites === 1 ? 'link' : 'links'}`);+ return parts.length ? `Proposed ${parts.join(', ')}.` : 'Nothing new to propose.';+}++/**+ * What a saved geolocation shares with the rest of the case, as one line+ * (`GET /entities/{id}/kin`). Null when it shares nothing, so no line is drawn.+ */+export function kinSentence(kin) {+ if (!kin) return null;+ const parts = [];+ const sites = kin.sites?.length ?? 0;+ const places = kin.places?.length ?? 0;+ if (sites) {+ parts.push(`On the same site as ${sites} other ${sites === 1 ? 'geolocation' : 'geolocations'}`);+ } else if (places) {+ parts.push(`${places} other ${places === 1 ? 'point' : 'points'} of the case within ${kin.radius ?? 300} m`);+ }+ for (const account of kin.accounts ?? []) {+ if (account.files) {+ parts.push(`${account.label} posted ${account.files} other ${account.files === 1 ? 'file' : 'files'} here`);+ }+ }+ return parts.length ? parts.join(' · ') : null;+}diff --git a/frontend/src/lib/proposalReview.test.js b/frontend/src/lib/proposalReview.test.jsnew file mode 100644index 0000000..e676e5d--- /dev/null+++ b/frontend/src/lib/proposalReview.test.js@@ -0,0 +1,53 @@+import { describe, expect, it } from 'vitest';++import { filedWords, proposalSentence, waitingCount } from './proposalReview.js';++describe('the proposal review words', () => {+ it('counts the edges waiting, not the accounts behind them', () => {+ expect(waitingCount({ accounts: 3, posted: 5, sites: 2 })).toBe(7);+ expect(waitingCount(null)).toBe(0);+ });++ it('reads each proposal as the sentence it stands for', () => {+ expect(+ proposalSentence({ type: 'posted', from: { label: '@BashaReport' }, to: { label: 'clip.mp4' } }),+ ).toBe('@BashaReport posted clip.mp4');+ expect(+ proposalSentence({+ type: 'same-site-as', from: { label: 'Hangar' }, to: { label: 'Runway' }, metres: 110,+ }),+ ).toBe('Hangar and Runway are one site, 110 m apart');+ });++ it('says what a pass filed, or that it found nothing', () => {+ expect(filedWords({ accounts: 1, posted: 2, sites: 1 })).toBe(+ 'Proposed 1 account, 2 posted links, 1 same-site link.',+ );+ expect(filedWords({ accounts: 0, posted: 0, sites: 0 })).toBe('Nothing new to propose.');+ });+});++describe('what a saved geolocation shares', () => {+ it('names the other geolocations on its site and what its account posted', async () => {+ const { kinSentence } = await import('./proposalReview.js');+ expect(+ kinSentence({+ sites: ['p1', 'p2'], places: ['a', 'b', 'c'], radius: 300,+ accounts: [{ label: '@BashaReport', files: 3 }, { label: '@quiet', files: 0 }],+ }),+ ).toBe('On the same site as 2 other geolocations · @BashaReport posted 3 other files here');+ });++ it('falls back to the points within reach when no other proof is there', async () => {+ const { kinSentence } = await import('./proposalReview.js');+ expect(kinSentence({ sites: [], places: ['a'], radius: 300, accounts: [] })).toBe(+ '1 other point of the case within 300 m',+ );+ });++ it('draws no line when it shares nothing', async () => {+ const { kinSentence } = await import('./proposalReview.js');+ expect(kinSentence({ sites: [], places: [], accounts: [{ label: '@x', files: 0 }] })).toBeNull();+ expect(kinSentence(null)).toBeNull();+ });+});diff --git a/frontend/src/lib/sheetHome.js b/frontend/src/lib/sheetHome.jsnew file mode 100644index 0000000..a94c05a--- /dev/null+++ b/frontend/src/lib/sheetHome.js@@ -0,0 +1,70 @@+/**+ * What the Sheet tab opens on: the sheets being worked on, and the sheets this case+ * could start right now.+ *+ * A tab that reopened the last sheet answered "where was I" and nothing else, and a case+ * with no sheet opened on an empty state listing what a sheet is for. Neither said that+ * the case already holds the makings of one: twenty files imported and not yet placed is+ * a worklist, eight proofs is an index. So the home leads with those, counted.+ */++/** The shapes the case builds by itself, and what each one is called on the home. */+export const CASE_SHAPES = {+ files: {+ title: 'Files to geolocate',+ hint: 'One row per picture or video you imported. A proof marks it done.',+ },+ proofs: {+ title: 'My geolocations',+ hint: 'One row per point of every proof, POV or not, with its date and source.',+ },+};++/** Newest edit first, with the sheet last opened here leading. */+export function recentSheets(sheets, lastId = null) {+ const stamp = (sheet) => sheet.modified_at ?? sheet.created_at ?? '';+ const ordered = [...(sheets ?? [])].sort((a, b) => stamp(b).localeCompare(stamp(a)));+ const at = ordered.findIndex((sheet) => sheet.id === lastId);+ if (at > 0) ordered.unshift(...ordered.splice(at, 1));+ return ordered;+}++/** The progress column's reading, in the footer's own words. */+export function progressWords(progress) {+ if (!progress || !progress.total) return '';+ const verb = progress.kind === 'state' ? 'done' : 'filled';+ return `${progress.count} of ${progress.total} ${verb}`;+}++/**+ * The sheets this case could start, each with what it would hold.+ *+ * `files` is the server's preview (`GET /sheets/from-case/files`), `proofs` how many+ * proofs the case holds. A shape the case has nothing for is not offered, and one+ * already built is opened rather than built twice: the second press is somebody going+ * back to their worklist, not asking for a twin of it.+ */+export function caseProposals({ files = null, proofs = 0, sheets = [] } = {}) {+ const built = (shape) => (sheets ?? []).find((sheet) => sheet.shape === shape)?.id ?? null;+ const out = [];+ if (files?.total) {+ const left = files.total - (files.answered ?? 0);+ out.push({+ shape: 'files',+ ...CASE_SHAPES.files,+ detail:+ `${files.total} imported ${files.total === 1 ? 'file' : 'files'}, ` ++ (left ? `${left} without a proof` : 'every one with a proof'),+ open: files.sheet ?? built('files'),+ });+ }+ if (proofs) {+ out.push({+ shape: 'proofs',+ ...CASE_SHAPES.proofs,+ detail: `${proofs} ${proofs === 1 ? 'proof' : 'proofs'}`,+ open: built('proofs'),+ });+ }+ return out;+}diff --git a/frontend/src/lib/sheetHome.test.js b/frontend/src/lib/sheetHome.test.jsnew file mode 100644index 0000000..713c9fe--- /dev/null+++ b/frontend/src/lib/sheetHome.test.js@@ -0,0 +1,66 @@+import { describe, expect, it } from 'vitest';++import { caseProposals, progressWords, recentSheets } from './sheetHome.js';++describe('recentSheets', () => {+ const sheets = [+ { id: 'a', modified_at: '2026-09-01T00:00:00Z' },+ { id: 'b', modified_at: '2026-09-30T00:00:00Z' },+ { id: 'c', created_at: '2026-09-15T00:00:00Z' },+ ];++ it('puts the newest edit first, and falls back to when it was filed', () => {+ expect(recentSheets(sheets).map((sheet) => sheet.id)).toEqual(['b', 'c', 'a']);+ });++ it('leads with the sheet last open', () => {+ expect(recentSheets(sheets, 'a').map((sheet) => sheet.id)).toEqual(['a', 'b', 'c']);+ });++ it('ignores a last sheet that is gone', () => {+ expect(recentSheets(sheets, 'gone').map((sheet) => sheet.id)).toEqual(['b', 'c', 'a']);+ });+});++describe('progressWords', () => {+ it('says done for a status column and filled for any other', () => {+ expect(progressWords({ kind: 'state', count: 8, total: 21 })).toBe('8 of 21 done');+ expect(progressWords({ kind: 'fill', count: 3, total: 4 })).toBe('3 of 4 filled');+ });++ it('says nothing about an empty sheet or one with no progress column', () => {+ expect(progressWords(null)).toBe('');+ expect(progressWords({ kind: 'state', count: 0, total: 0 })).toBe('');+ });+});++describe('caseProposals', () => {+ it('offers the files worklist with how many still lack a proof', () => {+ const [files] = caseProposals({ files: { total: 21, answered: 8, sheet: null } });+ expect(files.shape).toBe('files');+ expect(files.detail).toBe('21 imported files, 13 without a proof');+ expect(files.open).toBeNull();+ });++ it('says so when every file is answered', () => {+ const [files] = caseProposals({ files: { total: 2, answered: 2 } });+ expect(files.detail).toBe('2 imported files, every one with a proof');+ });++ it('opens a shape already built rather than offering a twin', () => {+ const answer = caseProposals({+ files: { total: 3, answered: 0, sheet: 'e_list' },+ proofs: 4,+ sheets: [{ id: 'e_index', shape: 'proofs' }],+ });+ expect(answer.map((proposal) => [proposal.shape, proposal.open])).toEqual([+ ['files', 'e_list'],+ ['proofs', 'e_index'],+ ]);+ });++ it('offers nothing the case has nothing for', () => {+ expect(caseProposals({ files: { total: 0 }, proofs: 0 })).toEqual([]);+ expect(caseProposals()).toEqual([]);+ });+});diff --git a/frontend/src/lib/sidebar.js b/frontend/src/lib/sidebar.jsindex 8e96ef1..42ec09d 100644--- a/frontend/src/lib/sidebar.js+++ b/frontend/src/lib/sidebar.js@@ -14,3 +14,24 @@ export const { maxWidth, clampWidth, loadWidth, saveWidth } = panelWidth({max: MAX_W,def: DEFAULT_W,});++/** What the sidebar body shows. Folders first: it is what it showed before. */+export const SIDEBAR_VIEWS = ['folders', 'todo', 'recent'];+const VIEW_KEY = 'azimut:sidebarView';++export function loadSidebarView() {+ try {+ const stored = localStorage.getItem(VIEW_KEY);+ return SIDEBAR_VIEWS.includes(stored) ? stored : 'folders';+ } catch {+ return 'folders';+ }+}++export function saveSidebarView(view) {+ try {+ localStorage.setItem(VIEW_KEY, view);+ } catch {+ /* a browser that keeps nothing still switches; it just forgets on reload */+ }+}diff --git a/frontend/src/lib/state.svelte.js b/frontend/src/lib/state.svelte.jsindex 4c2b8e4..1e9f808 100644--- a/frontend/src/lib/state.svelte.js+++ b/frontend/src/lib/state.svelte.js@@ -7,7 +7,7 @@*/import { api } from './api.js';import { formatCoords as renderCoords } from './coords.js';-import { loadWidth, saveWidth, clampWidth } from './sidebar.js';+import { loadWidth, saveWidth, clampWidth, loadSidebarView } from './sidebar.js';import { loadTheme, saveTheme, applyTheme } from './theme.js';import { shouldShowUpdate } from './appUpdate.js';import { extensionVersion, pingExtensions, extensionState } from './extBridge.js';@@ -236,6 +236,7 @@ export const uiState = $state({theme: loadTheme(), // 'dark' | 'light'; index.html stamps it before first paintsidebarOpen: true,sidebarW: loadWidth(), // px, drag-resizable and remembered across reloads+ sidebarView: loadSidebarView(), // 'folders' | 'todo' | 'recent', remembered across reloadstoasts: [],settingsTab: null, // settings section id to open when switching to Settings// Guide section to land on when switching to the Guide, from the `?` in the@@ -279,6 +280,8 @@ export const uiState = $state({* of `openBoardEntity`: a node has to be reachable from the row as much as a row* from the node. */openGraphEntity: null,+ /** A sheet id the Sheet tab should open instead of its home. Consumed once. */+ openSheet: null,/** Entity/item handed to Timeline from Details. Timeline consumes and clears it. */timelineFocus: null, // { entityId, entityLabel, itemId, producedHere }/** A fact-time range handed back to Timeline. Consumed once, never persisted. */@@ -287,6 +290,9 @@ export const uiState = $state({timelineQueue: null, // 'undated', or { queue: 'undated' | 'unplaced', itemId, item }/** Whether the Add event bar is open over the tool on screen. Session only. */noting: false,+ /** Entities the Move to… dialog is open on, from Files, the sidebar or a toast+ * that filed something into the work folder. Session only. */+ moving: null,/** Bumped to send the Timeline to its own entry line, which is the Add event bar* the Timeline already has. */timelineLineFocus: 0,@@ -599,10 +605,12 @@ function clearCaseHandoffs() {uiState.drawInGraph = null;uiState.openBoardEntity = null;uiState.openGraphEntity = null;+ uiState.openSheet = null;uiState.timelineFocus = null;uiState.timelineRange = null;uiState.timelineQueue = null;uiState.noting = false;+ uiState.moving = null;uiState.mapTimelineRange = null;uiState.gotoCoords = null;uiState.lookAt = null;diff --git a/frontend/src/lib/timeline.js b/frontend/src/lib/timeline.jsindex 8485baa..a8138de 100644--- a/frontend/src/lib/timeline.js+++ b/frontend/src/lib/timeline.js@@ -1013,6 +1013,30 @@ export function layoutTimelineItems(items, from, to, axisWidth = 1000, maxItemRo};}+/**+ * How many rows of marks each lane may take before the rest go to a `+N`, out of the+ * `room` rows the axis has. `needs` is what each lane would take uncapped, `null` for+ * one that is not shared out (opened, or folded). A lane that needs little takes only+ * that; the rest is split evenly among those that need more, and none gets under+ * `floor`, so a short axis reads as it always did.+ */+export function shareItemRows(needs, room, floor = 6) {+ const caps = needs.map(() => null);+ const order = needs+ .map((need, index) => ({ need, index }))+ .filter((one) => one.need !== null)+ .sort((a, b) => a.need - b.need);+ let left = Math.max(0, Math.floor(room));+ order.forEach(({ need, index }, at) => {+ const fair = Math.floor(left / (order.length - at));+ const cap = Math.max(floor, Math.min(need, fair));+ caps[index] = cap;+ // A lane under the floor keeps the floor but only uses what it needs.+ left = Math.max(0, left - Math.min(need, cap));+ });+ return caps;+}+/** The top of a card row under a track's marks, in pixels from the top of the track. */export function cardTop(layout, row) {return MARKS.top + layout.rows * MARKS.row + 6 + row * (MARKS.cardHeight + 6);diff --git a/frontend/src/lib/timeline.test.js b/frontend/src/lib/timeline.test.jsindex 4c01604..80410f1 100644--- a/frontend/src/lib/timeline.test.js+++ b/frontend/src/lib/timeline.test.js@@ -30,6 +30,7 @@ import {offsetLabel,layoutDensityBuckets,layoutTimelineItems,+ shareItemRows,moveTemporalRaw,nudgeTemporalRaw,resizeTemporalRaw,@@ -731,3 +732,24 @@ describe('two dated pictures', () => {expect(temporalKindLabel('something-new')).toBe('something-new');});});++describe('rows shared by the lanes', () => {+ it('gives a lane that needs little only that, and the rest to the crowded one', () => {+ expect(shareItemRows([3, 30], 25)).toEqual([6, 22]);+ expect(shareItemRows([3, 3, 30], 25)).toEqual([6, 6, 19]);+ expect(shareItemRows([3, 12], 25)).toEqual([6, 12]);+ });++ it('splits evenly between lanes that all need more than the room', () => {+ expect(shareItemRows([30, 30], 20)).toEqual([10, 10]);+ });++ it('never goes under the floor on a short axis', () => {+ expect(shareItemRows([30, 30], 4)).toEqual([6, 6]);+ expect(shareItemRows([30], -10)).toEqual([6]);+ });++ it('leaves out the lanes it is not asked about', () => {+ expect(shareItemRows([null, 30], 20)).toEqual([null, 20]);+ });+});diff --git a/frontend/src/lib/todos.svelte.js b/frontend/src/lib/todos.svelte.jsnew file mode 100644index 0000000..6a1c25d--- /dev/null+++ b/frontend/src/lib/todos.svelte.js@@ -0,0 +1,51 @@+/**+ * One copy of the open case's to-do lists, for every surface that shows them:+ * Home and the case sidebar. Each held its own copy before the sidebar had one,+ * and a tick in one would have made the other's next save a stale write.+ *+ * Saving sends the revision the copy was read at; the server refuses a write+ * over a newer one (another browser tab) with 409, and the copy then waits for+ * a reload rather than overwrite what it has not seen.+ */+import { api } from './api.js';++export const todos = $state({ caseId: null, data: null, busy: false, error: '', conflict: false });++const endpoint = (caseId) => `/api/cases/${encodeURIComponent(caseId)}/todos`;++export async function loadTodos(caseId) {+ if (todos.caseId !== caseId) {+ todos.caseId = caseId;+ todos.data = null;+ }+ todos.busy = true;+ todos.error = '';+ try {+ const data = await api.get(endpoint(caseId));+ if (todos.caseId !== caseId) return;+ todos.data = data;+ todos.conflict = false;+ } catch (e) {+ if (todos.caseId === caseId) todos.error = e.message;+ } finally {+ if (todos.caseId === caseId) todos.busy = false;+ }+}++/** Write `lists` over the copy; false when it was refused or not attempted. */+export async function saveTodos(caseId, lists) {+ if (todos.caseId !== caseId || !todos.data || todos.busy || todos.conflict) return false;+ todos.busy = true;+ todos.error = '';+ try {+ const saved = await api.put(endpoint(caseId), { revision: todos.data.revision, lists });+ if (todos.caseId === caseId) todos.data = saved;+ return true;+ } catch (e) {+ todos.error = e.message;+ todos.conflict = e.status === 409;+ return false;+ } finally {+ todos.busy = false;+ }+}diff --git a/frontend/src/lib/todos.test.js b/frontend/src/lib/todos.test.jsnew file mode 100644index 0000000..f79f287--- /dev/null+++ b/frontend/src/lib/todos.test.js@@ -0,0 +1,54 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const get = vi.fn();+const put = vi.fn();+vi.mock('./api.js', () => ({ api: { get: (...a) => get(...a), put: (...a) => put(...a) } }));++const { loadTodos, saveTodos, todos } = await import('./todos.svelte.js');++const lists = [{ id: 'default', name: 'Tasks', tasks: [] }];++beforeEach(() => {+ get.mockReset();+ put.mockReset();+ Object.assign(todos, { caseId: null, data: null, busy: false, error: '', conflict: false });+});++describe('the shared to-do copy', () => {+ it('is read once for every surface showing it', async () => {+ get.mockResolvedValue({ revision: 3, lists });+ await loadTodos('c1');+ expect(get).toHaveBeenCalledWith('/api/cases/c1/todos');+ expect(todos).toMatchObject({ caseId: 'c1', data: { revision: 3 }, busy: false });+ });++ it('saves at the revision it read, and keeps what the server answered', async () => {+ get.mockResolvedValue({ revision: 3, lists });+ put.mockImplementation(async (_url, body) => ({ ...body, revision: body.revision + 1 }));+ await loadTodos('c1');+ expect(await saveTodos('c1', [])).toBe(true);+ expect(put).toHaveBeenCalledWith('/api/cases/c1/todos', { revision: 3, lists: [] });+ expect(todos.data.revision).toBe(4);+ });++ it('stops writing after a newer revision refused it, until read again', async () => {+ get.mockResolvedValue({ revision: 3, lists });+ put.mockRejectedValueOnce(Object.assign(new Error('changed'), { status: 409 }));+ await loadTodos('c1');+ expect(await saveTodos('c1', [])).toBe(false);+ expect(todos.conflict).toBe(true);+ expect(await saveTodos('c1', [])).toBe(false);+ expect(put).toHaveBeenCalledTimes(1);+ await loadTodos('c1');+ expect(todos.conflict).toBe(false);+ });++ it('drops the previous case and never saves into the wrong one', async () => {+ get.mockResolvedValueOnce({ revision: 1, lists });+ await loadTodos('c1');+ get.mockReturnValueOnce(new Promise(() => {}));+ void loadTodos('c2');+ expect(todos.data).toBeNull();+ expect(await saveTodos('c1', [])).toBe(false);+ });+});diff --git a/frontend/src/tools/Detect.render.test.js b/frontend/src/tools/Detect.render.test.jsindex 26beb21..54c8cb4 100644--- a/frontend/src/tools/Detect.render.test.js+++ b/frontend/src/tools/Detect.render.test.js@@ -305,6 +305,8 @@ describe('Detect', () => {starts('One pass').click(); await settle();button('Use current view').click(); await settle();button('Next: What').click(); await settle();+ target.querySelector('.fold').click(); await settle();+ target.querySelector('[role="radio"]').click(); await settle();button('Next: When').click(); await settle();button('Find passes').click(); await settle();target.querySelector('[aria-label="Use 2026-09-26"] button:last-child').click(); await settle();diff --git a/frontend/src/tools/Files.svelte b/frontend/src/tools/Files.svelteindex 1a8bdf0..c2bd498 100644--- a/frontend/src/tools/Files.svelte+++ b/frontend/src/tools/Files.svelte@@ -12,10 +12,40 @@import { api } from '../lib/api.js';import { fileUrl } from '../lib/fileUrl.js';import { caseState, reloadCase, toast, uiState } from '../lib/state.svelte.js';- import { buildTree, subtreeCount, folderOf, flattenPaths, isInFolderSubtree } from '../lib/folderTree.js';- import { assignFolder, assignFolderBatch } from '../lib/filing.js';+ import {+ buildTree,+ subtreeCount,+ subtreeCountFrom,+ folderOf,+ flattenPaths,+ isInFolderSubtree,+ } from '../lib/folderTree.js';+ import { assignFolder, assignFolderBatch, renameEntity } from '../lib/filing.js';import { createNote } from '../lib/notes.js';- import { openEntity, openNotebook } from '../lib/navigate.js';+ import {+ gotoCapture,+ openEntity,+ openInTimeline,+ openNotebook,+ opensInFileManager,+ showInFolder,+ } from '../lib/navigate.js';+ import {+ inSubtree,+ leafOf,+ removeFolder,+ removeFolderPrompt,+ renameFolder,+ renamedPath,+ setWorkFolder,+ workFolder,+ } from '../lib/folders.js';+ import { openInOptions } from '../lib/openIn.js';+ import { TOOL_LABELS } from '../lib/workspaces.js';+ import { typeChips } from '../lib/sidebarSearch.js';+ import { entityLabel } from '../lib/entityTypes.svelte.js';+ import { mediaKindOf } from '../lib/entityIcon.js';+ import { uploadFiles } from '../lib/mediaImport.js';import { createBookmark } from '../lib/bookmarks.js';import { listenForPaste, pasteImage, resolvePaste } from '../lib/clipboardPaste.js';import { marqueeRect, marqueeHits, toggleSelection } from '../lib/gridSelect.js';@@ -41,6 +71,7 @@import EntityDetails from '../components/EntityDetails.svelte';import FolderSelect from '../components/FolderSelect.svelte';import PasteDialog from '../components/PasteDialog.svelte';+ import SourceDialog from '../components/SourceDialog.svelte';const TYPE_ICON = {media: 'image', capture: 'satellite', note: 'note', proof: 'proof',@@ -90,6 +121,9 @@loadedFor = id;pl.clear();showTrash = false;+ showUnfiled = false;+ // A case opens where the analyst is working, the way a save dialog does.+ cwd = caseState.current?.work_folder ?? '';}pl.reload();api@@ -114,6 +148,55 @@const tree = $derived(buildTree(caseState.current?.folders ?? [], confirmed));const allFolders = $derived(flattenPaths(tree));const unfiled = $derived(confirmed.filter((e) => !folderOf(e)));+ // Counts from the summary, which covers the whole case; the loaded page alone+ // undercounted every folder of a case past its first 200 items.+ const countOf = (node) => (summary?.by_folder ? subtreeCountFrom(node, summary.by_folder) : subtreeCount(node));+ const working = $derived(caseState.current?.work_folder ?? null);++ // ── filters ─────────────────────────────────────────────────────────────────+ // A type, and what nothing points at yet: the same narrowing the sidebar's chips+ // and the Board's "Nothing linked yet" make, asked of the open folder and below.+ // Either one turns the view into a flat result list, as a search does, because a+ // folder tile cannot say how many of its items are of one type.+ let typeFilter = $state(null);+ let unlinkedOnly = $state(false);+ const filtering = $derived(Boolean(typeFilter || unlinkedOnly));+ const chips = $derived(typeChips(summary));+ const fl = createPagedList({+ fetchPage: ({ query: serverQuery, cursor }) =>+ api.get(+ buildCatalogQuery(caseState.current?.id, {+ status: 'confirmed',+ query: serverQuery,+ types: typeFilter ? [typeFilter] : null,+ unlinked: unlinkedOnly,+ folder: !showUnfiled && cwd ? cwd : undefined,+ unfiled: showUnfiled,+ recursive: Boolean(!showUnfiled && cwd),+ limit: PAGE,+ cursor,+ })+ ),+ });+ let filteredKey = null; // non-reactive: only the effect below reads/writes it+ $effect(() => {+ const id = caseState.current?.id;+ const key = filtering && id+ ? [id, typeFilter, unlinkedOnly, cwd, showUnfiled, caseState.rev].join('|')+ : null;+ if (key === filteredKey) return;+ filteredKey = key;+ if (!key) fl.clear();+ else fl.reload();+ });+ $effect(() => {+ fl.setQuery(query);+ });+ const filteredRows = $derived(fl.serverMode ? fl.items : fl.items.filter((e) => matches(e)));+ function clearFilters() {+ typeFilter = null;+ unlinkedOnly = false;+ }function tileIcon(e) {if (e.type === 'media') {@@ -267,9 +350,11 @@const searchScope = $derived(showUnfiled ? unfiled : cwd ? confirmed.filter((e) => isInFolderSubtree(e, cwd)) : confirmed);- const visibleEntities = $derived(searching ? searchScope.filter(matches) : current.entities);+ const visibleEntities = $derived(+ filtering ? filteredRows : searching ? searchScope.filter(matches) : current.entities+ );const completeVisibleEntities = $derived(- completeFolderEntities === null+ completeFolderEntities === null || filtering? visibleEntities: (searching ? completeFolderEntities.filter(matches) : completeFolderEntities));@@ -278,18 +363,17 @@// row past 200: a delete silently spared them, and a move reported a count it// had not moved.const selectable = $derived(- completeFolderEntities === null- ? confirmed- : [...new Map([...confirmed, ...completeFolderEntities].map((e) => [e.id, e])).values()]+ [...new Map([...confirmed, ...(completeFolderEntities ?? []), ...fl.items].map((e) => [e.id, e])).values()]);- const curFolders = $derived(searching ? [] : sortFolders(current.children));+ const narrowed = $derived(searching || filtering);+ const curFolders = $derived(narrowed ? [] : sortFolders(current.children));const curEntities = $derived(sortEntities(completeVisibleEntities));const entityOrder = $derived(curEntities.map((e) => e.id));const crumbs = $derived(cwd ? cwd.split('/') : []);// the Unfiled bucket shows as a tile at the root, even when empty (drop here// to unfile). Folder to create a new folder into on empty-space right-click.- const showRootUnfiled = $derived(cwd === '' && !showUnfiled && !searching);- const ctxParent = $derived(showUnfiled || searching ? '' : cwd);+ const showRootUnfiled = $derived(cwd === '' && !showUnfiled && !narrowed);+ const ctxParent = $derived(showUnfiled || narrowed ? '' : cwd);function openFolder(path) {showTrash = false;@@ -338,6 +422,18 @@}function onFilesKeydown(event) {+ if (event.key === 'Escape' && ctx) {+ ctx = null;+ return;+ }+ if (event.key === 'F2' && uiState.tool === 'files' && selected.length === 1 && !renaming) {+ const entity = curEntities.find((e) => e.id === selected[0]);+ if (entity) {+ event.preventDefault();+ startRename({ kind: 'entity', entity });+ }+ return;+ }if (event.key !== 'Delete' ||event.repeat ||@@ -453,50 +549,109 @@// ── folders ────────────────────────────────────────────────────────────────let newFolder = $state('');- // create `leaf` under `parent` ('' = top level)+ // create `leaf` under `parent` ('' = top level); the new path, or nullasync function createFolderAt(parent, leaf) {const name = (parent ? `${parent}/` : '') + leaf.trim();try {await api.post(`/api/cases/${caseState.current.id}/folders`, { name });await reloadCase();+ if (parent) expanded[parent] = true; // show where it went+ return name;} catch (e) {toast(e.message, 'danger');+ return null;}}function createFolder() {const leaf = newFolder.trim();if (!leaf) return;newFolder = '';- createFolderAt(searching || showUnfiled ? '' : cwd, leaf);+ createFolderAt(narrowed || showUnfiled ? '' : cwd, leaf);}- // deleting a folder only clears the filing: items inside land in Unfiled,- // no files are touched. Same routing the case sidebar uses.+ // Removing a folder only clears the filing: the server unfiles every item+ // under it, the ones past the loaded page too, and no file is touched.function askDeleteFolder(path) {- const prefix = path + '/';- const inside = confirmed.filter((e) => {- const f = folderOf(e);- return f === path || (f && f.startsWith(prefix));- });- const subs = allFolders.filter((f) => f.startsWith(prefix)).length;confirmState = {- title: 'Remove this folder?',- message: subs- ? `“${path}” and its ${subs} subfolder(s) will be removed from My work.`- : `“${path}” will be removed from My work.`,- detail: 'Items inside are unfiled. No files are deleted.',- confirmLabel: 'Remove folder',- tone: 'default',- icon: 'folderMinus',+ ...removeFolderPrompt(path, allFolders),action: async () => {- if (inside.length) await assignFolderBatch(caseState.current.id, inside, '');- await api.del(`/api/cases/${caseState.current.id}/folders?name=${encodeURIComponent(path)}`);- await reloadCase();- if (cwd === path || cwd.startsWith(prefix)) cwd = '';+ await removeFolder(caseState.current.id, path);+ if (inSubtree(cwd, path)) cwd = '';},};}+ async function toggleWorkFolder(path) {+ try {+ await setWorkFolder(caseState.current.id, working === path ? null : path);+ } catch (e) {+ toast(e.message, 'danger');+ }+ }++ // ── rename (F2 or the menu) ─────────────────────────────────────────────────────+ // One field in place of the name, for an item or a folder. Enter or leaving the+ // field keeps it, Escape drops it.+ // A folder shows twice, in the tree rail and as a tile, so the field opens on the+ // one that was pressed (`inTree`): two fields would take focus from each other,+ // and losing focus keeps the name.+ let renaming = $state(null); // { kind: 'entity', id, value } | { kind: 'folder', path, value, inTree }+ let renameBusy = false;++ function startRename(target) {+ ctx = null;+ renaming = target.kind === 'folder'+ ? { kind: 'folder', path: target.path, value: leafOf(target.path), inTree: Boolean(target.inTree) }+ : { kind: 'entity', id: target.entity.id, value: target.entity.label };+ }++ async function commitRename() {+ const r = renaming;+ if (!r || renameBusy) return;+ renaming = null;+ const caseId = caseState.current.id;+ renameBusy = true;+ try {+ if (r.kind === 'folder') {+ if (r.value.includes('/')) {+ toast('A folder name cannot hold a slash', 'warn');+ return;+ }+ const target = renamedPath(r.path, r.value);+ if (!target) return;+ await renameFolder(caseId, r.path, target);+ if (inSubtree(cwd, r.path)) cwd = target + cwd.slice(r.path.length);+ } else {+ const entity = selectable.find((e) => e.id === r.id);+ if (!entity || !r.value.trim() || r.value.trim() === entity.label) return;+ await renameEntity(caseId, entity, r.value);+ await reloadCase();+ }+ } catch (e) {+ toast(e.message, 'danger');+ } finally {+ renameBusy = false;+ }+ }++ function onRenameKey(event) {+ // The field sits inside a tile whose Enter opens it, and the window's Delete+ // and F2 act on the selection: typing a name is none of those.+ event.stopPropagation();+ if (event.key === 'Enter') {+ event.preventDefault();+ commitRename();+ } else if (event.key === 'Escape') {+ event.preventDefault();+ event.stopPropagation();+ renaming = null;+ }+ }+ function focusSelect(node) {+ node.focus();+ node.select();+ }+// ── delete (irreversible; spells out what it touches) ─────────────────────let confirmState = $state(null); // { title, message, detail, consequences, confirmLabel, tone, icon, action }let confirmBusy = $state(false);@@ -572,45 +727,60 @@};}- // right-click → a small menu offering a new folder or a new note under- // whatever was clicked (a folder, or the open one on empty space). The menu- // opens in 'menu' mode; picking "New folder" swaps to the inline name field.- // Right-clicking an actual folder node (tree row or tile) also offers to- // delete it; right-clicking a file tile opens a separate entity menu.- let ctx = $state(null); // { x, y, parent, mode: 'menu' | 'folder', isFolder } | { x, y, kind: 'entity', ids }+ // ── right-click ───────────────────────────────────────────────────────────────+ // Three menus, by what was pressed. An item (or the selection it is part of):+ // open it, take it to a tool, rename, move, date it, delete. A folder: open,+ // rename, add inside it, import into it, work in it, remove. Empty space: add+ // to the folder on screen. "New folder" and "New folder with selection" swap+ // the menu for a name field rather than opening a dialog.+ //+ // ctx: { x, y, kind: 'entity', ids }+ // | { x, y, kind: 'folder', parent, isFolder, mode: 'menu' | 'name', withSelection }+ let ctx = $state(null);let ctxName = $state('');- function openCtx(e, parent, isFolder = false) {+ const MENU_W = 230;+ const MENU_H = 360;+ /** Keep the menu on screen: a press near the right or bottom edge opens it inward. */+ function at(e) {+ return {+ x: Math.min(e.clientX, window.innerWidth - MENU_W - 8),+ y: Math.min(e.clientY, Math.max(8, window.innerHeight - MENU_H - 8)),+ };+ }+ function openCtx(e, parent, isFolder = false, inTree = false) {e.preventDefault();e.stopPropagation();- ctx = { x: e.clientX, y: e.clientY, parent, mode: 'menu', isFolder };+ ctx = { ...at(e), kind: 'folder', parent, isFolder, inTree, mode: 'menu', withSelection: null };ctxName = '';}- function ctxNewFolder() {- ctx = { ...ctx, mode: 'folder' };+ function ctxNewFolder(withSelection = null) {+ ctx = { ...ctx, kind: 'folder', mode: 'name', withSelection };ctxName = '';}- function ctxCreate() {+ async function ctxCreate() {const leaf = ctxName.trim();- const parent = ctx?.parent ?? '';- ctx = null;- if (leaf) createFolderAt(parent, leaf);- }- function ctxNewNote() {- const parent = ctx?.parent ?? '';- ctx = null;- openNewNote(parent);- }-- function ctxNewBookmark() {- const parent = ctx?.parent ?? '';+ const { parent = '', withSelection = null } = ctx ?? {};ctx = null;- openNewBookmark(parent);+ if (!leaf) return;+ const path = await createFolderAt(parent, leaf);+ if (path && withSelection?.length) {+ const ents = selectable.filter((e) => withSelection.includes(e.id));+ try {+ await assignFolderBatch(caseState.current.id, ents, path);+ await reloadCase();+ selected = [];+ toast(`Moved ${ents.length} item${ents.length > 1 ? 's' : ''} to ${leaf}`, 'ok', 1800);+ } catch (e) {+ toast(e.message, 'danger');+ }+ }}-- function ctxDeleteFolder() {- const path = ctx?.parent;+ /** Close the menu, then act on what it was opened on. Read before closing:+ * `ctxEntities` and `ctxOne` follow `ctx` and are empty once it is null. */+ function ctxRun(fn) {+ const held = { ...ctx, entities: ctxEntities, one: ctxOne };ctx = null;- if (path) askDeleteFolder(path);+ fn(held);}// right-click on a file tile: select it (unless it's part of the current@@ -622,8 +792,19 @@selected = [entity.id];anchor = entity.id;}- ctx = { x: e.clientX, y: e.clientY, kind: 'entity', ids: [...selected] };+ ctx = { ...at(e), kind: 'entity', ids: [...selected] };}+ const ctxEntities = $derived(+ ctx?.kind === 'entity' ? selectable.filter((e) => ctx.ids.includes(e.id)) : []+ );+ const ctxOne = $derived(ctxEntities.length === 1 ? ctxEntities[0] : null);+ const ctxOpenIn = $derived(+ ctxOne && (ctxOne.type === 'media' || ctxOne.type === 'capture') && ctxOne.attrs?.path+ ? openInOptions({ path: ctxOne.attrs.path, kind: mediaKindOf(ctxOne), label: ctxOne.label })+ : []+ );+ const onMap = (e) =>+ e?.type === 'capture' && Number.isFinite(Number(e.attrs?.lat)) && Number.isFinite(Number(e.attrs?.lon));function openEntityTile(entity) {if (entity.type === 'note') {@@ -636,17 +817,54 @@}infoEntityId = entity.id;}- function ctxMoveToUnfiled() {- const ids = ctx?.ids ?? [];- ctx = null;- if (!ids.length) return;- draggingIds = ids;- dropInto('');- }- function ctxDeleteEntities() {- const ids = ctx?.ids ?? [];- ctx = null;- askDeleteEntities(ids);+ function moveTo(ents) {+ if (ents.length) uiState.moving = ents;+ }+ /** The Add event bar, seated on the item: Files offers what is selected. */+ function addEvent(entity) {+ selected = [entity.id];+ anchor = entity.id;+ uiState.noting = true;+ }++ // ── import into a folder ────────────────────────────────────────────────────+ // The Media Library's import, filed where it was asked for. The origin is asked+ // once for the batch, as there.+ let importInput = $state(null);+ let importFolder = '';+ let pendingImport = $state(null); // { files, folder }+ let importBusy = $state(false);+ function pickImport(folder) {+ importFolder = folder ?? '';+ importInput?.click();+ }+ function onImportPicked(event) {+ const files = [...(event.currentTarget.files ?? [])];+ event.currentTarget.value = '';+ if (files.length) pendingImport = { files, folder: importFolder };+ }+ async function runImport(sourceUrl) {+ if (!pendingImport || importBusy) return;+ importBusy = true;+ const { files, folder } = pendingImport;+ const caseId = caseState.current.id;+ try {+ const { filed, duplicates, failed } = await uploadFiles(caseId, files, sourceUrl);+ for (const refusal of failed) toast(`${refusal.name}: ${refusal.message}`, 'danger');+ const astray = filed.filter((e) => (folderOf(e) ?? '') !== folder);+ if (astray.length) await assignFolderBatch(caseId, astray, folder);+ pendingImport = null;+ await reloadCase();+ if (filed.length) {+ toast(`${filed.length} file${filed.length > 1 ? 's' : ''} filed in ${folder ? leafOf(folder) : 'Unfiled'}`, 'ok');+ revealFiled(folder);+ }+ if (duplicates) toast(`${duplicates} duplicate${duplicates > 1 ? 's' : ''} skipped (same SHA-256)`, 'warn');+ } catch (e) {+ toast(e.message, 'danger');+ } finally {+ importBusy = false;+ }}// ── notes ────────────────────────────────────────────────────────────────@@ -732,9 +950,10 @@});// A duplicate is left where it already sits: the case keeps the copy it has,// and refiling it under the folder of this paste would move an item the- // analyst filed on purpose the first time.- if (!result.duplicate && values.folder) {- await assignFolder(caseId, result.entity, values.folder);+ // analyst filed on purpose the first time. A new one may have landed in the+ // work folder, so it is moved whenever the dialog said somewhere else.+ if (!result.duplicate && (values.folder ?? '') !== (folderOf(result.entity) ?? '')) {+ await assignFolder(caseId, result.entity, values.folder ?? '');}pasted = null;await reloadCase();@@ -811,7 +1030,7 @@const id = caseState.current?.id;const folders = caseState.current?.folders ?? [];caseState.rev;- const needsCompleteList = view === 'list' && (Boolean(cwd) || showUnfiled || searching);+ const needsCompleteList = view === 'list' && !filtering && (Boolean(cwd) || showUnfiled || searching);if (!id || !needsCompleteList) {completeFolderRun += 1;completeFolderEntities = null;@@ -931,7 +1150,7 @@><Icon name="layers" size={14} /><span class="tname">All</span>- <span class="tcount">{confirmed.length}</span>+ <span class="tcount">{summary?.by_status?.confirmed ?? confirmed.length}</span></div>{#each tree as node (node.path)}@@ -991,12 +1210,55 @@{/if}{/each}{/if}+ {#if cwd && !showUnfiled && !showTrash}+ <button+ class="work-toggle"+ class:on={working === cwd}+ aria-pressed={working === cwd}+ title={working === cwd+ ? 'New files and saved work land here. Press to stop.'+ : 'Make this the work folder: new files and saved work land here'}+ onclick={() => toggleWorkFolder(cwd)}+ >+ <Icon name="pushpin" size={12} /> {working === cwd ? 'Work folder' : 'Work here'}+ </button>+ {/if}<div class="spacer"></div>{#if selected.length}<span class="sel-count">{selected.length} selected</span>{/if}</div>+ {#if !showTrash && chips.length > 1}+ <div class="filters" role="group" aria-label="Filters">+ <button class="chip" class:active={!typeFilter} onclick={() => (typeFilter = null)}>All</button>+ {#each chips as chip (chip.type)}+ <button+ class="chip"+ class:active={typeFilter === chip.type}+ aria-pressed={typeFilter === chip.type}+ onclick={() => (typeFilter = typeFilter === chip.type ? null : chip.type)}+ >+ {entityLabel(chip.type)}+ {#if !cwd && !showUnfiled}<span class="n">{chip.count}</span>{/if}+ </button>+ {/each}+ <span class="filters-sep"></span>+ <button+ class="chip"+ class:active={unlinkedOnly}+ aria-pressed={unlinkedOnly}+ title="In the case, and connected to nothing at all"+ onclick={() => (unlinkedOnly = !unlinkedOnly)}+ >+ Nothing linked yet+ </button>+ {#if filtering}+ <button class="clear" onclick={clearFilters}>Clear</button>+ {/if}+ </div>+ {/if}+{#if showTrash}<div class="trash-pane">{#if trashData.groups.length}@@ -1075,10 +1337,18 @@ondragleave={() => (dropTarget = dropTarget === node.path ? null : dropTarget)}ondrop={(e) => { e.preventDefault(); dropInto(node.path); }}>- <span class="lcol-name"><Icon name="folder" size={15} /><span class="ltext">{node.name}</span></span>+ <span class="lcol-name">+ <Icon name="folder" size={15} />+ {#if renaming?.kind === 'folder' && !renaming.inTree && renaming.path === node.path}+ {@render renameField()}+ {:else}+ <span class="ltext">{node.name}</span>+ {/if}+ {#if working === node.path}<span class="work-pin" title="Work folder"><Icon name="pushpin" size={12} /></span>{/if}+ </span><span class="lcol-type">folder</span><span class="lcol-size">—</span>- <span class="lcol-added">{subtreeCount(node)} item{subtreeCount(node) === 1 ? '' : 's'}</span>+ <span class="lcol-added">{countOf(node)} item{countOf(node) === 1 ? '' : 's'}</span></div>{/each}{#if showRootUnfiled}@@ -1123,7 +1393,11 @@{:else}<Icon name={tileIcon(e)} size={15} />{/if}- <span class="ltext">{e.label}</span>+ {#if renaming?.kind === 'entity' && renaming.id === e.id}+ {@render renameField()}+ {:else}+ <span class="ltext">{e.label}</span>+ {/if}</span><span class="lcol-type">{e.type}</span><span class="lcol-size">{fmtSize(tileSize(e))}</span>@@ -1134,7 +1408,8 @@<div class="grid-empty"><Icon name="folder" size={34} /><p>- {#if searching}No files match “{query.trim()}”.+ {#if filtering}Nothing here matches these filters.+ {:else if searching}No files match “{query.trim()}”.{:else if showUnfiled}Nothing unfiled.{:else}This folder is empty. Drag items here, or right-click to add a subfolder or note.{/if}</p>@@ -1166,8 +1441,15 @@ondrop={(e) => { e.preventDefault(); dropInto(node.path); }}><div class="thumb folder-thumb"><Icon name="folder" size={dense ? 26 : 38} /></div>- <span class="tile-name">{node.name}</span>- <span class="tile-sub">{subtreeCount(node)} item{subtreeCount(node) === 1 ? '' : 's'}</span>+ {#if renaming?.kind === 'folder' && !renaming.inTree && renaming.path === node.path}+ {@render renameField()}+ {:else}+ <span class="tile-name">{node.name}</span>+ {/if}+ {#if working === node.path}+ <span class="tile-pin" title="Work folder: new files and saved work land here"><Icon name="pushpin" size={12} /></span>+ {/if}+ <span class="tile-sub">{countOf(node)} item{countOf(node) === 1 ? '' : 's'}</span></div>{/each}@@ -1214,7 +1496,11 @@<Icon name={tileIcon(e)} size={dense ? 24 : 34} />{/if}</div>- <span class="tile-name">{e.label}</span>+ {#if renaming?.kind === 'entity' && renaming.id === e.id}+ {@render renameField()}+ {:else}+ <span class="tile-name">{e.label}</span>+ {/if}<span class="tile-sub">{e.type}</span><buttonclass="tile-info btn btn-ghost btn-sm"@@ -1230,7 +1516,8 @@<div class="grid-empty"><Icon name="folder" size={34} /><p>- {#if searching}No files match “{query.trim()}”.+ {#if filtering}Nothing here matches these filters.+ {:else if searching}No files match “{query.trim()}”.{:else if showUnfiled}Nothing unfiled.{:else}This folder is empty. Drag items here, or right-click to add a subfolder or note.{/if}</p>@@ -1245,7 +1532,14 @@{/if}</div>{/if}- {#if !showTrash && pl.hasMore}+ {#if !showTrash && filtering && fl.hasMore}+ <div class="show-more">+ <button class="btn" onclick={() => fl.loadMore()} disabled={fl.loading}>+ {fl.loading ? 'Loading…' : 'Show more'}+ </button>+ <span>Showing {fl.items.length} of {fl.total}</span>+ </div>+ {:else if !showTrash && !filtering && pl.hasMore}<div class="show-more"><button class="btn" onclick={() => pl.loadMore()} disabled={pl.loading}>{pl.loading ? 'Loading…' : 'Show more'}@@ -1258,6 +1552,22 @@{/if}</div>+<!-- the name, made editable in place (rename) -->+{#snippet renameField()}+ <!-- svelte-ignore a11y_autofocus -->+ <input+ class="input rename-field"+ aria-label="New name"+ bind:value={renaming.value}+ use:focusSelect+ onkeydown={onRenameKey}+ onblur={commitRename}+ onclick={(e) => e.stopPropagation()}+ ondblclick={(e) => e.stopPropagation()}+ onpointerdown={(e) => e.stopPropagation()}+ />+{/snippet}+<!-- one tree node + subtree (navigation + drop target) -->{#snippet treeNode(node, depth)}<div@@ -1269,7 +1579,7 @@tabindex="0"onclick={() => openFolder(node.path)}onkeydown={(e) => e.key === 'Enter' && openFolder(node.path)}- oncontextmenu={(e) => openCtx(e, node.path, true)}+ oncontextmenu={(e) => openCtx(e, node.path, true, true)}ondragover={(e) => { e.preventDefault(); dropTarget = node.path; }}ondragleave={() => (dropTarget = dropTarget === node.path ? null : dropTarget)}ondrop={(e) => { e.preventDefault(); dropInto(node.path); }}@@ -1289,8 +1599,15 @@<span class="tchevron spacer-icon"></span>{/if}<Icon name={isExpanded(node.path) ? 'folderOpen' : 'folder'} size={14} />- <span class="tname">{node.name}</span>- <span class="tcount">{subtreeCount(node)}</span>+ {#if renaming?.kind === 'folder' && renaming.inTree && renaming.path === node.path}+ {@render renameField()}+ {:else}+ <span class="tname">{node.name}</span>+ {/if}+ {#if working === node.path}+ <span class="work-pin" title="Work folder: new files and saved work land here"><Icon name="pushpin" size={12} /></span>+ {/if}+ <span class="tcount">{countOf(node)}</span></div>{#if isExpanded(node.path)}{#each node.children as child (child.path)}@@ -1299,7 +1616,7 @@{/if}{/snippet}-<!-- right-click menu: create a folder or a note under whatever was clicked -->+<!-- right-click menu: what can be done to what was pressed -->{#if ctx}<divclass="ctx-backdrop"@@ -1308,19 +1625,64 @@oncontextmenu={(e) => e.preventDefault()}></div><!-- svelte-ignore a11y_no_static_element_interactions -->- <div class="ctx-menu" style="left:{ctx.x}px; top:{ctx.y}px" onpointerdown={(e) => e.stopPropagation()}>+ <div class="ctx-menu" role="menu" tabindex="-1" style="left:{ctx.x}px; top:{ctx.y}px" onpointerdown={(e) => e.stopPropagation()}>{#if ctx.kind === 'entity'}- <div class="ctx-head">{ctx.ids.length > 1 ? `${ctx.ids.length} items` : 'Item'}</div>- {#if !showUnfiled}- <button class="ctx-item" onclick={ctxMoveToUnfiled}>+ <div class="ctx-head">{ctxOne ? ctxOne.label : `${ctxEntities.length} items`}</div>+ {#if ctxOne}+ <button class="ctx-item" role="menuitem" onclick={() => ctxRun((held) => openEntity(held.one))}>+ <Icon name="external" size={14} /> Open+ </button>+ {#each ctxOpenIn as option (option.id)}+ <button class="ctx-item" role="menuitem" onclick={() => ctxRun(() => option.run())}>+ <Icon name={option.icon} size={14} /> Open in {TOOL_LABELS[option.id]}+ </button>+ {/each}+ <div class="ctx-sep"></div>+ <button class="ctx-item" role="menuitem" onclick={() => startRename({ kind: 'entity', entity: ctxOne })}>+ <Icon name="edit" size={14} /> Rename <kbd>F2</kbd>+ </button>+ {/if}+ <button class="ctx-item" role="menuitem" onclick={() => ctxRun((held) => moveTo(held.entities))}>+ <Icon name="move" size={14} /> Move to…+ </button>+ <button class="ctx-item" role="menuitem" onclick={() => ctxNewFolder(ctx.ids)}>+ <Icon name="folder" size={14} /> New folder with {ctxOne ? 'this item' : 'these items'}+ </button>+ {#if !showUnfiled && ctxEntities.some((e) => folderOf(e))}+ <button class="ctx-item" role="menuitem" onclick={() => ctxRun((held) => assignFolderBatch(caseState.current.id, held.entities, '').then(reloadCase).catch((e) => toast(e.message, 'danger')))}><Icon name="folderMinus" size={14} /> Move to Unfiled</button>{/if}- <button class="ctx-item danger" onclick={ctxDeleteEntities}>+ {#if ctxOne}+ <div class="ctx-sep"></div>+ <button class="ctx-item" role="menuitem" onclick={() => ctxRun((held) => addEvent(held.one))}>+ <Icon name="eventAdd" size={14} /> Add event+ </button>+ <button class="ctx-item" role="menuitem" onclick={() => ctxRun((held) => openInTimeline(held.one))}>+ <Icon name="clock" size={14} /> Show in Timeline+ </button>+ {#if onMap(ctxOne)}+ <button class="ctx-item" role="menuitem" onclick={() => ctxRun((held) => gotoCapture(held.one))}>+ <Icon name="crosshair" size={14} /> Show on map+ </button>+ {/if}+ {#if (ctxOne.type === 'media' || ctxOne.type === 'capture') && ctxOne.attrs?.path && !opensInFileManager(ctxOne)}+ <button class="ctx-item" role="menuitem" onclick={() => ctxRun((held) => showInFolder(held.one))}>+ <Icon name="folderOpen" size={14} /> Show in folder+ </button>+ {/if}+ <button class="ctx-item" role="menuitem" onclick={() => ctxRun((held) => (infoEntityId = held.one.id))}>+ <Icon name="info" size={14} /> Details+ </button>+ {/if}+ <div class="ctx-sep"></div>+ <button class="ctx-item danger" role="menuitem" onclick={() => ctxRun((held) => askDeleteEntities(held.ids))}><Icon name="trash" size={14} /> Delete</button>- {:else if ctx.mode === 'folder'}- <div class="ctx-head">New folder{ctx.parent ? ` in ${ctx.parent.split('/').pop()}` : ''}</div>+ {:else if ctx.mode === 'name'}+ <div class="ctx-head">+ {ctx.withSelection ? 'New folder with the selection' : 'New folder'}{ctx.parent ? ` in ${leafOf(ctx.parent)}` : ''}+ </div><form onsubmit={(e) => { e.preventDefault(); ctxCreate(); }}><!-- svelte-ignore a11y_autofocus --><input@@ -1333,26 +1695,60 @@<button class="btn btn-primary btn-sm" type="submit" disabled={!ctxName.trim()}>Create</button></form>{:else}- <div class="ctx-head">{ctx.parent ? ctx.parent.split('/').pop() : 'All'}</div>- <button class="ctx-item" onclick={ctxNewFolder}>- <Icon name="folder" size={14} /> New folder+ <div class="ctx-head">{ctx.parent ? leafOf(ctx.parent) : 'All'}</div>+ {#if ctx.isFolder && ctx.parent}+ <button class="ctx-item" role="menuitem" onclick={() => ctxRun((held) => openFolder(held.parent))}>+ <Icon name="folderOpen" size={14} /> Open+ </button>+ <button class="ctx-item" role="menuitem" onclick={() => startRename({ kind: 'folder', path: ctx.parent, inTree: ctx.inTree })}>+ <Icon name="edit" size={14} /> Rename+ </button>+ <div class="ctx-sep"></div>+ {/if}+ <button class="ctx-item" role="menuitem" onclick={() => ctxNewFolder()}>+ <Icon name="folder" size={14} /> {ctx.isFolder && ctx.parent ? 'New subfolder' : 'New folder'}</button>- <button class="ctx-item" onclick={ctxNewNote}>+ <button class="ctx-item" role="menuitem" onclick={() => ctxRun((held) => openNewNote(held.parent))}><Icon name="note" size={14} /> New note</button>- <button class="ctx-item" onclick={ctxNewBookmark}>+ <button class="ctx-item" role="menuitem" onclick={() => ctxRun((held) => openNewBookmark(held.parent))}><Icon name="link" size={14} /> New bookmark</button>+ <button class="ctx-item" role="menuitem" onclick={() => ctxRun((held) => pickImport(held.parent))}>+ <Icon name="upload" size={14} /> Import files here+ </button>+ {#if ctx.parent}+ <div class="ctx-sep"></div>+ <button class="ctx-item" role="menuitem" onclick={() => ctxRun((held) => toggleWorkFolder(held.parent))}>+ <Icon name="pushpin" size={14} /> {working === ctx.parent ? 'Stop working here' : 'Work in this folder'}+ </button>+ {/if}{#if ctx.isFolder && ctx.parent}<div class="ctx-sep"></div>- <button class="ctx-item danger" onclick={ctxDeleteFolder}>- <Icon name="trash" size={14} /> Delete folder+ <button class="ctx-item danger" role="menuitem" onclick={() => ctxRun((held) => askDeleteFolder(held.parent))}>+ <Icon name="folderMinus" size={14} /> Remove folder</button>{/if}{/if}</div>{/if}+<input+ bind:this={importInput}+ type="file"+ multiple+ hidden+ onchange={onImportPicked}+/>+{#if pendingImport}+ <SourceDialog+ count={pendingImport.files.length}+ busy={importBusy}+ onconfirm={runImport}+ onclose={() => (pendingImport = null)}+ />+{/if}+<!-- delete confirmation (entities or a folder) -->{#if confirmState}<ConfirmDialog@@ -1377,7 +1773,7 @@<input id="fnote-title" class="input" placeholder="Note title…" bind:value={noteModal.title} /><span class="modal-label" style="margin-top:10px">Folder (in My work)</span>- <FolderSelect bind:value={noteModal.folder} folders={allFolders} emptyLabel="My work (root)" />+ <FolderSelect bind:value={noteModal.folder} folders={allFolders} emptyLabel="My work (root)" fresh /><div class="modal-row"><div style="flex:1"></div>@@ -1399,7 +1795,7 @@<input id="fbm-title" class="input" placeholder="Bookmark title…" bind:value={bookmarkModal.title} /><span class="modal-label" style="margin-top:10px">Folder (in My work)</span>- <FolderSelect bind:value={bookmarkModal.folder} folders={allFolders} emptyLabel="My work (root)" />+ <FolderSelect bind:value={bookmarkModal.folder} folders={allFolders} emptyLabel="My work (root)" fresh /><label class="modal-label" for="fbm-notes" style="margin-top:10px">Notes</label><textarea id="fbm-notes" class="textarea" rows="3" placeholder="Why this page matters…" bind:value={bookmarkModal.notes}></textarea>@@ -1494,7 +1890,9 @@.ctx-menu {position: fixed;z-index: 41;- width: 220px;+ width: 230px;+ max-height: calc(100vh - 16px);+ overflow-y: auto;padding: 8px;background: var(--bg-1);border: 1px solid var(--border-strong);@@ -1541,6 +1939,12 @@.ctx-item.danger > :global(svg) {color: inherit;}+ .ctx-item kbd {+ margin-left: auto;+ color: var(--text-3);+ font-family: inherit;+ font-size: var(--fs-xs);+ }.ctx-sep {height: 1px;margin: 6px 2px;@@ -1662,6 +2066,59 @@color: var(--text-3);font-size: var(--fs-xs);}+ .work-toggle {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ margin-left: 8px;+ padding: 2px 8px;+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ color: var(--text-3);+ font-size: var(--fs-xs);+ font-weight: 600;+ }+ .work-toggle:hover { color: var(--text-1); border-color: var(--border-strong); }+ .work-toggle.on { color: var(--accent); border-color: var(--accent); background: var(--accent-soft); }+ .work-pin,+ .tile-pin {+ display: inline-flex;+ flex-shrink: 0;+ color: var(--accent);+ }+ .tile-pin { position: absolute; top: 6px; left: 6px; }+ .filters {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 4px;+ padding: 8px 16px;+ border-bottom: 1px solid var(--border);+ flex-shrink: 0;+ }+ .filters .chip {+ display: flex;+ align-items: center;+ gap: 4px;+ padding: 2px 8px;+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ background: var(--bg-2);+ color: var(--text-3);+ font-size: var(--fs-xs);+ }+ .filters .chip:hover { color: var(--text-1); border-color: var(--border-strong); }+ .filters .chip.active { color: var(--text-1); border-color: var(--accent); background: var(--accent-soft); }+ .filters .n { font-weight: 600; }+ .filters-sep { width: 1px; height: 14px; margin: 0 4px; background: var(--border); }+ .filters .clear { color: var(--text-3); font-size: var(--fs-xs); text-decoration: underline; }+ .filters .clear:hover { color: var(--text-1); }+ .rename-field {+ width: 100%;+ min-width: 0;+ padding: 2px 4px;+ font-size: var(--fs-xs);+ }.sel-count {font-size: var(--fs-xs);color: var(--accent);diff --git a/frontend/src/tools/Files.test.js b/frontend/src/tools/Files.test.jsindex a0591b2..e9e1c00 100644--- a/frontend/src/tools/Files.test.js+++ b/frontend/src/tools/Files.test.js@@ -13,7 +13,7 @@ describe('Files bounded loading', () => {});it('offers Show more with an honest filtered total', () => {- expect(source).toContain('{#if !showTrash && pl.hasMore}');+ expect(source).toContain('{:else if !showTrash && !filtering && pl.hasMore}');expect(source).toContain('pl.loadMore()');expect(source).toContain('Showing {confirmed.length} of {total}');expect(source).toContain('/catalog/summary');@@ -166,7 +166,7 @@ describe('Ctrl+V on the desktop', () => {});it('files the image where the dialog said, and takes a link as a bookmark', () => {- expect(source).toContain('await assignFolder(caseId, result.entity, values.folder)');+ expect(source).toContain("await assignFolder(caseId, result.entity, values.folder ?? '')");expect(source).toContain('await createBookmark(caseId, { ...values, url: payload.url })');});@@ -178,7 +178,12 @@ describe('Ctrl+V on the desktop', () => {it('leaves a duplicate where it already sits', () => {// refiling it under this paste's folder would move an item filed on purpose- expect(source).toContain('if (!result.duplicate && values.folder)');+ expect(source).toContain('if (!result.duplicate && (values.folder');+ });++ it('moves a new image out of the work folder when the dialog named another', () => {+ // registration filed it in the work folder; "My work (root)" has to be applied too+ expect(source).toContain("(values.folder ?? '') !== (folderOf(result.entity) ?? '')");});it('offers the folder picker the same tree every other dialog here gets', () => {@@ -203,3 +208,131 @@ describe('Files offers what is open to the Add event bar', () => {expect(source).toContain("onDestroy(() => withdrawNote('files'))");});});++describe('Files counts folders across the whole case', () => {+ it('reads folder counts from the summary, not the loaded page', () => {+ expect(source).toContain('subtreeCountFrom(node, summary.by_folder)');+ expect(source).toContain('{countOf(node)}');+ expect(source).not.toContain('{subtreeCount(node)}');+ expect(source).toContain('summary?.by_status?.confirmed ?? confirmed.length');+ });++ it('removes a folder through the server, which unfiles items past the first page too', () => {+ expect(source).toContain('...removeFolderPrompt(path, allFolders)');+ expect(source).toContain('await removeFolder(caseState.current.id, path)');+ expect(source).not.toContain("assignFolderBatch(caseState.current.id, inside, '')");+ });+});++describe('Files right-click', () => {+ const menu = source.slice(source.indexOf('<!-- right-click menu'), source.indexOf('<!-- delete confirmation'));++ it('offers an item what Details and the Media Library offer it', () => {+ expect(menu).toContain('openEntity(held.one)');+ expect(menu).toContain('{#each ctxOpenIn as option (option.id)}');+ expect(menu).toContain("startRename({ kind: 'entity', entity: ctxOne })");+ expect(menu).toContain('moveTo(held.entities)');+ expect(menu).toContain('addEvent(held.one)');+ expect(menu).toContain('openInTimeline(held.one)');+ expect(menu).toContain('showInFolder(held.one)');+ expect(menu).toContain('askDeleteEntities(held.ids)');+ });++ it('takes a picture or a video to the same tools as the Media Library', () => {+ expect(source).toContain("import { openInOptions } from '../lib/openIn.js'");+ expect(source).toContain('openInOptions({ path: ctxOne.attrs.path, kind: mediaKindOf(ctxOne), label: ctxOne.label })');+ });++ it('reads what the menu was opened on before closing it', () => {+ // ctxOne and ctxEntities follow ctx, so after `ctx = null` they are empty and+ // every action did nothing (the browser spec caught Move to… opening nothing)+ expect(source).toContain('const held = { ...ctx, entities: ctxEntities, one: ctxOne };');+ expect(menu.replace('ctxRun(() => option.run())', '')).not.toMatch(/ctxRun\(\(\) =>/);+ });++ it('makes a folder out of the selection', () => {+ expect(menu).toContain('ctxNewFolder(ctx.ids)');+ expect(source).toContain('await assignFolderBatch(caseState.current.id, ents, path)');+ });++ it('offers a folder rename, import, the work folder and removal', () => {+ expect(menu).toContain("startRename({ kind: 'folder', path: ctx.parent, inTree: ctx.inTree })");+ expect(menu).toContain('pickImport(held.parent)');+ expect(menu).toContain('toggleWorkFolder(held.parent)');+ expect(menu).toContain('askDeleteFolder(held.parent)');+ });++ it('keeps the menu inside the window and closes it on Escape', () => {+ expect(source).toContain('window.innerWidth - MENU_W - 8');+ expect(source).toContain("if (event.key === 'Escape' && ctx)");+ });+});++describe('Files rename', () => {+ it('renames in place, from F2 or the menu', () => {+ expect(source).toContain("event.key === 'F2'");+ expect(source).toContain('{@render renameField()}');+ expect(source).toContain('onblur={commitRename}');+ });++ it('opens one field per rename, where it was asked for', () => {+ // a folder shows in the tree rail and as a tile; two fields took focus from+ // each other and the blur kept the old name+ expect(source).toContain("renaming?.kind === 'folder' && renaming.inTree && renaming.path === node.path");+ expect(source).toContain("renaming?.kind === 'folder' && !renaming.inTree && renaming.path === node.path");+ });++ it('keeps the keys typed in the field away from the tile and the window', () => {+ // Enter on the tile opens the folder, and F2 / Delete act on the selection+ expect(source).toMatch(/function onRenameKey\(event\) \{[^}]*event\.stopPropagation\(\);/);+ });++ it('renames an item through the route Details uses, and a folder with its subtree', () => {+ expect(source).toContain('await renameEntity(caseId, entity, r.value)');+ expect(source).toContain('const target = renamedPath(r.path, r.value)');+ expect(source).toContain('await renameFolder(caseId, r.path, target)');+ // the open folder follows its own rename+ expect(source).toContain('if (inSubtree(cwd, r.path)) cwd = target + cwd.slice(r.path.length)');+ });+});++describe('Files filters', () => {+ it('narrows by type and by what nothing points at, on the server past one page', () => {+ expect(source).toContain('types: typeFilter ? [typeFilter] : null');+ expect(source).toContain('unlinked: unlinkedOnly');+ expect(source).toContain('const chips = $derived(typeChips(summary))');+ expect(source).toContain('Nothing linked yet');+ });++ it('asks the open folder and what is under it', () => {+ expect(source).toContain('folder: !showUnfiled && cwd ? cwd : undefined');+ expect(source).toContain('recursive: Boolean(!showUnfiled && cwd)');+ });++ it('shows a flat result list while filtering, as a search does', () => {+ expect(source).toContain('const narrowed = $derived(searching || filtering)');+ expect(source).toContain('const curFolders = $derived(narrowed ? [] : sortFolders(current.children))');+ });+});++describe('Files and the work folder', () => {+ it('opens a case on its work folder', () => {+ expect(source).toContain("cwd = caseState.current?.work_folder ?? ''");+ });++ it('marks the work folder and toggles it from the crumbs', () => {+ expect(source).toContain('class="work-toggle"');+ expect(source).toContain('toggleWorkFolder(cwd)');+ expect(source).toContain('await setWorkFolder(caseState.current.id, working === path ? null : path)');+ });++ it('starts the new note and bookmark dialogs on it', () => {+ expect(source).toMatch(/<FolderSelect bind:value=\{noteModal\.folder\}[^>]*fresh/);+ expect(source).toMatch(/<FolderSelect bind:value=\{bookmarkModal\.folder\}[^>]*fresh/);+ });++ it('files an import where it was asked for, past the work folder', () => {+ expect(source).toContain('uploadFiles(caseId, files, sourceUrl)');+ expect(source).toContain("const astray = filed.filter((e) => (folderOf(e) ?? '') !== folder)");+ });+});diff --git a/frontend/src/tools/Graph.svelte b/frontend/src/tools/Graph.svelteindex 2db5c2d..a916587 100644--- a/frontend/src/tools/Graph.svelte+++ b/frontend/src/tools/Graph.svelte@@ -151,6 +151,7 @@import Icon, { paths } from '../components/Icon.svelte';import AnalysisViews from '../components/AnalysisViews.svelte';import PlateExport from '../components/PlateExport.svelte';+ import ProposalReview from '../components/ProposalReview.svelte';import AnalysisPeriodBar from '../components/AnalysisPeriodBar.svelte';import FilterBar from '../components/FilterBar.svelte';import Modal from '../components/Modal.svelte';@@ -2953,7 +2954,7 @@y: node.y + nodeRadius(data.degree) + 5,width: 140,align: 'center',- text: bidiIsolate(shortLabel(data.label)),+ text: bidiIsolate(shortLabel(data.caption ?? data.label)),fontSize: 11,fontFamily: fontStack,listening: false,@@ -3612,7 +3613,7 @@x: textLeft,y: CARD.pad + 1,width: textWidth,- text: data.label,+ text: data.caption ?? data.label,fontSize: 12,fontStyle: '600',fontFamily: fontStack,@@ -4903,6 +4904,12 @@<span class="spacer"></span>+ <!-- What the case proposed by itself, first among the counts: it is the one that asks+ for something, and the edges it names are dashed somewhere in the drawing. -->+ {#if !snapshotReading}+ <ProposalReview caseId={caseState.current?.id} />+ {/if}+{#if payload}<!-- What is **drawn**, which the folds change and the case does not hear about.Counting what the case sent would leave the number arguing with the picture@@ -5415,6 +5422,7 @@<Icon name="x" size={14} /></button></header>+ {#if chosen.caption}<p class="meta">{chosen.caption}</p>{/if}<p class="meta">{madeHereLabel(chosen) ?? entityKindLabel(chosen, entityLabel(chosen.type))}· {entityFamily(chosen.type)}diff --git a/frontend/src/tools/Inspector.svelte b/frontend/src/tools/Inspector.svelteindex f8dbf58..ae96e1b 100644--- a/frontend/src/tools/Inspector.svelte+++ b/frontend/src/tools/Inspector.svelte@@ -3,6 +3,7 @@import { api } from '../lib/api.js';import { fileUrl } from '../lib/fileUrl.js';import { caseState, uiState, reloadCase, toast } from '../lib/state.svelte.js';+ import { workFolder } from '../lib/folders.js';import {adjustDefaults, buildFrameOps, previewStyle, uid, videoSeed, VIDEO_ADJUST_IDS,hasVideoEdits, normalizeRightAngleRotation, rotationOps, sourceStem, frameSaveNames,@@ -645,7 +646,8 @@saving = 'all';try {const saved = await saveFrames(frames, {- folder: saveFolder || null, note: null, names: frames.map((f) => frameNames.get(f.id)),+ // as in SaveToCase: Unfiled has to be sent when the work folder filed them+ folder: saveFolder || (workFolder() ? '' : null), note: null, names: frames.map((f) => frameNames.get(f.id)),});toast(`Saved ${frames.length} frames to the case${dupeNote(saved)}`, 'ok');} catch (e) {diff --git a/frontend/src/tools/MediaLibrary.render.test.js b/frontend/src/tools/MediaLibrary.render.test.jsindex 96723df..2293357 100644--- a/frontend/src/tools/MediaLibrary.render.test.js+++ b/frontend/src/tools/MediaLibrary.render.test.js@@ -276,3 +276,52 @@ describe('open in… from a row', () => {expect(doors()).toHaveLength(0);});});++describe('the worklist of what was brought in', () => {+ const routes = get.getMockImplementation();+ const posts = post.getMockImplementation();+ afterEach(() => {+ get.mockImplementation(routes);+ post.mockImplementation(posts);+ uiState.openSheet = null;+ });++ const worklistButton = () =>+ [...target.querySelectorAll('button')].find((node) => node.textContent.trim() === 'Worklist');++ it('opens the worklist the case already has', async () => {+ get.mockImplementation(async (url) => {+ if (url.includes('/media/page')) return page;+ if (url.endsWith('/sheets/from-case/files')) return { total: 2, answered: 0, sheet: 'e_list' };+ return {};+ });+ await open();++ await press(worklistButton());++ expect(post).not.toHaveBeenCalledWith('/api/cases/case-a/sheets/from-case', expect.anything());+ expect(uiState.openSheet).toBe('e_list');+ expect(uiState.tool).toBe('sheet');+ });++ it('builds it on the first press', async () => {+ get.mockImplementation(async (url) => {+ if (url.includes('/media/page')) return page;+ if (url.endsWith('/sheets/from-case/files')) return { total: 2, answered: 0, sheet: null };+ return {};+ });+ post.mockImplementation(async (url) =>+ url.endsWith('/sheets/from-case') ? { id: 'e_new', taken: 2, total: 2 } : { queued: 1 },+ );+ await open();++ await press(worklistButton());++ expect(post).toHaveBeenCalledWith('/api/cases/case-a/sheets/from-case', {+ title: 'Files to geolocate',+ shape: 'files',+ });+ expect(uiState.openSheet).toBe('e_new');+ expect(uiState.tool).toBe('sheet');+ });+});diff --git a/frontend/src/tools/MediaLibrary.svelte b/frontend/src/tools/MediaLibrary.svelteindex f2a7f86..bbd8ae2 100644--- a/frontend/src/tools/MediaLibrary.svelte+++ b/frontend/src/tools/MediaLibrary.svelte@@ -18,7 +18,10 @@SORTS,} from '../lib/mediaFilter.js';import { listenForPaste, pasteImage, resolvePaste } from '../lib/clipboardPaste.js';- import { gotoPoint, openInReverseSearch } from '../lib/navigate.js';+ import { gotoPoint } from '../lib/navigate.js';+ import { openInOptions } from '../lib/openIn.js';+ import { filedToast } from '../lib/folders.js';+ import { uploadFiles } from '../lib/mediaImport.js';import { TOOL_LABELS } from '../lib/workspaces.js';import { revealMediaFolder } from '../lib/reveal.js';import { thisBrowser } from '../lib/thisBrowser.js';@@ -523,20 +526,8 @@importBusy = true;try {const c = await ensureCase();- let dups = 0;- const landed = [];- for (const file of files) {- const form = new FormData();- form.append('file', file);- if (sourceUrl) form.append('source_url', sourceUrl);- try {- const res = await api.post(`/api/cases/${c.id}/media/upload`, form);- if (res.duplicate) dups++;- else if (res.item?.path) landed.push(res.item.path);- } catch (e) {- toast(`${file.name}: ${e.message}`, 'danger');- }- }+ const { landed, filed, duplicates: dups, failed } = await uploadFiles(c.id, files, sourceUrl);+ for (const refusal of failed) toast(`${refusal.name}: ${refusal.message}`, 'danger');lastSource = sourceUrl;pendingImport = null;await Promise.all([refresh(), reloadCase()]);@@ -547,7 +538,7 @@const offer = sourceUrl? null: { label: 'Set source', onClick: () => (statingSource = { paths: landed }) };- toast(`${count} added to the case`, 'ok', offer ? 6000 : 3800, offer);+ filedToast(`${count} filed`, filed, { fallback: `${count} added to the case`, action: offer });}if (dups) toast(`${dups} duplicate${dups > 1 ? 's' : ''} skipped (same SHA-256)`, 'warn');} finally {@@ -574,6 +565,41 @@}}+ /**+ * Open the case's files worklist in Sheet, building it on the first press.+ *+ * The second press opens the one already built rather than a twin of it: the worklist+ * is where the statuses are, and a fresh copy would start them all over.+ */+ let worklistBusy = $state(false);+ async function openWorklist() {+ const id = caseState.current?.id;+ if (!id || worklistBusy) return;+ worklistBusy = true;+ try {+ const preview = await api.get(`/api/cases/${id}/sheets/from-case/files`);+ if (!preview.total && !preview.sheet) {+ toast('No picture or video was imported into this case yet.');+ return;+ }+ let sheetId = preview.sheet;+ if (!sheetId) {+ const made = await api.post(`/api/cases/${id}/sheets/from-case`, {+ title: 'Files to geolocate',+ shape: 'files',+ });+ sheetId = made.id;+ await reloadCase();+ }+ uiState.openSheet = sheetId;+ uiState.tool = 'sheet';+ } catch (error) {+ toast(error.message || 'The worklist could not be opened.', 'error');+ } finally {+ worklistBusy = false;+ }+ }+async function download() {const target = url.trim();if (!target) return;@@ -670,13 +696,12 @@// several attachments — nothing was downloaded yet, let the analyst pickpicker = { url: job.url, items: status.result.items.map((i) => ({ ...i, selected: true })) };} else if (status.status === 'done') {- toast(- status.result?.duplicate- ? 'Already in the case (same SHA-256)'- : `Downloaded: ${status.result?.item?.filename}`,- status.result?.duplicate ? 'warn' : 'ok'- );await Promise.all([refresh(), reloadCase()]);+ if (status.result?.duplicate) toast('Already in the case (same SHA-256)', 'warn');+ else {+ const name = status.result?.item?.filename;+ filedToast(`Downloaded ${name}`, [status.result?.entity], { fallback: `Downloaded: ${name}` });+ }} else {toast(`Download failed: ${status.error}`, 'danger', 6000);}@@ -708,22 +733,6 @@}}- function sendToComposer(item) {- if (!uiState.composeQueue.includes(item.path)) {- uiState.composeQueue.push(item.path);- }- uiState.tool = 'proof';- }-- function inspect(item) {- uiState.inspectPath = item.path;- uiState.tool = 'inspect';- }-- function reverseSearch(item) {- openInReverseSearch({ path: item.path, kind: item.kind, label: item.title ?? item.filename });- }-// --- open in… ---// The tools a picture can be taken on to, behind one door per row. Three of them// side by side made the widest row seven buttons, and a small card more buttons@@ -731,11 +740,7 @@const OPEN_IN_HEIGHT = 130; // room the menu needs under its button before it opens upwardlet openIn = $state(null); // { item, left, right, top, bottom } while a row's menu is up- const openInOptions = (item) => [- { id: 'inspect', icon: 'inspect', run: inspect },- { id: 'reverse', icon: 'search', run: reverseSearch },- ...(item.kind === 'image' ? [{ id: 'proof', icon: 'proof', run: sendToComposer }] : []),- ];+ const fileOf = (item) => ({ path: item.path, kind: item.kind, label: item.title ?? item.filename });/*** Open a row's menu beside its button. Placed against the window rather than@@ -762,9 +767,8 @@}function runOpenIn(option) {- const { item } = openIn;openIn = null;- option.run(item);+ option.run();}function fmtSize(bytes) {@@ -818,7 +822,7 @@// the one it has, and saying so is what stops the analyst pasting again.if (result.duplicate) toast('Already in the case (same SHA-256)', 'warn');else {- toast('Image added to the case', 'ok');+ filedToast('Image filed', [result.entity], { fallback: 'Image added to the case' });uiState.focusMedia = result.item.path;}} catch (e) {@@ -931,6 +935,11 @@<button class="btn" onclick={() => fileInput.click()}><Icon name="upload" size={15} /> Import</button>+ <!-- The pictures and videos brought in here, as the sheet they are worked down in. -->+ <button class="btn" onclick={openWorklist} disabled={!items.length || worklistBusy}+ title="The imported pictures and videos as a sheet, each marked done once a proof answers it">+ <Icon name="table" size={15} /> Worklist+ </button><!-- The two upkeep sweeps, behind one door. The door stays put on an emptycase with its rows disabled: a header that reorganises itself on thefirst import is a header nobody learns. -->@@ -1379,7 +1388,7 @@style:top={openIn.top == null ? null : `${openIn.top}px`}style:bottom={openIn.bottom == null ? null : `${openIn.bottom}px`}>- {#each openInOptions(openIn.item) as option (option.id)}+ {#each openInOptions(fileOf(openIn.item)) as option (option.id)}<button class="upkeep-option" role="menuitem" onclick={() => runOpenIn(option)}><Icon name={option.icon} size={14} /><span>{TOOL_LABELS[option.id]}</span>diff --git a/frontend/src/tools/MediaLibrary.test.js b/frontend/src/tools/MediaLibrary.test.jsindex d954f90..c6a07d0 100644--- a/frontend/src/tools/MediaLibrary.test.js+++ b/frontend/src/tools/MediaLibrary.test.js@@ -475,7 +475,8 @@ describe('where an imported file came from', () => {});it('carries the stated origin on every file of the batch', () => {- expect(source).toContain("if (sourceUrl) form.append('source_url', sourceUrl)");+ // lib/mediaImport.js sends it on each upload, tested there+ expect(source).toContain('uploadFiles(c.id, files, sourceUrl)');});it('remembers the last one stated, since a thread arrives in several drops', () => {diff --git a/frontend/src/tools/Notebook.svelte b/frontend/src/tools/Notebook.svelteindex dcc7376..405335c 100644--- a/frontend/src/tools/Notebook.svelte+++ b/frontend/src/tools/Notebook.svelte@@ -872,7 +872,7 @@ flowchart LR<input id="notebook-note-title" class="input" placeholder="Note title…" bind:value={noteModal.title} /><span class="modal-label" style="margin-top:10px">Folder (in My work)</span>- <FolderSelect bind:value={noteModal.folder} folders={caseState.current?.folders ?? []} emptyLabel="My work (root)" />+ <FolderSelect bind:value={noteModal.folder} folders={caseState.current?.folders ?? []} emptyLabel="My work (root)" fresh /><div class="modal-row"><div style="flex:1"></div>diff --git a/frontend/src/tools/PostComposer.svelte b/frontend/src/tools/PostComposer.svelteindex 29175bf..97f49d2 100644--- a/frontend/src/tools/PostComposer.svelte+++ b/frontend/src/tools/PostComposer.svelte@@ -1130,9 +1130,6 @@<div class="tool"><div class="tool-header">- <div class="head-text">- <h2>Geo Report</h2>- </div>{#if caseState.current}<input class="input title-input" bind:value={postName} maxlength="200" aria-label="Post name" />{/if}@@ -1580,7 +1577,7 @@<input id="report-note-title" class="input" placeholder="Report title…" bind:value={reportModal.title} /><span class="modal-label" style="margin-top:10px">Folder (in My work)</span>- <FolderSelect bind:value={reportModal.folder} folders={caseState.current?.folders ?? []} emptyLabel="My work (root)" />+ <FolderSelect bind:value={reportModal.folder} folders={caseState.current?.folders ?? []} emptyLabel="My work (root)" fresh /><div class="modal-row"><div style="flex:1"></div>@@ -1846,18 +1843,12 @@/* header actions */.tool-header {- display: flex;- align-items: flex-start;gap: 16px;}- .head-text {- display: flex;- flex-direction: column;- min-width: 0;- }.head-actions {margin-left: auto;display: flex;+ align-items: center;gap: 10px;flex-shrink: 0;}diff --git a/frontend/src/tools/ProofComposer.svelte b/frontend/src/tools/ProofComposer.svelteindex 573efeb..c617163 100644--- a/frontend/src/tools/ProofComposer.svelte+++ b/frontend/src/tools/ProofComposer.svelte@@ -12,6 +12,7 @@// one a coordinate row is written in (decimal, hemispheres, or DMS).import { parseLatLon } from '../lib/sheetRoles.js';import { zoneAt } from '../lib/localZone.js';+ import { kinSentence } from '../lib/proposalReview.js';import { caseState, uiState, ensureCase, reloadCase, toast, prefs, fmtCoords } from '../lib/state.svelte.js';import { templatesState } from '../lib/state.svelte.js';import Icon from '../components/Icon.svelte';@@ -3712,6 +3713,26 @@// [{ id, label }] — points this save moved the proof off that nothing else in// the case holds. Asked about after the question above, never beside it.let orphanOffer = $state(null);+ /** What the proof just saved shares with the rest of the case: other geolocations on+ * its site, what its account posted. Read once after a save, gone at the next edit. */+ let kin = $state(null);+ const kinWords = $derived(kin && kin.name === savedName && !dirty ? kinSentence(kin) : null);++ async function readKin(caseId, entityId, name) {+ if (!entityId) return;+ try {+ const answer = await api.get(`/api/cases/${caseId}/entities/${entityId}/kin`);+ kin = { ...answer, id: entityId, name };+ } catch {+ kin = null;+ }+ }++ function showKin() {+ if (!kin) return;+ uiState.openGraphEntity = kin.id;+ uiState.tool = 'graph';+ }let orphanDeleting = $state(false);/** Say yes to the points: they are filed exactly as the automatic path files@@ -3871,6 +3892,7 @@savedSnapshot = docSnapshot();await reloadCase();toast(`Proof saved: ${result.png}`, 'ok');+ void readKin(c.id, result.id, result.name);// The points this proof carries. Filed already, or a question — the server// answers with nothing at all when the case already holds them, so// re-saving never asks twice.@@ -4411,10 +4433,10 @@<div class="tool"><div class="tool-header">- <h2>Geo Proof</h2>{#if proofStarted}<inputclass="input title-input"+ aria-label="Proof name"bind:value={proof.title}oninput={() => (dirty = true)}/>@@ -4477,6 +4499,20 @@</button></div>+ {#if kinWords}+ <!-- What the save just joined: the site this point shares with other geolocations,+ the account behind the footage. Said here because this is where the analyst is,+ not in a graph they would have to think of opening. -->+ <div class="kin">+ <Icon name="link" size={13} />+ <span>{kinWords}</span>+ <button class="btn btn-ghost btn-xs" onclick={showKin}>See in the graph</button>+ <button class="btn btn-ghost btn-xs" aria-label="Dismiss" title="Dismiss" onclick={() => (kin = null)}>+ <Icon name="x" size={12} />+ </button>+ </div>+ {/if}+<div class="body"><!-- The drawing tools act on a proof; until one is open or created there isnothing to draw on, so the rail stays out of the way. -->@@ -5370,9 +5406,6 @@padding: 14px 16px 12px;flex-shrink: 0;}- .tool-header h2 {- font-weight: 700;- }.spacer { flex: 1; }.export-split {position: relative;@@ -5739,4 +5772,10 @@.open-meta { display: flex; flex-direction: column; gap: 2px; }.open-title { font-weight: 600; font-size: var(--fs-sm); }.open-sub { font-size: var(--fs-xs); color: var(--text-3); }+ .kin {+ display: flex; align-items: center; gap: 8px; padding: 5px 14px;+ border-bottom: 1px solid var(--border); background: var(--accent-soft);+ color: var(--text-2); font-size: var(--fs-xs);+ }+ .kin span { flex: 1; min-width: 0; }</style>diff --git a/frontend/src/tools/ProofComposer.test.js b/frontend/src/tools/ProofComposer.test.jsindex ae422ac..4dcebb6 100644--- a/frontend/src/tools/ProofComposer.test.js+++ b/frontend/src/tools/ProofComposer.test.js@@ -36,7 +36,8 @@ describe('Proof Composer empty state', () => {describe('Proof Composer header', () => {it('uses the same compact controls as Inspect', () => {- const header = source.slice(source.indexOf('<div class="tool-header">'), source.indexOf('</div>\n\n <div class="body">'));+ // Up to the body: the line a save writes under the header sits between the two.+ const header = source.slice(source.indexOf('<div class="tool-header">'), source.indexOf('\n <div class="body">'));expect(header).not.toContain('class="btn"');expect(header).not.toContain('btn-primary');@@ -52,7 +53,8 @@ describe('Proof Composer header', () => {});it('exports the current proof and exposes its remembered destination', () => {- const header = source.slice(source.indexOf('<div class="tool-header">'), source.indexOf('</div>\n\n <div class="body">'));+ // Up to the body: the line a save writes under the header sits between the two.+ const header = source.slice(source.indexOf('<div class="tool-header">'), source.indexOf('\n <div class="body">'));expect(header).toContain("exporting ? 'Exporting…' : 'Export PNG'");expect(header).toContain('onclick={exportProofPng}');@@ -400,7 +402,7 @@ describe('Proof naming', () => {});it('names the proof in the header and nowhere else', () => {- expect(source).toContain('<input\n class="input title-input"\n bind:value={proof.title}');+ expect(source).toContain('<input\n class="input title-input"\n aria-label="Proof name"\n bind:value={proof.title}');expect(source).not.toContain('newProofName');});diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelteindex ff6af34..8252993 100644--- a/frontend/src/tools/Satellite.svelte+++ b/frontend/src/tools/Satellite.svelte@@ -36,6 +36,7 @@import { panelWidth } from '../lib/panelWidth.js';import PlaceSearch from './satellite/PlaceSearch.svelte';import { assignFolder } from '../lib/filing.js';+ import { filedToast } from '../lib/folders.js';import { saveRelation } from '../lib/relations.svelte.js';import { openComparison, openEntity, openMapAt } from '../lib/navigate.js';import { offerNote, withdrawNote } from '../lib/noteHere.svelte.js';@@ -1844,14 +1845,14 @@savingPlace = true;try {const c = await ensureCase();- await api.post(`/api/cases/${c.id}/satellite/place`, {+ const place = await api.post(`/api/cases/${c.id}/satellite/place`, {lat: displayCoords.lat,lon: displayCoords.lon,zoom: center.zoom,bearing,});await reloadCase();- toast('Place saved. Find it in the case sidebar', 'ok');+ filedToast('Place saved', [place], { fallback: 'Place saved. Find it in the case sidebar' });} catch (e) {toast(`Could not save place: ${e.message}`, 'danger', 6000);} finally {diff --git a/frontend/src/tools/Sheet.fromProofs.render.test.js b/frontend/src/tools/Sheet.fromProofs.render.test.jsindex 1f4b4f3..e8bcf33 100644--- a/frontend/src/tools/Sheet.fromProofs.render.test.js+++ b/frontend/src/tools/Sheet.fromProofs.render.test.js@@ -98,11 +98,17 @@ function route(path) {return Promise.resolve({});}-async function open() {+async function open({ home = false } = {}) {target = document.createElement('div');document.body.append(target);live = mount(Sheet, { target });await settle();+ // The tab lands on its home. Most tests are about a sheet, so they go in the way the+ // analyst does: the first of the recent sheets.+ if (!home) {+ target.querySelector('.home .sheet')?.click();+ await settle();+ }return target;}diff --git a/frontend/src/tools/Sheet.render.test.js b/frontend/src/tools/Sheet.render.test.jsindex 5b5f1d3..2c55ba2 100644--- a/frontend/src/tools/Sheet.render.test.js+++ b/frontend/src/tools/Sheet.render.test.js@@ -164,11 +164,17 @@ function route(path) {return Promise.resolve({});}-async function open() {+async function open({ home = false } = {}) {target = document.createElement('div');document.body.append(target);live = mount(Sheet, { target });await settle();+ // The tab lands on its home. Most tests are about a sheet, so they go in the way the+ // analyst does: the first of the recent sheets.+ if (!home) {+ target.querySelector('.home .sheet')?.click();+ await settle();+ }return target;}@@ -1590,11 +1596,17 @@ describe('a column that knows what it holds', () => {expect(chip.classList.contains('unknown')).toBe(true);});- it('filters on a chip when it is clicked', async () => {+ it('opens the list on a status chip rather than filtering on it', async () => {await openBinder();- rows()[0].querySelectorAll('.cell-chip')[0].click();+ const chip = rows()[0].querySelectorAll('.cell-chip')[0];+ const before = rows().length;+ chip.click();await settle();- expect(rows()).toHaveLength(1);+ // The chip reads as the control that changes it: the editor opens with the column's+ // words, and the rows stay as they were.+ expect(rows()).toHaveLength(before);+ expect(target.querySelector('.editor')).not.toBeNull();+ expect(target.textContent).toContain('in progress');});it('says when a point claims less than it looks like it claims', async () => {@@ -2758,9 +2770,13 @@ describe('the sheet itself', () => {get.mockImplementation((path) =>path.endsWith('/sheets') ? Promise.resolve({ sheets: [] }) : route(path),);- await open();- expect(target.querySelector('.empty')).not.toBeNull();- expect(button('New sheet')).not.toBeUndefined();+ await open({ home: true });+ expect(target.querySelector('.home')).not.toBeNull();+ expect(target.textContent).toContain('No sheet in this case yet.');+ // The templates and the three ways a table comes in, all on the home.+ expect(button('Verification worklist')).not.toBeUndefined();+ expect(button('Paste a table')).not.toBeUndefined();+ expect(button('From the case')).not.toBeUndefined();});it('exports the rows on screen rather than the file on disk', async () => {@@ -3952,3 +3968,115 @@ describe('a geolocation index into proofs', () => {expect(post.mock.calls.at(-1)[1].skip).toEqual(['r2']);});});+++describe('the home the tab lands on', () => {+ const TWO = [+ { id: 'e_old', title: 'Old list', rows: 4, columns: 3, modified_at: '2026-09-01T10:00:00Z' },+ {+ id: SHEET.id, title: SHEET.title, rows: 3, columns: 3, modified_at: '2026-09-30T10:00:00Z',+ progress: { kind: 'state', column: 'Status', count: 1, total: 3 },+ },+ ];++ function withHome({ sheets = TWO, files = null, proofs = 0 } = {}) {+ get.mockImplementation((path) => {+ if (path.endsWith('/sheets')) return Promise.resolve({ sheets });+ if (path.endsWith('/sheets/from-case/files')) {+ return Promise.resolve(files ?? { total: 0, answered: 0, sheet: null });+ }+ if (path.includes('/catalog/summary')) {+ return Promise.resolve({ total: proofs, by_type: proofs ? { proof: proofs } : {} });+ }+ return route(path);+ });+ }++ afterEach(() => {+ localStorage.clear();+ uiState.openSheet = null;+ });++ it('opens on the recent sheets rather than on one of them', async () => {+ withHome();+ await open({ home: true });++ expect(target.querySelector('.rows')).toBeNull();+ const recent = [...target.querySelectorAll('.home .sheet .name')].map((n) => n.textContent);+ // Newest edit first.+ expect(recent).toEqual(['Candidates', 'Old list']);+ // With the footer's own progress words.+ expect(target.querySelector('.home .sheet small').textContent).toContain('1 of 3 done');+ });++ it('leads with the sheet last open here', async () => {+ localStorage.setItem('azimut.sheet.last', JSON.stringify({ 'case-a': 'e_old' }));+ withHome();+ await open({ home: true });++ const first = target.querySelector('.home .sheet');+ expect(first.textContent).toContain('Old list');+ expect(first.textContent).toContain('Last open');+ });++ it('offers the worklist the case holds the makings of, counted', async () => {+ post.mockResolvedValue({ id: SHEET.id, taken: 21, total: 21 });+ withHome({ files: { total: 21, answered: 8, sheet: null }, proofs: 8 });+ await open({ home: true });++ expect(target.textContent).toContain('21 imported files, 13 without a proof');+ expect(target.textContent).toContain('8 proofs');+ button('Files to geolocate').click();+ await settle();++ const [path, body] = post.mock.calls.at(-1);+ expect(path).toBe('/api/cases/case-a/sheets/from-case');+ expect(body).toEqual({ title: 'Files to geolocate', shape: 'files' });+ });++ it('opens the worklist already built instead of building a twin', async () => {+ withHome({ files: { total: 21, answered: 8, sheet: SHEET.id } });+ await open({ home: true });++ button('Files to geolocate').click();+ await settle();++ expect(post).not.toHaveBeenCalledWith('/api/cases/case-a/sheets/from-case', expect.anything());+ expect(rows()).toHaveLength(3);+ });++ it('closes back to the home, saving what was typed first', async () => {+ withHome();+ await open();+ expect(rows()).toHaveLength(3);+ put.mockClear();+ const cell = rows()[0].querySelectorAll('.cell:not(.gutter)')[1];+ cell.dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));+ flushSync();+ const editor = target.querySelector('.editor');+ editor.value = 'Quai nord';+ editor.dispatchEvent(new Event('input', { bubbles: true }));+ editor.dispatchEvent(new Event('blur', { bubbles: true }));+ flushSync();+ // Pressed before the autosave's own delay has run out.+ expect(put).not.toHaveBeenCalled();++ button('Close').click();+ await settle();++ expect(target.querySelector('.home')).not.toBeNull();+ expect(target.querySelector('.rows')).toBeNull();+ expect(put).toHaveBeenCalledTimes(1);+ expect(put.mock.calls[0][1].rows[0]).toEqual(['r1', 'Quai nord', 'ruled out']);+ });++ it('opens straight onto a sheet another tool asked for', async () => {+ uiState.openSheet = SHEET.id;+ withHome();+ await open({ home: true });++ expect(rows()).toHaveLength(3);+ expect(uiState.openSheet).toBeNull();+ });+});+diff --git a/frontend/src/tools/Sheet.svelte b/frontend/src/tools/Sheet.svelteindex aead40f..56effd6 100644--- a/frontend/src/tools/Sheet.svelte+++ b/frontend/src/tools/Sheet.svelte@@ -155,6 +155,7 @@import SheetGeocode from '../components/SheetGeocode.svelte';import SheetHeadingMenu from '../components/SheetHeadingMenu.svelte';import SheetHelp from '../components/SheetHelp.svelte';+ import SheetHome from '../components/SheetHome.svelte';import SheetLegend from '../components/SheetLegend.svelte';import SheetAnchors from '../components/SheetAnchors.svelte';import SheetToCase from '../components/SheetToCase.svelte';@@ -485,19 +486,46 @@const answer = await api.get(`/api/cases/${id}/sheets`);sheets = answer.sheets ?? [];if (openId && !sheets.some((sheet) => sheet.id === openId)) close();- // The one that was being worked on, and the first sheet only as a fallback. A tool- // that reopened on sheet number one sent the analyst back through the picker every- // morning, and on a case holding nine worklists that is the wrong nine times out of- // ten.- if (!openId && sheets.length) {- const last = lastOpened(id);- open(sheets.some((sheet) => sheet.id === last) ? last : sheets[0].id);+ // The tab lands on its home rather than reopening a sheet: the one last open leads+ // the recent list there, one click away, beside what the case could start.+ lastId = lastOpened(id);+ if (!openId && uiState.openSheet && sheets.some((sheet) => sheet.id === uiState.openSheet)) {+ const asked = uiState.openSheet;+ uiState.openSheet = null;+ open(asked);}} catch {sheets = [];}}+ /** The sheet last open in this case, which leads the home's recent list. */+ let lastId = $state(null);++ // A sheet asked for from another tool: the Media Library's worklist, a toast. Consumed+ // once, like every other `uiState.open*` handoff.+ $effect(() => {+ const asked = uiState.openSheet;+ if (!asked || !caseId) return;+ untrack(() => {+ if (sheets.some((sheet) => sheet.id === asked)) {+ uiState.openSheet = null;+ openId = null;+ open(asked);+ } else {+ list(caseId);+ }+ });+ });++ /** Back to the home. Whatever is unsaved is written first, as on any other switch, so+ * closing never loses an edit. */+ async function goHome() {+ await flush();+ close();+ await list(caseId);+ }+/** Which sheet this case was last left on. Kept in the browser rather than in the case:* it is where *this* analyst was reading, not something the case believes, and a bundle* carrying it would hand a colleague somebody else's place in the work. */@@ -1609,15 +1637,23 @@* Press a chip in a cell.** A yes/no column **flips**: two words is a toggle, and the tooltip said as much while- * the only way to do it was a double-click or Enter. Everything else **filters** on the- * value pressed — on the value and not on the cell's text, so `2x S-125` asks for- * `S-125` and finds the rows holding three of them too.+ * the only way to do it was a double-click or Enter. A status or a set of values+ * **opens its list**, because a chip reads as the control that changes it: a click on+ * `to do` that filtered the column instead was the grid answering a question nobody+ * asked. Filtering on a value is the heading's funnel. A chip the app wrote, or one+ * naming another row, still **filters** on the value pressed — on the value and not on+ * the cell's text, so `2x S-125` asks for `S-125` and finds the rows holding three.*/function onChipClick(rowIndex, column, chip) {- if (roles[column.name]?.kind === 'boolean') {+ const kind = roles[column.name]?.kind;+ if (kind === 'boolean') {flipCell(rowIndex, column.index);return;}+ if ((kind === 'state' || kind === 'choice') && !appFilled(column.name)) {+ edit(rowIndex, column.index);+ return;+ }toggleValue(column.name, chip.value);}@@ -2233,6 +2269,8 @@* whose headings happen to spell `Title` is not this shape, and `built` is the record* only the build writes. */const refreshable = $derived(Object.keys(meta.built ?? {}).length > 0);+ /** Which of the two built shapes: one row per imported file, or one per proof. */+ const builtFiles = $derived(meta.roles?.File?.kind === 'locked');let refreshing = $state(false);/**@@ -2260,7 +2298,9 @@await reloadCase();const said = [answer.added ? `${answer.added} row${answer.added === 1 ? '' : 's'} added` : '',- answer.gone ? `${answer.gone} proof${answer.gone === 1 ? '' : 's'} no longer in the case` : '',+ answer.gone+ ? `${answer.gone} ${builtFiles ? 'file' : 'proof'}${answer.gone === 1 ? '' : 's'} no longer in the case`+ : '',].filter(Boolean);toast(said.length ? `${said.join(', ')}.` : 'Already level with the case.');} catch (error) {@@ -3796,6 +3836,10 @@onclick={() => (confirming = { kind: 'sheet' })}><Icon name="trash" size={13} /></button>+ <!-- Back to the home, saved first: the way out Collage has, under the same word. -->+ <button class="btn btn-ghost btn-sm" onclick={goHome} title="Save and go back to the sheets">+ <Icon name="x" size={14} /> Close+ </button>{/if}<!-- The grid keeps its power under a right-click, which is right — and a right-clicknobody tries is a feature nobody has. So one door says what there is. -->@@ -3806,42 +3850,24 @@</header>{#if !openId}- <div class="empty">- {#if loading}- <p>Opening.</p>- {:else}- <Icon name="table" size={30} />- <p>No sheet in this case.</p>- <small>A sheet is a CSV in the case folder.</small>- <!-- What the grid is *for*, in an empty state that used to say only that it was- empty. A worklist, a comparison grid and the half-facts are the three things no- other tool here covers, and an analyst who does not know that files a- spreadsheet somewhere else instead. -->- <ul class="empty-what">- <li>A worklist that counts what is left</li>- <li>A comparison grid: candidates down, criteria across</li>- <li>Notes too rough for the graph</li>- </ul>- <div class="row-actions">- <button class="btn btn-primary btn-sm" onclick={() => (creating = { title: '' })}>- New sheet- </button>- <!-- The same file kinds the header takes, workbooks included: an empty state that- refused an `.xlsx` the menu accepts is the app disagreeing with itself. -->- <label class="btn btn-sm">- Import a file- <input type="file" accept=".csv,.tsv,.xlsx,text/csv,text/plain" hidden- onchange={(event) => { importFile(event.currentTarget.files); event.currentTarget.value = ''; }} />- </label>- <button class="btn btn-sm" onclick={() => (creating = { title: '', text: '' })}>- Paste a table- </button>- <button class="btn btn-sm" onclick={() => (fromCase = true)}>- From the case- </button>- </div>- {/if}- </div>+ {#if loading}+ <div class="empty"><p>Opening.</p></div>+ {:else}+ <!-- The tab opens here, not on the last sheet: recent work and a way in, the two+ halves Inspect opens on. The case's own proposals lead the way in, counted. -->+ <SheetHome+ {caseId}+ {sheets}+ last={lastId}+ busy={building}+ onopen={open}+ onbuild={buildFromCase}+ ontemplate={(template) => (creating = { title: sheetTemplate(template).label, template })}+ onimport={importFile}+ onpaste={() => (creating = { title: '', text: '' })}+ onfromcase={() => (fromCase = true)}+ />+ {/if}{:else}<div class="question">{#if refreshable}@@ -3849,7 +3875,9 @@bar is the one that does. Pressed, never automatic — refreshing on open wouldrewrite a file somebody opened to read. It adds and never removes. --><button class="btn btn-ghost btn-sm" disabled={refreshing} onclick={refreshFromCase}- title="File the proofs added since, and restate the columns the case owns">+ title={builtFiles+ ? 'Add the files imported since, and mark done the ones a proof now answers'+ : 'Add the proofs filed since, and restate the columns the case owns'}><Icon name="reset" size={13} /> {refreshing ? 'Refreshing' : 'Refresh'}</button>{/if}@@ -5139,16 +5167,6 @@justify-content: center; gap: 8px; color: var(--text-3);}.empty p { color: var(--text-2); font-size: var(--fs-md); }- .empty small { font-size: var(--fs-sm); }- /* What the grid is for, in the state that has nothing to show. A list without- bullets: three short lines read as three answers, and the browser's own discs- and indent read as prose in a panel that is centred. */- .empty-what {- display: flex; flex-direction: column; gap: 3px;- margin: 4px 0 2px; padding: 0; list-style: none; text-align: center;- color: var(--text-3); font-size: var(--fs-sm);- }- .row-actions { display: flex; gap: 8px; margin-top: 6px; }/* -- the question bar ---------------------------------------------------- */.question {diff --git a/frontend/src/tools/Timeline.svelte b/frontend/src/tools/Timeline.svelteindex 6532ca6..98f1644 100644--- a/frontend/src/tools/Timeline.svelte+++ b/frontend/src/tools/Timeline.svelte@@ -37,6 +37,7 @@densityUnit,layoutDensityBuckets,layoutTimelineItems,+ shareItemRows,machineZone,moveTemporalRaw,nowPosition,@@ -207,9 +208,10 @@** The two are one reading, so both are always there. `view_mode` from a saved view* says which of them it favours, and dragging the bar between them moves it for now- * without rewriting what the view says.+ * without rewriting what the view says. The share is a ceiling: lanes with few entries+ * leave the rest to the list, and crowded ones fill it before any `+n`.*/- const SHARES = { plot: 0.62, list: 0.28 };+ const SHARES = { plot: 0.75, list: 0.28 };let axisShare = $state(SHARES.plot);let chronologyHeight = $state(0);let overviewHeight = $state(0);@@ -311,22 +313,36 @@* one left without its name. A plate is not being read by anyone yet, so it asks for* no selection and comes out the same whatever was clicked.*/- function buildTracks(axisWidth, selectedId = null) {- return groupedTimelineTracks(trackSpecs, baseTrackItems, groupBy, entityLabel).map((track) => {+ function buildTracks(axisWidth, selectedId = null, height = 0) {+ const drawn = groupedTimelineTracks(trackSpecs, baseTrackItems, groupBy, entityLabel).map((track) => {const baseId = track.parentId ?? track.id;const expanded = Boolean(expandedTracks[baseId]);+ const dated = track.items.filter((item) => item.earliest);return {...track,expanded,+ dated,total: groupBy === 'none' ? (trackPages[baseId]?.total ?? track.items.length) : track.items.length,- layout: layoutTimelineItems(- track.items.filter((item) => item.earliest), from, to, axisWidth,- expanded ? PAGE : 6, { selectedId }- ),+ layout: layoutTimelineItems(dated, from, to, axisWidth, PAGE, { selectedId }),};});+ // The lanes share the axis's height: what is left once the ruler, the folded lanes+ // and the opened ones are drawn goes to rows of marks, before any `+n`.+ const shared = (track) => !track.expanded && !track.collapsed;+ let room = height - 68;+ for (const track of drawn) {+ if (!shared(track)) room -= track.collapsed ? 43 : Math.max(46, track.layout.height) + 1;+ else room -= MARKS.top + MARKS.row + MARKS.bottom + 1;+ }+ const caps = shareItemRows(drawn.map((track) => shared(track) ? track.layout.rows : null), room / MARKS.row);+ return drawn.map(({ dated, ...track }, index) => {+ const cap = caps[index] ?? (track.collapsed ? 6 : null);+ return cap === null || track.layout.rows <= cap+ ? track+ : { ...track, layout: layoutTimelineItems(dated, from, to, axisWidth, cap, { selectedId }) };+ });}- const tracks = $derived(buildTracks(plotWidth, selected?.id ?? null));+ const tracks = $derived(buildTracks(plotWidth, selected?.id ?? null, axisMax));const density = $derived(layoutDensityBuckets(overview, extent));/*** The date scale under the minimap: one slot per period, named under its own bar.@@ -559,10 +575,33 @@landOnUndated = true;return;}- queue.scrollIntoView({ block: 'start' });queue.querySelector('.holding-list button')?.focus({ preventScroll: true });+ settleOn(queue);}));});+ /**+ * Scrolls the queue to the top of its pane, and again while it keeps moving: the axis,+ * the lanes and the pane take their measured room over several frames on a slow+ * machine, and a landing made once is left behind by whatever shifts after it. Ends+ * once the queue has held still for a few frames, or after about a second and a half.+ */+ function settleOn(queue) {+ let last = null;+ let still = 0;+ let frames = 0;+ const step = () => {+ if (!queue.isConnected) return;+ if (queue.getBoundingClientRect().top === last) still += 1;+ else {+ queue.scrollIntoView({ block: 'start' });+ last = queue.getBoundingClientRect().top;+ still = 0;+ }+ frames += 1;+ if (still < 6 && frames < 90) requestAnimationFrame(step);+ };+ step();+ }$effect(() => rangeMenu ? closeOnOutsidePointer(rangeElement, () => (rangeMenu = false)) : undefined);$effect(() => {diff --git a/frontend/src/tools/Timeline.test.js b/frontend/src/tools/Timeline.test.jsindex 9838dd0..6fdf70d 100644--- a/frontend/src/tools/Timeline.test.js+++ b/frontend/src/tools/Timeline.test.js@@ -341,7 +341,7 @@ describe('measuring between two entries', () => {describe('one reading, the axis over the list', () => {it('draws both whatever the mode, which only says which one gets the room', () => {expect(source).not.toContain("{#if viewMode === 'plot'}");- expect(source).toContain('const SHARES = { plot: 0.62, list: 0.28 };');+ expect(source).toContain('const SHARES = { plot: 0.75, list: 0.28 };');expect(source).toContain('style:max-height={`${axisMax}px`}');expect(source).toContain('role="separator"');expect(source).toContain("onclick={() => setViewMode('list')}");@@ -451,7 +451,7 @@ describe('reading a mark', () => {describe('exporting the axis', () => {it('serialises the tracks the tool laid out, never a canvas', () => {expect(source).toContain('timelinePlate({');- expect(source).toContain('const tracks = $derived(buildTracks(plotWidth, selected?.id ?? null));');+ expect(source).toContain('const tracks = $derived(buildTracks(plotWidth, selected?.id ?? null, axisMax));');});it('lays the page out at the plate’s width, not the browser’s', () => {diff --git a/frontend/src/tools/detect/AnalyzerLibrary.svelte b/frontend/src/tools/detect/AnalyzerLibrary.svelteindex 0ec6970..b4a529a 100644--- a/frontend/src/tools/detect/AnalyzerLibrary.svelte+++ b/frontend/src/tools/detect/AnalyzerLibrary.svelte@@ -21,6 +21,7 @@import AnalyzerBuilder from './AnalyzerBuilder.svelte';import AnalyzerLabel from './AnalyzerLabel.svelte';import AnalyzerSettings from './AnalyzerSettings.svelte';+ import FoldGroup from './FoldGroup.svelte';import Icon from '../../components/Icon.svelte';let {@@ -47,6 +48,8 @@/** Where the builder opens: `{ tab, check }`. */let start = $state(null);let readonly = $state(false);+ /** Built-in categories opened by hand; all start folded. */+ let openKinds = $state({});let busy = $state(false);let error = $state('');@@ -170,20 +173,22 @@<section aria-label="Built-in analyzers"><strong>Built in</strong>{#each analyzerGroups({ ...catalogue, custom: [] }) as group (group.label)}- <p class="group">{group.label}</p>- {#each group.list as entry (entry.id)}- {@const trust = catalogue?.reliability?.[entry.id]}- {@const locked = analyzerLock(entry, catalogue)}- <div class="row entry">- <button class="pick grow" style={`--tint: ${entry.colour}`} onclick={() => view(entry)} title={locked || undefined}>- <span class="swatch" aria-hidden="true"></span>- <span class="name">{entry.name}{#if trust} <span class="trust {trust}">({trust})</span>{/if}{#if locked} <span class="lock"><Icon name="key" size={10} /> set up</span>{/if}<small>{entry.description}</small></span>- </button>- <button class="cmp-icon" title="Copy to tune" aria-label={`Copy ${entry.name}`} onclick={() => copy(entry)}>- <Icon name="copy" size={13} />- </button>- </div>- {/each}+ <FoldGroup label={group.label} count={group.list.length} open={!!openKinds[group.label]}+ ontoggle={() => (openKinds = { ...openKinds, [group.label]: !openKinds[group.label] })}>+ {#each group.list as entry (entry.id)}+ {@const trust = catalogue?.reliability?.[entry.id]}+ {@const locked = analyzerLock(entry, catalogue)}+ <div class="row entry">+ <button class="pick grow" style={`--tint: ${entry.colour}`} onclick={() => view(entry)} title={locked || undefined}>+ <span class="swatch" aria-hidden="true"></span>+ <span class="name">{entry.name}{#if trust} <span class="trust {trust}">({trust})</span>{/if}{#if locked} <span class="lock"><Icon name="key" size={10} /> set up</span>{/if}<small>{entry.description}</small></span>+ </button>+ <button class="cmp-icon" title="Copy to tune" aria-label={`Copy ${entry.name}`} onclick={() => copy(entry)}>+ <Icon name="copy" size={13} />+ </button>+ </div>+ {/each}+ </FoldGroup>{/each}</section></div>@@ -311,14 +316,6 @@.measures span { margin-right: 4px; color: var(--text-3); font-weight: 700; }.fields { display: grid; gap: 8px; min-width: 0; margin: 0; padding: 0; border: 0; }.own { border-color: var(--accent); --tint: var(--accent); }- .group {- margin: 8px 0 2px;- color: var(--text-3);- font-size: 10px;- font-weight: 700;- letter-spacing: 0.06em;- text-transform: uppercase;- }.trust { color: var(--text-3); font-size: 10.5px; font-weight: 400; }.trust.reliable { color: var(--ok, #46a758); }.trust.rough { color: var(--warn, #e2a03f); }diff --git a/frontend/src/tools/detect/DetectPanel.svelte b/frontend/src/tools/detect/DetectPanel.svelteindex 3315c43..f4b85c4 100644--- a/frontend/src/tools/detect/DetectPanel.svelte+++ b/frontend/src/tools/detect/DetectPanel.svelte@@ -16,6 +16,7 @@import { detectRuns, refreshRuns } from '../../lib/detectRuns.svelte.js';import { clone, zoneRing } from '../../lib/map/analyzers.js';import { passBefore } from '../../lib/map/detectWhen.js';+ import { candidatePair } from '../../lib/map/detectReview.js';import { recipeCapability } from '../../lib/map/analyzerRules.js';import { containsPoint } from '../../lib/measure.js';import { detectionsWithRuns, isActive, plural } from '../../lib/map/detections.js';@@ -375,7 +376,11 @@acceptRun(run);if (resultId) candidateId = resultId;zones = [];- const shown = day(run.input.b);+ // The pass the candidate was read on, not the end of the run's window: a+ // click on the map reopens the run, and the review already showing that+ // candidate would not put its own pass back.+ const candidate = run.results?.find((row) => row.id === resultId);+ const shown = day(candidatePair(candidate, run).b);if (shown) onshow(shown);libraryFrom = detectionId && run.input.followup_id === detectionId ? 'detection' : 'home';view = 'review';diff --git a/frontend/src/tools/detect/DetectPanel.test.js b/frontend/src/tools/detect/DetectPanel.test.jsindex 04c2402..b0b5f15 100644--- a/frontend/src/tools/detect/DetectPanel.test.js+++ b/frontend/src/tools/detect/DetectPanel.test.js@@ -41,6 +41,17 @@ const button = (text) => [...document.querySelectorAll('button')].find((b) => b.const starts = (text) => [...document.querySelectorAll('button')].find((b) => b.textContent.trim().startsWith(text));const labelled = (label) => target.querySelector(`button[aria-label="${label}"]`);const heading = () => target.querySelector('h3')?.textContent.trim();+/** Every category of analyzers starts folded; open them all. */+async function unfold() {+ target.querySelectorAll('.fold[aria-expanded="false"]').forEach((fold) => fold.click());+ await settle();+}+/** Nothing is picked in What until asked: open the category holding an analyzer, then pick it. */+async function pickAnalyzer(name = recipe.name) {+ const radio = () => [...target.querySelectorAll('[role="radio"]')].find((b) => b.textContent.includes(name));+ if (!radio()) await unfold();+ radio().click(); await settle();+}const ceilingSlider = () => target.querySelector('input[aria-label="Maximum cloud cover"]');function slide(value) {const slider = ceilingSlider();@@ -316,8 +327,13 @@ it('shows shared groups and ungrouped areas in Where without selecting an area texpect(where.textContent).toContain('Ungrouped');expect(where.textContent).toContain('River');labelled('Use Ports').click(); await settle();- labelled('Use Priority').click(); await settle();+ // Harbor is all of Priority too, so that group reads as ticked, and unticking it takes Harbor out+ expect(labelled('Use Priority').getAttribute('aria-checked')).toBe('true');expect(where.querySelectorAll('.area-row')).toHaveLength(1);+ labelled('Use Priority').click(); await settle();+ expect(where.querySelectorAll('.area-row')).toHaveLength(0);+ expect(labelled('Use Ports').getAttribute('aria-checked')).toBe('false');+ labelled('Use Ports').click(); await settle();const search = where.querySelector('[aria-label="Search areas or groups"]');search.value = 'River'; search.dispatchEvent(new Event('input', { bubbles: true })); await settle();expect(where.textContent).not.toContain('Ports');@@ -644,8 +660,8 @@ it('walks a single pass through its steps and runs it once', async () => {post.mockResolvedValue({ id: RUN, status: 'queued', input: {}, results: [], total: 1, progress: 0 });await open({ opening: 'zones-aaaaaaaaaaaa' });expect(heading()).toBe('Where to look');- expect(target.textContent).toContain('1 tile · 4 requests a run');- button('Next: What').click(); await settle();+ expect(target.textContent).toContain('1 tile');+ button('Next: What').click(); await settle(); await pickAnalyzer();expect(heading()).toBe('What to look for');button('Next: When').click(); await settle();expect(heading()).toBe('Which two images');@@ -667,6 +683,7 @@ it('walks a single pass through its steps and runs it once', async () => {expect(button('Next: Start').disabled).toBe(false);button('Next: Start').click(); await settle();expect(heading()).toBe('Name and start');+ expect(target.textContent).toContain('4 requests a run');expect(target.textContent).toContain('2026-08-01 → 2026-09-06');const note = target.querySelector('[aria-label="Detection description"]');note.value = 'Checking the strike'; note.dispatchEvent(new Event('input', { bubbles: true }));@@ -681,7 +698,7 @@ it('pages back through a pass list the catalogue cut short', async () => {answer({ '/api/cases/case-a/analysis/zones/aaaaaaaaaaaa': { id: 'aaaaaaaaaaaa', title: 'Port', zones: area } });const ago = (days) => new Date(Date.now() - days * 86400000).toISOString().slice(0, 10);await open({ opening: 'zones-aaaaaaaaaaaa' });- button('Next: What').click(); await settle();+ button('Next: What').click(); await settle(); await pickAnalyzer();button('Next: When').click(); await settle();button('1 year').click(); await settle();post.mockResolvedValueOnce({ dates: [{ date: ago(10), cloud: 2, coverage: 1 }, { date: ago(100), cloud: 5, coverage: 0.4 }],@@ -703,7 +720,7 @@ it('says why a pass did not start, beside the button that started it', async ()answer({ '/api/cases/case-a/analysis/zones/aaaaaaaaaaaa': { id: 'aaaaaaaaaaaa', title: 'Port', zones: area } });post.mockRejectedValue(new Error('an area of this detection was deleted; choose its areas again'));await open({ opening: 'zones-aaaaaaaaaaaa' });- button('Next: What').click(); await settle();+ button('Next: What').click(); await settle(); await pickAnalyzer();button('Next: When').click(); await settle();await typeWhenDay('Date A', 'Day of A', '01/08/2026');await typeWhenDay('Date B', 'Day of B', '06/09/2026');@@ -740,7 +757,7 @@ it('asks a routine what each pass compares against, not which day to read', asynlabelled('New routine').click(); await settle();expect(target.textContent).toContain('New routine');labelled('Use Port').click(); await settle();- button('Next: What').click(); await settle();+ button('Next: What').click(); await settle(); await pickAnalyzer();expect(ceilingSlider().value).toBe('30');slide(40);button('Next: When').click(); await settle();@@ -782,7 +799,7 @@ it('says which day the newest pass is and why newer ones were skipped, and reads: { id: RUN, status: 'queued', input: {}, results: [], total: 1, progress: 0 }));const onshow = vi.fn();await open({ opening: 'zones-aaaaaaaaaaaa', onshow });- button('Next: What').click(); await settle();+ button('Next: What').click(); await settle(); await pickAnalyzer('Vessels');button('Next: When').click(); await settle();button('Find passes').click(); await settle();expect(target.textContent).toContain(@@ -819,7 +836,7 @@ it('reads the newest pass for a one-image sweep unless a day is asked for', asyn? { dates: [{ date: '2026-09-16', cloud: 4, granules: 1, coverage: 1 }], truncated: false }: { id: RUN, status: 'queued', input: {}, results: [], total: 1, progress: 0 }));await open({ opening: 'zones-aaaaaaaaaaaa' });- button('Next: What').click(); await settle();+ button('Next: What').click(); await settle(); await pickAnalyzer('Vessels');button('Next: When').click(); await settle();expect(heading()).toBe('Which image');// the newest pass is a whole answer, so the step can be passed as it opens@@ -846,7 +863,7 @@ it('shows each area its own dates and pass lookup in When', async () => {? { dates: [{ date: '2026-08-01', cloud: 2, granules: 2, coverage: 1 }], truncated: false }: { id: RUN, status: 'queued', input: {}, results: [], total: 1, progress: 0 }));await open({ opening: 'zones-aaaaaaaaaaaa' });- button('Next: What').click(); await settle();+ button('Next: What').click(); await settle(); await pickAnalyzer();button('Next: When').click(); await settle();expect(target.querySelectorAll('[aria-label^="Dates for "]')).toHaveLength(2);labelled('Find passes for Area').click(); await settle();@@ -875,7 +892,7 @@ it('asks a routine of one image for nothing but its picture', async () => {button('New detection').click(); await settle();labelled('New routine').click(); await settle();labelled('Use Port').click(); await settle();- button('Next: What').click(); await settle();+ button('Next: What').click(); await settle(); await pickAnalyzer('Vessels');slide(45);expect(target.textContent).toContain('Above 30%, the pass taken can be mostly cloud, and ground under cloud is left out.');button('Next: When').click(); await settle();@@ -899,7 +916,7 @@ it('holds a routine to one fixed picture when asked', async () => {button('New detection').click(); await settle();labelled('New routine').click(); await settle();labelled('Use Port').click(); await settle();- button('Next: What').click(); await settle();+ button('Next: What').click(); await settle(); await pickAnalyzer();button('Next: When').click(); await settle();[...target.querySelectorAll('[role="radio"]')].find((node) => node.textContent.includes('A fixed picture')).click();await settle();@@ -931,7 +948,7 @@ it('refuses an area the engine would reject before the next step', async () => {it('sets a size as a whole set of numbers, and shows when it was tuned by hand', async () => {answer({ '/api/cases/case-a/analysis/zones/aaaaaaaaaaaa': { id: 'aaaaaaaaaaaa', title: 'Port', zones: area } });await open({ opening: 'zones-aaaaaaaaaaaa' });- button('Next: What').click(); await settle();+ button('Next: What').click(); await settle(); await pickAnalyzer();const pressed = () => [...target.querySelectorAll('[aria-label="Target size"] button')].filter((b) => b.getAttribute('aria-pressed') === 'true').map((b) => b.textContent.trim());expect(pressed()).toEqual(['Medium']);@@ -944,26 +961,37 @@ it('sets a size as a whole set of numbers, and shows when it was tuned by hand',expect(pressed()).toEqual([]);});-it('asks the size above the analyzers, and holds a pressed size for the next one picked', async () => {+it('picks no analyzer for you, keeps its categories folded, and holds a pressed size for the next one', async () => {answer({ '/api/cases/case-a/analysis/zones/aaaaaaaaaaaa': { id: 'aaaaaaaaaaaa', title: 'Port', zones: area } });await open({ opening: 'zones-aaaaaaaaaaaa' });button('Next: What').click(); await settle();const step = target.querySelector('section[aria-label="What to look for"]');- const sizes = step.querySelectorAll('[aria-label="Target size"]');const list = step.querySelector('[aria-label="Analyzer"]');+ expect([...list.querySelectorAll('.fold')].map((fold) => fold.getAttribute('aria-expanded'))).toEqual(['false']);+ expect(list.querySelectorAll('[role="radio"]')).toHaveLength(0);+ expect(step.querySelector('[aria-label="Target size"]')).toBe(null);+ expect(button('Next: When').disabled).toBe(true);+ expect(target.textContent).toContain('Pick what to look for.');+ await pickAnalyzer();+ expect(button('Next: When').disabled).toBe(false);+ // the size is asked once something is picked, under the list+ const sizes = step.querySelectorAll('[aria-label="Target size"]');expect(sizes.length).toBe(1);- expect(sizes[0].compareDocumentPosition(list) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ expect(list.compareDocumentPosition(sizes[0]) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();const pressed = () => [...step.querySelectorAll('[aria-label="Target size"] button')].filter((b) => b.getAttribute('aria-pressed') === 'true').map((b) => b.textContent.trim());button('Large').click(); await settle();[...list.querySelectorAll('[role="radio"]')].find((b) => b.textContent.includes('Vessels')).click(); await settle();expect(pressed()).toEqual(['Large']);+ // folded, a category still names what was picked in it+ list.querySelector('.fold').click(); await settle();+ expect(list.querySelector('.fold').textContent).toContain('Vessels');});it('offers the cloud switch on by default, and none for a method that rejects cloud itself', async () => {answer({ '/api/cases/case-a/analysis/zones/aaaaaaaaaaaa': { id: 'aaaaaaaaaaaa', title: 'Port', zones: area } });await open({ opening: 'zones-aaaaaaaaaaaa' });- button('Next: What').click(); await settle();+ button('Next: What').click(); await settle(); await pickAnalyzer();const chip = [...document.querySelectorAll('button')].find((b) => b.textContent.includes('Clouds & shadows'));expect(chip.getAttribute('aria-pressed')).toBe('true');expect(target.textContent).toContain('traced from the sun');@@ -973,7 +1001,7 @@ it('offers the cloud switch on by default, and none for a method that rejects cl'/api/cases/case-a/analysis/zones/aaaaaaaaaaaa': { id: 'aaaaaaaaaaaa', title: 'Port', zones: area },});await open({ opening: 'zones-aaaaaaaaaaaa' });- button('Next: What').click(); await settle();+ button('Next: What').click(); await settle(); await pickAnalyzer();expect(target.textContent).not.toContain('Clouds & shadows');});@@ -981,7 +1009,7 @@ it('says what a partial pass will leave unswept before the run, not after', asynanswer({ '/api/cases/case-a/analysis/zones/aaaaaaaaaaaa': { id: 'aaaaaaaaaaaa', title: 'Port', zones: area } });post.mockResolvedValue({ dates: [{ date: '2026-05-04', cloud: 12, granules: 1, coverage: 0.62 }], truncated: false });await open({ opening: 'zones-aaaaaaaaaaaa' });- button('Next: What').click(); await settle();+ button('Next: What').click(); await settle(); await pickAnalyzer();button('Next: When').click(); await settle();// Pass lookups stay explicit.expect(target.querySelector('input[type="date"]')).toBe(null);@@ -999,12 +1027,14 @@ it('makes an analyzer of its own from the closest built-in, and never writes oveawait open();labelled('Analyzers').click(); await settle();expect(target.textContent).toContain('build your own from rules you prove on the map, or copy a calibrated built-in');+ await unfold();starts('Vessels').click(); await settle();expect(target.textContent).toContain('Measures Vessels: infrared contrast over water');expect(button('Save changes')).toBeUndefined();expect(button('Copy to tune')).toBeDefined();button('Back').click(); await settle();+ await unfold();labelled(`Copy ${recipe.name}`).click(); await settle();const name = target.querySelector('[aria-label="Analyzer name"]');expect(name.value).toBe(`${recipe.name} copy`);@@ -1398,6 +1428,7 @@ it('opens a calibrated index built-in as the rules it applies', async () => {answer({ '/api/compare/analyzers': rulesCatalogue({ as_rules: { 'large-change': asRules } }) });await open({ viewBounds: () => VIEW });labelled('Analyzers').click(); await settle();+ await unfold();starts('Any surface change').click(); await settle();button('Open as rules').click(); await settle();expect(heading()).toBe('Build an analyzer');@@ -1563,7 +1594,7 @@ it('reopens a run saved against Wayback without pretending it had a Sentinel-2 dexpect(target.textContent).toContain('Wayback release 1 → Wayback release 2');button('Edit and rerun').click(); await settle();expect(heading()).toBe('Where to look');- button('Next: What').click(); await settle();+ button('Next: What').click(); await settle(); await pickAnalyzer();button('Next: When').click(); await settle();expect(target.textContent).toContain('Choose A, the picture before.');expect(button('Next: Start').disabled).toBe(true);@@ -1601,12 +1632,13 @@ it('says a radar analyzer needs its layer before a detection is built on it', as? catalogue({ builtins: [radar], methods: [...methods, radarMethod], radar_layer: '' }): path in table ? structuredClone(table[path]) : []));await open({ opening: 'zones-aaaaaaaaaaaa' });- // the water it is judged against is one more request a tile- expect(target.textContent).toContain('1 tile · 3 requests a run');- button('Next: What').click(); await settle();+ button('Next: What').click(); await settle(); await pickAnalyzer('Vessels by radar');expect(target.textContent).toContain('not set up yet');expect(button('How to add it, in Settings → Imagery')).toBeDefined();expect(button('Next: When').disabled).toBe(true);+ // the water it is judged against is one more request a tile, said back in Where+ button('Back').click(); await settle();+ expect(target.textContent).toContain('1 tile · 3 requests a run');});it('lists the analyzers by what they look for, each saying how far it can be trusted', async () => {@@ -1622,8 +1654,8 @@ it('lists the analyzers by what they look for, each saying how far it can be trureliability: { 'radar-vessels': 'reliable', boats: 'approximate', 'large-change': 'rough' } }): path in table ? structuredClone(table[path]) : []));await open({ opening: 'zones-aaaaaaaaaaaa' });- button('Next: What').click(); await settle();- const groups = [...target.querySelectorAll('.choices .group')].map((node) => node.textContent);+ button('Next: What').click(); await settle(); await pickAnalyzer();+ const groups = [...target.querySelectorAll('.choices .fold .label')].map((node) => node.textContent);expect(groups).toEqual(['Vessels', 'Any change']);const radarRow = [...target.querySelectorAll('.choice')].find((node) => node.textContent.includes('Vessels by radar'));expect(radarRow.textContent).toContain('(reliable)');diff --git a/frontend/src/tools/detect/DetectReview.show.svelte.test.js b/frontend/src/tools/detect/DetectReview.show.svelte.test.jsindex 06a6db0..559f0d9 100644--- a/frontend/src/tools/detect/DetectReview.show.svelte.test.js+++ b/frontend/src/tools/detect/DetectReview.show.svelte.test.js@@ -86,3 +86,21 @@ it('keeps every verdict tab while another is open, and lands on its first candidawait press('Pinned');expect(target.textContent).toContain('Kept as a pin in this case');});++it('keeps the candidate\'s pass when its mark on the map is clicked', async () => {+ // the run's window ends on the 23rd, the candidate was read on the 27th+ const optical = { provider: 'sentinel2', date: '2026-09-23', layer: 'TRUE-COLOR', maxcc: 100 };+ const read = { ...optical, date: '2026-09-27' };+ served = { ...run, input: { ...run.input, a: optical, b: optical }, results: [row('0-1', read), row('0-2', read)] };+ const shown = [];+ target = document.createElement('div'); document.body.append(target);+ live = mount(Panel, { target, props: { caseId: 'case-a', opening: `runs-${RUN}`,+ onshow: (source) => shown.push(source.date) } });+ await settle();+ expect(shown.at(-1)).toBe('2026-09-27');+ const before = shown.length;+ live.pick(RUN, '0-2');+ await settle();+ expect(target.textContent).toContain('2 of 2');+ expect(shown.slice(before)).toEqual(['2026-09-27']);+});diff --git a/frontend/src/tools/detect/DetectWizard.svelte b/frontend/src/tools/detect/DetectWizard.svelteindex cbe68b7..cd70155 100644--- a/frontend/src/tools/detect/DetectWizard.svelte+++ b/frontend/src/tools/detect/DetectWizard.svelte@@ -33,6 +33,7 @@import AnalyzerSettings from './AnalyzerSettings.svelte';import AnalyzerSize from './AnalyzerSize.svelte';import WhenStep from './WhenStep.svelte';+ import FoldGroup from './FoldGroup.svelte';import Icon from '../../components/Icon.svelte';let {@@ -63,6 +64,8 @@} = $props();const EMPTY_SOURCE = { provider: 'sentinel2', date: '', layer: 'TRUE_COLOR', maxcc: ADVISED_MAXCC };+ /** What a new area is saved in before an analyzer gives it a colour. */+ const AREA_COLOUR = '#38bdf8';const STEPS = [[1, 'Where'], [2, 'What'], [3, 'When'], [4, 'Start']];const SIZE_NAMES = { small: 'Small', medium: 'Medium', large: 'Large', all: 'All sizes' };@@ -85,6 +88,8 @@let areaSearch = $state('');/** Groups opened by hand; every group starts folded, the first one too. */let openGroups = $state({});+ /** Analyzer categories opened by hand; they start folded but for the one holding the pick. */+ let openKinds = $state({});let pairs = $state([]);/** A one pass reads B on a chosen day rather than the newest pass. */let chooseB = $state(false);@@ -128,14 +133,15 @@// start, and saying why here beats a run that comes back failed.const groups = $derived(analyzerGroups(catalogue));const lock = $derived(analyzerLock(recipe, catalogue));- const radarNeeds = $derived(- !lock ? ''+ const whatNeeds = $derived(+ !recipe ? 'Pick what to look for.'+ : !lock ? '': radar && catalogue?.copernicus_key !== false? 'Radar analyzers read a Sentinel-1 layer of your Copernicus configuration, not set up yet.': 'Detect reads Copernicus, and no key is set up yet. It is free.');- const needsOf = (n) => (n === 1 ? areaNeeds : n === 2 ? radarNeeds : n === 3 ? imageryNeeds : '');- const blocked = $derived(areaNeeds || radarNeeds || imageryNeeds);+ const needsOf = (n) => (n === 1 ? areaNeeds : n === 2 ? whatNeeds : n === 3 ? imageryNeeds : '');+ const blocked = $derived(areaNeeds || whatNeeds || imageryNeeds);/** A step opens once every one before it has what it needs. */const reachable = (n) => STEPS.every(([k]) => k >= n || !needsOf(k));const defaultName = $derived(@@ -166,7 +172,6 @@untrack(() => {kind = seed.kind ?? (seed.followupId ? 'routine' : 'once');if (!seed.body) {- choose(builtins[0]?.id);return;}const body = seed.body;@@ -175,6 +180,8 @@note = body.note ?? '';recipe = clone(body.recipe);chosen = body.recipe.id;+ const holder = groups.find((group) => group.list.some((entry) => entry.id === chosen));+ if (holder) openKinds = { [holder.label]: true };a = sentinelSource(body.a);b = sentinelSource(body.b);offline = !!body.offline;@@ -186,7 +193,12 @@});$effect(() => {- if (offer) untrack(() => choose(offer));+ if (!offer) return;+ untrack(() => {+ choose(offer);+ const holder = groups.find((group) => group.list.some((entry) => entry.id === offer));+ if (holder) openKinds = { ...openKinds, [holder.label]: true };+ });});// Leaving the first step must not leave the map armed to draw an area.@@ -238,9 +250,26 @@const groupedIds = $derived(new Set(areaGroups.flatMap((group) => group.area_ids ?? [])));const ungrouped = $derived(areas.filter((area) => !groupedIds.has(area.id)));const matching = (name) => name.toLowerCase().includes(areaSearch.trim().toLowerCase());+ const loose = $derived(ungrouped.filter((area) => !areaSearch || matching(area.name)));++ const isOn = (id) => zones.some((zone) => zone.id === id);+ /** All, some or none of a group's areas are in the selection. */+ function groupState(members) {+ const picked = members.filter((zone) => isOn(zone.id)).length;+ return !picked ? 'false' : picked === members.length ? 'true' : 'mixed';+ }+ const additionsOf = (members) => members.filter((zone) => !isOn(zone.id));- function useGroup(group) {- const additions = groupZones(group).filter((zone) => !zones.some((selected) => selected.id === zone.id));+ /** A group goes in whole, or comes out whole once every area of it is in. */+ function toggleGroup(group) {+ const members = groupZones(group);+ if (groupState(members) === 'true') {+ const ids = new Set(members.map((zone) => zone.id));+ zones = zones.filter((zone) => !ids.has(zone.id));+ if (ids.has(selectedZone)) selectedZone = null;+ return;+ }+ const additions = additionsOf(members);if (zones.length + additions.length > 32) return;zones = [...zones, ...additions];}@@ -254,7 +283,7 @@if (areas.some((area) => area.id === zone.id)) continue;const ring = zoneRing(zone);const saved = await api.post(`/api/cases/${owner.id}/analysis/areas`, {- name: zone.name, colour: recipe.colour,+ name: zone.name, colour: recipe?.colour ?? AREA_COLOUR,geometry: { type: 'Polygon', coordinates: [[...ring, ring[0]]] },});replacements.set(zone.id, saved.id);@@ -278,7 +307,7 @@const owner = await ensureCase();const ring = zoneRing(zone);const saved = await api.post(`/api/cases/${owner.id}/analysis/areas`, {- name: zone.name, colour: recipe.colour, geometry: { type: 'Polygon', coordinates: [[...ring, ring[0]]] },+ name: zone.name, colour: recipe?.colour ?? AREA_COLOUR, geometry: { type: 'Polygon', coordinates: [[...ring, ring[0]]] },});pairs = pairs.map((pair) => pair.area_id === zone.id ? { ...pair, area_id: saved.id } : pair);zones = zones.map((entry) => entry.id === zone.id ? { ...entry, id: saved.id } : entry);@@ -331,90 +360,112 @@{#if areas.length || areaGroups.length}<input class="area-search" aria-label="Search areas or groups" placeholder="Search areas or groups…"bind:value={areaSearch} />- {#each areaGroups as group (group.id)}- {@const members = groupZones(group)}- {@const shown = members.filter((zone) => !areaSearch || matching(group.title) || matching(zone.name))}- {#if !areaSearch || matching(group.title) || shown.length}+ <div class="area-list">+ {#each areaGroups as group (group.id)}+ {@const members = groupZones(group)}+ {@const shown = members.filter((zone) => !areaSearch || matching(group.title) || matching(zone.name))}+ {@const state = groupState(members)}+ {@const open = !!areaSearch || !!openGroups[group.id]}+ {@const pending = !!group.pending_review?.length}+ {#if !areaSearch || matching(group.title) || shown.length}+ <div class="area-group">+ <div class="area-group-head">+ <button type="button" role="checkbox" class="tick" aria-checked={state}+ aria-label={`Use ${group.title}`}+ title={state === 'true' ? `Leave out ${group.title}` : `Look in all of ${group.title}`}+ disabled={pending || !members.length || (state !== 'true' && zones.length + additionsOf(members).length > 32)}+ onclick={() => toggleGroup(group)}>+ {#if state === 'true'}<Icon name="check" size={11} />{:else if state === 'mixed'}<Icon name="minus" size={11} />{/if}+ </button>+ <button type="button" class="group-fold" aria-expanded={open}+ onclick={() => (openGroups = { ...openGroups, [group.id]: !openGroups[group.id] })}>+ <span class="name">{group.title}</span>+ <small>{plural(members.length, 'area')}</small>+ <Icon name={open ? 'chevronDown' : 'chevronRight'} size={12} />+ </button>+ </div>+ {#if pending}+ <button class="link review" onclick={onopenareas}>Review saved shapes in Areas</button>+ {/if}+ {#if open}+ <div class="members">+ {#each shown as zone (zone.id)}+ {@const area = areas.find((item) => item.id === zone.id)}+ {@const on = isOn(zone.id)}+ <button type="button" class="area-item" class:on aria-pressed={on}+ disabled={pending || (!on && zones.length >= 32)}+ onclick={() => (on ? removeZone(zone.id) : area ? useArea(area) : (zones = [...zones, zone]))}>+ <span class="tick" aria-hidden="true">{#if on}<Icon name="check" size={11} />{/if}</span>+ <span class="swatch" style={`--tint: ${area?.colour ?? AREA_COLOUR}`}></span>{zone.name}+ </button>+ {/each}+ </div>+ {/if}+ </div>+ {/if}+ {/each}+ {#if loose.length}<div class="area-group">- <div class="area-group-head">- <button class="group-fold grow" aria-expanded={!!areaSearch || !!openGroups[group.id]}- onclick={() => (openGroups = { ...openGroups, [group.id]: !openGroups[group.id] })}>- <Icon name={(areaSearch || openGroups[group.id]) ? 'chevronDown' : 'chevronRight'} size={12} />- {group.title} <small>{plural(members.length, 'area')}</small>- </button>- <button class="btn btn-sm" aria-label={`Use ${group.title}`}- disabled={!!group.pending_review?.length || !members.length || zones.length + members.filter((zone) => !zones.some((selected) => selected.id === zone.id)).length > 32}- onclick={() => useGroup(group)}>Use</button>+ <p class="loose-head">Ungrouped</p>+ <div class="members flat">+ {#each loose as area (area.id)}+ {@const on = isOn(area.id)}+ <button type="button" class="area-item" class:on aria-pressed={on}+ disabled={!on && zones.length >= 32}+ onclick={() => (on ? removeZone(area.id) : useArea(area))}>+ <span class="tick" aria-hidden="true">{#if on}<Icon name="check" size={11} />{/if}</span>+ <span class="swatch" style={`--tint: ${area.colour}`}></span>{area.name}+ </button>+ {/each}</div>- {#if group.pending_review?.length}- <button class="link" onclick={onopenareas}>Review saved shapes in Areas</button>- {/if}- {#if areaSearch || openGroups[group.id]}- <div class="shared">- {#each shown as zone (zone.id)}- {@const area = areas.find((item) => item.id === zone.id)}- {@const on = zones.some((selected) => selected.id === zone.id)}- <button class="area-chip" class:on aria-pressed={on}- disabled={!!group.pending_review?.length || (!on && zones.length >= 32)}- onclick={() => (on ? removeZone(zone.id) : area ? useArea(area) : (zones = [...zones, zone]))}>- <span class="swatch" style={`--tint: ${area?.colour ?? '#38bdf8'}`}></span>{zone.name}- </button>- {/each}- </div>- {/if}</div>{/if}- {/each}- {@const loose = ungrouped.filter((area) => !areaSearch || matching(area.name))}- {#if loose.length}- <div class="area-group">- <div class="area-group-head"><strong>Ungrouped</strong><small>{plural(loose.length, 'area')}</small></div>- <div class="shared">- {#each loose as area (area.id)}- {@const on = zones.some((zone) => zone.id === area.id)}- <button class="area-chip" class:on aria-pressed={on} disabled={!on && zones.length >= 32}- onclick={() => (on ? removeZone(area.id) : useArea(area))}>- <span class="swatch" style={`--tint: ${area.colour}`}></span>{area.name}- </button>- {/each}- </div>- </div>- {/if}+ </div>{/if}- <div class="row wrap">- {#each [['rect', 'Rectangle'], ['polygon', 'Polygon'], ['ellipse', 'Circle']] as [shape, label]}- <button class="btn btn-sm" class:active={drawing === shape} disabled={zones.length >= 32}- onclick={() => { drawing = drawing === shape ? 'select' : shape; showZones = true; }}>{label}</button>- {/each}+ <div class="draw">+ <span class="draw-label">{areas.length || areaGroups.length ? 'Or draw' : 'Draw'}</span>+ <div class="cmp-seg" role="group" aria-label="Draw an area">+ {#each [['rect', 'Rectangle'], ['polygon', 'Polygon'], ['ellipse', 'Circle']] as [shape, label]}+ <button type="button" class:on={drawing === shape} aria-pressed={drawing === shape}+ disabled={zones.length >= 32}+ onclick={() => { drawing = drawing === shape ? 'select' : shape; showZones = true; }}>{label}</button>+ {/each}+ </div><button class="btn btn-sm" disabled={zones.length >= 32} onclick={onusecurrentview}>Use current view</button></div>{#if drawing !== 'select'}<p class="hint">{drawing === 'polygon' ? 'Click corners on the map; Enter finishes, Escape cancels.' : 'Drag on the map. Escape cancels.'}</p>{:else if !zones.length}- <p class="hint">{areas.length ? 'Pick an area above, draw on the map, or take the current view.' : 'Draw on the map, or take the current view.'}</p>+ <p class="hint">{areas.length ? 'Tick saved areas above, draw on the map, or take the current view.' : 'Draw on the map, or take the current view.'}</p>{/if}- {#each zones as zone (zone.id)}- <div class="row area-row">- <button class="cmp-icon" aria-label={`Show ${zone.name}`} title={`Show ${zone.name}`}- onclick={() => { selectedZone = zone.id; drawing = 'select'; onfocus(zone.points[0]); }}>- <Icon name="pin" size={13} />- </button>- <input class="grow" aria-label="Area name" bind:value={zone.name} maxlength="120" />- {#if !areas.some((area) => area.id === zone.id)}- <button class="btn btn-sm" disabled={working} onclick={() => act(() => saveArea(zone))}>Save as area</button>- {/if}- <button class="cmp-icon" aria-label={`Remove ${zone.name}`} title={`Remove ${zone.name}`}- onclick={() => removeZone(zone.id)}>- <Icon name="x" size={12} />- </button>- </div>- {/each}{#if zones.length}- <p class="hint" class:warn={tooMany}>{[- area,- Number.isFinite(cost.tiles) ? plural(cost.tiles, 'tile') : 'over the tile limit',- tooMany ? '' : `${plural(frames, 'request')} a run, about ${duration}`,- ].filter(Boolean).join(' · ')}</p>+ <div class="picked">+ <p class="picked-head">+ <span>Looking in {plural(zones.length, 'area')}</span>+ <small class:warn={tooMany}>{[+ area,+ Number.isFinite(cost.tiles) ? plural(cost.tiles, 'tile') : 'over the tile limit',+ // what a tile costs depends on the analyzer, so it waits for one+ recipe && !tooMany ? `${plural(frames, 'request')} a run` : '',+ ].filter(Boolean).join(' · ')}</small>+ </p>+ {#each zones as zone (zone.id)}+ <div class="row area-row" class:selected={selectedZone === zone.id}>+ <button class="cmp-icon" aria-label={`Show ${zone.name}`} title={`Show ${zone.name}`}+ onclick={() => { selectedZone = zone.id; drawing = 'select'; onfocus(zone.points[0]); }}>+ <Icon name="pin" size={13} />+ </button>+ <input class="grow" aria-label="Area name" bind:value={zone.name} maxlength="120" />+ {#if !areas.some((saved) => saved.id === zone.id)}+ <button class="btn btn-sm" disabled={working} onclick={() => act(() => saveArea(zone))}>Save as area</button>+ {/if}+ <button class="cmp-icon" aria-label={`Remove ${zone.name}`} title={`Remove ${zone.name}`}+ onclick={() => removeZone(zone.id)}>+ <Icon name="x" size={12} />+ </button>+ </div>+ {/each}+ </div>{/if}{#if zones.length}<details>@@ -429,7 +480,34 @@{:else if step === 2}<section class="step" aria-label="What to look for"><h3>What to look for</h3>+ <div class="choices" role="radiogroup" aria-label="Analyzer">+ {#each groups as group (group.label)}+ <FoldGroup label={group.label} count={group.list.length}+ note={group.list.find((entry) => entry.id === chosen)?.name ?? ''}+ open={!!openKinds[group.label]}+ ontoggle={() => (openKinds = { ...openKinds, [group.label]: !openKinds[group.label] })}>+ {#each group.list as entry (entry.id)}+ {@const locked = analyzerLock(entry, catalogue)}+ {@const trust = catalogue?.reliability?.[entry.id]}+ <button type="button" role="radio" aria-checked={chosen === entry.id} class="choice"+ class:on={chosen === entry.id} class:locked={!!locked} style={`--tint: ${entry.colour}`}+ title={locked || undefined} onclick={() => choose(entry.id)}>+ <span class="swatch" aria-hidden="true"></span>{entry.name}+ {#if trust}<span class="trust {trust}">({trust})</span>{/if}+ {#if locked}<small class="lock"><Icon name="key" size={11} /> set up</small>{/if}+ </button>+ {/each}+ </FoldGroup>+ {/each}+ {#if unlisted}+ <p class="group">This detection</p>+ <button type="button" role="radio" aria-checked="true" class="choice on" style={`--tint: ${recipe.colour}`}>+ <span class="swatch" aria-hidden="true"></span>{recipe.name}<small>as saved</small>+ </button>+ {/if}+ </div>{#if recipe}+ {#if recipe.description}<p class="hint">{recipe.description}</p>{/if}<div class="size"><p class="group">Target size</p><AnalyzerSize bind:recipe {capability} onpick={(name) => (pickedSize = name)} />@@ -445,31 +523,8 @@</label>{#if ceilingWarning(b.maxcc)}<p class="hint warn">{ceilingWarning(b.maxcc)}</p>{/if}{/if}+ <AnalyzerSettings bind:recipe {capability} showSize={false} showCloud={false} />{/if}- <div class="choices" role="radiogroup" aria-label="Analyzer">- {#each groups as group (group.label)}- <p class="group">{group.label}</p>- {#each group.list as entry (entry.id)}- {@const locked = analyzerLock(entry, catalogue)}- {@const trust = catalogue?.reliability?.[entry.id]}- <button type="button" role="radio" aria-checked={chosen === entry.id} class="choice"- class:on={chosen === entry.id} class:locked={!!locked} style={`--tint: ${entry.colour}`}- title={locked || undefined} onclick={() => choose(entry.id)}>- <span class="swatch" aria-hidden="true"></span>{entry.name}- {#if trust}<span class="trust {trust}">({trust})</span>{/if}- {#if locked}<small class="lock"><Icon name="key" size={11} /> set up</small>{/if}- </button>- {/each}- {/each}- {#if unlisted}- <p class="group">This detection</p>- <button type="button" role="radio" aria-checked="true" class="choice on" style={`--tint: ${recipe.colour}`}>- <span class="swatch" aria-hidden="true"></span>{recipe.name}<small>as saved</small>- </button>- {/if}- </div>- {#if recipe.description}<p class="hint">{recipe.description}</p>{/if}- <AnalyzerSettings bind:recipe {capability} showSize={false} showCloud={false} /><button class="link" onclick={onlibrary}>Make an analyzer of your own…</button></section>{:else if step === 3}@@ -542,7 +597,7 @@</div>{#if step < 4 && needsOf(step)}<span class="reason">{needsOf(step)}</span>- {#if step === 2 && radarNeeds}+ {#if step === 2 && lock}<button class="link centre" onclick={openCopernicusSettings}>How to add it, in Settings → Imagery</button>{/if}{:else if step === 4 && blocked}@@ -556,28 +611,93 @@<style>.area-search { width: 100%; }- .area-group { display: grid; gap: 6px; }- .area-group-head { display: flex; align-items: center; gap: 7px; min-height: 30px;- padding: 3px 0; font-size: var(--fs-xs); }- .area-group-head strong { flex: 1; }- .area-group-head small { color: var(--text-3); }- .group-fold { display: flex; align-items: center; gap: 5px; min-width: 0; text-align: left;- font-size: var(--fs-xs); }- .group-fold small { margin-left: auto; }- .shared { display: flex; flex-wrap: wrap; gap: 5px; }- .area-chip {+ .area-list {+ display: grid;+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ overflow: hidden;+ }+ .area-group + .area-group { border-top: 1px solid var(--border); }+ .area-group-head { display: flex; align-items: center; gap: 8px; padding: 0 10px; }+ .area-group-head:hover { background: var(--bg-2); }+ .group-fold {display: flex;+ flex: 1;align-items: center;- gap: 6px;- padding: 4px 9px;- border: 1px solid var(--border);- border-radius: 999px;+ gap: 8px;+ min-width: 0;+ min-height: 36px;+ color: var(--text-1);+ font-size: var(--fs-sm);+ font-weight: 600;+ text-align: left;+ }+ .group-fold .name { overflow: hidden; min-width: 0; text-overflow: ellipsis; white-space: nowrap; }+ .group-fold small { margin-left: auto; color: var(--text-3); font-size: var(--fs-xs); font-weight: 400; }+ .group-fold :global(svg) { flex: 0 0 auto; color: var(--text-3); }+ .tick {+ display: inline-grid;+ flex: 0 0 auto;+ place-items: center;+ width: 16px;+ height: 16px;+ border: 1px solid var(--text-3);+ border-radius: 4px;+ color: var(--bg-0);+ }+ .tick[aria-checked='true'], .tick[aria-checked='mixed'], .area-item.on .tick {+ border-color: var(--accent);+ background: var(--accent);+ }+ .tick:disabled { opacity: 0.4; cursor: not-allowed; }+ .review { margin: 0 10px 8px 34px; }+ .members { display: grid; padding: 0 0 4px 24px; }+ .members.flat { padding-left: 0; }+ .loose-head {+ margin: 0;+ padding: 9px 10px 3px;+ color: var(--text-3);+ font-size: 10px;+ font-weight: 700;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ }+ .area-item {+ display: flex;+ align-items: center;+ gap: 8px;+ min-height: 30px;+ padding: 4px 10px;color: var(--text-2);font-size: var(--fs-xs);+ text-align: left;+ }+ .area-item:hover:not(:disabled) { color: var(--text-1); background: var(--bg-2); }+ .area-item.on { color: var(--text-1); }+ .area-item:disabled { opacity: 0.45; cursor: not-allowed; }+ .area-item .tick { width: 14px; height: 14px; }+ .area-item .swatch { width: 8px; height: 8px; border-radius: 2px; }+ .draw { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }+ .draw-label { color: var(--text-3); font-size: var(--fs-xs); }+ .picked {+ display: grid;+ gap: 4px;+ padding: 8px 10px;+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ }+ .picked-head {+ display: flex;+ align-items: baseline;+ gap: 8px;+ margin: 0 0 2px;+ color: var(--text-1);+ font-size: var(--fs-xs);+ font-weight: 700;}- .area-chip:hover:not(:disabled) { color: var(--text-1); border-color: var(--text-3); }- .area-chip.on { color: var(--accent); border-color: var(--accent); background: var(--accent-soft); }- .area-chip .swatch { width: 8px; height: 8px; border-radius: 2px; background: var(--tint); }+ .picked-head small { margin-left: auto; color: var(--text-3); font-weight: 400; }+ .picked-head small.warn { color: var(--warn, #e2a03f); }+ .area-row.selected input { border-color: var(--accent); }.stepper {display: grid;grid-template-columns: repeat(4, 1fr);@@ -609,7 +729,6 @@.step { display: grid; gap: 12px; }h3 { margin: 0 0 3px; font-size: var(--fs-lg); font-weight: 650; }.row.wrap { flex-wrap: wrap; }- .active { outline: 1px solid var(--accent); }.area-row input { font-size: var(--fs-xs); }details { display: grid; gap: 8px; }details[open] { padding-bottom: 2px; }@@ -618,7 +737,7 @@.link:disabled { opacity: 0.5; }.centre { justify-self: center; text-align: center; }.size { display: grid; gap: 5px; }- .choices { display: grid; gap: 0; }+ .choices { display: grid; gap: 0; border-top: 1px solid var(--border); }.group {margin: 6px 0 2px;color: var(--text-3);@@ -640,6 +759,7 @@text-align: left;}.choice:hover { background: var(--bg-2); }+ .choice:last-child { border-bottom: 0; }.choice.on { color: var(--text-1); background: var(--accent-soft); font-weight: 600; }.choice small { margin-left: auto; color: var(--text-3); font-weight: 400; }.choice.locked { color: var(--text-2); }diff --git a/frontend/src/tools/detect/FoldGroup.svelte b/frontend/src/tools/detect/FoldGroup.sveltenew file mode 100644index 0000000..52cfe39--- /dev/null+++ b/frontend/src/tools/detect/FoldGroup.svelte@@ -0,0 +1,55 @@+<script>+ /**+ * A category of analyzers that opens on demand, so a long list reads as a+ * handful of headings. A folded one names the analyzer picked inside it,+ * which keeps the choice in sight with every category shut.+ */+ import Icon from '../../components/Icon.svelte';++ let { label, count = 0, note = '', open = false, ontoggle = () => {}, children } = $props();+</script>++<div class="fold-group">+ <button type="button" class="fold" aria-expanded={open} onclick={ontoggle}>+ <Icon name={open ? 'chevronDown' : 'chevronRight'} size={12} />+ <span class="label">{label}</span>+ {#if note && !open}<span class="note">{note}</span>{/if}+ {#if count}<small>{count}</small>{/if}+ </button>+ {#if open}<div class="fold-body">{@render children()}</div>{/if}+</div>++<style>+ .fold-group { border-bottom: 1px solid var(--border); }+ .fold {+ display: flex;+ align-items: center;+ gap: 7px;+ width: 100%;+ min-height: 36px;+ padding: 6px 4px;+ color: var(--text-1);+ font-size: var(--fs-sm);+ font-weight: 600;+ text-align: left;+ }+ .fold:hover { background: var(--bg-2); }+ .fold :global(svg) { flex: 0 0 auto; color: var(--text-3); }+ .label { flex: 0 1 auto; min-width: 0; }+ .note {+ overflow: hidden;+ min-width: 0;+ color: var(--accent);+ font-size: var(--fs-xs);+ font-weight: 500;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ small {+ margin-left: auto;+ color: var(--text-3);+ font-size: var(--fs-xs);+ font-weight: 400;+ }+ .fold-body { display: grid; padding: 0 0 6px 19px; }+</style>diff --git a/frontend/src/tools/inspect/SaveToCase.render.test.js b/frontend/src/tools/inspect/SaveToCase.render.test.jsindex 75a3b87..258ceba 100644--- a/frontend/src/tools/inspect/SaveToCase.render.test.js+++ b/frontend/src/tools/inspect/SaveToCase.render.test.js@@ -3,10 +3,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import { flushSync, mount, unmount } from 'svelte';const uiState = { tool: 'inspect', focusMedia: null };-vi.mock('../../lib/state.svelte.js', () => ({- caseState: { current: { id: 'case-a', folders: ['Roofs'] } },- uiState,-}));+const caseState = { current: { id: 'case-a', folders: ['Roofs'] } };+vi.mock('../../lib/state.svelte.js', () => ({ caseState, uiState }));const { default: SaveToCase } = await import('./SaveToCase.svelte');@@ -25,6 +23,7 @@ const nameField = () => target.querySelector('input[aria-label="Name"]');const saveButton = () => [...target.querySelectorAll('button')].find((b) => /Save to case|Saved|Saving/.test(b.textContent) && b.classList.contains('btn-primary'));afterEach(() => {+ caseState.current = { id: 'case-a', folders: ['Roofs'] };if (live) unmount(live);live = null;target?.remove();@@ -92,3 +91,31 @@ describe('Save to case', () => {expect(target.textContent).toContain('Add a piece first.');});});++describe('Save to case with a work folder', () => {+ const option = (label) =>+ [...document.querySelectorAll('.menu .opt')].find((b) => b.textContent.trim().startsWith(label));++ it('starts on the work folder and files there', async () => {+ caseState.current = { id: 'case-a', folders: ['Roofs'], work_folder: 'Roofs' };+ const onsave = vi.fn(async () => {});+ show({ onsave });+ expect(target.textContent).toContain('Work folder');+ saveButton().click();+ await Promise.resolve();+ expect(onsave).toHaveBeenLastCalledWith({ name: '00-00-12 roof', folder: 'Roofs', note: null });+ });++ it('sends Unfiled as a choice, since filing already put the output in the work folder', async () => {+ caseState.current = { id: 'case-a', folders: ['Roofs'], work_folder: 'Roofs' };+ const onsave = vi.fn(async () => {});+ show({ onsave });+ target.querySelector('.folder-select .trigger').click();+ flushSync();+ option('Unfiled').click();+ flushSync();+ saveButton().click();+ await Promise.resolve();+ expect(onsave).toHaveBeenLastCalledWith({ name: '00-00-12 roof', folder: '', note: null });+ });+});diff --git a/frontend/src/tools/inspect/SaveToCase.svelte b/frontend/src/tools/inspect/SaveToCase.svelteindex 614a9e1..798143f 100644--- a/frontend/src/tools/inspect/SaveToCase.svelte+++ b/frontend/src/tools/inspect/SaveToCase.svelte@@ -3,6 +3,7 @@import { saveNameOf } from '../../lib/inspect.js';import Icon from '../../components/Icon.svelte';import FolderSelect from '../../components/FolderSelect.svelte';+ import { workFolder } from '../../lib/folders.js';// Files one output as case media: a frame, the adjusted video, an exported// collage. Everything else in Examine is kept with the work as it is made; this@@ -29,7 +30,10 @@const folders = $derived(caseState.current?.folders ?? []);async function save() {- await onsave({ name: saveNameOf({ defaultName }, name), folder: folder || null, note: note.trim() || null });+ // With a work folder, filing has already put the output there, so Unfiled+ // has to be sent to mean it; without one, empty leaves a re-save where it was.+ const chosen = folder || (workFolder() ? '' : null);+ await onsave({ name: saveNameOf({ defaultName }, name), folder: chosen, note: note.trim() || null });typed = null;note = '';noting = false;@@ -57,7 +61,7 @@aria-label="Name"maxlength="200"/>- <FolderSelect bind:value={folder} {folders} emptyLabel="Unfiled" />+ <FolderSelect bind:value={folder} {folders} emptyLabel="Unfiled" fresh />{#if noting}<textarea class="input note" bind:value={note} rows="2" placeholder="Why it matters" maxlength="2000" aria-label="Note"></textarea>{:else}diff --git a/frontend/src/tools/overview/CaseTodos.svelte b/frontend/src/tools/overview/CaseTodos.svelteindex e637168..001c37b 100644--- a/frontend/src/tools/overview/CaseTodos.svelte+++ b/frontend/src/tools/overview/CaseTodos.svelte@@ -1,15 +1,19 @@<script>- import { onMount, tick } from 'svelte';- import { api } from '../../lib/api.js';+ import { tick, untrack } from 'svelte';+ import { loadTodos, saveTodos, todos } from '../../lib/todos.svelte.js';import Icon from '../../components/Icon.svelte';import ConfirmDialog from '../../components/ConfirmDialog.svelte';- let { caseId } = $props();- let data = $state(null);+ // `compact` is the sidebar's: no heading of its own (the view switch names it)+ // and a list that runs the panel's height rather than a dashboard cell's.+ let { caseId, compact = false } = $props();+ // The lists are shared with every other surface showing them (lib/todos.svelte.js);+ // what is local is which one is open and what is being typed.+ const data = $derived(todos.caseId === caseId ? todos.data : null);+ const busy = $derived(todos.caseId === caseId && todos.busy);+ const error = $derived(todos.caseId === caseId ? todos.error : '');+ const conflict = $derived(todos.caseId === caseId && todos.conflict);let active = $state('');- let busy = $state(false);- let error = $state('');- let conflict = $state(false);let taskText = $state('');let naming = $state(null);let listName = $state('');@@ -18,33 +22,24 @@let deleting = $state(null);let menu = $state(false);const selected = $derived(data?.lists.find((list) => list.id === active));- const endpoint = $derived(`/api/cases/${encodeURIComponent(caseId)}/todos`);- onMount(() => { void load(); });+ // Read on mount and again for another case, which a surface that stays mounted+ // across a case switch would otherwise go on showing.+ $effect(() => {+ const id = caseId;+ untrack(() => void loadTodos(id));+ });+ // The open list survives a reload, and the first one opens when there is none.+ $effect(() => {+ if (data && !data.lists.some((list) => list.id === active)) active = data.lists[0]?.id ?? '';+ });async function load() {- busy = true;- error = '';- try {- data = await api.get(endpoint);- active = data.lists.some((list) => list.id === active) ? active : (data.lists[0]?.id ?? '');- conflict = false;- } catch (e) { error = e.message; }- finally { busy = false; }+ await loadTodos(caseId);}- async function save(lists) {- if (busy || conflict) return false;- busy = true;- error = '';- try {- data = await api.put(endpoint, { revision: data.revision, lists });- return true;- } catch (e) {- error = e.message;- conflict = e.status === 409;- return false;- } finally { busy = false; }+ function save(lists) {+ return saveTodos(caseId, lists);}function copy() { return JSON.parse(JSON.stringify(data.lists)); }@@ -108,8 +103,12 @@}</script>-<section class="todos" aria-label="To-do">- <header><h2 class="label">To-do</h2><span aria-live="polite">{busy && data ? 'Saving…' : ''}</span></header>+<section class="todos" class:compact aria-label="To-do">+ {#if compact}+ <span class="saving" aria-live="polite">{busy && data ? 'Saving…' : ''}</span>+ {:else}+ <header><h2 class="label">To-do</h2><span aria-live="polite">{busy && data ? 'Saving…' : ''}</span></header>+ {/if}{#if error}<p role="alert">{error} <button class="btn btn-sm" onclick={load} disabled={busy}>Reload lists</button></p>{/if}@@ -183,6 +182,10 @@.entry, .options { margin-top: 10px; }.entry .input { flex: 1; min-width: 0; }ul { list-style: none; margin: 0; padding: 0; max-height: 300px; overflow-y: auto; }+ .compact ul { max-height: none; }+ .compact .task { font-size: var(--fs-sm); padding: 4px; }+ .compact .tab { padding: 6px 8px; font-size: var(--fs-xs); }+ .saving { display: block; min-height: 1em; color: var(--text-3); font-size: var(--fs-xs); text-align: right; }/* The Recent work row: a hairline between rows, the amber edge under the pointer. */li { padding: 2px 4px 2px 8px; border-bottom: 1px solid var(--border); border-left: 2px solid transparent; transition: background 0.14s var(--ease), border-color 0.14s var(--ease); }li:hover, li:focus-within { background: var(--bg-1); border-left-color: var(--accent); }diff --git a/frontend/src/tools/satellite/PlaceDialog.svelte b/frontend/src/tools/satellite/PlaceDialog.svelteindex 58fdc6e..efeff56 100644--- a/frontend/src/tools/satellite/PlaceDialog.svelte+++ b/frontend/src/tools/satellite/PlaceDialog.svelte@@ -17,6 +17,7 @@import Modal from '../../components/Modal.svelte';import ConfirmDialog from '../../components/ConfirmDialog.svelte';import FolderSelect from '../../components/FolderSelect.svelte';+ import { workFolder } from '../../lib/folders.js';import RelationList from '../../components/RelationList.svelte';import RelationPicker from '../../components/RelationPicker.svelte';@@ -44,6 +45,11 @@// was found — is edited in the panel every other surface opens. So this hands over// rather than growing a second copy of that form, and asks first if anything was// typed: handing over re-reads the place from the case, which would drop it.+ // A new point starts in the work folder, before what it opened on is read, so+ // that default is not taken for something the analyst typed.+ untrack(() => {+ if (!draft.id && !draft.folder && workFolder()) draft.folder = workFolder();+ });// read once, on purpose: this is what the dialog opened on, not what it now holdsconst opened = untrack(() => ({title: draft.title,diff --git a/frontend/src/tools/textDirection.test.js b/frontend/src/tools/textDirection.test.jsindex 334eec3..e8332fe 100644--- a/frontend/src/tools/textDirection.test.js+++ b/frontend/src/tools/textDirection.test.js@@ -38,7 +38,7 @@ describe('text direction on the surfaces that hold the analyst\'s words', () =>});it('isolates what a canvas or a plate draws', () => {- expect(read('./Graph.svelte')).toContain('text: bidiIsolate(shortLabel(data.label)),');+ expect(read('./Graph.svelte')).toContain('text: bidiIsolate(shortLabel(data.caption ?? data.label)),');expect(read('../lib/plate.js')).toContain('const clean = bidiIsolate(text);');});});diff --git a/src/azimut/api/cases/folders.py b/src/azimut/api/cases/folders.pyindex 8298a18..805ccdf 100644--- a/src/azimut/api/cases/folders.py+++ b/src/azimut/api/cases/folders.py@@ -29,3 +29,32 @@ def add_folder(case_id: str, body: FolderIn) -> list[str]:@router.delete("/{case_id}/folders")def remove_folder(case_id: str, name: str) -> list[str]:return get_case(case_id).remove_folder(name)+++class FolderRenameIn(BaseModel):+ source: str = Field(min_length=1, max_length=400)+ target: str = Field(min_length=1, max_length=400)++[email protected]("/{case_id}/folders/rename")+def rename_folder(case_id: str, body: FolderRenameIn) -> list[str]:+ """Rename a folder. Its subfolders, items and their files follow."""+ case = get_case(case_id)+ try:+ return case.rename_folder(body.source, body.target)+ except CaseError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+++class WorkFolderIn(BaseModel):+ folder: str | None = Field(default=None, max_length=400)++[email protected]("/{case_id}/work-folder")+def set_work_folder(case_id: str, body: WorkFolderIn) -> dict[str, str | None]:+ """Choose the folder new files and saved work land in, or none."""+ case = get_case(case_id)+ try:+ return {"work_folder": case.set_work_folder(body.folder)}+ except CaseError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from excdiff --git a/src/azimut/api/ingest.py b/src/azimut/api/ingest.pyindex 319bbc1..4f4babe 100644--- a/src/azimut/api/ingest.py+++ b/src/azimut/api/ingest.py@@ -477,7 +477,6 @@ def ingest_bookmark({"url": url,"site": split.hostname,- "folder": "","fetched_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),},by="ingest",diff --git a/src/azimut/api/proofs.py b/src/azimut/api/proofs.pyindex e887310..ef2cd94 100644--- a/src/azimut/api/proofs.py+++ b/src/azimut/api/proofs.py@@ -574,6 +574,8 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:place, released = _place_for(case, entity_id, spec)return {+ # The proof's entity, so the composer can ask what it shares with the case.+ "id": entity_id,"name": name,"title": name,"png": png_rel,diff --git a/src/azimut/api/proposals.py b/src/azimut/api/proposals.pynew file mode 100644index 0000000..3678e04--- /dev/null+++ b/src/azimut/api/proposals.py@@ -0,0 +1,116 @@+"""The links the case proposes by itself (`engine/proposals.py`): read them, ask for a+pass, drop one, and what a geolocation shares with the rest of the case.++Confirming one is the ordinary link patch (`api/cases/links.py`), so a proposal+confirmed here and one confirmed in the graph are the same act.+"""++from __future__ import annotations++from typing import Any++from fastapi import APIRouter, HTTPException++from ..engine import links as link_engine+from ..engine import proposals as proposal_engine+from ..workspace import CaseError+from .cases.common import delete_entity_deep, get_case++router = APIRouter(prefix="/api/cases", tags=["proposals"])++#: How many waiting proposals one read lists. The count is always whole; past this the+#: list is a sample, and confirming the first page brings up the next.+MAX_LISTED = 200+++def _waiting(case: Any) -> dict[str, Any]:+ """The proposals still waiting, with both ends named so a row reads as a sentence."""+ waiting = [link for link in case.list_links() if proposal_engine.unreviewed(link)]+ listed = waiting[:MAX_LISTED]+ ends = {+ entity["id"]: entity+ for entity in case.entities_by_ids(+ sorted({link["from"] for link in listed} | {link["to"] for link in listed})+ )+ }+ items: list[dict[str, Any]] = []+ for link in listed:+ start, end = ends.get(link["from"]), ends.get(link["to"])+ if start is None or end is None:+ continue+ item: dict[str, Any] = {+ "id": link["id"],+ "type": link["type"],+ "from": {"id": start["id"], "label": start["label"], "type": start["type"]},+ "to": {"id": end["id"], "label": end["label"], "type": end["type"]},+ }+ if link["type"] == link_engine.SAME_SITE_AS:+ a, b = proposal_engine.point_of(start), proposal_engine.point_of(end)+ if a is not None and b is not None:+ item["metres"] = round(proposal_engine.metres(a, b))+ items.append(item)+ return {+ "pending": proposal_engine.pending(case),+ "items": items,+ "listed": len(items),+ "through": (case.link_pass() or {}).get("at"),+ "radius": proposal_engine.SITE_RADIUS_M,+ }++[email protected]("/{case_id}/proposals")+def list_proposals(case_id: str) -> dict[str, Any]:+ """What is waiting, and when the case was last read for it."""+ return _waiting(get_case(case_id))++[email protected]("/{case_id}/proposals")+def run_proposals(case_id: str) -> dict[str, Any]:+ """Read what was filed since the last pass now, rather than after the next import.++ Pressed by the analyst, never run on open: a pass writes, and looking at a case+ must not change it.+ """+ case = get_case(case_id)+ filed = proposal_engine.propose(case)+ return {"filed": filed, **_waiting(case)}++[email protected]("/{case_id}/proposals/{link_id}")+def drop_proposal(case_id: str, link_id: str) -> dict[str, Any]:+ """Drop one proposal. An account the pass filed for it goes too when nothing else+ holds it, since an account nobody posted anything as was only ever the proposal."""+ case = get_case(case_id)+ link = case.get_link(link_id)+ if link is None:+ raise HTTPException(status_code=404, detail=f"link '{link_id}' not found")+ if (link.get("provenance") or {}).get("by") != proposal_engine.BY:+ raise HTTPException(status_code=400, detail="this link was not proposed by the case")+ try:+ link_engine.remove_relation(case, link_id)+ dropped: list[str] = []+ for end_id in (link["from"], link["to"]):+ end = case.get_entity(end_id)+ provenance = (end or {}).get("provenance") or {}+ if (+ end is not None+ and end["type"] == "account"+ and provenance.get("by") == proposal_engine.BY+ and provenance.get("status") == "suggested"+ and not case.links_of(end_id)+ ):+ delete_entity_deep(case, end_id)+ dropped.append(end_id)+ except CaseError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ return {"status": "deleted", "dropped": dropped, **_waiting(case)}++[email protected]("/{case_id}/entities/{entity_id}/kin")+def entity_kin(case_id: str, entity_id: str) -> dict[str, Any]:+ """Other geolocations on the same site, and the accounts behind its material."""+ case = get_case(case_id)+ try:+ return proposal_engine.kin(case, entity_id)+ except KeyError as exc:+ raise HTTPException(status_code=404, detail=f"entity '{entity_id}' not found") from excdiff --git a/src/azimut/api/satellite.py b/src/azimut/api/satellite.pyindex 818a1f6..fbebfc2 100644--- a/src/azimut/api/satellite.py+++ b/src/azimut/api/satellite.py@@ -1504,7 +1504,8 @@ def save_place(case_id: str, body: PlaceIn) -> dict[str, Any]:extra: dict[str, Any] = {}if body.notes and body.notes.strip():extra["notes"] = body.notes.strip()- if body.folder and body.folder.strip():+ # Sent empty, it is a choice of no folder, so the work folder is not applied.+ if body.folder is not None:extra["folder"] = body.folder.strip()entity = satellite_engine.save_place(case, body.lat, body.lon, body.zoom, body.bearing, body.title, extra_attrs=extradiff --git a/src/azimut/api/sheets.py b/src/azimut/api/sheets.pyindex fe3773b..0c1a200 100644--- a/src/azimut/api/sheets.py+++ b/src/azimut/api/sheets.py@@ -166,9 +166,12 @@ class SheetFromCaseIn(SheetIn):media it was made from and the place it puts on the map. It takes neither ``type``nor ``fields`` — its shape is fixed, which is what lets it be kept level with the caseafterwards.++ ``files`` is the same kind of fixed shape turned the other way: one row per picture+ or video the analyst imported, with the proof that answers for it when there is one."""- shape: Literal["generic", "proofs"] = "generic"+ shape: Literal["generic", "proofs", "files"] = "generic"# Required by `generic` and unread by `proofs`, so it cannot be a required field on# the model: a caller asking for the proofs shape has no type to name.type: str = Field(default="", max_length=40)@@ -189,13 +192,14 @@ def sheet_from_case(case_id: str, body: SheetFromCaseIn) -> dict[str, Any]:if body.shape == "generic" and not body.type.strip():raise HTTPException(status_code=422, detail="a worklist needs a type to be built from")try:- built = (- fromcase_engine.build_proofs(case, limit=body.limit)- if body.shape == "proofs"- else fromcase_engine.build(+ if body.shape == "proofs":+ built = fromcase_engine.build_proofs(case, limit=body.limit)+ elif body.shape == "files":+ built = fromcase_engine.build_files(case, limit=body.limit)+ else:+ built = fromcase_engine.build(case, entity_type=body.type, fields=body.fields, limit=body.limit)- )entity = sheet_engine.create(case, body.title.strip(), built["columns"], built["rows"])saved = sheet_engine.write(case, entity["id"], built["columns"], built["rows"], built["meta"]@@ -206,6 +210,13 @@ def sheet_from_case(case_id: str, body: SheetFromCaseIn) -> dict[str, Any]:return {**entity, "taken": built["taken"], "total": built["total"]}[email protected]("/{case_id}/sheets/from-case/files")+def files_worklist(case_id: str) -> dict[str, Any]:+ """How many imported files a worklist would hold, how many a proof answers, and the+ worklist the case already has. Read only: offering the list must not build it."""+ return fromcase_engine.files_preview(get_case(case_id))++#: How many entities one request may ask the place of, and how many addresses one row may#: offer the media library. A bound rather than the row limit: both are answered out of the#: graph in one read, and a caller asking about twenty thousand is not asking a question.@@ -524,7 +535,7 @@ def save_sheet(case_id: str, sheet_id: str, body: SheetSaveIn) -> dict[str, Any]class SheetRefreshIn(SheetSaveIn):- """The proofs sheet as the grid holds it, to be brought level with the case.+ """A sheet built out of the case, as the grid holds it, to be brought level with the case.The table travels with the request for the same reason a move's does: the analystpresses this on what is on screen, and the copy on disk may be a minute behind. The@@ -534,7 +545,10 @@ class SheetRefreshIn(SheetSaveIn):@router.post("/{case_id}/sheets/{sheet_id}/refresh")def refresh_sheet(case_id: str, sheet_id: str, body: SheetRefreshIn) -> dict[str, Any]:- """Add the proofs filed since this sheet was built, and rewrite what the case owns.+ """Add what was filed since this sheet was built, and rewrite what the case owns.++ Proofs for `My geolocations`, imported files for `Files to geolocate`; the second+ also moves a status on to `done` once a proof answers for its file.Pressed, never automatic. Refreshing on open would mean that looking at a sheetchanges it — and it would fight the stamp, which exists so that two readers of one@@ -546,7 +560,7 @@ def refresh_sheet(case_id: str, sheet_id: str, body: SheetRefreshIn) -> dict[str"""case = get_case(case_id)try:- fresh = fromcase_engine.refresh_proofs(case, body.columns, body.rows, body.meta)+ fresh = fromcase_engine.refresh(case, body.columns, body.rows, body.meta)saved = sheet_engine.write(case, sheet_id, fresh["columns"], fresh["rows"], fresh["meta"], expected=body.stamp)diff --git a/src/azimut/casestore.py b/src/azimut/casestore.pyindex c2e804c..887c0df 100644--- a/src/azimut/casestore.py+++ b/src/azimut/casestore.py@@ -429,8 +429,8 @@ class CaseStore:def add_folder(self, name: str) -> list[str]:return self._graph().add_folder(name)- def remove_folder(self, name: str) -> list[str]:- return self._graph().remove_folder(name)+ def entities_in_folder(self, root: str) -> list[dict[str, Any]]:+ return self._graph().entities_in_folder(root)# -- trash journal (engine/trash.py owns the files) ----------------------diff --git a/src/azimut/engine/cities.py b/src/azimut/engine/cities.pyindex ea41d08..50d42a6 100644--- a/src/azimut/engine/cities.py+++ b/src/azimut/engine/cities.py@@ -14,6 +14,7 @@ CC BY 4.0 — the attribution rides with every answer.from __future__ import annotationsimport gzip+import mathimport threadingimport unicodedatafrom bisect import bisect_left@@ -88,9 +89,100 @@ def _load() -> None:def _reset() -> None:"""Test seam: forget the loaded table."""- global _rows, _index+ global _rows, _index, _cellswith _lock:- _rows, _index = None, []+ _rows, _index, _cells = None, [], None+++#: The cities bucketed on a one-degree grid, built the first time a point asks, so+#: "which town is this near" reads a handful of cells rather than 34 000 rows.+_cells: dict[tuple[int, int], list[int]] | None = None++_COMPASS = ("N", "NE", "E", "SE", "S", "SW", "W", "NW")+++def _grid() -> dict[tuple[int, int], list[int]]:+ global _cells+ if _rows is None:+ _load()+ with _lock:+ if _cells is None:+ cells: dict[tuple[int, int], list[int]] = {}+ for row, line in enumerate(_rows or []):+ parts = line.split("\t")+ try:+ lat, lon = float(parts[4]), float(parts[5])+ except (IndexError, ValueError):+ continue+ cells.setdefault((math.floor(lat), math.floor(lon)), []).append(row)+ _cells = cells+ return _cells+++def nearest(lat: float, lon: float, *, within_km: float = 100.0) -> dict[str, Any] | None:+ """The closest city to a point, how far and which way, or None past ``within_km``.++ What a point named only by its coordinates is called where a person reads it:+ "8 km W of Al Hazm" says where `16.98, 45.05` is to anybody who does not read+ coordinates. The cities are those of 15 000 people or more, so in empty country+ the answer is honestly none rather than a hamlet.+ """+ if not (-90 <= lat <= 90 and -180 <= lon <= 180):+ return None+ cells = _grid()+ rows = _rows or []+ best: tuple[float, int] | None = None+ # Enough one-degree cells around the point to hold the whole radius: a degree of+ # latitude is 111 km everywhere, a degree of longitude shrinks towards the poles.+ reach_lat = math.ceil(within_km / 111.0)+ span = 111.0 * max(math.cos(math.radians(lat)), 0.01)+ reach_lon = min(180, math.ceil(within_km / span))+ base_lat, base_lon = math.floor(lat), math.floor(lon)+ for dlat in range(-reach_lat, reach_lat + 1):+ for dlon in range(-reach_lon, reach_lon + 1):+ wrapped = (base_lon + dlon + 180) % 360 - 180+ for row in cells.get((base_lat + dlat, wrapped), ()):+ parts = rows[row].split("\t")+ km = _km(lat, lon, float(parts[4]), float(parts[5]))+ if best is None or km < best[0]:+ best = (km, row)+ if best is None or best[0] > within_km:+ return None+ km, row = best+ city = _unpack(rows[row])+ return {+ "name": city["name"],+ "country": city["country"],+ "km": round(km),+ "bearing": _bearing(city["lat"], city["lon"], lat, lon),+ }+++def _km(lat1: float, lon1: float, lat2: float, lon2: float) -> float:+ p1, p2 = math.radians(lat1), math.radians(lat2)+ dp, dl = p2 - p1, math.radians(lon2 - lon1)+ h = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2+ return 2 * 6371.0 * math.asin(min(1.0, math.sqrt(h)))+++def _bearing(lat1: float, lon1: float, lat2: float, lon2: float) -> str:+ """Which way the second point lies from the first, on eight points of the compass."""+ p1, p2 = math.radians(lat1), math.radians(lat2)+ dl = math.radians(lon2 - lon1)+ y = math.sin(dl) * math.cos(p2)+ x = math.cos(p1) * math.sin(p2) - math.sin(p1) * math.cos(p2) * math.cos(dl)+ degrees = (math.degrees(math.atan2(y, x)) + 360) % 360+ return _COMPASS[int((degrees + 22.5) // 45) % 8]+++def describe(lat: float, lon: float) -> str | None:+ """A point as the town it is near: `Al Hazm`, or `8 km W of Al Hazm`."""+ city = nearest(lat, lon)+ if city is None:+ return None+ if city["km"] < 2:+ return str(city["name"])+ return f"{city['km']} km {city['bearing']} of {city['name']}"def _unpack(line: str) -> dict[str, Any]:diff --git a/src/azimut/engine/entities.py b/src/azimut/engine/entities.pyindex a4318ac..cd0c816 100644--- a/src/azimut/engine/entities.py+++ b/src/azimut/engine/entities.py@@ -842,6 +842,13 @@ def types_in(*families: str) -> frozenset[str]:return frozenset(e.type for e in ENTITY_TYPES if e.family in wanted)+#: What the case's work folder files by itself: what was gathered, written or+#: pinned while working, never the people and things the work is about, nor the+#: statements made about them. A subject is shared across every thread of a case,+#: so filing it under the one being worked on would be a guess.+WORK_FOLDER_TYPES: frozenset[str] = types_in(COLLECTED, DOCUMENT, PLACE)++def role_of(type_: str) -> str | None:"""What a type is for once the case is drawn, or None for a free type.diff --git a/src/azimut/engine/graph.py b/src/azimut/engine/graph.pyindex ea36bee..457500e 100644--- a/src/azimut/engine/graph.py+++ b/src/azimut/engine/graph.py@@ -113,12 +113,14 @@ already the axis this module varies.from __future__ import annotations+import re+from dataclasses import dataclassfrom typing import Anyfrom ..repository import CaseRepositoryfrom ..workspace import CaseError-from . import entities, links+from . import cities, entities, links#: **How many nodes a case opens on, not how many it may hold.** A ceiling that#: refuses is the app overruling the analyst about their own picture, and the drawing@@ -1925,6 +1927,27 @@ def _origins(case: CaseRepository, entities: list[dict[str, Any]]) -> dict[str,}+#: A label that is nothing but a position: decimal degrees, DMS, the `-2` suffix a second+#: capture of one spot gets. Such a node is read by where it is, not by its digits.+_COORDS_ONLY = re.compile(r"^[\d\s.,;°'\"′″_+\-NSEWnsew~]+$")+++def _caption(entity: dict[str, Any]) -> str | None:+ """What a point named only by its coordinates is called on the drawing: the town it+ is near, from the offline gazetteer. Nothing for a point somebody named."""+ if entity.get("type") not in ("place", "capture"):+ return None+ label = str(entity.get("label") or "")+ if sum(ch.isdigit() for ch in label) < 4 or not _COORDS_ONLY.match(label):+ return None+ attrs = entity.get("attrs") or {}+ try:+ lat, lon = float(attrs["lat"]), float(attrs["lon"])+ except (KeyError, TypeError, ValueError):+ return None+ return cities.describe(lat, lon)++def _node(entity: dict[str, Any],degree: int,@@ -1994,6 +2017,10 @@ def _node("at": entity.get("provenance", {}).get("at", ""),"degree": degree,}+ # The name the drawing writes when the label is only a position. The label stays the+ # entity's: the panel shows both, and search still matches the digits.+ if caption := _caption(entity):+ node["caption"] = captionfolder = entity.get("attrs", {}).get("folder")if folder:node["folder"] = folderdiff --git a/src/azimut/engine/inspect.py b/src/azimut/engine/inspect.pyindex 671d148..1d64fb4 100644--- a/src/azimut/engine/inspect.py+++ b/src/azimut/engine/inspect.py@@ -491,7 +491,11 @@ def _apply_meta(exactly the case where a name the user just typed seems to vanish. The gateis an explicit act: the last one through it wins."""- patch = {k: v for k, v in (("title", label), ("folder", folder), ("notes", notes)) if v}+ patch = {k: v for k, v in (("title", label), ("notes", notes)) if v}+ # An empty folder is the analyst choosing none, over the work folder the+ # registration filed the item in.+ if folder is not None:+ patch["folder"] = folderif patch:result["item"] = media_engine.update_media(case, result["item"]["path"], patch)diff --git a/src/azimut/engine/inspectwork.py b/src/azimut/engine/inspectwork.pyindex b50407f..4e822da 100644--- a/src/azimut/engine/inspectwork.py+++ b/src/azimut/engine/inspectwork.py@@ -698,9 +698,9 @@ def _extract_collages(**body,"migrated_from": {"session": marker[0], "collage": marker[1]},})- attrs: dict[str, Any] = {"spec": target}- if folder:- attrs["folder"] = folder+ # Explicit even when empty: a migration keeps where the work was filed,+ # and the folder being worked in today is not where it was.+ attrs: dict[str, Any] = {"spec": target, "folder": folder or ""}case.add_entity(COLLAGE_TYPE, title, attrs=attrs, by=PRODUCER)done.add(marker)diff --git a/src/azimut/engine/links.py b/src/azimut/engine/links.pyindex 67534ad..5de9803 100644--- a/src/azimut/engine/links.py+++ b/src/azimut/engine/links.py@@ -116,6 +116,7 @@ CHAIN_ENDPOINTS: dict[str, dict[str, frozenset[str]]] = {LOCATED_AT = "located-at"SAME_IMAGE_AS = "same-image-as"+SAME_SITE_AS = "same-site-as"DEPICTS = "depicts"OWNS = "owns"PART_OF = "part-of"@@ -348,6 +349,21 @@ RELATION_TYPES: tuple[RelationType, ...] = (to_families=frozenset({entities.PLACE}),from_only=frozenset({"structure"}),),+ # Two points that belong to one site: the hangar and the runway, the camera and+ # what it filmed across the street. Without it, two geolocations on one airfield+ # drew as two islands. `engine/proposals` files it for points under 300 m apart;+ # the analyst states it by hand for a site wider than that.+ #+ # Symmetric, like `associated-with`, and not ratable: whether two points are one+ # site is answered by confirming or dropping the edge, not by grading it.+ RelationType(+ SAME_SITE_AS, "is on the same site as",+ inverse_label="is on the same site as",+ hint="the two points belong to one site",+ from_families=frozenset({entities.PLACE}),+ to_families=frozenset({entities.PLACE}),+ ratable=False,+ ),# The only verb the `class` family takes from below. It runs object → model,# because a named tank is one of a model and never the other way round, and it is# ratable: "this is probably a T-72B3" is a reading of the footage, not a factdiff --git a/src/azimut/engine/media.py b/src/azimut/engine/media.pyindex 694f1a0..13a37b8 100644--- a/src/azimut/engine/media.py+++ b/src/azimut/engine/media.py@@ -396,6 +396,10 @@ def _register(thumb_rel = thumbnail_engine.on_register(case, rel_path, digest, kind)display_name = media_path.stem+ # Filed into the work folder here rather than by `add_entity`, so the+ # sidecar and the browse index carry the same folder as the row.+ extra_attrs = case.in_work_folder(entity_type, extra_attrs)+ folder = (extra_attrs or {}).get("folder")sidecar = {"filename": media_path.name,"title": display_name,@@ -405,6 +409,7 @@ def _register("added_at": _now(),"source": source,"thumbnail": thumb_rel,+ **({"folder": folder} if folder else {}),}_write_sidecar(media_path, sidecar)diff --git a/src/azimut/engine/proposals.py b/src/azimut/engine/proposals.pynew file mode 100644index 0000000..46701b6--- /dev/null+++ b/src/azimut/engine/proposals.py@@ -0,0 +1,494 @@+"""Links the case proposes by itself, out of what it already holds.++Two things an analyst writes by hand on every case, which the files already say:++- **Who posted this.** A download keeps the address of the post it came from, and on+ most platforms that address names the account. The account is filed, or found when+ the case already holds that handle, and joined to the file with ``posted``.+- **Which points are one site.** Two geolocations 200 m apart on one airfield draw as+ two islands until somebody says they belong together. Points closer than+ ``SITE_RADIUS_M`` are joined with ``same-site-as``.++Everything is filed ``suggested`` (ONTOLOGY §4). The analyst confirms it or drops it+wherever the edge is read.++**Each entity is read once.** The manifest keeps how far the last pass read+(``Case.link_pass``): the newest filing moment it saw, and which entities filed in that+same second it already read, since a filing time has no finer grain than the second and+the job runs the moment something is filed. A pass reads only what lies past that mark,+which is what makes a dismissal stick: a dropped edge belongs to an entity already read,+so no later pass proposes it again. Enrichment keeps the same promise with its version+stamp.++**One edge per join, never one per pair.** Eight points on one site get seven edges,+a spanning tree, not twenty-eight. The edge says "these belong together", and a mesh+would bury the picture it is there to clear up.++It runs as a queued job when a place, a file or a bookmark is filed, and on demand+from the graph. Nothing is fetched: an address is parsed, a distance is computed.+"""++from __future__ import annotations++import math+import re+from typing import TYPE_CHECKING, Any+from urllib.parse import urlsplit++from . import entities as entity_engine+from . import links as link_engine+from . import workqueue++if TYPE_CHECKING:+ from ..workspace import Case++#: How close two points must be to be proposed as one site. Measured on real cases: at+#: 300 m the points of one airfield join, and a city full of geolocations does not chain+#: into a single blob the way it starts to at 500 m.+SITE_RADIUS_M = 300++#: The provenance every proposal carries, so the analyst and the code can tell them+#: from the edges somebody stated.+BY = "link-finder"++#: The durable job that runs a pass. Keyed on the case, so a burst of imports queues+#: one pass rather than one per file.+KIND = "propose-links"++#: What a pass reads for accounts, and where each keeps its address.+URL_ATTRS = {"media": "source_url", "bookmark": "url"}++#: Which types are read for a site. Only `place`: a capture is imagery of a point+#: rather than a point, and it already hangs off the place it was framed on.+SITE_TYPES = ("place",)++#: Grid cell, in degrees, the points are bucketed in so a pass compares a point with its+#: neighbours rather than with the whole case. About 1.1 km, wider than the radius.+_CELL = 0.01++_PAGE = 500++#: Path words a platform uses for itself, which an address can hold where a handle goes.+_RESERVED = frozenset({+ "i", "home", "search", "hashtag", "intent", "share", "explore", "settings", "p",+ "reel", "reels", "tv", "stories", "s", "c", "joinchat", "watch", "shorts", "channel",+ "user", "profile", "status", "video", "post", "messages", "notifications", "web",+})++_HANDLE = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9_.\-]{0,63}$")++#: Prefixes a host is written with that name the same site.+_HOST_PREFIXES = ("www.", "mobile.", "m.")+++# -- who posted it ------------------------------------------------------------+++def account_from_url(url: Any) -> dict[str, str] | None:+ """The account a post's address names, or None when it names none.++ Read off the address alone, so only where the platform writes the handle into it:+ X, Telegram, TikTok, YouTube, Instagram, Threads, Bluesky and the fediverse's+ ``/@user/123``. A YouTube ``watch`` link or an Instagram ``/p/`` link names no+ account, and guessing one from the uploader's display name would join two people+ who share a name.+ """+ if not isinstance(url, str) or not url.strip():+ return None+ try:+ parts = urlsplit(url.strip())+ except ValueError:+ return None+ if parts.scheme not in ("http", "https"):+ return None+ host = (parts.hostname or "").lower()+ for prefix in _HOST_PREFIXES:+ if host.startswith(prefix):+ host = host[len(prefix):]+ segs = [seg for seg in parts.path.split("/") if seg]++ handle, platform, profile = "", "", ""+ if host in ("x.com", "twitter.com"):+ if len(segs) >= 3 and segs[1] == "status":+ handle, platform = segs[0], "X"+ profile = f"https://x.com/{handle}"+ elif host in ("t.me", "telegram.me"):+ if segs and segs[0] == "s":+ segs = segs[1:]+ if len(segs) >= 2 and segs[1].isdigit():+ handle, platform = segs[0], "Telegram"+ profile = f"https://t.me/{handle}"+ elif host in ("tiktok.com", "youtube.com", "threads.net", "threads.com"):+ if segs and segs[0].startswith("@") and (host == "youtube.com" or len(segs) >= 2):+ handle = segs[0][1:]+ platform = {"tiktok.com": "TikTok", "youtube.com": "YouTube"}.get(host, "Threads")+ profile = f"https://{host}/@{handle}"+ elif host == "instagram.com":+ if len(segs) >= 3 and segs[1] in ("p", "reel"):+ handle, platform = segs[0], "Instagram"+ profile = f"https://instagram.com/{handle}"+ elif host == "bsky.app":+ if len(segs) >= 4 and segs[0] == "profile" and segs[2] == "post":+ handle, platform = segs[1], "Bluesky"+ profile = f"https://bsky.app/profile/{handle}"+ elif len(segs) == 2 and segs[0].startswith("@") and segs[1].isdigit():+ # A Mastodon status, on any server: the handle carries the server, since the+ # same name on two servers is two people.+ if _HANDLE.match(segs[0][1:]):+ handle, platform = f"{segs[0][1:]}@{host}", "Mastodon"+ profile = f"https://{host}/{segs[0]}"+ return {"label": f"@{handle}", "platform": platform, "url": profile}+ if not handle or handle.lower() in _RESERVED or not _HANDLE.match(handle):+ return None+ return {"label": f"@{handle}", "platform": platform, "url": profile}+++def _address(entity: dict[str, Any]) -> Any:+ key = URL_ATTRS.get(str(entity.get("type") or ""))+ return (entity.get("attrs") or {}).get(key) if key else None+++def _page_all(case: "Case", types: list[str], since: str | None = None) -> list[dict[str, Any]]:+ out: list[dict[str, Any]] = []+ cursor: str | None = None+ while True:+ page = case.page_entities(limit=_PAGE, cursor=cursor, types=types, since=since)+ out.extend(page["items"])+ cursor = page.get("next_cursor")+ if not cursor:+ return out+++def _filed_at(entity: dict[str, Any]) -> str:+ return str((entity.get("provenance") or {}).get("at") or "")+++class _Mark:+ """How far the passes have read, and the question "is this one new?".++ ``at`` is the newest filing moment read so far and ``read`` the ids filed in that+ second that were. Asking about an entity records it, so the mark a pass leaves+ behind is exactly what it read.+ """++ def __init__(self, stored: dict[str, Any] | None) -> None:+ stored = stored or {}+ self.at: str | None = stored.get("at") or None+ self.read: set[str] = set(stored.get("read") or [])+ self.newest, self.newest_ids = self.at, set(self.read)++ def fresh(self, entity: dict[str, Any]) -> bool:+ at, entity_id = _filed_at(entity), str(entity["id"])+ if self.at is not None and (at < self.at or (at == self.at and entity_id in self.read)):+ return False+ if at and (self.newest is None or at > self.newest):+ self.newest, self.newest_ids = at, {entity_id}+ elif at and at == self.newest:+ self.newest_ids.add(entity_id)+ return True++ def stored(self) -> dict[str, Any] | None:+ if self.newest is None:+ return None+ return {"at": self.newest, "read": sorted(self.newest_ids)}+++def _propose_accounts(case: "Case", mark: _Mark, counts: dict[str, int]) -> None:+ """Join each file and bookmark filed since the last pass to the account that posted it.++ A file somebody already said who posted is left alone, whatever they said: the+ analyst's ``posted`` is an answer, and a second one beside it would be an argument.+ """+ held: dict[str, str] = {}+ for account_id, label in case.labels_of_type("account"):+ held.setdefault(entity_engine.identity_key("account", label), account_id)+ for entity in _page_all(case, list(URL_ATTRS), mark.at):+ if not mark.fresh(entity):+ continue+ account = account_from_url(_address(entity))+ if account is None:+ continue+ if any(link["type"] == link_engine.POSTED for link in case.links_of(entity["id"])):+ continue+ key = entity_engine.identity_key("account", account["label"])+ found = held.get(key)+ if found is not None:+ account_id = found+ else:+ made = case.add_entity(+ "account",+ account["label"],+ attrs={"platform": account["platform"], "url": account["url"]},+ by=BY,+ status="suggested",+ )+ account_id = held[key] = made["id"]+ counts["accounts"] += 1+ case.add_link(+ account_id, entity["id"], link_engine.POSTED, by=BY, status="suggested", unique=True+ )+ counts["posted"] += 1+++# -- which points are one site -------------------------------------------------+++def point_of(entity: dict[str, Any]) -> tuple[float, float] | None:+ attrs = entity.get("attrs") or {}+ try:+ lat, lon = float(attrs["lat"]), float(attrs["lon"])+ except (KeyError, TypeError, ValueError):+ return None+ if not (-90 <= lat <= 90 and -180 <= lon <= 180):+ return None+ return lat, lon+++def metres(a: tuple[float, float], b: tuple[float, float]) -> float:+ """Great-circle distance between two ``(lat, lon)`` points, in metres."""+ lat1, lat2 = math.radians(a[0]), math.radians(b[0])+ dlat, dlon = lat2 - lat1, math.radians(b[1] - a[1])+ h = math.sin(dlat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2+ return 2 * 6_371_000 * math.asin(min(1.0, math.sqrt(h)))+++class _Points:+ """Points bucketed on a grid, so "what is near this" reads nine cells."""++ def __init__(self, points: dict[str, tuple[float, float]]) -> None:+ self.points = points+ self.cells: dict[tuple[int, int], list[str]] = {}+ for entity_id, point in points.items():+ self.cells.setdefault(self._cell(point), []).append(entity_id)++ @staticmethod+ def _cell(point: tuple[float, float]) -> tuple[int, int]:+ return int(math.floor(point[0] / _CELL)), int(math.floor(point[1] / _CELL))++ def near(self, point: tuple[float, float], radius: float = SITE_RADIUS_M) -> list[str]:+ """The ids within ``radius`` of ``point``, nearest first. The radius stays under+ a cell, so the cell and its eight neighbours hold every answer."""+ row, col = self._cell(point)+ found: list[tuple[float, str]] = []+ for dr in (-1, 0, 1):+ for dc in (-1, 0, 1):+ for entity_id in self.cells.get((row + dr, col + dc), ()):+ distance = metres(point, self.points[entity_id])+ if distance <= radius:+ found.append((distance, entity_id))+ return [entity_id for _, entity_id in sorted(found)]+++def _propose_sites(case: "Case", mark: _Mark, counts: dict[str, int]) -> None:+ """Join each point filed since the last pass to the sites standing within reach.++ Union-find over the joins already standing, whoever made them, so a site the+ analyst has already tied together gets no second edge, and a new point between two+ sites gets one edge to each.+ """+ places = _page_all(case, list(SITE_TYPES))+ points = {place["id"]: point for place in places if (point := point_of(place)) is not None}+ fresh = sorted(+ (place for place in places if mark.fresh(place) and place["id"] in points),+ key=lambda place: (_filed_at(place), place["id"]),+ )+ if not fresh:+ return++ parent = {entity_id: entity_id for entity_id in points}++ def root(entity_id: str) -> str:+ while parent[entity_id] != entity_id:+ parent[entity_id] = parent[parent[entity_id]]+ entity_id = parent[entity_id]+ return entity_id++ for link in case.links_touching(sorted(points), types=[link_engine.SAME_SITE_AS]):+ if link["from"] in parent and link["to"] in parent:+ parent[root(link["from"])] = root(link["to"])++ grid = _Points(points)+ for place in fresh:+ for other in grid.near(points[place["id"]]):+ if other == place["id"] or root(other) == root(place["id"]):+ continue+ # Symmetric in meaning, canonical in storage, like `same-image-as`.+ first, second = sorted((place["id"], other))+ case.add_link(+ first, second, link_engine.SAME_SITE_AS, by=BY, status="suggested", unique=True+ )+ parent[root(other)] = root(place["id"])+ counts["sites"] += 1+++# -- the pass ------------------------------------------------------------------+++def propose(case: "Case") -> dict[str, int]:+ """Read what was filed past the mark and propose what it says.++ One transaction. The mark moves to what was actually read, so anything filed while+ the pass runs is read by the next one rather than skipped.+ """+ mark = _Mark(case.link_pass())+ counts = {"accounts": 0, "posted": 0, "sites": 0}+ with case.batch():+ _propose_accounts(case, mark, counts)+ _propose_sites(case, mark, counts)+ stored = mark.stored()+ if stored is not None:+ case.set_link_pass(stored)+ return counts+++#: The types whose filing queues a pass.+TRIGGER_TYPES = frozenset({*URL_ATTRS, *SITE_TYPES})+++def on_filed(case: "Case", entity_type: str) -> None:+ """Queue a pass after something it reads was filed. One per case at a time."""+ if entity_type in TRIGGER_TYPES:+ workqueue.enqueue(case, KIND, key="case")+++def _handle(case: "Case", job: dict[str, Any]) -> None:+ propose(case)+++workqueue.register(KIND, _handle)+++def unreviewed(link: dict[str, Any]) -> bool:+ """Whether this edge is a proposal of this module nobody has looked at yet.++ Such an edge holds nothing up. A place a proof lets go of is the analyst's leftover+ even when a pass has proposed its neighbour as the same site: the proposal was made+ about the place, not by the analyst for it.+ """+ provenance = link.get("provenance") or {}+ return provenance.get("by") == BY and provenance.get("status") == "suggested"+++def pending(case: "Case") -> dict[str, int]:+ """How many proposals still wait for the analyst, by what they say."""+ waiting = {"accounts": 0, "posted": 0, "sites": 0}+ for link in case.list_links():+ if not unreviewed(link):+ continue+ if link["type"] == link_engine.POSTED:+ waiting["posted"] += 1+ elif link["type"] == link_engine.SAME_SITE_AS:+ waiting["sites"] += 1+ waiting["accounts"] = sum(+ 1+ for entity in _page_all(case, ["account"])+ if (entity.get("provenance") or {}).get("by") == BY+ and (entity.get("provenance") or {}).get("status") == "suggested"+ )+ return waiting+++# -- what a proof shares with the rest of the case -----------------------------++#: How far up a derivation a proof's sources are looked for. A proof made from a frame+#: of a video is two steps from the file that was downloaded.+_ANCESTRY = 6+++def _sources(case: "Case", entity_id: str) -> list[str]:+ """What this was made from, every step up, nearest first."""+ seen: list[str] = []+ frontier = [entity_id]+ for _ in range(_ANCESTRY):+ step: list[str] = []+ for current in frontier:+ for link in case.links_of(current):+ if link["type"] == link_engine.DERIVED_FROM and link["from"] == current:+ if link["to"] not in seen and link["to"] != entity_id:+ seen.append(link["to"])+ step.append(link["to"])+ if not step:+ break+ frontier = step+ return seen+++def kin(case: "Case", entity_id: str) -> dict[str, Any]:+ """What a geolocation shares with the rest of the case: other geolocations on the+ same site, the other points within reach whatever filed them, and the account its+ material came from with what else that account posted here.++ Read, never written, and answered from geometry and addresses rather than from the+ proposed edges: it is asked the moment a proof is saved, before the pass that will+ file those edges has run.+ """+ entity = case.get_entity(entity_id)+ if entity is None:+ raise KeyError(entity_id)++ # Its places: what it shows or was recorded at.+ shown = link_engine.DEPICTS, link_engine.LOCATED_AT+ own_places = [+ link["to"] for link in case.links_of(entity_id)+ if link["from"] == entity_id and link["type"] in shown+ ]+ own_points = [+ point+ for place in case.entities_by_ids(own_places)+ if (point := point_of(place)) is not None+ ]+ others: set[str] = set()+ near: set[str] = set()+ if own_points:+ places = _page_all(case, list(SITE_TYPES))+ points = {place["id"]: point for place in places if (point := point_of(place)) is not None}+ grid = _Points(points)+ near = {+ other for point in own_points for other in grid.near(point)+ } - set(own_places)+ for link in case.links_touching(sorted(near), types=[link_engine.DEPICTS]):+ proof = link["from"]+ if link["to"] in near and proof != entity_id:+ others.add(proof)+ known = {item["id"]: item for item in case.entities_by_ids(sorted(others))}+ others = {proof for proof in others if (known.get(proof) or {}).get("type") == "proof"}++ # Its accounts: whoever posted the files it was made from.+ sources = [entity_id, *_sources(case, entity_id)]+ mine = set(sources)+ accounts: dict[str, dict[str, Any]] = {}+ for source in case.entities_by_ids(sources):+ for link in case.links_of(source["id"]):+ if link["type"] == link_engine.POSTED and link["to"] == source["id"]:+ poster = case.get_entity(link["from"])+ if poster is not None:+ key = entity_engine.identity_key("account", poster["label"])+ accounts.setdefault(key, {"label": poster["label"], "id": poster["id"]})+ parsed = account_from_url(_address(source))+ if parsed is not None:+ key = entity_engine.identity_key("account", parsed["label"])+ accounts.setdefault(key, {"label": parsed["label"], "id": None})++ if accounts:+ posted: dict[str, set[str]] = {key: set() for key in accounts}+ for item in _page_all(case, list(URL_ATTRS)):+ parsed = account_from_url(_address(item))+ if parsed is not None:+ key = entity_engine.identity_key("account", parsed["label"])+ if key in posted:+ posted[key].add(item["id"])+ for key, account in accounts.items():+ if account["id"]:+ for link in case.links_of(account["id"]):+ if link["type"] == link_engine.POSTED and link["from"] == account["id"]:+ posted[key].add(link["to"])+ account["files"] = len(posted[key] - mine)++ return {+ "sites": sorted(others),+ "places": sorted(near),+ "radius": SITE_RADIUS_M,+ "accounts": sorted(+ accounts.values(), key=lambda account: (-account.get("files", 0), account["label"])+ ),+ }diff --git a/src/azimut/engine/satellite.py b/src/azimut/engine/satellite.pyindex e62a96a..7e2dd2b 100644--- a/src/azimut/engine/satellite.py+++ b/src/azimut/engine/satellite.py@@ -30,6 +30,7 @@ from . import countriesfrom . import geo as geo_enginefrom . import linksfrom . import media as media_engine+from . import proposals as proposal_enginefrom . import timeline# Saved work is places, captures and saved comparisons; a screenshot filed by the@@ -227,7 +228,8 @@ def restate_proof_point(Answers with the places this proof let go of that nothing else holds — thecaller asks about deleting them (``api/proofs``), since a point nobody points- at is the analyst's own leftover to keep or drop, not ours to sweep.+ at is the analyst's own leftover to keep or drop, not ours to sweep. A link+ proposal nobody has reviewed holds nothing (``proposals.unreviewed``)."""material = _material_of(case, proof_id)wanted = {entry["id"]: bool(entry.get("pov")) for entry in stated}@@ -237,7 +239,9 @@ def restate_proof_point(continue_withdraw_point(case, proof_id, old_id, material)old = case.get_entity(old_id)- if old is not None and not case.links_of(old_id):+ if old is not None and all(+ proposal_engine.unreviewed(link) for link in case.links_of(old_id)+ ):released.append(old)for place_id, pov in wanted.items():_state_point(case, proof_id, place_id, material, pov=pov, by=by)diff --git a/src/azimut/engine/sheetfromcase.py b/src/azimut/engine/sheetfromcase.pyindex 7a3b249..7bad737 100644--- a/src/azimut/engine/sheetfromcase.py+++ b/src/azimut/engine/sheetfromcase.py@@ -135,7 +135,7 @@ def build(}-# -- the outgoing shape: one row per proof -------------------------------------+# -- the outgoing shape: one row per point a proof concludes on ------------------## The other document in this app carrying these columns is the `geoloc` template, and it# runs the other way: addresses pasted in, pressed, downloaded, turned into proofs. This@@ -143,6 +143,10 @@ def build(# the two is the mistake to avoid — the incoming one holds *text of URLs*, this one holds# *links to entities*, and `canBuild()` refuses to offer the sheet-to-proofs build here# because there is nothing left to fetch.+#+# **One row per point, not per proof.** A video placed at three spots is three+# geolocations, and an index that gave it one row with one of the three places on it+# lost the other two. A proof that concludes nowhere yet still gets its one row.#: The label of the proof, and the column its link hangs on.TITLE_COLUMN = "Title"@@ -164,21 +168,33 @@ POINT_COLUMN = "Coordinates"#: here — which is the column the analyst filters on to find them and decide.IN_CASE_COLUMN = "In case"+#: What Geo Proof says about the proof, restated per row: the date of the event as the+#: analyst wrote it (`2026-09-08~` keeps its `~`), whether this point is where the camera+#: stood, the address of the post the footage came from, and the description.+DATE_COLUMN = "Date"+POV_COLUMN = "POV"+SOURCE_URL_COLUMN = "Source URL"+DESCRIPTION_COLUMN = "Description"+#: What the proof derives from. `capture` as well as `media`: a frame grabbed out of a#: video is a source like any other, and a column that skipped it would be blank on#: exactly the proofs built the careful way.SOURCE_TYPES = ("media", "capture")+#: How far up a derivation the footage behind a proof is looked for: the frame, the+#: video it was cut from, the post that video came from.+_ASCENT = 6+def _edges(case: "Case") -> dict[str, dict[str, list[str]]]:- """The two edges this shape reads, indexed by the proof they leave.+ """The edges this shape reads, indexed by the entity they leave.- One pass over the graph rather than two queries per row: a build may take two- thousand proofs and the graph is the same graph for all of them.+ One pass over the graph rather than queries per row: a build may take two thousand+ proofs and the graph is the same graph for all of them."""from . import links as link_engine- wanted = (link_engine.DERIVED_FROM, link_engine.DEPICTS)+ wanted = (link_engine.DERIVED_FROM, link_engine.DEPICTS, link_engine.LOCATED_AT)found: dict[str, dict[str, list[str]]] = {}for link in case.list_links():kind = str(link.get("type") or "")@@ -190,15 +206,36 @@ def _edges(case: "Case") -> dict[str, dict[str, list[str]]]:return found+def _ancestors(edges: dict[str, dict[str, list[str]]], entity_id: str) -> list[str]:+ """What this was made from, every step up, nearest first."""+ from . import links as link_engine++ seen: list[str] = []+ frontier = [entity_id]+ for _ in range(_ASCENT):+ step = [+ parent+ for current in frontier+ for parent in edges.get(current, {}).get(link_engine.DERIVED_FROM, [])+ if parent not in seen and parent != entity_id+ ]+ step = list(dict.fromkeys(step))+ if not step:+ break+ seen.extend(step)+ frontier = step+ return seen++def _first(ids: list[str], known: dict[str, dict[str, Any]], types: tuple[str, ...]) -> str:"""Which of these a cell holds, when a cell holds one and the proof has several.- A proof rests on up to eight sources and a cell carries one link, so one is chosen —- otherwise "one row per proof" stops being true. Chosen **by label**, not by whatever- order the graph hands back: `list_links()` reads in insertion order today, which is- stable but arbitrary, and a bundle restored elsewhere may insert them in another one.- Sorting by what the analyst can see means two builds of the same case agree, and- agree with what somebody reading the panel would have picked.+ A proof rests on up to eight sources and a cell carries one link, so one is chosen.+ Chosen **by label**, not by whatever order the graph hands back: `list_links()` reads+ in insertion order today, which is stable but arbitrary, and a bundle restored+ elsewhere may insert them in another one. Sorting by what the analyst can see means+ two builds of the same case agree, and agree with what somebody reading the panel+ would have picked."""holding = [entity_id@@ -215,9 +252,13 @@ def proof_columns() -> list[str]:return [sheet_engine.ID_COLUMN,TITLE_COLUMN,- SOURCE_COLUMN,+ DATE_COLUMN,PLACE_COLUMN,+ POV_COLUMN,POINT_COLUMN,+ SOURCE_COLUMN,+ SOURCE_URL_COLUMN,+ DESCRIPTION_COLUMN,IN_CASE_COLUMN,STATUS_COLUMN,NOTES_COLUMN,@@ -227,15 +268,20 @@ def proof_columns() -> list[str]:def proof_roles() -> dict[str, Any]:"""What each column is, which is also what may be typed in and what may not.- Three locked, two computed, one state, one free. The analyst's half of the table is- `Status`, `Notes` and any column they add: the case's half is the app's to write, and- a view somebody can type over is a view that starts lying the first time they do.+ The analyst's half of the table is `Status`, `Notes` and any column they add: the+ case's half is the app's to write, and a view somebody can type over is a view that+ starts lying the first time they do. The date and the description are Geo Proof's,+ so they are changed there."""return {TITLE_COLUMN: {"kind": "locked"},- SOURCE_COLUMN: {"kind": "locked"},+ DATE_COLUMN: {"kind": "locked"},PLACE_COLUMN: {"kind": "locked"},+ POV_COLUMN: {"kind": "locked"},POINT_COLUMN: {"kind": "computed", "of": "point", "from": PLACE_COLUMN},+ SOURCE_COLUMN: {"kind": "locked"},+ SOURCE_URL_COLUMN: {"kind": "locked"},+ DESCRIPTION_COLUMN: {"kind": "locked"},IN_CASE_COLUMN: {"kind": "computed", "of": "in_case"},STATUS_COLUMN: {"kind": "state"},}@@ -250,68 +296,121 @@ def _resolve(case: "Case", proofs: list[dict[str, Any]]) -> tuple[for proof in proofs:for targets in edges.get(str(proof["id"]), {}).values():reachable.update(targets)+ reachable.update(_ancestors(edges, str(proof["id"])))known = {str(entity["id"]): entity for entity in case.entities_by_ids(sorted(reachable))}return edges, known-def _proof_cells(+def _proof_points(proof: dict[str, Any],edges: dict[str, dict[str, list[str]]],known: dict[str, dict[str, Any]],-) -> tuple[dict[str, str], dict[str, str]]:- """One proof as the three cells it fills and the three links behind them.+) -> list[tuple[str, dict[str, str], dict[str, str]]]:+ """One proof as one row per point it concludes on: the match key the refresh finds+ the row by, the cells, and the links behind them.- A proof with no place gives a row whose `Place` and `Coordinates` are empty, and the+ A proof with no place gives one row whose `Place` and `Coordinates` are empty, and therow is filed anyway. That is information — the case holds a proof nobody has placed —and refusing the row would be the build deciding which of the analyst's proofs count."""from . import links as link_engine- held = edges.get(str(proof["id"]), {})+ proof_id = str(proof["id"])+ held = edges.get(proof_id, {})media = _first(held.get(link_engine.DERIVED_FROM, []), known, SOURCE_TYPES)- place = _first(held.get(link_engine.DEPICTS, []), known, ("place",))- label = _cell(proof.get("label"))- cells = {- TITLE_COLUMN: label,+ ancestry = _ancestors(edges, proof_id)+ # The post the footage came from, so a file's address and not a capture's: a capture+ # records the imagery provider it was framed on, which is not a source anybody cites.+ address = next(+ (+ str(url)+ for entity_id in ancestry+ if (known.get(entity_id) or {}).get("type") == "media"+ and (url := ((known.get(entity_id) or {}).get("attrs") or {}).get("source_url"))+ ),+ "",+ )+ recorded = {+ place for entity_id in ancestry for place in edges.get(entity_id, {}).get(link_engine.LOCATED_AT, [])+ }+ places = sorted(+ {+ place for place in held.get(link_engine.DEPICTS, [])+ if (known.get(place) or {}).get("type") == "place"+ },+ key=lambda place: (str(known[place].get("label") or "").casefold(), place),+ )+ attrs = proof.get("attrs") or {}+ shared = {+ TITLE_COLUMN: _cell(proof.get("label")),+ DATE_COLUMN: _cell(attrs.get("when")),SOURCE_COLUMN: _cell((known.get(media) or {}).get("label")) if media else "",- PLACE_COLUMN: _cell((known.get(place) or {}).get("label")) if place else "",+ SOURCE_URL_COLUMN: address,+ DESCRIPTION_COLUMN: _cell(attrs.get("notes")),}- links = {TITLE_COLUMN: str(proof["id"])}- if media:- links[SOURCE_COLUMN] = media- if place:- links[PLACE_COLUMN] = place- return cells, links+ base_links = {TITLE_COLUMN: proof_id, **({SOURCE_COLUMN: media} if media else {})}+ if not places:+ return [(_match(proof_id, ""), {**shared, PLACE_COLUMN: "", POV_COLUMN: ""}, base_links)]+ return [+ (+ _match(proof_id, place),+ {+ **shared,+ PLACE_COLUMN: _cell(known[place].get("label")),+ POV_COLUMN: "YES" if place in recorded else "NO",+ },+ {**base_links, PLACE_COLUMN: place},+ )+ for place in places+ ]-def build_proofs(case: "Case", *, limit: int = MAX_FROM_CASE) -> dict[str, Any]:- """The table, the sidecar and the counts for one row per proof the case holds.+def _match(proof_id: str, place_id: str) -> str:+ return f"{proof_id}|{place_id}"- Ordered by label like the generic shape, because that is how a row is looked up.- `Status` arrives at `done` on every row rather than `to do`: each line is a proof that- exists, and forty rows claiming work still to do would be forty lies. The column earns- its keep the moment the analyst adds a line for a place **not** yet proven — that one- arrives at `to do`, and the column then means "is there a proof for this row".- """- columns = proof_columns()+def _proof_rows(case: "Case", limit: int) -> tuple[list[dict[str, Any]], int]:+ """Every point of the proofs taken, as the items a build or a refresh lays out."""taken = max(0, min(int(limit), MAX_FROM_CASE))page = case.page_entities(limit=taken or 1, types=["proof"], order="label")proofs = list(page.get("items", []))[:taken]edges, known = _resolve(case, proofs)+ items = [+ {"id": str(proof["id"]), "match": match, "cells": cells, "links": cell_links}+ for proof in proofs+ for match, cells, cell_links in _proof_points(proof, edges, known)+ ]+ return items, int(page.get("total", len(proofs)))+++def build_proofs(case: "Case", *, limit: int = MAX_FROM_CASE) -> dict[str, Any]:+ """The table, the sidecar and the counts for one row per point the proofs conclude on.++ Ordered by proof label like the generic shape, because that is how a row is looked up,+ and a proof's points by their own labels under it.++ `Status` arrives at `done` on every row rather than `to do`: each line is a+ geolocation that exists, and forty rows claiming work still to do would be forty lies.+ The column earns its keep the moment the analyst adds a line for a place **not** yet+ proven — that one arrives at `to do`, and the column then means "is there a proof for+ this row".++ ``taken``/``total`` count proofs, which is what the limit is on.+ """+ columns = proof_columns()+ items, total = _proof_rows(case, limit)rows: list[list[str]] = []links: dict[str, dict[str, str]] = {}promoted: dict[str, dict[str, str]] = {}built: dict[str, str] = {}- for proof in proofs:+ for item in items:key = sheet_engine.new_row_id()- cells, cell_links = _proof_cells(proof, edges, known)- filled = {sheet_engine.ID_COLUMN: key, STATUS_COLUMN: "done", **cells}+ filled = {sheet_engine.ID_COLUMN: key, STATUS_COLUMN: "done", **item["cells"]}rows.append([filled.get(name, "") for name in columns])- links[key] = cell_links- promoted[key] = {TITLE_COLUMN: cells[TITLE_COLUMN]}- built[key] = str(proof["id"])+ links[key] = item["links"]+ promoted[key] = {TITLE_COLUMN: item["cells"][TITLE_COLUMN]}+ built[key] = item["id"]meta = {**sheet_engine.empty_meta(),@@ -325,8 +424,8 @@ def build_proofs(case: "Case", *, limit: int = MAX_FROM_CASE) -> dict[str, Any]:"columns": columns,"rows": rows,"meta": meta,- "taken": len(rows),- "total": int(page.get("total", len(rows))),+ "taken": len(set(built.values())),+ "total": total,}@@ -348,11 +447,15 @@ def refresh_proofs(**Only the case's columns are rewritten.** `Status`, `Notes` and anything the analystadded are read and put back untouched. A refresh that reset a status would be a- refresh nobody presses twice.+ refresh nobody presses twice. A sheet built before a column existed keeps its own+ columns: the new ones are not forced on it.**New rows land at the end**, in label order among themselves. Inserting them inplace would reshuffle a table somebody is working down; the sheet's own sort is where- order is decided.+ order is decided. A point added to a proof is a new row like any other.++ A row is found again by its proof and its place, so one per point: a sheet built when+ this shape was one row per proof finds its rows by the place they carry.Refused on any other sheet. The shape is recognised by its `Title` column being`locked` — a heading alone would not do, since nothing stops an imported binder from@@ -362,30 +465,59 @@ def refresh_proofs(roles = (meta.get("roles") or {}) if isinstance(meta, dict) else {}if (roles.get(TITLE_COLUMN) or {}).get("kind") != "locked" or TITLE_COLUMN not in columns:raise sheet_engine.SheetError("this sheet was not built out of the case's proofs")+ items, _ = _proof_rows(case, limit)+ return _refresh(+ case,+ columns,+ rows,+ meta,+ items,+ key_column=TITLE_COLUMN,+ born=lambda cells: "done",+ row_match=lambda built_id, row_links: _match(built_id, row_links.get(PLACE_COLUMN, "")),+ )+++def _refresh(+ case: "Case",+ columns: list[str],+ rows: list[list[str]],+ meta: dict[str, Any],+ items: list[dict[str, Any]],+ *,+ key_column: str,+ born: Any,+ row_match: Any,+ advance: Any = None,+) -> dict[str, Any]:+ """The refresh both fixed shapes share: rewrite the case's columns on the rows that+ stand for an item, add a row for each item that has none, count the rows whose entity+ is gone.++ An item is ``{id, match, cells, links}``: the entity a row is built from, the key it+ is found again by, and what it fills. ``row_match`` reads that key back off a standing+ row. ``born`` is the status a new row starts at; ``advance`` may move a standing row's+ status on, and returns None to leave it alone."""key_at = sheet_engine.key_index(columns)index = {name: position for position, name in enumerate(columns)}links = {str(key): dict(cells) for key, cells in (meta.get("links") or {}).items()}promoted = {str(key): dict(cells) for key, cells in (meta.get("promoted") or {}).items()}built = {str(key): str(value) for key, value in (meta.get("built") or {}).items() if value}- taken = max(0, min(int(limit), MAX_FROM_CASE))- page = case.page_entities(limit=taken or 1, types=["proof"], order="label")- proofs = list(page.get("items", []))[:taken]- edges, known = _resolve(case, proofs)-- # Which row already stands for which proof. The sidecar's own record rather than a+ # Which row already stands for which item. The sidecar's own record rather than a# match on the text: the label is what changes, so matching on it would file a second- # row for every proof somebody renamed.- at_proof: dict[str, str] = {}+ # row for every entity somebody renamed.+ standing_at: dict[str, str] = {}for row_key, entity_id in built.items():- at_proof.setdefault(entity_id, row_key)+ standing_at.setdefault(row_match(entity_id, links.get(row_key) or {}), row_key)table = [list(row) for row in rows]where = {row[key_at]: position for position, row in enumerate(table) if key_at < len(row)}+ status_at = index.get(STATUS_COLUMN)updated, added = 0, 0- for proof in proofs:- cells, cell_links = _proof_cells(proof, edges, known)- standing = at_proof.get(str(proof["id"]))+ for item in items:+ cells, cell_links = item["cells"], item["links"]+ standing = standing_at.get(item["match"])if standing is not None and standing in where:row = table[where[standing]]for name, value in cells.items():@@ -393,32 +525,37 @@ def refresh_proofs(if position is not None and position < len(row) and row[position] != value:row[position] = valueupdated += 1+ if advance is not None and status_at is not None and status_at < len(row):+ moved = advance(row[status_at], cells)+ if moved is not None and moved != row[status_at]:+ row[status_at] = moved+ updated += 1links[standing] = cell_links- promoted[standing] = {TITLE_COLUMN: cells[TITLE_COLUMN]}+ promoted[standing] = {key_column: cells[key_column]}continuekey = sheet_engine.new_row_id()row = [""] * len(columns)if key_at < len(row):row[key_at] = key- for name, value in {**cells, STATUS_COLUMN: "done"}.items():+ for name, value in {**cells, STATUS_COLUMN: born(cells)}.items():position = index.get(name)if position is not None and position < len(row):row[position] = valuetable.append(row)links[key] = cell_links- promoted[key] = {TITLE_COLUMN: cells[TITLE_COLUMN]}- built[key] = str(proof["id"])+ promoted[key] = {key_column: cells[key_column]}+ built[key] = item["id"]added += 1# What the rows already on the table were built from, and which of those the case# still holds. Asked of the case rather than of the page above: a build cut at the- # limit must not report every proof past it as deleted.+ # limit must not report every entity past it as deleted.carried = {str(key): built[key] for key in where if key in built}alive = {str(entity["id"])for entity in case.entities_by_ids(sorted(set(carried.values())))}- gone = sum(1 for entity_id in carried.values() if entity_id not in alive)+ gone = sum(1 for entity_id in set(carried.values()) if entity_id not in alive)return {"columns": list(columns),"rows": table,@@ -427,3 +564,300 @@ def refresh_proofs("updated": updated,"gone": gone,}+++# -- the worklist shape: one row per file to geolocate ---------------------------+#+# The analyst's queue rather than their index. `My geolocations` lists what has been+# done, one row per proof; this lists what was brought in to be done, one row per picture+# or video the analyst imported, and says which of them a proof already answers. Only+# imported material: a frame cut in Inspect, a capture or a Compare render is the work+# itself, and a row for each would be a worklist of the worklist.++#: The file, and the column its link hangs on.+FILE_COLUMN = "File"++#: The address of the post the file came from, as the case recorded it at import. Locked+#: and linkless: it is a fact about the file, and the grid opens any address it shows.+ADDRESS_COLUMN = "Source URL"++#: The proof made out of this file, however many steps down: a proof built on a frame of+#: a video answers for the video.+PROOF_COLUMN = "Proof"++#: What a file must be to have a row: something a place can be read off.+FILE_KINDS = ("image", "video")++#: How far down a derivation a file's proofs are looked for.+_DESCENT = 6++#: The words a refresh may move on to `done` when a proof appears. A status the analyst+#: set to anything else — `ruled out`, a word of their own — is theirs and stays.+_OPEN_STATES = ("", "to do", "in progress")+++def files_columns() -> list[str]:+ """The shape's headings: what the case says, then what you say."""+ return [+ sheet_engine.ID_COLUMN,+ FILE_COLUMN,+ ADDRESS_COLUMN,+ PROOF_COLUMN,+ PLACE_COLUMN,+ POINT_COLUMN,+ IN_CASE_COLUMN,+ STATUS_COLUMN,+ NOTES_COLUMN,+ ]+++def files_roles() -> dict[str, Any]:+ """Locked where the case answers, free where the analyst does: `Status` and `Notes`."""+ return {+ FILE_COLUMN: {"kind": "locked"},+ ADDRESS_COLUMN: {"kind": "locked"},+ PROOF_COLUMN: {"kind": "locked"},+ PLACE_COLUMN: {"kind": "locked"},+ POINT_COLUMN: {"kind": "computed", "of": "point", "from": PLACE_COLUMN},+ IN_CASE_COLUMN: {"kind": "computed", "of": "in_case"},+ STATUS_COLUMN: {"kind": "state"},+ }+++def imported_files(case: "Case") -> list[dict[str, Any]]:+ """Every picture and video the analyst brought in, by name.++ What the Media Library calls collected: not a route the app produced it by+ (``links.PRODUCED_HERE``), and a kind a place can be read off.+ """+ from . import links as link_engine++ files: list[dict[str, Any]] = []+ cursor: str | None = None+ while True:+ page = case.page_entities(limit=500, cursor=cursor, types=["media"], order="label")+ items = list(page.get("items", []))+ ids = [str(item["id"]) for item in items]+ kinds = case.media_kinds(ids)+ origins = case.media_origins(ids)+ for item in items:+ origin = (origins.get(str(item["id"])) or {}).get("type")+ if kinds.get(str(item["id"])) in FILE_KINDS and origin not in link_engine.PRODUCED_HERE:+ files.append(item)+ cursor = page.get("next_cursor")+ if not cursor:+ return files+++def _file_graph(case: "Case") -> tuple[dict[str, list[str]], dict[str, list[str]], dict[str, Any]]:+ """Which proofs answer for each file, where each file and proof is placed, and the+ entities those name. One pass over the links for the whole build."""+ from . import links as link_engine++ parents: dict[str, list[str]] = {}+ shows: dict[str, list[str]] = {}+ for link in case.list_links():+ kind = str(link.get("type") or "")+ source, target = str(link.get("from") or ""), str(link.get("to") or "")+ if not source or not target:+ continue+ if kind == link_engine.DERIVED_FROM:+ parents.setdefault(source, []).append(target)+ elif kind in (link_engine.DEPICTS, link_engine.LOCATED_AT):+ shows.setdefault(source, []).append(target)++ proofs: list[dict[str, Any]] = []+ cursor: str | None = None+ while True:+ page = case.page_entities(limit=500, cursor=cursor, types=["proof"])+ proofs.extend(page.get("items", []))+ cursor = page.get("next_cursor")+ if not cursor:+ break++ answered: dict[str, list[str]] = {}+ for proof in proofs:+ proof_id = str(proof["id"])+ seen: set[str] = set()+ frontier = [proof_id]+ for _ in range(_DESCENT):+ frontier = [+ parent for current in frontier for parent in parents.get(current, [])+ if parent not in seen+ ]+ frontier = list(dict.fromkeys(frontier))+ if not frontier:+ break+ for parent in frontier:+ seen.add(parent)+ answered.setdefault(parent, []).append(proof_id)++ named = {target for targets in shows.values() for target in targets}+ known = {str(proof["id"]): proof for proof in proofs}+ known.update(+ {str(entity["id"]): entity for entity in case.entities_by_ids(sorted(named))}+ )+ return answered, shows, known+++def _file_cells(+ item: dict[str, Any],+ answered: dict[str, list[str]],+ shows: dict[str, list[str]],+ known: dict[str, Any],+) -> tuple[dict[str, str], dict[str, str]]:+ """One file as its four cells and the links behind them. The place is the proof's+ when there is one, else wherever the case already puts the file itself."""+ file_id = str(item["id"])+ proof = _first(answered.get(file_id, []), known, ("proof",))+ place = (_first(shows.get(proof, []), known, ("place",)) if proof else "") or _first(+ shows.get(file_id, []), known, ("place",)+ )+ cells = {+ FILE_COLUMN: _cell(item.get("label")),+ ADDRESS_COLUMN: _cell((item.get("attrs") or {}).get("source_url")),+ PROOF_COLUMN: _cell((known.get(proof) or {}).get("label")) if proof else "",+ PLACE_COLUMN: _cell((known.get(place) or {}).get("label")) if place else "",+ }+ links = {FILE_COLUMN: file_id}+ if proof:+ links[PROOF_COLUMN] = proof+ if place:+ links[PLACE_COLUMN] = place+ return cells, links+++def _born(cells: dict[str, str]) -> str:+ return "done" if cells.get(PROOF_COLUMN) else "to do"+++def _advance(status: str, cells: dict[str, str]) -> str | None:+ """A file that now has a proof is done, unless the analyst already said otherwise."""+ if cells.get(PROOF_COLUMN) and status.strip().casefold() in _OPEN_STATES:+ return "done"+ return None+++def build_files(case: "Case", *, limit: int = MAX_FROM_CASE) -> dict[str, Any]:+ """The table, the sidecar and the counts for one row per imported picture or video.++ A row starts at `done` when a proof already answers for its file and at `to do`+ otherwise, so the progress count on the day it is built is the true one.+ """+ columns = files_columns()+ taken = max(0, min(int(limit), MAX_FROM_CASE))+ everything = imported_files(case)+ files = everything[:taken]+ answered, shows, known = _file_graph(case)++ rows: list[list[str]] = []+ links: dict[str, dict[str, str]] = {}+ promoted: dict[str, dict[str, str]] = {}+ built: dict[str, str] = {}+ for item in files:+ key = sheet_engine.new_row_id()+ cells, cell_links = _file_cells(item, answered, shows, known)+ filled = {sheet_engine.ID_COLUMN: key, STATUS_COLUMN: _born(cells), **cells}+ rows.append([filled.get(name, "") for name in columns])+ links[key] = cell_links+ promoted[key] = {FILE_COLUMN: cells[FILE_COLUMN]}+ built[key] = str(item["id"])++ meta = {+ **sheet_engine.empty_meta(),+ "links": links,+ "promoted": promoted,+ "built": built,+ "roles": files_roles(),+ "progress": STATUS_COLUMN,+ }+ return {+ "columns": columns,+ "rows": rows,+ "meta": meta,+ "taken": len(rows),+ "total": len(everything),+ }+++def refresh_files(+ case: "Case",+ columns: list[str],+ rows: list[list[str]],+ meta: dict[str, Any],+ *,+ limit: int = MAX_FROM_CASE,+) -> dict[str, Any]:+ """Bring a files worklist level with the case: the proofs rules, plus one more.++ **A status moves on by itself, once.** A file that a proof now answers goes from+ `to do` or `in progress` to `done`. That is the whole point of the list, and the only+ status a refresh ever writes; one the analyst set to anything else stays.++ Recognised by its `File` column being `locked`, which only this build writes.+ """+ roles = (meta.get("roles") or {}) if isinstance(meta, dict) else {}+ if (roles.get(FILE_COLUMN) or {}).get("kind") != "locked" or FILE_COLUMN not in columns:+ raise sheet_engine.SheetError("this sheet was not built out of the case's files")+ taken = max(0, min(int(limit), MAX_FROM_CASE))+ files = imported_files(case)[:taken]+ answered, shows, known = _file_graph(case)+ items = []+ for item in files:+ cells, cell_links = _file_cells(item, answered, shows, known)+ file_id = str(item["id"])+ items.append({"id": file_id, "match": file_id, "cells": cells, "links": cell_links})+ return _refresh(+ case,+ columns,+ rows,+ meta,+ items,+ key_column=FILE_COLUMN,+ born=_born,+ row_match=lambda built_id, row_links: built_id,+ advance=_advance,+ )+++def files_preview(case: "Case") -> dict[str, Any]:+ """What a files worklist would hold, and the one the case already has.++ ``total`` is every imported picture and video, ``answered`` how many a proof already+ answers for. ``sheet`` is the newest sheet built in this shape, so a second press+ opens the worklist the analyst is working down instead of starting a twin of it.+ """+ files = imported_files(case)+ answered, _, _ = _file_graph(case) if files else ({}, {}, {})+ sheets = sorted(+ (entity for entity in case.list_entities() if entity.get("type") == "sheet"),+ key=lambda entity: str((entity.get("provenance") or {}).get("at") or ""),+ reverse=True,+ )+ existing = next(+ (+ str(entity["id"])+ for entity in sheets+ if (sheet_engine.stored_roles(case, entity).get(FILE_COLUMN) or {}).get("kind")+ == "locked"+ ),+ None,+ )+ return {+ "total": len(files),+ "answered": sum(1 for item in files if answered.get(str(item["id"]))),+ "sheet": existing,+ }+++def refresh(+ case: "Case",+ columns: list[str],+ rows: list[list[str]],+ meta: dict[str, Any],+) -> dict[str, Any]:+ """Refresh whichever fixed shape this sheet was built as."""+ roles = (meta.get("roles") or {}) if isinstance(meta, dict) else {}+ if (roles.get(FILE_COLUMN) or {}).get("kind") == "locked":+ return refresh_files(case, columns, rows, meta)+ return refresh_proofs(case, columns, rows, meta)diff --git a/src/azimut/engine/sheets.py b/src/azimut/engine/sheets.pyindex 958e8da..7a2e551 100644--- a/src/azimut/engine/sheets.py+++ b/src/azimut/engine/sheets.py@@ -35,6 +35,7 @@ import jsonimport osimport tempfileimport uuid+from datetime import UTC, datetimefrom pathlib import Pathfrom typing import TYPE_CHECKING, Any@@ -713,6 +714,53 @@ def _paths(case: "Case", entity: dict[str, Any]) -> tuple[Path, Path]:return case.resolve_inside(rel), case.resolve_inside(layout.sheet_meta_rel(stem))+def _stored_meta(case: "Case", entity: dict[str, Any]) -> dict[str, Any]:+ try:+ _, meta_path = _paths(case, entity)+ stored = json.loads(meta_path.read_text(encoding="utf-8"))+ except (OSError, ValueError, CaseError):+ return {}+ return stored if isinstance(stored, dict) else {}+++def stored_roles(case: "Case", entity: dict[str, Any]) -> dict[str, Any]:+ """The column roles a sheet's sidecar declares, read without the table.++ What tells a sheet the case built apart from one somebody typed, and a list of+ sheets asks it of every one: reading each CSV whole to learn that would read the+ case's tables to answer a question about their sidecars.+ """+ roles = _stored_meta(case, entity).get("roles")+ return roles if isinstance(roles, dict) else {}+++#: The shapes a sheet built out of the case is recognised by: the column only that build+#: writes as `locked`. Mirrors `sheetfromcase` (`FILE_COLUMN`, `TITLE_COLUMN`), named here+#: so the list can say what each sheet is without importing the builder.+BUILT_SHAPES = (("files", "File"), ("proofs", "Title"))++#: The state words that mean a row needs nothing more, for the list's progress reading.+FINISHED_STATES = frozenset({"done", "ruled out"})+++def _progress(+ columns: list[str], rows: list[list[str]], meta: dict[str, Any]+) -> dict[str, Any] | None:+ """How far along the sheet's progress column is, the way its footer reads it: the+ finished rows of a status column, or the filled rows of any other."""+ name = meta.get("progress")+ if not isinstance(name, str) or name not in columns:+ return None+ at = columns.index(name)+ values = [str(row[at]).strip() if at < len(row) else "" for row in rows]+ role = (meta.get("roles") or {}).get(name) or {}+ if isinstance(role, dict) and role.get("kind") == "state":+ count = sum(1 for value in values if value.casefold() in FINISHED_STATES)+ return {"kind": "state", "column": name, "count": count, "total": len(values)}+ count = sum(1 for value in values if value)+ return {"kind": "fill", "column": name, "count": count, "total": len(values)}++def target(case: "Case", title: str, *, taken_by: str | None = None) -> str:"""A free case-relative path for a sheet called *title*.@@ -1541,18 +1589,36 @@ def summary(case: "Case", entity: dict[str, Any]) -> dict[str, Any]:rel = (entity.get("attrs") or {}).get("path")rows = 0headings: list[str] = []+ table: list[list[str]] = []+ modified: str | None = Noneif isinstance(rel, str) and rel:try:- raw = case.resolve_inside(rel).read_text(encoding="utf-8-sig")+ path = case.resolve_inside(rel)+ raw = path.read_text(encoding="utf-8-sig")+ modified = datetime.fromtimestamp(path.stat().st_mtime, UTC).strftime(+ "%Y-%m-%dT%H:%M:%SZ"+ )except (OSError, CaseError):raw = ""if raw.strip():reader = csv.reader(io.StringIO(raw.lstrip("")), delimiter=sniff_delimiter(raw))try:headings = [str(name) for name in next(reader, [])]- rows = sum(1 for _ in reader)+ table = [list(row) for row in reader]+ rows = len(table)except csv.Error:- headings, rows = [], 0+ headings, rows, table = [], 0, []+ stored = _stored_meta(case, entity)+ held_roles = stored.get("roles")+ roles: dict[str, Any] = held_roles if isinstance(held_roles, dict) else {}+ shape = next(+ (+ name+ for name, column in BUILT_SHAPES+ if (roles.get(column) or {}).get("kind") == "locked"+ ),+ None,+ )return {"id": entity.get("id"),"title": entity.get("label") or "Sheet",@@ -1568,4 +1634,10 @@ def summary(case: "Case", entity: dict[str, Any]) -> dict[str, Any]:# this answered null on every sheet — and the newest-first sort built on it# sorted nothing."created_at": (entity.get("provenance") or {}).get("at"),+ # When the file last changed, which is what "recent" means on the Sheet home:+ # the worklist being worked down, not the one filed last.+ "modified_at": modified,+ # Which fixed shape the case built it as, or None for a sheet somebody made.+ "shape": shape,+ "progress": _progress(headings, table, stored),}diff --git a/src/azimut/repository.py b/src/azimut/repository.pyindex 1ca3ee6..b4aad4c 100644--- a/src/azimut/repository.py+++ b/src/azimut/repository.py@@ -569,6 +569,14 @@ class CaseRepository(Protocol):def add_folder(self, name: str) -> list[str]:...+ def entities_in_folder(self, root: str) -> list[dict[str, Any]]:+ """Every entity filed under ``root`` or a folder below it."""+ ...++ def rename_folder(self, old: str, new: str) -> list[str]:+ """Move a folder subtree and refile its entities, in one transaction."""+ ...+def remove_folder(self, name: str) -> list[str]:...diff --git a/src/azimut/server.py b/src/azimut/server.pyindex 3ab1a37..6b51f1e 100644--- a/src/azimut/server.py+++ b/src/azimut/server.py@@ -308,8 +308,8 @@ def create_app() -> FastAPI:from .api import (analysis_views, analyzers, cases, compare, drafts, events, files, folders, ingest, inspect,- maplayers, media, notes, plates, proofimports, proofs, satellite, settings, sheetproofs,- sheets, templates,+ maplayers, media, notes, plates, proofimports, proofs, proposals, satellite, settings,+ sheetproofs, sheets, templates,)from .engine import sheets as sheet_engine@@ -330,6 +330,7 @@ def create_app() -> FastAPI:app.include_router(maplayers.geoconfirmed_router)app.include_router(proofs.router)app.include_router(proofimports.router)+ app.include_router(proposals.router)app.include_router(drafts.router)app.include_router(files.router)app.include_router(folders.router)diff --git a/src/azimut/sqlite_backend.py b/src/azimut/sqlite_backend.pyindex 7974da6..1361599 100644--- a/src/azimut/sqlite_backend.py+++ b/src/azimut/sqlite_backend.py@@ -53,6 +53,7 @@ from .store.filters import (_linked_at_all,lacking,)+from .store import folders as folder_storefrom .store import merges as merge_storefrom .store.migrations import _SQLITE_MIGRATIONSfrom .store.rows import (@@ -761,10 +762,7 @@ class SqliteCase:self._entity(r) for r in conn.execute("SELECT * FROM entities ORDER BY rowid")]links = [self._link(r) for r in conn.execute("SELECT * FROM links ORDER BY rowid")]- folders = [- r["path"]- for r in conn.execute("SELECT path FROM folders ORDER BY path COLLATE NOCASE")- ]+ folders = folder_store.listed(conn)conn.execute("COMMIT")except BaseException:conn.execute("ROLLBACK")@@ -1724,10 +1722,7 @@ class SqliteCase:def list_folders(self) -> list[str]:with self._connect() as conn:- return [- r["path"]- for r in conn.execute("SELECT path FROM folders ORDER BY path COLLATE NOCASE")- ]+ return folder_store.listed(conn)# -- entity image galleries ------------------------------------------@@ -2811,6 +2806,7 @@ class SqliteCase:source or None,),)+ folder_store.register(conn, _folder_of(entity["attrs"]))_sync_entity_temporal(conn, entity)self._touch(conn)return entity@@ -2823,6 +2819,9 @@ class SqliteCase:if row is None:raise CaseError(f"entity '{entity_id}' not found")entity = self._entity(row)+ # The folder an item leaves stays listed: it may have existed only+ # through the item, and moving the last one out is not deleting it.+ folder_store.register(conn, row["folder"])for key in ("type", "label"):if key in patch:entity[key] = patch[key]@@ -2851,6 +2850,7 @@ class SqliteCase:entity_id,),)+ folder_store.register(conn, _folder_of(entity["attrs"]))_sync_entity_temporal(conn, entity)self._touch(conn)return entity@@ -2921,6 +2921,7 @@ class SqliteCase:),)provenance = {"by": by, "at": now, "status": status}+ folder_store.register(conn, _folder_of(attrs))if connectors is not None:for type_, raw_targets in connectors.items():@@ -3169,27 +3170,67 @@ class SqliteCase:def op(conn: sqlite3.Connection) -> list[str]:before = conn.total_changes- segments = path.split("/")- for i in range(1, len(segments) + 1):- ancestor = "/".join(segments[:i])- conn.execute("INSERT OR IGNORE INTO folders(path) VALUES(?)", (ancestor,))+ folder_store.register(conn, path)if conn.total_changes > before:self._touch(conn)+ return folder_store.listed(conn)++ return self._write(op)++ def entities_in_folder(self, root: str) -> list[dict[str, Any]]:+ """Every entity filed under `root` or a folder below it."""+ with self._connect() as conn:return [- r["path"]- for r in conn.execute("SELECT path FROM folders ORDER BY path COLLATE NOCASE")+ self._entity(row)+ for row in conn.execute(+ "SELECT * FROM entities WHERE folder = ? OR substr(folder, 1, ?) = ?",+ (root, len(root) + 1, root + "/"),+ )]+ def rename_folder(self, old: str, new: str) -> list[str]:+ """Move `old` and everything below it to `new`, in one transaction.++ Entities are refiled in the same write, so the folder list and the items+ never disagree about where the subtree is. The files a note or a media+ keeps beside its row are the caller's (`Case.rename_folder`).+ """++ def op(conn: sqlite3.Connection) -> list[str]:+ paths = [r["path"] for r in conn.execute("SELECT path FROM folders")]+ doomed = [(p,) for p in paths if folder_store.in_subtree(p, old)]+ conn.executemany("DELETE FROM folders WHERE path = ?", doomed)+ folder_store.register(conn, new)+ for (path,) in doomed:+ folder_store.register(conn, folder_store.moved(path, old, new))+ for row in conn.execute(+ "SELECT id, type, label, attrs_json, folder FROM entities"+ " WHERE folder = ? OR substr(folder, 1, ?) = ?",+ (old, len(old) + 1, old + "/"),+ ).fetchall():+ attrs = json.loads(row["attrs_json"])+ attrs["folder"] = folder_store.moved(row["folder"], old, new)+ conn.execute(+ "UPDATE entities SET attrs_json = ?, folder = ?, search_text = ? WHERE id = ?",+ (+ json.dumps(attrs, ensure_ascii=False),+ attrs["folder"],+ _entity_search_text(row["type"], row["label"], attrs),+ row["id"],+ ),+ )+ folder_store.register(conn, attrs["folder"])+ self._touch(conn)+ return folder_store.listed(conn)+return self._write(op)def remove_folder(self, name: str) -> list[str]:- prefix = name + "/"-def op(conn: sqlite3.Connection) -> list[str]:doomed = [(p["path"],)for p in conn.execute("SELECT path FROM folders")- if p["path"] == name or p["path"].startswith(prefix)+ if folder_store.in_subtree(p["path"], name)]if doomed:conn.executemany("DELETE FROM folders WHERE path = ?", doomed)@@ -3198,8 +3239,7 @@ class SqliteCase:"SELECT id, type, label, attrs_json FROM entities").fetchall():attrs = json.loads(row["attrs_json"])- folder = attrs.get("folder")- if folder is not None and (folder == name or folder.startswith(prefix)):+ if folder_store.in_subtree(attrs.get("folder"), name):attrs.pop("folder", None)conn.execute("UPDATE entities SET attrs_json = ?, folder = NULL,"@@ -3211,10 +3251,7 @@ class SqliteCase:),)self._touch(conn)- return [- r["path"]- for r in conn.execute("SELECT path FROM folders ORDER BY path COLLATE NOCASE")- ]+ return folder_store.listed(conn)return self._write(op)@@ -3603,6 +3640,8 @@ class SqliteCase:prov.get("source"),),)+ # Put back into a folder removed since, it brings the folder back.+ folder_store.register(conn, _folder_of(attrs))_sync_entity_temporal(conn, entity)present = {r["id"]diff --git a/src/azimut/store/folders.py b/src/azimut/store/folders.pynew file mode 100644index 0000000..c40bbc1--- /dev/null+++ b/src/azimut/store/folders.py@@ -0,0 +1,45 @@+"""The case's folder list, kept whole whichever door a folder came in by.++A folder used to exist only when `POST /folders` wrote it. Filing an item into a+name typed in a save dialog set `attrs.folder` and nothing else, so the folder+showed in Files (which builds its tree from the items it loaded) and nowhere a+folder is picked (which reads this list). Every entity write now registers the+folder it carries, and the list also reads the folders items already sit in, so+a case filed before this rule shows them too.+"""++from __future__ import annotations++import sqlite3+++def ancestors(path: str) -> list[str]:+ """The path and every folder above it, outermost first."""+ segments = [segment for segment in path.split("/") if segment]+ return ["/".join(segments[: i + 1]) for i in range(len(segments))]+++def register(conn: sqlite3.Connection, folder: str | None) -> None:+ """Make sure the folder an entity is filed under, and its parents, are listed."""+ if not folder:+ return+ for path in ancestors(folder):+ conn.execute("INSERT OR IGNORE INTO folders(path) VALUES(?)", (path,))+++def listed(conn: sqlite3.Connection) -> list[str]:+ """Every folder: the registered ones, plus any an entity is filed under."""+ paths = {row["path"] for row in conn.execute("SELECT path FROM folders")}+ for row in conn.execute("SELECT DISTINCT folder FROM entities WHERE folder IS NOT NULL"):+ paths.update(ancestors(row["folder"]))+ return sorted(paths, key=str.casefold)+++def in_subtree(folder: str | None, root: str) -> bool:+ """Whether `folder` is `root` or sits somewhere under it."""+ return bool(folder) and (folder == root or str(folder).startswith(root + "/"))+++def moved(folder: str, old: str, new: str) -> str:+ """Where `folder` lands when `old` is renamed to `new`."""+ return new + folder[len(old):]diff --git a/src/azimut/workspace.py b/src/azimut/workspace.pyindex ff4c400..8341839 100644--- a/src/azimut/workspace.py+++ b/src/azimut/workspace.py@@ -954,6 +954,7 @@ class Case(CaseStore):status: EntityStatus = "confirmed",source: str | None = None,) -> dict[str, Any]:+ attrs = self.in_work_folder(type_, attrs)if type_ == "note":note_attrs = attrs or {}return self.create_note(@@ -964,7 +965,11 @@ class Case(CaseStore):status=status,source=source,)- return self._graph().add_entity(type_, label, attrs, by=by, status=status, source=source)+ entity = self._graph().add_entity(type_, label, attrs, by=by, status=status, source=source)+ from .engine import proposals++ proposals.on_filed(self, type_)+ return entitydef update_entity(self, entity_id: str, patch: dict[str, Any]) -> dict[str, Any]:with self._lock:@@ -1140,6 +1145,132 @@ class Case(CaseStore):raise CaseError(f"a folder path is at most {layout.MAX_FOLDER_PATH} characters")return path+ def rename_folder(self, old: str, new: str) -> list[str]:+ """Rename a folder, carrying its subfolders, its items and their files.++ Refused onto a name another folder already has, ignoring case: two+ folders a letter's case apart would mirror onto one directory of notes+ on Windows and macOS.+ """+ from .store import folders as folder_store++ source = self._normalize_folder(old)+ target = self._normalize_folder(new)+ with self._lock:+ existing = self.list_folders()+ if source not in existing:+ raise CaseError(f"folder '{source}' not found")+ if target == source:+ return existing+ if folder_store.in_subtree(target, source):+ raise CaseError("a folder cannot move inside itself")+ outside = {p.casefold() for p in existing if not folder_store.in_subtree(p, source)}+ if target.casefold() in outside:+ raise CaseError("another folder already has that name")+ for path in existing:+ if folder_store.in_subtree(path, source):+ self._normalize_folder(folder_store.moved(path, source, target))+ inside = self._graph().entities_in_folder(source)+ folders = self._graph().rename_folder(source, target)+ self._follow_refiled(inside)+ current = self.work_folder()+ if current and folder_store.in_subtree(current, source):+ self._store_work_folder(folder_store.moved(current, source, target))+ return folders++ def remove_folder(self, name: str) -> list[str]:+ """Drop a folder and its subfolders. Items inside are unfiled, not deleted."""+ from .store import folders as folder_store++ with self._lock:+ inside = self._graph().entities_in_folder(name)+ folders = self._graph().remove_folder(name)+ self._follow_refiled(inside)+ current = self.work_folder()+ if current and folder_store.in_subtree(current, name):+ self._store_work_folder(None)+ return folders++ def _follow_refiled(self, entities: list[dict[str, Any]]) -> None:+ """Bring the files beside refiled rows in line with where the rows now are.++ A note's markdown mirrors its folder on disk, and a media's sidecar and+ browse index carry a copy of it. The rows have already moved; without+ this a removed folder stayed in the Media Library's folder filter.+ """+ from .engine import media as media_engine++ for entity in entities:+ current = self.get_entity(entity["id"])+ if current is None:+ continue+ folder = (current.get("attrs") or {}).get("folder") or ""+ path = (current.get("attrs") or {}).get("path")+ if current["type"] == "note":+ # An empty patch: the note rename hook reads the folder off the+ # row and moves the markdown to match.+ self.update_entity(current["id"], {})+ elif current["type"] in ("media", "capture") and isinstance(path, str):+ try:+ media_engine.update_media(self, path, {"folder": folder})+ except (ValueError, CaseError, OSError):+ continue # a file gone from disk keeps only its row, already moved++ # -- the work folder ---------------------------------------------------+ #+ # The folder the analyst is working in, kept in the manifest. New files and+ # saved work land in it when nothing else was chosen, so filing needs no+ # second pass. A rename carries it and a removal clears it.++ def work_folder(self) -> str | None:+ folder = self.read().get("work_folder")+ return folder if isinstance(folder, str) and folder else None++ def set_work_folder(self, folder: str | None) -> str | None:+ with self._lock:+ path = self._normalize_folder(folder) if folder else None+ if path:+ self.add_folder(path)+ self._store_work_folder(path)+ return path++ def _store_work_folder(self, path: str | None) -> None:+ with self._lock:+ data = self.read()+ if path:+ data["work_folder"] = path+ else:+ data.pop("work_folder", None)+ self._write_json(data)++ def in_work_folder(+ self, type_: str, attrs: dict[str, Any] | None+ ) -> dict[str, Any] | None:+ """`attrs` filed into the work folder, when this type is one it takes and+ the caller named no folder. An empty folder is a choice and is kept."""+ from .engine import entities as entity_engine++ if type_ not in entity_engine.WORK_FOLDER_TYPES or "folder" in (attrs or {}):+ return attrs+ folder = self.work_folder()+ return {**(attrs or {}), "folder": folder} if folder else attrs++ # -- proposed links ------------------------------------------------------+ #+ # How far `engine/proposals` has read the case, kept in the manifest so it travels+ # with a bundle: `{"at": <newest filing moment read>, "read": [ids filed then]}`.+ # A pass reads only past it, which is what keeps a dropped proposal from coming back.++ def link_pass(self) -> dict[str, Any] | None:+ mark = self.read().get("link_pass")+ return mark if isinstance(mark, dict) and isinstance(mark.get("at"), str) else None++ def set_link_pass(self, mark: dict[str, Any]) -> None:+ with self._lock:+ data = self.read()+ data["link_pass"] = mark+ self._write_json(data)+@propertydiff --git a/tests/test_folders.py b/tests/test_folders.pynew file mode 100644index 0000000..695dafe--- /dev/null+++ b/tests/test_folders.py@@ -0,0 +1,274 @@+"""Folders: one list whichever door a folder came in by, renames that carry their+items and files, removals that leave no copy behind, and the work folder."""++import io+import json+import sqlite3+from contextlib import closing++import graph_read+from PIL import Image++from azimut.engine import bundles+from azimut.engine.media import _sidecar_path+from azimut.workspace import Case+++def _png(color=(30, 60, 90)) -> bytes:+ buf = io.BytesIO()+ Image.new("RGB", (40, 30), color).save(buf, "PNG")+ return buf.getvalue()+++def _case(client, name="Folders") -> str:+ return client.post("/api/cases", json={"name": name}).json()["id"]+++def _upload(client, cid, name="shot.png", color=(30, 60, 90)) -> dict:+ res = client.post(+ f"/api/cases/{cid}/media/upload",+ files={"file": (name, io.BytesIO(_png(color)), "image/png")},+ )+ assert res.status_code == 200, res.text+ return res.json()+++def _file(client, cid, path, folder):+ res = client.patch(f"/api/cases/{cid}/media", json={"path": path, "folder": folder})+ assert res.status_code == 200, res.text+++def _sidecar(cid, path) -> dict:+ media = Case.open(cid).resolve_inside(path)+ return json.loads(_sidecar_path(media).read_text(encoding="utf-8"))+++def _media_folder_counts(client, cid) -> dict:+ return client.get(f"/api/cases/{cid}/media/page").json()["facets"]["folder_counts"]+++# -- one list -------------------------------------------------------------------+++def test_a_folder_named_while_saving_is_listed_everywhere_a_folder_is_picked(client):+ """Typed into a save dialog's picker, a folder used to exist only on the item."""+ cid = _case(client)+ client.post(+ f"/api/cases/{cid}/entities",+ json={"type": "place", "label": "Hangar", "attrs": {"folder": "Airbase/North"}},+ )+ assert client.get(f"/api/cases/{cid}/folders").json() == ["Airbase", "Airbase/North"]+ assert client.get(f"/api/cases/{cid}").json()["folders"] == ["Airbase", "Airbase/North"]+++def test_a_folder_known_only_through_its_items_is_listed_and_outlives_them(client):+ """A case filed before the rule: the item names a folder the table never had."""+ cid = _case(client)+ entity = client.post(+ f"/api/cases/{cid}/entities",+ json={"type": "place", "label": "Pier", "attrs": {"folder": "Port"}},+ ).json()+ # `closing`: a bare `with connect()` only commits, and Windows cannot delete a+ # workspace whose case.db is still open.+ with closing(sqlite3.connect(Case.open(cid).db_path)) as conn, conn:+ conn.execute("DELETE FROM folders")+ assert client.get(f"/api/cases/{cid}/folders").json() == ["Port"]++ client.patch(f"/api/cases/{cid}/entities/{entity['id']}", json={"attrs": {"folder": ""}})+ assert client.get(f"/api/cases/{cid}/folders").json() == ["Port"]+++def test_restoring_an_item_brings_back_the_folder_removed_since(client):+ cid = _case(client)+ entity = client.post(+ f"/api/cases/{cid}/entities",+ json={"type": "place", "label": "Pier", "attrs": {"folder": "Port"}},+ ).json()+ deleted = client.delete(f"/api/cases/{cid}/entities/{entity['id']}").json()+ client.delete(f"/api/cases/{cid}/folders", params={"name": "Port"})+ assert client.get(f"/api/cases/{cid}/folders").json() == []++ client.post(f"/api/cases/{cid}/trash/{deleted['trash']}/restore", json={})+ assert client.get(f"/api/cases/{cid}/folders").json() == ["Port"]+++# -- rename ---------------------------------------------------------------------+++def test_renaming_a_folder_carries_its_subfolders_items_and_their_files(client):+ cid = _case(client)+ client.post(f"/api/cases/{cid}/folders", json={"name": "Airbase/Empty"})+ note = client.post(+ f"/api/cases/{cid}/notes", json={"title": "Log", "folder": "Airbase/North"}+ ).json()+ place = client.post(+ f"/api/cases/{cid}/entities",+ json={"type": "place", "label": "Hangar", "attrs": {"folder": "Airbase"}},+ ).json()+ path = _upload(client, cid)["item"]["path"]+ _file(client, cid, path, "Airbase/North")+ client.post(f"/api/cases/{cid}/folders", json={"name": "Other"})++ res = client.post(+ f"/api/cases/{cid}/folders/rename", json={"source": "Airbase", "target": "Isfahan"}+ )+ assert res.status_code == 200, res.text+ assert res.json() == ["Isfahan", "Isfahan/Empty", "Isfahan/North", "Other"]++ by_id = {e["id"]: e for e in graph_read.entities(cid)}+ assert by_id[place["id"]]["attrs"]["folder"] == "Isfahan"+ moved = by_id[note["id"]]["attrs"]+ assert moved["folder"] == "Isfahan/North"+ assert moved["path"] == "notes/Isfahan/North/Log.md"+ assert Case.open(cid).resolve_inside(moved["path"]).is_file()+ assert graph_read.entity(cid, path=path)["attrs"]["folder"] == "Isfahan/North"+ assert _sidecar(cid, path)["folder"] == "Isfahan/North"+ assert _media_folder_counts(client, cid) == {"Isfahan/North": 1}+ # a search finds an item by the folder's new name, not its old one+ hits = client.get(f"/api/cases/{cid}/catalog/entities", params={"q": "isfahan"}).json()+ assert {item["id"] for item in hits["items"]} >= {place["id"]}+++def test_a_rename_onto_another_folder_is_refused_ignoring_case(client):+ cid = _case(client)+ client.post(f"/api/cases/{cid}/folders", json={"name": "Port"})+ client.post(f"/api/cases/{cid}/folders", json={"name": "Airbase"})++ res = client.post(f"/api/cases/{cid}/folders/rename", json={"source": "Port", "target": "airbase"})+ assert res.status_code == 400+ assert "already" in res.json()["detail"]+ assert client.get(f"/api/cases/{cid}/folders").json() == ["Airbase", "Port"]+++def test_a_rename_that_only_changes_case_is_allowed(client):+ cid = _case(client)+ client.post(f"/api/cases/{cid}/folders", json={"name": "port/east"})+ res = client.post(f"/api/cases/{cid}/folders/rename", json={"source": "port", "target": "Port"})+ assert res.json() == ["Port", "Port/east"]+++def test_a_rename_is_refused_into_itself_too_deep_or_for_a_missing_folder(client):+ cid = _case(client)+ client.post(f"/api/cases/{cid}/folders", json={"name": "A/B/C"})++ def rename(source, target):+ return client.post(+ f"/api/cases/{cid}/folders/rename", json={"source": source, "target": target}+ )++ assert rename("A", "A/B/D").status_code == 400+ assert rename("A", "W/X/Y").status_code == 400 # A/B/C would sit five deep+ assert rename("Nope", "Yes").status_code == 400+ assert client.get(f"/api/cases/{cid}/folders").json() == ["A", "A/B", "A/B/C"]+++# -- remove ---------------------------------------------------------------------+++def test_removing_a_folder_clears_every_copy_of_it(client):+ """The media sidecar and browse index kept the folder, so the Media Library's+ folder filter still listed one Files had removed."""+ cid = _case(client)+ path = _upload(client, cid)["item"]["path"]+ _file(client, cid, path, "Port/Docks")+ note = client.post(f"/api/cases/{cid}/notes", json={"title": "Log", "folder": "Port"}).json()++ client.delete(f"/api/cases/{cid}/folders", params={"name": "Port"})++ assert client.get(f"/api/cases/{cid}/folders").json() == []+ assert "folder" not in _sidecar(cid, path)+ assert _media_folder_counts(client, cid) == {}+ attrs = next(e for e in graph_read.entities(cid) if e["id"] == note["id"])["attrs"]+ assert attrs["path"] == "notes/Log.md"+ assert Case.open(cid).resolve_inside(attrs["path"]).is_file()+++# -- the work folder ------------------------------------------------------------+++def _work(client, cid, folder):+ res = client.put(f"/api/cases/{cid}/work-folder", json={"folder": folder})+ assert res.status_code == 200, res.text+ return res.json()["work_folder"]+++def test_the_work_folder_is_kept_on_the_case_and_registered(client):+ cid = _case(client)+ assert client.get(f"/api/cases/{cid}").json().get("work_folder") is None+ assert _work(client, cid, " Airbase / North ") == "Airbase/North"+ case = client.get(f"/api/cases/{cid}").json()+ assert case["work_folder"] == "Airbase/North"+ assert case["folders"] == ["Airbase", "Airbase/North"]+ assert _work(client, cid, None) is None+ assert "work_folder" not in client.get(f"/api/cases/{cid}").json()+++def test_new_files_and_saved_work_land_in_the_work_folder(client):+ cid = _case(client)+ _work(client, cid, "Airbase")++ uploaded = _upload(client, cid)+ assert uploaded["entity"]["attrs"]["folder"] == "Airbase"+ assert _sidecar(cid, uploaded["item"]["path"])["folder"] == "Airbase"+ assert _media_folder_counts(client, cid) == {"Airbase": 1}++ place = client.post(f"/api/cases/{cid}/entities", json={"type": "place", "label": "Gate"}).json()+ assert place["attrs"]["folder"] == "Airbase"+++def test_the_work_folder_never_files_subjects_or_statements(client):+ cid = _case(client)+ _work(client, cid, "Airbase")+ person = client.post(f"/api/cases/{cid}/entities", json={"type": "person", "label": "Pilot"}).json()+ claim = client.post(f"/api/cases/{cid}/entities", json={"type": "claim", "label": "Seen"}).json()+ assert "folder" not in person["attrs"]+ assert "folder" not in claim["attrs"]+++def test_choosing_no_folder_wins_over_the_work_folder(client):+ cid = _case(client)+ _work(client, cid, "Airbase")+ place = client.post(+ f"/api/cases/{cid}/entities",+ json={"type": "place", "label": "Gate", "attrs": {"folder": ""}},+ ).json()+ assert not place["attrs"]["folder"]+ saved = client.post(+ f"/api/cases/{cid}/satellite/place",+ json={"lat": 1.0, "lon": 2.0, "zoom": 12, "title": "Pin", "folder": ""},+ ).json()+ assert not saved["attrs"]["folder"]+ note = client.post(f"/api/cases/{cid}/notes", json={"title": "Loose", "folder": ""}).json()+ assert not note["attrs"].get("folder")+++def test_a_bookmark_from_the_extension_lands_in_the_work_folder(client):+ cid = _case(client)+ _work(client, cid, "Leads")+ token = client.post("/api/settings/ingest-token").json()["ingest_token"]+ res = client.post(+ "/api/ingest/bookmark",+ data={"url": "https://example.org/post", "case_id": cid, "title": "Post"},+ headers={"X-Azimut-Token": token},+ )+ assert res.status_code == 200, res.text+ entity = next(e for e in graph_read.entities(cid) if e["id"] == res.json()["entity_id"])+ assert entity["attrs"]["folder"] == "Leads"+++def test_the_work_folder_follows_a_rename_and_leaves_with_a_removal(client):+ cid = _case(client)+ _work(client, cid, "Airbase/North")+ client.post(f"/api/cases/{cid}/folders/rename", json={"source": "Airbase", "target": "Isfahan"})+ assert client.get(f"/api/cases/{cid}").json()["work_folder"] == "Isfahan/North"+ client.delete(f"/api/cases/{cid}/folders", params={"name": "Isfahan"})+ assert "work_folder" not in client.get(f"/api/cases/{cid}").json()+++def test_a_bundle_carries_the_work_folder(client):+ cid = _case(client, "Travels")+ _work(client, cid, "Airbase")+ source = Case.open(cid)+ destination = Case.create(bundles.imported_name("Travels"))+ result = bundles.import_into(destination, bundles.export_case(source))+ assert Case.open(result["case_id"]).work_folder() == "Airbase"diff --git a/tests/test_media_api.py b/tests/test_media_api.pyindex 52648e9..8072a84 100644--- a/tests/test_media_api.py+++ b/tests/test_media_api.py@@ -1627,7 +1627,8 @@ def test_concurrent_downloads_dont_lose_entities(client, monkeypatch):t.join()assert errors == [], "\n\n".join(errors)- assert len(case.list_entities()) == n+ # Media only: the link pass may have filed the account the address names.+ assert len([e for e in case.list_entities() if e["type"] == "media"]) == nassert len(client.get(f"/api/cases/{cid}/media").json()) == ndiff --git a/tests/test_proposals.py b/tests/test_proposals.pynew file mode 100644index 0000000..fc03d2c--- /dev/null+++ b/tests/test_proposals.py@@ -0,0 +1,517 @@+"""Links the case proposes by itself: who posted a file, and which points share a site.++What each group guards:++- an address names an account only where the platform writes the handle into it, and+ never by guessing from a display name;+- a pass files the account once, reuses one the case already holds under that handle,+ and leaves alone a file somebody already said who posted;+- points within reach are joined by a spanning tree, never a mesh, and joins already+ standing are counted rather than doubled;+- a dropped proposal never comes back, because each entity is read once;+- filing a place, a file or a bookmark queues a pass, and nothing else does;+- what a proof shares with the case is read from geometry and addresses, so it answers+ before the pass has run.+"""++import io++import pytest+from PIL import Image++from azimut.engine import media as media_engine+from azimut.engine import proposals+from azimut.engine import workqueue++[email protected](autouse=True)+def no_background_worker(monkeypatch):+ """Passes run when a test runs them, so what each one filed is the test's to count."""+ monkeypatch.setattr(workqueue, "start_workers", False)+++def make_case(client, name="Proposals"):+ return client.post("/api/cases", json={"name": name}).json()["id"]+++def case_of(case_id):+ from azimut.api.cases import get_case++ return get_case(case_id)+++def add(client, case_id, entity_type, label, **attrs):+ body = {"type": entity_type, "label": label}+ if attrs:+ body["attrs"] = attrs+ response = client.post(f"/api/cases/{case_id}/entities", json=body)+ assert response.status_code == 200, response.text+ return response.json()+++def png(shade):+ buffer = io.BytesIO()+ Image.new("RGB", (8, 8), (shade, 40, 90)).save(buffer, "PNG")+ return buffer.getvalue()+++def download(case, url, shade, name="clip.png"):+ """A file brought in from a post, the way a download files one."""+ return media_engine._register_downloaded_item(+ case, url, name, png(shade), title=f"clip {shade}", source_extra={"downloader": "test"}+ )["entity"]+++def links_of_type(case, kind):+ return [link for link in case.list_links() if link["type"] == kind]+++# -- reading an address ---------------------------------------------------------+++ ("url", "label", "platform"),+ [+ ("https://x.com/OSINTWarfare/status/2097292381120876606/", "@OSINTWarfare", "X"),+ ("https://twitter.com/war_noir/status/1", "@war_noir", "X"),+ ("https://mobile.twitter.com/war_noir/status/1?s=20", "@war_noir", "X"),+ ("https://t.me/rybar/61234", "@rybar", "Telegram"),+ ("https://t.me/s/rybar/61234", "@rybar", "Telegram"),+ ("https://www.tiktok.com/@someone/video/7312", "@someone", "TikTok"),+ ("https://www.youtube.com/@somechannel/videos", "@somechannel", "YouTube"),+ ("https://www.instagram.com/someone/p/Cx12/", "@someone", "Instagram"),+ ("https://www.threads.net/@someone/post/Cx12", "@someone", "Threads"),+ ("https://bsky.app/profile/name.bsky.social/post/3kq", "@name.bsky.social", "Bluesky"),+ ("https://mastodon.social/@user/1123", "@[email protected]", "Mastodon"),+ ],+)+def test_an_address_names_the_account_where_the_platform_writes_it(url, label, platform):+ account = proposals.account_from_url(url)+ assert account is not None+ assert account["label"] == label+ assert account["platform"] == platform+ assert account["url"].startswith("https://")+++ "url",+ [+ "https://www.youtube.com/watch?v=abc", # names a video, not who posted it+ "https://www.instagram.com/p/Cx12/",+ "https://x.com/i/status/1", # the platform's own word where a handle goes+ "https://t.me/c/1234/56", # a private channel's number+ "https://bsky.app/profile/did:plc:abc/post/3kq",+ "https://example.org/article",+ "ftp://x.com/user/status/1",+ "not an address",+ "",+ None,+ ],+)+def test_an_address_that_names_no_account_gives_none(url):+ assert proposals.account_from_url(url) is None+++# -- who posted it ----------------------------------------------------------------+++def test_a_pass_files_the_account_and_joins_it_to_each_file(client):+ case_id = make_case(client)+ case = case_of(case_id)+ first = download(case, "https://x.com/BashaReport/status/1", 1)+ second = download(case, "https://x.com/bashareport/status/2", 2)++ filed = proposals.propose(case)++ assert filed == {"accounts": 1, "posted": 2, "sites": 0}+ accounts = [e for e in case.list_entities() if e["type"] == "account"]+ assert len(accounts) == 1+ account = accounts[0]+ assert account["label"] == "@BashaReport"+ assert account["attrs"]["platform"] == "X"+ assert account["attrs"]["url"] == "https://x.com/BashaReport"+ assert account["provenance"]["status"] == "suggested"+ assert account["provenance"]["by"] == proposals.BY+ posted = links_of_type(case, "posted")+ assert {(link["from"], link["to"]) for link in posted} == {+ (account["id"], first["id"]),+ (account["id"], second["id"]),+ }+ assert all(link["provenance"]["status"] == "suggested" for link in posted)+++def test_an_account_the_case_holds_is_reused_whatever_its_sigil(client):+ case_id = make_case(client)+ held = add(client, case_id, "account", "bashareport")+ case = case_of(case_id)+ item = download(case, "https://x.com/BashaReport/status/1", 1)++ filed = proposals.propose(case)++ assert filed["accounts"] == 0+ assert [e["id"] for e in case.list_entities() if e["type"] == "account"] == [held["id"]]+ [link] = links_of_type(case, "posted")+ assert (link["from"], link["to"]) == (held["id"], item["id"])+++def test_a_file_somebody_said_who_posted_is_left_alone(client):+ case_id = make_case(client)+ case = case_of(case_id)+ stated = add(client, case_id, "account", "@someone_else")+ item = download(case, "https://x.com/BashaReport/status/1", 1)+ case.add_link(stated["id"], item["id"], "posted", by="user")++ filed = proposals.propose(case)++ assert filed == {"accounts": 0, "posted": 0, "sites": 0}+ assert len(links_of_type(case, "posted")) == 1+++def test_a_bookmark_is_read_for_its_account_too(client):+ case_id = make_case(client)+ bookmark = add(client, case_id, "bookmark", "Post", url="https://t.me/rybar/61234")+ case = case_of(case_id)++ proposals.propose(case)++ [link] = links_of_type(case, "posted")+ assert link["to"] == bookmark["id"]+++# -- which points are one site -------------------------------------------------------++# About 110 m between neighbours along the meridian, and the last one far away.+NEAR = [(15.7400, 45.0300), (15.7410, 45.0300), (15.7420, 45.0300)]+FAR = (15.9000, 45.5000)+++def test_points_within_reach_are_joined_by_a_tree_not_a_mesh(client):+ case_id = make_case(client)+ ids = [add(client, case_id, "place", f"P{n}", lat=lat, lon=lon)["id"]+ for n, (lat, lon) in enumerate(NEAR)]+ far = add(client, case_id, "place", "Far", lat=FAR[0], lon=FAR[1])["id"]+ case = case_of(case_id)++ filed = proposals.propose(case)++ sites = links_of_type(case, "same-site-as")+ # Three points, one site: two edges, never three.+ assert filed["sites"] == 2 and len(sites) == 2+ joined = {link["from"] for link in sites} | {link["to"] for link in sites}+ assert joined == set(ids)+ assert far not in joined+ # Stored canonically, so the same pair can never be filed twice the other way round.+ assert all(link["from"] < link["to"] for link in sites)+++def test_a_join_already_standing_is_counted_not_doubled(client):+ case_id = make_case(client)+ first = add(client, case_id, "place", "A", lat=NEAR[0][0], lon=NEAR[0][1])["id"]+ second = add(client, case_id, "place", "B", lat=NEAR[1][0], lon=NEAR[1][1])["id"]+ case = case_of(case_id)+ case.add_link(first, second, "same-site-as", by="user")++ filed = proposals.propose(case)++ assert filed["sites"] == 0+ assert len(links_of_type(case, "same-site-as")) == 1+++def test_a_point_filed_later_joins_the_site_it_lands_on(client):+ case_id = make_case(client)+ add(client, case_id, "place", "A", lat=NEAR[0][0], lon=NEAR[0][1])+ add(client, case_id, "place", "B", lat=NEAR[1][0], lon=NEAR[1][1])+ case = case_of(case_id)+ proposals.propose(case)+ assert len(links_of_type(case, "same-site-as")) == 1++ later = add(client, case_id, "place", "C", lat=NEAR[2][0], lon=NEAR[2][1])["id"]+ filed = proposals.propose(case)++ assert filed["sites"] == 1+ [new] = [link for link in links_of_type(case, "same-site-as") if later in (link["from"], link["to"])]+ assert new["provenance"]["status"] == "suggested"+++# -- read once ------------------------------------------------------------------------+++def test_a_dropped_proposal_does_not_come_back(client):+ case_id = make_case(client)+ add(client, case_id, "place", "A", lat=NEAR[0][0], lon=NEAR[0][1])+ add(client, case_id, "place", "B", lat=NEAR[1][0], lon=NEAR[1][1])+ case = case_of(case_id)+ download(case, "https://x.com/BashaReport/status/1", 1)+ proposals.propose(case)+ for link in case.list_links():+ if proposals.unreviewed(link):+ case.remove_link(link["id"])++ filed = proposals.propose(case)++ assert filed == {"accounts": 0, "posted": 0, "sites": 0}+ assert not [link for link in case.list_links() if proposals.unreviewed(link)]+++def test_the_mark_travels_in_the_manifest_and_names_what_was_read(client):+ case_id = make_case(client)+ place = add(client, case_id, "place", "A", lat=1.0, lon=2.0)+ case = case_of(case_id)+ assert case.link_pass() is None++ proposals.propose(case)++ mark = case.read()["link_pass"]+ assert mark == case.link_pass()+ assert mark["at"] == place["provenance"]["at"]+ assert mark["read"] == [place["id"]]+++def test_a_point_filed_in_the_same_second_as_the_mark_is_still_read(client):+ case_id = make_case(client)+ first = add(client, case_id, "place", "A", lat=NEAR[0][0], lon=NEAR[0][1])+ case = case_of(case_id)+ proposals.propose(case)+ second = add(client, case_id, "place", "B", lat=NEAR[1][0], lon=NEAR[1][1])+ # Pinned to the mark's own second: the case the bare moment could not tell apart.+ case.set_link_pass({"at": second["provenance"]["at"], "read": [first["id"]]})++ filed = proposals.propose(case)++ assert filed["sites"] == 1+++# -- when a pass runs --------------------------------------------------------------------+++def queued(case):+ return [job for job in case.list_jobs(state="queued") if job["kind"] == proposals.KIND]+++def test_filing_a_place_queues_one_pass(client):+ case_id = make_case(client)+ case = case_of(case_id)+ assert queued(case) == []++ add(client, case_id, "place", "A", lat=1.0, lon=2.0)+ add(client, case_id, "place", "B", lat=1.0, lon=2.001)++ assert len(queued(case)) == 1+++def test_filing_what_a_pass_does_not_read_queues_nothing(client):+ case_id = make_case(client)+ add(client, case_id, "person", "Somebody")+ add(client, case_id, "account", "@someone")++ assert queued(case_of(case_id)) == []+++def test_the_queued_pass_files_what_it_finds(client):+ case_id = make_case(client)+ case = case_of(case_id)+ download(case, "https://x.com/BashaReport/status/1", 1)++ workqueue.drain(case)++ assert len(links_of_type(case, "posted")) == 1+++# -- the routes ---------------------------------------------------------------------------+++def test_the_list_names_both_ends_and_the_distance(client):+ case_id = make_case(client)+ add(client, case_id, "place", "Hangar", lat=NEAR[0][0], lon=NEAR[0][1])+ add(client, case_id, "place", "Runway", lat=NEAR[1][0], lon=NEAR[1][1])++ ran = client.post(f"/api/cases/{case_id}/proposals")+ assert ran.status_code == 200, ran.text+ body = ran.json()+ assert body["filed"]["sites"] == 1+ assert body["pending"]["sites"] == 1++ listed = client.get(f"/api/cases/{case_id}/proposals").json()+ [item] = listed["items"]+ assert item["type"] == "same-site-as"+ assert {item["from"]["label"], item["to"]["label"]} == {"Hangar", "Runway"}+ assert 100 <= item["metres"] <= 120+ assert listed["radius"] == proposals.SITE_RADIUS_M+ assert listed["through"]+++def test_dropping_the_last_proposal_of_an_account_drops_the_account(client):+ case_id = make_case(client)+ case = case_of(case_id)+ download(case, "https://x.com/BashaReport/status/1", 1)+ client.post(f"/api/cases/{case_id}/proposals")+ [link] = links_of_type(case, "posted")++ dropped = client.delete(f"/api/cases/{case_id}/proposals/{link['id']}")++ assert dropped.status_code == 200, dropped.text+ assert dropped.json()["dropped"] == [link["from"]]+ assert not [e for e in case.list_entities() if e["type"] == "account"]+ assert dropped.json()["pending"] == {"accounts": 0, "posted": 0, "sites": 0}+++def test_an_account_still_holding_a_file_stays_when_one_proposal_goes(client):+ case_id = make_case(client)+ case = case_of(case_id)+ download(case, "https://x.com/BashaReport/status/1", 1)+ download(case, "https://x.com/BashaReport/status/2", 2)+ client.post(f"/api/cases/{case_id}/proposals")+ first = links_of_type(case, "posted")[0]++ dropped = client.delete(f"/api/cases/{case_id}/proposals/{first['id']}").json()++ assert dropped["dropped"] == []+ assert len([e for e in case.list_entities() if e["type"] == "account"]) == 1+++def test_only_a_proposal_can_be_dropped_here(client):+ case_id = make_case(client)+ first = add(client, case_id, "place", "A", lat=1.0, lon=2.0)["id"]+ second = add(client, case_id, "place", "B", lat=1.0, lon=2.001)["id"]+ stated = client.post(+ f"/api/cases/{case_id}/links",+ json={"from_id": first, "to_id": second, "type": "same-site-as"},+ )+ assert stated.status_code == 200, stated.text++ refused = client.delete(f"/api/cases/{case_id}/proposals/{stated.json()['id']}")++ assert refused.status_code == 400+ assert client.delete(f"/api/cases/{case_id}/proposals/nope").status_code == 404+++def test_confirming_a_proposal_is_the_ordinary_link_patch(client):+ case_id = make_case(client)+ case = case_of(case_id)+ download(case, "https://x.com/BashaReport/status/1", 1)+ client.post(f"/api/cases/{case_id}/proposals")+ [link] = links_of_type(case, "posted")++ confirmed = client.patch(+ f"/api/cases/{case_id}/links/{link['id']}", json={"status": "confirmed"}+ )++ assert confirmed.status_code == 200, confirmed.text+ account = case.get_entity(link["from"])+ # A confirmed relation confirms the endpoint that was still a proposal.+ assert account["provenance"]["status"] == "confirmed"+ assert client.get(f"/api/cases/{case_id}/proposals").json()["items"] == []+++def test_the_verb_joins_two_places_and_nothing_else(client):+ case_id = make_case(client)+ first = add(client, case_id, "place", "A", lat=1.0, lon=2.0)["id"]+ far = add(client, case_id, "place", "B", lat=3.0, lon=4.0)["id"]+ person = add(client, case_id, "person", "Somebody")["id"]++ by_hand = client.post(+ f"/api/cases/{case_id}/links",+ json={"from_id": first, "to_id": far, "type": "same-site-as"},+ )+ refused = client.post(+ f"/api/cases/{case_id}/links",+ json={"from_id": first, "to_id": person, "type": "same-site-as"},+ )++ # A site wider than the radius is the analyst's to state.+ assert by_hand.status_code == 200, by_hand.text+ assert refused.status_code == 400+++# -- what a proof shares --------------------------------------------------------------------+++def a_proof(client, case_id, label, *, made_from=None, shows=None):+ proof = add(client, case_id, "proof", label)["id"]+ case = case_of(case_id)+ if made_from:+ case.add_link(proof, made_from, "derived-from", by="test")+ if shows:+ case.add_link(proof, shows, "depicts", by="test")+ return proof+++def test_kin_names_the_geolocations_on_the_same_site_and_the_points_near(client):+ case_id = make_case(client)+ here = add(client, case_id, "place", "Hangar", lat=NEAR[0][0], lon=NEAR[0][1])["id"]+ there = add(client, case_id, "place", "Runway", lat=NEAR[1][0], lon=NEAR[1][1])["id"]+ loose = add(client, case_id, "place", "Gate", lat=NEAR[2][0], lon=NEAR[2][1])["id"]+ add(client, case_id, "place", "Far", lat=FAR[0], lon=FAR[1])+ mine = a_proof(client, case_id, "Mine", shows=here)+ theirs = a_proof(client, case_id, "Theirs", shows=there)++ answer = client.get(f"/api/cases/{case_id}/entities/{mine}/kin").json()++ assert answer["sites"] == [theirs]+ assert set(answer["places"]) == {there, loose}+ assert answer["radius"] == proposals.SITE_RADIUS_M+++def test_kin_reads_the_account_through_a_frame_before_any_pass(client):+ case_id = make_case(client)+ case = case_of(case_id)+ video = download(case, "https://x.com/BashaReport/status/1", 1)+ download(case, "https://x.com/BashaReport/status/2", 2)+ download(case, "https://x.com/someone/status/3", 3)+ frame = add(client, case_id, "media", "Frame")["id"]+ case.add_link(frame, video["id"], "derived-from", by="test")+ proof = a_proof(client, case_id, "From a frame", made_from=frame)++ answer = client.get(f"/api/cases/{case_id}/entities/{proof}/kin").json()++ # No pass has run, so no account exists yet: the address alone answers.+ assert answer["accounts"] == [{"label": "@BashaReport", "id": None, "files": 1}]+ assert answer["sites"] == []+++def test_kin_of_nothing_is_a_404(client):+ case_id = make_case(client)+ assert client.get(f"/api/cases/{case_id}/entities/nope/kin").status_code == 404+++def test_an_unreviewed_proposal_holds_no_place_a_proof_lets_go(client):+ case_id = make_case(client)+ case = case_of(case_id)+ kept = add(client, case_id, "place", "Kept", lat=NEAR[0][0], lon=NEAR[0][1])["id"]+ left = add(client, case_id, "place", "Left", lat=NEAR[1][0], lon=NEAR[1][1])["id"]+ proposals.propose(case)+ [link] = links_of_type(case, "same-site-as")+ assert {link["from"], link["to"]} == {kept, left}+ assert proposals.unreviewed(link)++ case.update_link(link["id"], {"status": "confirmed"})++ assert not proposals.unreviewed(case.get_link(link["id"]))+++# -- a point named by its coordinates, as the drawing names it ----------------------+++def test_a_point_is_described_by_the_town_it_is_near():+ from azimut.engine import cities++ # In the city, its name alone; out in the desert, how far and which way.+ assert cities.describe(10.49, -66.88) == "Caracas"+ far = cities.nearest(16.982714, 45.053931)+ assert far is not None and far["bearing"] == "N" and 80 <= far["km"] <= 110+ assert cities.describe(16.982714, 45.053931).endswith(f"km N of {far['name']}")+ # Mid-ocean has no town within reach, and saying the nearest anyway would mislead.+ assert cities.describe(0.0, -30.0) is None+ assert cities.nearest(91.0, 0.0) is None+++def test_the_graph_names_a_coordinate_point_and_leaves_a_named_one(client):+ case_id = make_case(client)+ coords = add(client, case_id, "place", "10.490000, -66.880000", lat=10.49, lon=-66.88)["id"]+ named = add(client, case_id, "place", "Rooftop", lat=10.49, lon=-66.88)["id"]++ nodes = {node["id"]: node for node in client.get(f"/api/cases/{case_id}/graph").json()["nodes"]}++ assert nodes[coords]["caption"] == "Caracas"+ assert nodes[coords]["label"] == "10.490000, -66.880000"+ assert "caption" not in nodes[named]diff --git a/tests/test_release_gate.py b/tests/test_release_gate.pyindex b2668cb..8afca90 100644--- a/tests/test_release_gate.py+++ b/tests/test_release_gate.py@@ -27,6 +27,7 @@ from azimut.engine import extinstallfrom azimut.engine import links as link_enginefrom azimut.engine import media as media_enginefrom azimut.engine import thumbnails+from azimut.engine import workqueuefrom azimut.workspace import Case_PROV = {"by": "user", "at": "2026-01-01T00:00:00Z", "status": "confirmed"}@@ -79,11 +80,13 @@ def test_legacy_json_case_migrates_and_every_workflow_answers(tmp_workspace):assert case.count_jobs() == {"queued": 1}-def test_a_closed_case_folder_copy_opens_identically(tmp_workspace):+def test_a_closed_case_folder_copy_opens_identically(tmp_workspace, monkeypatch):"""Copying a closed case directory yields a complete, openable case — thedoc's "case bundle / manual copy is guaranteed when the case is closed". Therollback journal (no WAL) means no checkpoint is owed, so a plain folder copycarries the whole graph."""+ # Closed means nothing is draining it: the jobs are copied as they were queued.+ monkeypatch.setattr(workqueue, "start_workers", False)src = Case.create("Bundle")p = src.add_entity("person", "Ada", {"handle": "@ada"}, by="user")m = src.add_entity("media", "shot", {"path": "media/x.jpg"}, by="user")@@ -100,7 +103,10 @@ def test_a_closed_case_folder_copy_opens_identically(tmp_workspace):assert copied["entities"] == original["entities"]assert copied["links"] == original["links"]assert copied["folders"] == original["folders"]- assert copy.count_jobs() == {"queued": 1}+ # The thumbnail travels, and so does the link pass the media's filing queued.+ assert sorted(job["kind"] for job in copy.list_jobs(state="queued")) == [+ "propose-links", "thumbnail",+ ]# -- load: bounded loading on a large migrated case -------------------------diff --git a/tests/test_sheet_files_worklist.py b/tests/test_sheet_files_worklist.pynew file mode 100644index 0000000..abbeaf9--- /dev/null+++ b/tests/test_sheet_files_worklist.py@@ -0,0 +1,249 @@+"""A worklist built out of the files the analyst imported, and kept level with the case.++`My geolocations` lists what was done, one row per proof. This lists what was brought in+to be done, one row per imported picture or video, and what each test guards:++- only imported material gets a row: a frame cut in Inspect, a sound file or a capture is+ not a file to geolocate;+- a proof answers for its file however many steps down it was made, so a proof built on a+ frame of a video marks the video done;+- the case's columns are locked and the analyst's two are free;+- refresh adds the files imported since, and moves a status to `done` once a proof+ answers for its file, but never over a status the analyst set to something else;+- the list says what each sheet is and how far along it is, so the Sheet home can.+"""++import io++import pytest+from PIL import Image++from azimut.engine import media as media_engine+from azimut.engine import sheetfromcase as fromcase_engine+from azimut.engine import sheets as sheet_engine+from azimut.engine import workqueue++from test_sheet_bridge import add, make_case, post_sheet, read_sheet++[email protected](autouse=True)+def no_background_worker(monkeypatch):+ """The link pass would otherwise file accounts while a test counts the case."""+ monkeypatch.setattr(workqueue, "start_workers", False)+++def case_of(case_id):+ from azimut.api.cases import get_case++ return get_case(case_id)+++def png(shade):+ buffer = io.BytesIO()+ Image.new("RGB", (8, 8), (shade, 20, 60)).save(buffer, "PNG")+ return buffer.getvalue()+++def download(case, title, shade, *, name="clip.png", url="https://x.com/someone/status/1"):+ return media_engine._register_downloaded_item(+ case, url, name, png(shade), title=title, source_extra={"downloader": "test"}+ )+++def build(client, case_id, title="Files to geolocate"):+ made = client.post(+ f"/api/cases/{case_id}/sheets/from-case", json={"title": title, "shape": "files"}+ )+ assert made.status_code == 200, made.text+ return made.json()+++COLUMNS = [+ "id", "File", "Source URL", "Proof", "Place", "Coordinates", "In case", "Status", "Notes",+]+++def a_scene(client):+ """A video with a frame cut out of it and a proof built on the frame, a picture+ nobody has placed, a sound file and a frame: what an afternoon leaves in a case."""+ case_id = make_case(client)+ case = case_of(case_id)+ video = download(case, "Street video", 1, name="street.mp4",+ url="https://x.com/BashaReport/status/7")+ picture = download(case, "Market picture", 2)+ download(case, "Radio chatter", 3, name="chatter.mp3")+ frame = media_engine.import_image(+ case, Image.new("RGB", (8, 8), (9, 9, 9)), "frame.png",+ {"type": "inspect", "op": "frame", "from": video["item"]["path"]},+ )+ place = add(client, case_id, "place", "Roundabout", lat=15.74, lon=45.03)["id"]+ proof = add(client, case_id, "proof", "Roundabout proof")["id"]+ case.add_link(proof, frame["entity"]["id"], "derived-from", by="test")+ case.add_link(proof, place, "depicts", by="test")+ return case_id, video["entity"]["id"], picture["entity"]["id"], proof, place+++# -- the shape --------------------------------------------------------------------+++def test_one_row_per_imported_picture_or_video_and_nothing_else(client):+ case_id, video, picture, _, _ = a_scene(client)++ made = build(client, case_id)++ assert made["taken"] == 2 and made["total"] == 2+ sheet = read_sheet(client, case_id, made["id"])+ assert sheet["columns"] == COLUMNS+ assert sorted(row[1] for row in sheet["rows"]) == ["Market picture", "Street video"]+ assert set(sheet["meta"]["built"].values()) == {video, picture}+++def test_a_proof_on_a_frame_answers_for_the_video(client):+ case_id, video, _, proof, place = a_scene(client)++ sheet = read_sheet(client, case_id, build(client, case_id)["id"])+ row = next(row for row in sheet["rows"] if row[1] == "Street video")++ assert row[2] == "https://x.com/BashaReport/status/7"+ assert row[3:5] == ["Roundabout proof", "Roundabout"]+ assert row[5] == "15.74000, 45.03000"+ assert row[6] == "YES"+ assert row[7] == "done"+ assert sheet["meta"]["links"][row[0]] == {"File": video, "Proof": proof, "Place": place}+++def test_a_file_nobody_placed_starts_to_do(client):+ case_id, *_ = a_scene(client)++ sheet = read_sheet(client, case_id, build(client, case_id)["id"])+ row = next(row for row in sheet["rows"] if row[1] == "Market picture")++ assert row[3:5] == ["", ""]+ assert row[7] == "to do"+++def test_the_case_columns_are_locked_and_the_analysts_are_free(client):+ case_id, *_ = a_scene(client)++ roles = read_sheet(client, case_id, build(client, case_id)["id"])["meta"]["roles"]++ for column in ("File", "Source URL", "Proof", "Place"):+ assert roles[column]["kind"] == "locked"+ assert roles["Coordinates"] == {"kind": "computed", "of": "point", "from": "Place"}+ assert roles["Status"]["kind"] == "state"+ assert "Notes" not in roles+++# -- refresh ------------------------------------------------------------------------+++def test_refresh_adds_new_files_and_moves_answered_ones_to_done(client):+ case_id, _, picture, _, _ = a_scene(client)+ case = case_of(case_id)+ made = build(client, case_id)+ later = download(case, "Later picture", 4)["entity"]["id"]+ place = add(client, case_id, "place", "Market", lat=15.0, lon=45.0)["id"]+ proof = add(client, case_id, "proof", "Market proof")["id"]+ case.add_link(proof, picture, "derived-from", by="test")+ case.add_link(proof, place, "depicts", by="test")++ sheet = read_sheet(client, case_id, made["id"])+ answer = post_sheet(client, case_id, made["id"], "refresh", sheet)++ assert answer.status_code == 200, answer.text+ body = answer.json()+ assert body["added"] == 1+ fresh = read_sheet(client, case_id, made["id"])+ by_file = {row[1]: row for row in fresh["rows"]}+ assert by_file["Market picture"][3] == "Market proof"+ assert by_file["Market picture"][7] == "done"+ assert by_file["Later picture"][7] == "to do"+ assert later in fresh["meta"]["built"].values()+++def test_refresh_leaves_a_status_the_analyst_set(client):+ case_id, _, picture, _, _ = a_scene(client)+ case = case_of(case_id)+ made = build(client, case_id)+ sheet = read_sheet(client, case_id, made["id"])+ at = next(index for index, row in enumerate(sheet["rows"]) if row[1] == "Market picture")+ sheet["rows"][at][7] = "ruled out"+ sheet["rows"][at][8] = "Too dark to read"+ saved = client.put(+ f"/api/cases/{case_id}/sheets/{made['id']}",+ json={"columns": sheet["columns"], "rows": sheet["rows"], "meta": sheet["meta"],+ "stamp": sheet["stamp"]},+ )+ assert saved.status_code == 200, saved.text+ proof = add(client, case_id, "proof", "Market proof")["id"]+ case.add_link(proof, picture, "derived-from", by="test")++ sheet = read_sheet(client, case_id, made["id"])+ assert post_sheet(client, case_id, made["id"], "refresh", sheet).status_code == 200++ row = next(row for row in read_sheet(client, case_id, made["id"])["rows"]+ if row[1] == "Market picture")+ assert row[3] == "Market proof"+ assert row[7:9] == ["ruled out", "Too dark to read"]+++def test_a_proofs_sheet_still_refreshes_as_one(client):+ case_id, *_ = a_scene(client)+ made = client.post(+ f"/api/cases/{case_id}/sheets/from-case",+ json={"title": "My geolocations", "shape": "proofs"},+ ).json()+ add(client, case_id, "proof", "Second proof")++ sheet = read_sheet(client, case_id, made["id"])+ answer = post_sheet(client, case_id, made["id"], "refresh", sheet)++ assert answer.status_code == 200, answer.text+ assert answer.json()["added"] == 1+++def test_a_sheet_somebody_typed_is_not_refreshed(client):+ case_id = make_case(client)+ made = client.post(f"/api/cases/{case_id}/sheets", json={"title": "Mine"}).json()++ sheet = read_sheet(client, case_id, made["id"])+ answer = post_sheet(client, case_id, made["id"], "refresh", sheet)++ assert answer.status_code == 422+++# -- what the home reads ------------------------------------------------------------------+++def test_the_preview_counts_and_finds_the_worklist_already_built(client):+ case_id, *_ = a_scene(client)+ before = client.get(f"/api/cases/{case_id}/sheets/from-case/files").json()+ assert before == {"total": 2, "answered": 1, "sheet": None}++ made = build(client, case_id)++ after = client.get(f"/api/cases/{case_id}/sheets/from-case/files").json()+ assert after["sheet"] == made["id"]+++def test_the_list_says_what_each_sheet_is_and_how_far_along(client):+ case_id, *_ = a_scene(client)+ built = build(client, case_id)+ typed = client.post(f"/api/cases/{case_id}/sheets", json={"title": "Mine"}).json()++ listed = {sheet["id"]: sheet for sheet in client.get(f"/api/cases/{case_id}/sheets").json()["sheets"]}++ assert listed[built["id"]]["shape"] == "files"+ assert listed[built["id"]]["progress"] == {+ "kind": "state", "column": "Status", "count": 1, "total": 2,+ }+ assert listed[built["id"]]["modified_at"]+ assert listed[typed["id"]]["shape"] is None+ assert listed[typed["id"]]["progress"] is None+++def test_the_list_and_the_builder_name_the_shapes_by_the_same_column():+ assert dict(sheet_engine.BUILT_SHAPES) == {+ "files": fromcase_engine.FILE_COLUMN,+ "proofs": fromcase_engine.TITLE_COLUMN,+ }diff --git a/tests/test_sheet_from_proofs.py b/tests/test_sheet_from_proofs.pyindex ee4e2e4..0972c25 100644--- a/tests/test_sheet_from_proofs.py+++ b/tests/test_sheet_from_proofs.py@@ -53,7 +53,19 @@ def build(client, case_id, title="My geolocations"):return made.json()-COLUMNS = ["id", "Title", "Source media", "Place", "Coordinates", "In case", "Status", "Notes"]+COLUMNS = [+ "id", "Title", "Date", "Place", "POV", "Coordinates", "Source media", "Source URL",+ "Description", "In case", "Status", "Notes",+]+++def cell(sheet, row, name):+ """One cell by its column's name, so a test reads the way the sheet does."""+ return sheet["rows"][row][sheet["columns"].index(name)]+++def put_cell(sheet, row, name, value):+ sheet["rows"][row][sheet["columns"].index(name)] = value# -- the shape ----------------------------------------------------------------@@ -70,12 +82,14 @@ def test_one_row_per_proof_carrying_its_media_and_its_place(client):sheet = read_sheet(client, case_id, made["id"])assert sheet["columns"] == COLUMNS- assert sheet["rows"][0][1:4] == ["Rooftop shot", "GX010234", "Rooftop"]+ assert [cell(sheet, 0, name) for name in ("Title", "Source media", "Place")] == [+ "Rooftop shot", "GX010234", "Rooftop",+ ]# Filled off the graph rather than copied in by hand, which is what keeps it true.- assert sheet["rows"][0][4] == "47.10000, 37.50000"- assert sheet["rows"][0][5] == "YES"+ assert cell(sheet, 0, "Coordinates") == "47.10000, 37.50000"+ assert cell(sheet, 0, "In case") == "YES"# Every line is a proof that exists: `to do` on all of them would be a lie.- assert sheet["rows"][0][6] == "done"+ assert cell(sheet, 0, "Status") == "done"key = sheet["rows"][0][0]assert sheet["meta"]["links"][key] == {@@ -93,9 +107,8 @@ def test_the_three_case_columns_are_the_apps_and_the_two_work_columns_are_not(clsheet = read_sheet(client, case_id, build(client, case_id)["id"])roles = sheet["meta"]["roles"]- assert roles["Title"]["kind"] == "locked"- assert roles["Source media"]["kind"] == "locked"- assert roles["Place"]["kind"] == "locked"+ for column in ("Title", "Date", "Place", "POV", "Source media", "Source URL", "Description"):+ assert roles[column]["kind"] == "locked", columnassert roles["Coordinates"] == {"kind": "computed", "of": "point", "from": "Place"}assert roles["In case"]["of"] == "in_case"assert roles["Status"]["kind"] == "state"@@ -109,7 +122,9 @@ def test_a_proof_with_no_place_still_gets_its_row(client):a_proof(client, case_id, "Unplaced", media=media)sheet = read_sheet(client, case_id, build(client, case_id)["id"])- assert sheet["rows"][0][1:5] == ["Unplaced", "GX010234", "", ""]+ assert [cell(sheet, 0, name) for name in ("Title", "Source media", "Place", "Coordinates")] == [+ "Unplaced", "GX010234", "", "",+ ]key = sheet["rows"][0][0]assert "Place" not in sheet["meta"]["links"][key]@@ -120,7 +135,9 @@ def test_a_proof_with_no_media_still_gets_its_row(client):a_proof(client, case_id, "Sourceless", place=place)sheet = read_sheet(client, case_id, build(client, case_id)["id"])- assert sheet["rows"][0][1:5] == ["Sourceless", "", "Rooftop", "47.10000, 37.50000"]+ assert [cell(sheet, 0, name) for name in ("Title", "Source media", "Place", "Coordinates")] == [+ "Sourceless", "", "Rooftop", "47.10000, 37.50000",+ ]key = sheet["rows"][0][0]assert "Source media" not in sheet["meta"]["links"][key]@@ -135,8 +152,90 @@ def test_a_proof_on_several_medias_takes_one_and_the_same_one_twice(client):first = read_sheet(client, case_id, build(client, case_id, "One")["id"])second = read_sheet(client, case_id, build(client, case_id, "Two")["id"])- assert first["rows"][0][2] == "alpha.mp4"- assert second["rows"][0][2] == "alpha.mp4"+ assert cell(first, 0, "Source media") == "alpha.mp4"+ assert cell(second, 0, "Source media") == "alpha.mp4"+++def test_a_proof_placed_at_three_points_is_three_rows(client):+ case_id = make_case(client)+ proof = add(client, case_id, "proof", "Three strikes", when="2026-01-03~",+ notes="Three impacts filmed from one rooftop.")["id"]+ for label, lat in (("impact 2", 47.2), ("impact 1", 47.1), ("POV", 47.3)):+ place = add(client, case_id, "place", label, lat=lat, lon=37.5)["id"]+ link(case_id, proof, place, "depicts")++ made = build(client, case_id)+ sheet = read_sheet(client, case_id, made["id"])++ # The limit counts proofs, the rows are the points.+ assert made["taken"] == 1+ assert [cell(sheet, row, "Place") for row in range(3)] == ["impact 1", "impact 2", "POV"]+ assert {cell(sheet, row, "Title") for row in range(3)} == {"Three strikes"}+ assert {cell(sheet, row, "Date") for row in range(3)} == {"2026-01-03~"}+ assert {cell(sheet, row, "Description") for row in range(3)} == {+ "Three impacts filmed from one rooftop."+ }+ assert set(sheet["meta"]["built"].values()) == {proof}+++def test_pov_says_where_the_camera_stood_and_the_source_url_is_the_post(client):+ case_id = make_case(client)+ video = add(client, case_id, "media", "clip.mp4",+ source_url="https://x.com/someone/status/1")["id"]+ frame = add(client, case_id, "media", "frame")["id"]+ link(case_id, frame, video, "derived-from")+ camera = add(client, case_id, "place", "Rooftop", lat=47.1, lon=37.5)["id"]+ target = add(client, case_id, "place", "Bridge", lat=47.11, lon=37.5)["id"]+ proof = a_proof(client, case_id, "Bridge from the roof", media=frame, place=camera)+ link(case_id, proof, target, "depicts")+ # What the composer writes on the footage: recorded where the camera stood.+ link(case_id, video, camera, "located-at")+ link(case_id, video, target, "depicts")++ sheet = read_sheet(client, case_id, build(client, case_id)["id"])+ by_place = {cell(sheet, row, "Place"): row for row in range(len(sheet["rows"]))}++ assert cell(sheet, by_place["Rooftop"], "POV") == "YES"+ assert cell(sheet, by_place["Bridge"], "POV") == "NO"+ assert cell(sheet, by_place["Bridge"], "Source URL") == "https://x.com/someone/status/1"+++def test_refresh_adds_a_point_added_to_a_proof_and_keeps_the_others(client):+ case_id = make_case(client)+ first = add(client, case_id, "place", "impact 1", lat=47.1, lon=37.5)["id"]+ proof = a_proof(client, case_id, "Strikes", place=first)+ sheet = read_sheet(client, case_id, build(client, case_id)["id"])+ put_cell(sheet, 0, "Notes", "checked")+ second = add(client, case_id, "place", "impact 2", lat=47.2, lon=37.5)["id"]+ link(case_id, proof, second, "depicts")++ answer = post_sheet(client, case_id, sheet["id"], "refresh", sheet)++ assert answer.status_code == 200, answer.text+ assert answer.json()["added"] == 1+ fresh = read_sheet(client, case_id, sheet["id"])+ assert [cell(fresh, row, "Place") for row in range(2)] == ["impact 1", "impact 2"]+ assert cell(fresh, 0, "Notes") == "checked"+++def test_a_sheet_built_with_the_old_columns_keeps_them_on_refresh(client):+ case_id = make_case(client)+ place = add(client, case_id, "place", "Rooftop", lat=47.1, lon=37.5)["id"]+ a_proof(client, case_id, "Rooftop shot", place=place)+ sheet = read_sheet(client, case_id, build(client, case_id)["id"])+ # The shape before the per-point rows: eight columns, no date, no description.+ old = ["id", "Title", "Source media", "Place", "Coordinates", "In case", "Status", "Notes"]+ sheet["rows"] = [[cell(sheet, 0, name) for name in old]]+ sheet["columns"] = old+ sheet["meta"]["roles"] = {+ name: role for name, role in sheet["meta"]["roles"].items() if name in old+ }++ answer = post_sheet(client, case_id, sheet["id"], "refresh", sheet)++ assert answer.status_code == 200, answer.text+ assert answer.json()["added"] == 0+ assert answer.json()["columns"] == olddef test_rows_are_ordered_by_the_proofs_label(client):@@ -206,14 +305,14 @@ def test_refresh_leaves_the_analysts_own_columns_alone(client):case_id = make_case(client)a_proof(client, case_id, "Alpha")sheet = read_sheet(client, case_id, build(client, case_id)["id"])- sheet["rows"][0][6] = "in progress"- sheet["rows"][0][7] = "waiting on the second angle"+ put_cell(sheet, 0, "Status", "in progress")+ put_cell(sheet, 0, "Notes", "waiting on the second angle")saved = post_sheet(client, case_id, sheet["id"], "refresh", sheet)assert saved.status_code == 200, saved.textfresh = read_sheet(client, case_id, sheet["id"])- assert fresh["rows"][0][6] == "in progress"- assert fresh["rows"][0][7] == "waiting on the second angle"+ assert cell(fresh, 0, "Status") == "in progress"+ assert cell(fresh, 0, "Notes") == "waiting on the second angle"def test_refresh_restates_a_proof_renamed_since_without_filing_a_second_row(client):@@ -237,7 +336,7 @@ def test_refresh_never_removes_a_row_and_says_the_proof_is_gone(client):dropped = a_proof(client, case_id, "Bravo")sheet = read_sheet(client, case_id, build(client, case_id)["id"])sheet_id = sheet["id"]- sheet["rows"][1][7] = "worth keeping"+ put_cell(sheet, 1, "Notes", "worth keeping")assert post_sheet(client, case_id, sheet_id, "refresh", sheet).status_code == 200client.delete(f"/api/cases/{case_id}/entities/{dropped}")@@ -246,10 +345,10 @@ def test_refresh_never_removes_a_row_and_says_the_proof_is_gone(client):assert len(fresh["rows"]) == 2# The row keeps its text and the note nobody else wrote.assert fresh["rows"][1][1] == "Bravo"- assert fresh["rows"][1][7] == "worth keeping"+ assert cell(fresh, 1, "Notes") == "worth keeping"# The link is swept, as it is on every sheet — and `built` is what survives to answer.- assert fresh["rows"][0][5] == "YES"- assert fresh["rows"][1][5] == "NO"+ assert cell(fresh, 0, "In case") == "YES"+ assert cell(fresh, 1, "In case") == "NO"assert "Title" not in fresh["meta"]["links"].get(fresh["rows"][1][0], {})assert fresh["meta"]["built"][fresh["rows"][1][0]] == droppedassert fresh["meta"]["built"][fresh["rows"][0][0]] == kept@@ -265,7 +364,10 @@ def test_a_row_nobody_built_is_left_out_of_the_in_case_column(client):sheet = read_sheet(client, case_id, build(client, case_id)["id"])# A line the analyst adds for a place not yet proven: it arrives as work to do, and# the question `In case` asks does not apply to it.- sheet["rows"].append(["", "A place still to prove", "", "", "", "", "to do", ""])+ line = [""] * len(sheet["columns"])+ line[sheet["columns"].index("Title")] = "A place still to prove"+ line[sheet["columns"].index("Status")] = "to do"+ sheet["rows"].append(line)saved = client.put(f"/api/cases/{case_id}/sheets/{sheet['id']}",json={k: sheet[k] for k in ("columns", "rows", "meta", "stamp")},@@ -273,8 +375,8 @@ def test_a_row_nobody_built_is_left_out_of_the_in_case_column(client):assert saved.status_code == 200, saved.textfresh = read_sheet(client, case_id, sheet["id"])- assert fresh["rows"][1][5] == ""- assert fresh["rows"][1][6] == "to do"+ assert cell(fresh, 1, "In case") == ""+ assert cell(fresh, 1, "Status") == "to do"def test_the_coordinates_follow_a_place_that_moves(client):@@ -288,7 +390,7 @@ def test_the_coordinates_follow_a_place_that_moves(client):json={"attrs": {"lat": 48.9, "lon": 24.7}},)fresh = read_sheet(client, case_id, sheet_id)- assert fresh["rows"][0][4] == "48.90000, 24.70000"+ assert cell(fresh, 0, "Coordinates") == "48.90000, 24.70000"def test_the_build_is_bounded(client):diff --git a/tests/test_thumbnails.py b/tests/test_thumbnails.pyindex 761f3ae..4f432c4 100644--- a/tests/test_thumbnails.py+++ b/tests/test_thumbnails.py@@ -76,8 +76,9 @@ def test_drain_generates_the_queued_thumbnail_and_updates_the_sidecar(case, monkmonkeypatch.setattr(thumbnails, "_render", fake_render)item = _register_video(case)["item"]- # The generic queue drains both the thumbnail and video-enrichment jobs.- assert workqueue.drain(case) == 2+ # The generic queue drains the thumbnail, the video-enrichment job and the link pass+ # every import queues.+ assert workqueue.drain(case) == 3job = case.list_jobs(kind=thumbnails.THUMB_KIND)[0]assert job["state"] == "ready"# the sidecar now points at the freshly generated, content-addressed file@@ -91,7 +92,7 @@ def test_a_failing_render_retries_then_fails_without_looping(case, monkeypatch):_register_video(case)handled = workqueue.drain(case) # claims, fails, requeues, up to the budget- assert handled == 4 # three thumbnail attempts + one video-enrichment job+ assert handled == 5 # three thumbnail attempts + video enrichment + the link passjob = case.list_jobs(kind=thumbnails.THUMB_KIND)[0]assert job["state"] == "failed" and job["attempts"] == 3