The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.
JavaScript
Files tool, bookmarks, in-app updater; v0.1.2 (#16)
OsintMeThat81dac37c6371
diff --git a/README.md b/README.mdindex 5a836e7..3552e4f 100644--- a/README.md+++ b/README.md@@ -41,10 +41,15 @@ New in v0.1.1, a polish pass over the v1 tools:## Install & run```bash-pip install azimut-azimut # starts on http://127.0.0.1:8477 and opens a browser tab+pipx install azimut # isolated app install; plain `pip install azimut` also works+azimut # starts on http://127.0.0.1:8477 and opens a browser tab```+Update with `pipx upgrade azimut`, remove with `pipx uninstall azimut`. Your+cases and settings live under `~/Azimut` and are left untouched by both — an+upgrade never makes you redo an investigation, and an uninstall never deletes+your data (delete `~/Azimut` by hand if you also want the data gone).+Azimut runs in a normal browser tab (Firefox/Chrome); there is no separatewindow. Closing the terminal it prints its URL into stops the app.@@ -70,6 +75,11 @@ open:info** → **Run anyway**.- **Linux**: mark it executable with `chmod +x azimut-linux-x86_64`.+To update, **Settings → About → Check for updates** tells you when a newer+release is out and links the download; replace the old file with the new one.+To uninstall, delete the file. Either way `~/Azimut` stays put, so your cases+open unchanged in the new version.+Optional: install **ffmpeg** on your `PATH` for video thumbnails and videometadata (dimensions/duration). Everything else works without it.diff --git a/docs/SPEC.md b/docs/SPEC.mdindex 32bf2f0..596f32b 100644--- a/docs/SPEC.md+++ b/docs/SPEC.md@@ -1,406 +1,243 @@# Azimut — the OSINT investigator's workbench-> One case, one folder, every tool. Local-first: your media and your investigations-> never leave your machine. Built for the open-source-investigation community-> (GeoConfirmed contributors, journalists, researchers).+> One case, one folder, every tool. Local-first: your media and your+> investigations never leave your machine. Built for the open-source-investigation+> community (GeoConfirmed contributors, journalists, researchers).-Status: **draft spec v0.2** (2026-07-08) — supersedes v0.1, which framed Azimut as a-collection of geolocation tools. v0.2 reframes it around a single story. Everything-here is open to change.+Status: **spec v0.3** (2026-07-18). Reads top to bottom as: the story → what+ships today (Done) → the roadmap (v2+) → loose ideas. Shipped-tool detail lives+in code + tests; imagery in [IMAGERY_PROVIDERS.md](IMAGERY_PROVIDERS.md), UI in+[UI.md](UI.md), entities in [ONTOLOGY.md](ONTOLOGY.md).----## 1. The story (read this first)--Azimut is **not** a geolocation app, and it is **not** a Maltego competitor.+## 1. The storyAzimut is **the desk where an OSINT investigation lives**. GEOINT (geolocation-proofs) is its flagship pillar and the v1 focus, but every facet of an-investigation — media, people, places, timelines, evidence, reports — belongs in-the same case.--Today an investigation is scattered across 50 browser tabs, three Windows folders,-Obsidian, Draw.io, Google Earth, a paint program and a notepad. Azimut replaces-that mess with one promise:--> **Close Azimut. Reopen the case six months later. Everything is there:**-> the downloaded media, the annotated proofs, the entities and their links, the-> timeline, the notes, the exports — in one plain folder you can zip, git, or share.--Every design decision is tested against that sentence.--## 2. Why--Practitioners juggle a dozen half-broken web pages and manual workflows every day:-composing a geolocation proof in a paint program, comparing satellite providers in-four tabs, losing evidence to link rot, re-deriving sun positions, and — worst of-all — **losing the thread of the investigation itself** because nothing ties the-artifacts together. The tools that exist are abandoned, paid, or require uploading-sensitive media to someone's server.--Azimut bundles the daily gestures into one installable app and ties their outputs-into a case, with a simple guarantee: **everything runs on your machine.**--## 3. Principles--1. **Local-first, privacy-first.** No account, no telemetry, no upload. Network is- used only when a tool inherently needs it (map tiles, geocoding, media download)- and always to third parties directly — never through an Azimut server.-2. **The case is the product.** Tools are how you work; the case folder is what you- keep. Plain files (JSON + media), human-readable, versionable, portable.-3. **One tab = one tool, useful in 30 seconds.** Every tool works one-shot with no- case open (a scratch case is created silently and can be discarded or promoted).- Tools share data through the case, but never require ceremony.-4. **Orchestrator, not replacer.** Azimut does not rebuild specialized OSINT- services (email lookup, username search engines, …). It launches them,- collects what the analyst selects, and files the results as entities with- provenance. Build integrations, not clones.-5. **Tools emit facts, the analyst decides.** Tools may *suggest* entities and- links (OCR found "Rue Victor Hugo", EXIF found GPS) but never create them- silently. Every suggestion is confirmed or dismissed by a human. No automated- geolocation "magic button".-6. **Honest, auditable output.** Every artifact records how it was produced —- source, timestamps, parameters, imagery attribution. Proofs are auditable by- design; hints (e.g. manipulation analysis) are labeled as hints.-7. **Free and open source.** Free APIs and local computation only; no paid keys- required for any core feature. Users may *optionally* supply their own API keys- to unlock extra providers (e.g. official Google imagery), never as a requirement.+proofs) is the flagship pillar and the v1 focus, but media, people, places,+timelines, evidence and reports all belong in the same case.++> **Close Azimut. Reopen the case six months later. Everything is there:** the+> media, the annotated proofs, the entities and their links, the timeline, the+> notes, the exports — in one plain folder you can zip, git, or share.++Every design decision is tested against that sentence. Today an investigation is+scattered across 50 tabs, three folders, Obsidian, Draw.io, Google Earth and a+notepad; Azimut bundles the daily gestures into one installable app and files+their outputs into the case.++## 2. Principles++1. **Local-first, privacy-first.** No account, no telemetry, no upload. Network+ only when a tool inherently needs it (tiles, geocoding, download), always to+ third parties directly, never through an Azimut server.+2. **The case is the product.** Tools are how you work; the case folder is what+ you keep — plain JSON + media, human-readable, versionable, portable.+3. **One tab = one tool, useful in 30 seconds.** Every tool works one-shot with+ no case open (a silent scratch case, discardable or promotable).+4. **Orchestrator, not replacer.** Azimut launches specialized services and files+ what the analyst picks as entities with provenance; it never clones them.+5. **Tools emit facts, the analyst decides.** Tools suggest entities/links but+ nothing enters the case without a human click. No automated geolocation magic.+6. **Honest, auditable output.** Every artifact records how it was produced;+ hints are labeled as hints.+7. **Free and open source.** Free APIs and local computation only; user keys are+ optional extras (e.g. official Google imagery), never a requirement.8. **English UI**, international community.-## 4. The case workspace (the heart)+## 3. The case workspaceA directory per investigation (`~/Azimut/cases/<case>/` by default):```-case.json # case metadata + entities + links (schema below, from v1)-notes.md # free-form case notes (markdown)-media/ # source videos/photos/audio + download/import metadata-proofs/ # composed proofs: exported PNGs + their editable JSON specs-exports/ # post drafts, reports, shared bundles-evidence.jsonl # append-only journal: sha256, timestamp, source, action (v3)-inspect/ # saved Inspect session specs+case.json # metadata + entities + links (schema from v1)+notes.md # free-form case notes (markdown)+media/ # source + captured + extracted media, with metadata + sha256+proofs/ # composed proofs: exported PNGs + editable JSON specs+exports/ # post drafts, reports, shared bundles+evidence.jsonl # append-only journal (v3)+inspect/ # saved Inspect session specs```-Satellite captures and extracted frames are media too, so they land in-`media/` — no per-tool imagery folders.--Rules:--- **Every tool reads and writes here.** A proof spec saved once reopens for- re-editing. A downloaded video is immediately available to every other tool.-- **One-shot mode** = a scratch case in a temp/inbox location. Same code path; the- user can promote it to a named case or let it be cleaned up.-- **Plain files first.** No database server; SQLite only for local indexes/caches- that can be rebuilt from the files.--## 5. Data model — entities & links (foundation from v1)--The entity model is the backbone of the workbench, so the **schema exists from-v1** even though the rich UI (graph, map, timeline views) arrives later. This-avoids painful migrations and lets early tools file their outputs correctly.--> Full vocabulary — entity types, per-type attribute schemas, the link registry-> (incl. the `derived-from` chain), provenance/confidence/`same-as` rules — lives-> in the versioned [**ONTOLOGY.md**](ONTOLOGY.md). This section stays a summary.--**Entity types** (extensible): `person`, `organization`, `alias/username`,-`account` (X, Telegram, VK, …), `email`, `phone`, `domain`, `ip`, `vehicle`,-`place`, `event`, `media` (photo/video/audio/document), `proof`.--**Links**: typed, directed edges between entities (`owns`, `appears-in`,-`located-at`, `same-as`, `posted`, `mentions`, …) — plus free-typed labels.--**Every entity and link carries provenance**: which tool or manual action created-it, from which source, when, with what confidence (`confirmed` by analyst vs-`suggested` by a tool).--Sketch (in `case.json`):--```jsonc-{- "entities": [- { "id": "e12", "type": "media", "label": "strike_video.mp4",- "attrs": { "path": "media/strike_video.mp4", "sha256": "…", "source_url": "…" },- "provenance": { "by": "media-library", "at": "2026-07-08T14:02:11Z", "status": "confirmed" } }- ],- "links": [- { "from": "e12", "to": "e7", "type": "located-at",- "provenance": { "by": "proof-composer", "at": "…", "status": "confirmed" } }- ]-}-```+Every tool reads and writes here. Plain files first; SQLite only for rebuildable+indexes. One-shot mode = a scratch case in a temp/inbox location, same code path,+promotable to a named case or reaped when idle.++## 4. Data model — entities & links++The schema exists from **v1** so early tools file their outputs correctly and to+avoid painful migrations. Full vocabulary in [ONTOLOGY.md](ONTOLOGY.md).++- **Entity types** (extensible): person, organization, alias/username, account,+ email, phone, domain, ip, vehicle, place, event, media, proof.+- **Links**: typed directed edges (owns, appears-in, located-at, same-as, posted,+ mentions, …) plus free-typed labels.+- **Provenance on everything**: which tool/action, source, when, confidence+ (`confirmed` by analyst vs `suggested` by a tool).++Enrichment loop: a tool runs → suggests entities/links → the analyst confirms or+dismisses → the case graph grows. UI progression: v1 a sidebar list; v3 adds the+Relations, graph, map and timeline views.++---++## 5. Done — v1 Proof Studio (shipped as GitHub `v0.1.0`)++The end-to-end daily gesture, GeoConfirmed-style: media in → annotate the match →+publish the proof. Milestones M0–M7 delivered it (AGPL-3.0, frontend bundled in+the wheel, cross-platform binaries, tag-driven release CI).++| Tool | What it does |+|------|--------------|+| ✅ **Media Library** | Case media shelf. Import (drag & drop) or download by URL (yt-dlp + gallery-dl fallback + Telegram photo scraper) → clean file + metadata + sha256, each a `media` entity. Multi-attachment picker, facet bar (type/source + virtual folders), per-item notes, lightbox, provenance modal. |+| ✅ **Inspect** | Scratch workspace over any photo/video, nothing saved until Save. Sharpest-frame scan, per-frame adjustments, view-only zoom/pan/rotate, editable crop, multi-piece warp collage with auto-stitch (planar/cylindrical/spherical), ELA hint, reopenable sessions. |+| ✅ **Satellite** | Coordinate map over an XYZ tile abstraction. Save a `place` or capture a sourced crop (→ `capture`, filed in `media/`). Standard-size or marquee capture, resolution multiplier, marker styles, map rotation, move-pin, dual dates, measure, OSM overlay, reference windows, external-map links. |+| ✅ **Proof Composer** | The v1 heart. Multi-row grid or free layout of panels; resize, tweet-crop guide, magic tweet-fit. Draw boxes/ellipses/lines/arrows/curves/text, all editable after placing; per-color legend; captions; a Coordinates + Source header traced through the derivation chain; signature. Export `proof.png` + re-editable JSON spec. |+| ✅ **Post Composer** | GeoConfirmed thread from a proof: place + plus code, decimal coords, mention, source, optional media tweet, extra tweets, char counts. Save drafts, publish (opens X prefilled — never posts for you). |+| ✅ **Case sidebar** | Resizable. Case notes, suggestions inbox, nested "My work" folders + Unfiled, a details/selection editor, two-way delete sync, and the case switcher (create/open/promote/rename/delete, unique names). |++**Also shipped** (folded in from the old backlog): Sentinel-2 (user-keyed, layer+picker + pass calendar), OpenTopoMap, OSM overlay, Google Maps JS basemap for the+EEA, Esri overzoom, keyed Mapbox/Google with monthly usage counters + eco mode ++cost controls, the capture browser extension, the settings tabs+(Preferences/Imagery/About) + settings backup, scraper self-update, the launcher,+server security hardening, and the two-regime dependency setup.++**Key constraints** (carried forward):++- **Legal-only imagery**: built-in providers are Esri (default, key-less), OSM,+ OpenTopoMap and Sentinel-2 only. Keyed providers need the user's own key.+ Unofficial key-less endpoints of keyed services (`mt1.google.com`) are never+ shipped. Custom XYZ templates stay supported.+- **Two-way delete/edit sync**: an artifact and its sidebar entity are one thing;+ deleting either removes the other. One capture ⇄ one `capture` entity.+- **Frame-geolocator engine is not reused**; v1 is a fresh implementation.++----**Enrichment loop** (grows version by version): a tool runs → it emits suggested-entities/links → the analyst confirms or dismisses → the case graph grows. The-analyst never re-types information a tool already produced — but nothing enters-the case without a human click (principle 5).--UI progression: v1 shows entities as a simple sidebar list; v3 adds the Relations-view (select an entity → see its accounts, media, places, people), graph, map and-timeline views.--## 6. Tools by version--Phasing rule: each version must deliver **one complete workflow people will use-daily**, not a spread of half-tools. The case workspace and entity schema underpin-all of them from day one.--Placement rule: where a tool lives on screen is set by the **workspace model**-in [UI.md](UI.md) — new tools land as tabs/modes inside an existing workspace-(Collect / Examine / Map / Compose / Case), never as new rail entries.--### v1 — Proof Studio (media → annotated proof → publishable post)--The workflow nothing else provides end-to-end, and the GeoConfirmed daily gesture:-get media in, annotate the match, publish the proof.--| Tab | What it does |-|-----|--------------|-| ✅ **Media Library** | The case's media shelf. Import local files (drag & drop) or download by URL (X, Telegram, TikTok, YouTube, … via yt-dlp, with a **gallery-dl fallback** for image-only posts yt-dlp's video-first extractors drop — photo tweets, direct image links, Instagram, Facebook photos; a small **Telegram photo scraper** additionally fills in photos on mixed video+photo albums, which yt-dlp's Telegram extractor silently ignores) → clean local file + metadata JSON + sha256, with a **Title** field auto-filled from the extracted title. A link with several attachments (e.g. a tweet with multiple photos/a video) opens a **picker** to choose which ones to fetch, each with its own editable Title before download; a single-item link downloads straight away as before. Every media becomes a `media` entity. A **facet bar** groups the shelf on the fly — auto **type/source facets** (Images, Videos, Collages, Imports, Downloads, Other, derived from `kind` + `source`) alongside the user's **virtual folders**. Items can be assigned a **virtual folder** (stored in sidecar) and annotated with **notes**; an info modal surfaces full provenance (source URL, title, uploader, duration) + editable notes + folder; images show a **lightbox** on click. |-| ✅ **Inspect** | A scratch workspace over any photo/video — **nothing enters the case until Save**. **Selection** (video): scrub, step, scan *sharpest* frames (**every** frame scored in one streamed pass, on a **contrast-invariant** focus measure so a soft-but-punchy frame can't outrank a sharp flat one; picks are spread across distinct moments), capture into a transient tray; a gear tunes the whole clip (brightness…) for an optional enhanced-video export. **Frame**: per-frame brightness/contrast/saturation/gamma/sharpness/grayscale/invert, a **view-only zoom/pan/rotate** viewer (never saved — middle-drag turns the image around the grabbed point, marked by a "target", Google-Earth style; composes over any prior zoom/pan/rotate), and an **editable crop** — draw or nudge its 8 handles, **aspect-lock presets + numeric px entry**, **Enter/Apply** commits to a cropped preview, re-open (button or **double-click**) to edit the original — with a fold-out **Analyze** (histogram, EXIF, ELA *hint*). **Collage**: **multiple collages per session** (tab strip to add/switch/delete). Per piece: drag, **round corner handles warp**, **square side handles uniform-scale** (composes with the warp, holds up on an already-warped piece), a **rotate knob** on a stem that **follows the piece**; a small top bar carries only the **ghost** preview + **±1 stacking**, while the right panel keeps precise scale/rotate (±/↺↻) and all-the-way **Front/Back**; **Delete** removes it. **Shift-click selects several pieces**: a dashed **block frame** then moves / corner-scales / rotates them as one rigid unit about the block's centre (right panel mirrors it with precise ±/↺↻ + bulk remove), a plain click collapses back to one, and **Delete** clears the block. **Per-piece crop** is the same editable box (handles, aspect lock, numeric) over the piece's snapshot, baked before the warp — the quad is re-projected to the crop so proportions stay correct and it stays in place. Tray frames (thumbnails show each frame's current adjustments) compose on a full-bleed scratch surface into a hand-made panorama. Each collage exports as a **transparent PNG of just its pieces, auto-trimmed to their bounds** — no manual canvas size. ✅ **Auto-stitch** solves the pieces' layout from the imagery itself and drops them back as ordinary pieces — machine stitch first, hand-tune after; a **mode** picks the projection (**Planar** quads, still corner-warpable, vs **Cylindrical**/**Spherical** for a panning camera — see § Panorama). Pieces it can't place are **left where they were, never guessed at**, and a coincidental match is refused rather than invented. **Save**: tick which of {enhanced video, adjusted frames, each collage} to file — each re-derived full-res on the backend with provenance back to its source, into an optional folder; every collage shows a **true-to-export composited miniature** (the real backend warp, on a transparency checker) in the picker. Frames captured from a tuned clip inherit its look; collage pieces are **frozen snapshots** taken when added. The whole workspace can be **saved as a reopenable session** (`inspect-session` entity, spec in `inspect/`) — reload it later from the sidebar with every frame/adjustment/collage (all of them) intact; re-saving a reopened session **overwrites it in place** (even after a rename). Adjust/analysis controls come from self-describing filter/analysis registries. |-| ✅ **Satellite** | Enter/click coordinates, then **Save place** (a navigable `place` — coordinates only, no image, clickable to fly back) **or Capture** (a sourced imagery crop → `capture` image entity, **filed in `media/`** so it also lists in the Media Library and opens in Inspect). A single **split capture button** re-runs whichever mode was used last — **Capture** for a centred **standard size** (Tweet 16:9 / Square / OG card / Wide / custom), or **Select area**, which arms a **mouse marquee** to drag a rectangle (live px/dimension readout) for an optional **ratio lock** (16:9 / 4:3 / 1:1 / free) — with its arrow opening a compact **mode/size/ratio/resolution popover** (closes on outside click) and a **resolution** control (1× / 2× / provider max-zoom, sized so 2×/max always yield a sharper file on every built-in preset) that captures a deeper zoom. **Marker style** (crosshair / Google-Maps pin / none) baked in; centred-Capture **frame outline** previewed on hover. **Map rotation** — **middle-drag turns the map around the grabbed point** (sober target marker, Google-Earth style), click the bearing to **type an exact angle**, click the compass rose to reset north (capture matches the on-screen heading, bearing in provenance). **Move-pin mode** decouples the marker from center — drag it anywhere in frame (e.g. bottom of shot) and the **recorded coordinates follow the pin** for both actions. **Two dates per capture**: the **capture timestamp** and the **imagery acquisition date** (Esri best-effort, if known) — both recorded and shown. **Map workspace**: toggle an **OSM labels overlay** (roads / place names over the imagery — disabled over a street base map, where it'd only double the labels), read the imagery acquisition date under the crosshair (shown as an unobtrusive corner pill), go **true browser fullscreen** (dialogs follow the map in, and actions that would leave it — another tool, another tab — grey out), **measure** distance / area / **angle** (reported as the acute + obtuse pair), and float **reference windows** over the map (pick any case **image or video**; drag / roll-up / resize — images wheel-zoom & pan, videos get a native player) to eyeball the shot you're geolocating against the imagery — a **session-only scratch aid, never captured or saved**. The tool's side panel lists both in **collapsible** sections — **Places** (fly the map back) and **Captures** (open the full image, or **go to** their coordinates — also from the case sidebar) — each with an inline **title + note editor**; the case sidebar's info panel is the same editor for any capture/place/media. A collapsible **Open in…** list jumps to external maps we can't embed (Google/Earth, Apple, Bing, Yandex, Satellites.pro, Copernicus, Zoom Earth) at the current target. Provenance (provider, zoom, both dates, bearing, marker, center) recorded — feeds the composer. XYZ tile-provider abstraction (see note below). Editable title + notes per capture. |-| ✅ **Proof Composer** | The heart of v1. Compose panels in a **multi-row grid** (frames, photos, satellite crops, imported screenshots) — arrange side by side *and* stack rows (select a panel — canvas click or side list — and move it with **on-canvas arrows**) so the composite stays near-square instead of a wide bandeau. Each panel can be **resized** (corner-drag the selected panel, or ± in the side list; 40–250%) — its drawn elements scale with it, and shorter panels bottom-align in their row. A grid/free **mode switcher** can drop the grid for a **free layout**: **drag panels anywhere** (their elements follow), **overlap allowed** with array order as **z-order** (front/back per panel), select a panel to **corner-drag resize** it (aspect locked, no rotation); saved per proof, magic tweet-fit snaps back to the grid. A toggleable **tweet-crop guide** (16:9 / 4:5) dims whatever X would centre-crop; a **magic tweet-fit** button auto-repacks the panels into rows to land closest to the active guide's aspect (16:9 default) and resets panel sizes. Draw colored boxes/ellipses/lines/arrows, multi-point **curves** (rounded, click points + double-click to finish) and **text labels** (optional **frame and/or background box**, from the Elements tab) with the mouse — same color = same feature across panels. Every element stays **editable after placing**: boxes/ellipses/text via transformer handles (text corner-drag = font size), lines/arrows/curves via draggable per-vertex handles; selecting an element lets you change its **color and stroke/font size live**, **copy/paste/duplicate** it (Ctrl+C/V/D, cascading offset), and **drag it onto any panel** (it re-binds to whatever panel it's dropped over). Palette presets **+ custom color picker**. Legend **annotations are written per color** (one note per feature), **manually reorderable** from the Annotations tab, and auto-flow into up to 3 columns; a separate **element list** (id + kind) selects/copies/deletes/**reorders** individual shapes (order = z-order within their panel). Optional per-panel captions (**off by default**; a satellite crop auto-captions with provider · coordinates · **imagery acquisition date** — the date omitted when unknown, never the fetch date). A **Coordinates + Source** header (above the panels) auto-fills from them: coordinates from the first satellite panel (falls back to the next if it's deleted), source **traced through the derivation chain** back to the downloaded original (a collage/frame from a video resolves to that video's link) — a source is **always a link**, so a disk-uploaded file counts as none; both are editable and flag a **!** while empty. These carry into the **Post Composer** (on *To Post* export or when attaching the proof there). An **Advanced** panel exposes the trickier knobs: independent **caption / legend / footer font sizes**, an **editable footer** (blank = automatic imagery/source attribution), and a **signature** tick that stamps your Settings logo on the composite — pick a **corner**, size (share of doc width) and opacity, then **drag it on canvas** to nudge; stored as an anchor + offset, so it holds its corner as the document grows. Feature legend (color dot only, numbered in the Annotations tab for reference); export `proof.png` + re-editable JSON spec (`notes`/`legendOrder` per color, `layout`, panel `row`/`scale`/`x,y`, `coords`/`coordsText`, `source`, `caption/legend/footerSize`, `footer`, `signature`) saved in `proofs/`. |-| ✅ **Post Composer** | Build a GeoConfirmed-style thread from a proof. Tweet 1 = `Place - Plus code`, description, decimal coordinates (6 digits — the posting convention, unaffected by the coordinate-format preference), mention (defaults to `@GeoConfirmed`, configurable in Settings → Preferences), source. Tweet 2 = optional media (Video / Image, removable), with media picked from the case library. Add extra context tweets; per-tweet character count; copy-per-tweet or copy-all. **Save drafts** (in `exports/`, reopenable from the sidebar as `post` entities) and **Publish** (copies the thread and opens X compose prefilled). Copy-paste ready — Azimut never posts on your behalf. |-| ✅ **Case sidebar** | Always visible; **drag its left edge to resize** (240–640 px, never past half the window — width remembered across sessions, double-click to reset). **Case Notes** (`notes.md`). **Suggestions** — tool-suggested entities, confirm or dismiss. **My work** — every saved artifact under the analyst's own **nested folders** (`/`-separated, e.g. `Sources/Telegram`) plus an **Unfiled** inbox; file items by **dragging onto a folder** or from the **details panel** (folder field); unfiling deletes nothing, removing a folder just unfiles its subtree. **Details panel** — selection editor for any artifact: preview, title/notes, provenance (created by/at, source), My-work folder, open-in-tool / open-file / go-to-coords, and **Delete everywhere** (drops the file — danger confirm). Saved artifacts are reopened **in their tools** (Open lists in Proof/Post/Inspect — each row deletable — plus the Media & Satellite shelves); the sidebar no longer duplicates a by-tool listing. Styled confirm dialogs, not browser popups. Create/open/promote/**rename**/**delete** cases from the switcher — names must be **unique** (case-insensitive, enforced on create/rename/promote); delete wipes the **whole case folder** and everything in it, gated behind typing `DELETE` in uppercase. |--v1 notes:--- **Tile providers**: the Satellite tool is a thin UI over an XYZ tile-source- abstraction (URL template `{x}/{y}/{z}`, Web Mercator math, tile stitching with- bounded concurrency, per-tile error handling, provenance recorded per crop).- Default provider: **Esri World Imagery** (key-less, attribution required).- **Legal-only policy**: built-in presets are exclusively providers whose terms- permit this use (Esri, OSM, OpenTopoMap; later Sentinel-2). More imagery comes from official- APIs with the user's own key (e.g. Google Map Tiles API), configured in- settings. Unofficial key-less endpoints of keyed services (e.g.- `mt1.google.com`) are **never** shipped, suggested, or documented — Azimut will- be used by many people and must not carry that risk for them. Custom XYZ- templates remain supported for legitimate sources (self-hosted or licensed tile- servers).-- The composer also accepts **imported screenshots** (Google Earth, historical- imagery, …) with a source/attribution field — built-in fetch and manual import- coexist.-- **Delete/edit sync is two-way**: an artifact and its sidebar entity are one- thing. Deleting a media / satellite capture / proof / post in its tool removes- the matching entity, and deleting the entity in the sidebar removes the- underlying file(s). One satellite capture ⇄ one `capture` entity (tied by file- path): a capture is filed through the **media pipeline** (lives in `media/`,- hashed + thumbnailed, shown in the Media Library, openable in Inspect) but under- a `capture` entity — not `media` — carrying its coordinates; its media sidecar's- `source.type == "satellite"` is what tells the two apart. Captures never dedupe- (1:1 with their entity). The entity title defaults to the coordinates but is- editable, and deleting either side removes the other. A `place` is coordinates- only — no file.-- The previous frame-geolocator engine is **not** reused; v1 is a fresh,- minimal implementation. Frame extraction and image adjustments ship in the- **Inspect** tab (above); v1 also lets you bring images (screenshots/exports)- into the composer directly.--### v2 — the GEOINT suite--| Tab | What it does |-|-----|--------------|-| ✅ **Frame Extractor** | *Shipped early inside **Inspect** (§ v1)* — video scrubber, sharpest-frame suggestions, one-click capture into the case and composer. |-| **Satellite Compare** | Same coordinates across providers (Esri / Sentinel-2 with date slider / Bing / user-keyed providers), synchronized pan/zoom — imagery history and provider comparison. Builds on the v1 tile abstraction. |-| **Image Compare** | Overlay two images with opacity/swipe slider + pixel difference — frame vs satellite, or two imagery dates. |-| **Coordinates** | Convert DMS/decimal/MGRS/plus code/geohash; reverse geocode (Nominatim); quick-open links to Google Maps/Yandex/Bing/OSM. |-| **EXIF & Metadata** | Photos and videos: GPS, timestamps, device, codecs — parsed locally, with a "what was stripped" hint. Suggests `place`/`event` entities. |-| **Shadow Clock** | Mark a shadow on a photo, get possible capture times for given coordinates and date range (sun-position math, local). |-| **Reverse Search Launcher** | *Entry point in **Media Library**.* Any image/frame → reverse-search links for Google/Yandex/Bing/TinEye (opens browser tabs; no scraping). First orchestrator-pattern tool. Twist beyond plain links: an **age/origin hint** — surface the *oldest* dates the engines expose for a match so the analyst can spot recycled/old imagery and trace toward the original source. Analyst files what they pick as entities with provenance; no automated verdict. |-| **OCR** | Read signs/plates on a frame (tesseract), detect script/language. Suggests entities. |-| **Ground Imagery** | See ground-level photos around a coordinate. **Key-less open sources first** — Panoramax, Mapillary, KartaView — so it works for everyone (principle 7). **Street View**: a zero-config **easy link** (`google.com/maps?layer=c`) ships first; an optional user-keyed in-app view is gated by the settings usage counter. Picked shots file as sourced `media`/`capture` entities with provenance. |-| **Panorama** | Stitch a video time window (or a set of frames) into one wide view. ✅ **Pulled early into Inspect** (like Frame Extractor): an **auto-stitch** button on the collage that complements the existing hand-made warp collage — machine stitch first, hand-tune after. ✅ A **mode** picks the projection: **Planar** (homography chain — one flat surface, pieces stay corner-warpable, but a wide pan blows the end pieces up) vs **Cylindrical**/**Spherical** (rotation + focal per piece, bundle-adjusted and wave-corrected, so a pan stays bounded and evenly sized however far it turns; the warp bakes into the piece's recipe as a `remap` op — full-res on export — and the piece places as an upright rectangle, draggable but no longer warpable). Per-piece **exposure gain** evens the brightness steps. Still to come: **stitch a video time window** directly (auto-sample the frames), and **seam blending** — piece edges are still hard. |--### v3 — the investigation layer (entities take the front seat)--| Tab | What it does |-|-----|--------------|-| **Case Board / Relations** | The entity UI: browse, create, merge entities; typed links; **graph, timeline and map views** over the schema that has been filling up since v1. Select a person → see their accounts, media, places, connections. |-| **Map Board (MyMaps-style)** | An interactive, editable case map: drop **custom pins** (icon/color) with **notes + links**, draw shapes, group into layers; save/reopen as a case artifact; **import & export KML/KMZ/GeoJSON** to round-trip with Google Earth/MyMaps. Pins bind to `place` entities — the case's map view, exportable and handable to someone else. |-| **Evidence Locker** | Every piece of evidence: sha256, timestamps, source URL, notes; one-click Wayback Machine archiving; exportable chain-of-custody log (`evidence.jsonl`). |-| **Timeline Builder** | Timestamped events from mixed sources aligned on an interactive timeline + map. |-| **Report Builder** | Assemble proofs, maps, timeline extracts, entity summaries and notes into a publishable HTML/PDF report. |+## 6. Roadmap++Each version must deliver **one complete workflow people use daily**, not a+spread of half-tools. Ideas that firm up get promoted into these tables (§7);+new tools land as tabs/modes inside an existing workspace (see [UI.md](UI.md)),+never as new rail entries. Releases ship as GitHub `v0.x` tags.++### v2 — GEOINT suite++| Tool | What it does |+|------|--------------|+| **Satellite Compare** | Same coords across providers (Esri / Sentinel-2 date slider / Bing / keyed), synced pan/zoom. Copernicus easy link. |+| **Image Compare** | Overlay two images with opacity/swipe + pixel diff. Sat-vs-screen alignment aid (assist, never a verdict). |+| **Coordinates** | Paste anything (any format or a map URL) → normalize; convert DMS/decimal/MGRS/plus code/geohash; reverse geocode (Nominatim); quick-open map links. |+| **EXIF & Metadata** | GPS/timestamps/device/codecs parsed locally + a "what was stripped" hint; suggests place/event. |+| **Shadow Clock** | Mark a shadow → possible capture times (sun-position math, local); sun times + solar azimuth readout at coords+date. Pairs with weather/METAR history. |+| **Reverse Search Launcher** | Image/frame → reverse-search links (Google/Yandex/Bing/TinEye) + an oldest-date origin hint. First orchestrator tool. |+| **OCR** | Read signs/plates (tesseract), detect script/language. |+| **Ground Imagery** | Ground-level photos: Panoramax/Mapillary/KartaView key-less first; Street View easy link, optional keyed in-app view. |+| **Panorama** | Stitch a video window / frame set. Auto-stitch already in Inspect; still to do: sample a video window directly, seam blending. |++Also toward v2: GIF maker, curated tools-links page, command palette (Ctrl+K),+full-text case search, timezone + local-time readout at coords.++### v3 — investigation layer++| Tool | What it does |+|------|--------------|+| **Case Board / Relations** | Browse/create/merge entities; typed links; graph/timeline/map views over the schema filling since v1. |+| **Map Board (MyMaps-style)** | Editable case map: custom pins + notes/links, shapes, layers; import/export KML/KMZ/GeoJSON; pins bind to `place`. |+| **Evidence Locker** | Per-item sha256/timestamps/source/notes; Wayback archiving; exportable chain-of-custody (`evidence.jsonl`). |+| **Timeline Builder** | Timestamped events from mixed sources aligned on timeline + map. |+| **Report Builder** | Assemble proofs/maps/timeline/entities/notes into HTML/PDF. |++Also toward v3: dependency-aware delete (partly done), downloader cookies,+archive-on-download + archive time machine (Wayback CDX snapshot timeline ++diff), web-page save extension, case bundle export/import, an editable/filterable+places table (CSV/GeoJSON export), a Proof Composer free image-overlay layer,+callout/detail insets, audio analyzer (Whisper) + acoustic context hints+(bells/adhan/aircraft/language), auto-translation → English (offline), temporal+change detection over imagery dates, a pattern-of-life map (a source's+extractable locations on map + timeline), a full chronolocation solver+(shadow + sun + weather → dated window), optional X/Twitter API key in Settings+(with quota) to auto-publish Post Composer threads when enabled.### v4 — orchestration & advanced-| Tab | What it does |-|-----|--------------|-| **Search Orchestrator** | The orchestrator pattern generalized: run a username/alias/email across multiple external services, collect results, analyst selects → entities with provenance. Integrations, not clones. |-| **OSM Query (Overpass)** | Form-based feature search ("water towers within 2 km of a railway") → results on map, no Overpass QL needed. |-| **Viewshed / Line of Sight** | From a point, what terrain is visible (public DEM tiles) — validate "can this ridge be seen from here?". |-| **Map Measures** | Distance, bearing/azimuth (the app's namesake), area, camera field-of-view cone on the map. |-| **Déjà Vu** | Perceptual-hash index of known/old clips — flags recycled footage. Local index first; optional community-shared index later. |-| **Manipulation Hints** | ELA (*shipped in Inspect*), JPEG quantization, noise inconsistencies — first-pass tampering indicators, honestly labeled as *hints*. |-| **Channel Monitor** | Watch Telegram channels/accounts, auto-archive media into the case, queue items for geolocation. (Needs care: rate limits, ToS.) |--### Idea backlog (grouped by likely version)--Loose ideas, sorted by the version they'd most likely land in — a rough order,-not a commitment. Promote into a table above when a workflow firms up; delete if-it stops making sense. One line each.--**Toward v2 (GEOINT suite) — mostly grow existing v2 tools:**-- **More satellite basemaps** — user-keyed **Sentinel-2** ✅ via Copernicus/Sentinel Hub WMTS (free open data, 10 m/px native to z14 but **viewable to z18** ✅ on magnified native tiles — no extra quota; own eco threshold; **layer picker** ✅ read from the user's own instance (true/false colour, SWIR — vessels at sea) and a **date calendar** ✅ where only days with a real pass are selectable, coloured by cloud cover, resolved free-ish over WFS; the pinned day becomes the capture's imagery date — see [IMAGERY_PROVIDERS.md](IMAGERY_PROVIDERS.md)), user-keyed Bing (grows Satellite Compare). **OSM context** ✅. **OpenTopoMap** ✅ — key-less topographic base map (SRTM contour lines + hillshade) for reading relief; CC-BY-SA, caps at z17. User-keyed **Mapbox & Google** basemaps + API-keys settings tab + monthly usage counters ✅ — their legal rules, costs and quirks are in [IMAGERY_PROVIDERS.md](IMAGERY_PROVIDERS.md).-- **Keyed-provider cost controls** ✅ — per-provider enable/disable toggles; usage/limits page links in Settings; soft-block keyed maps at 90% of the free tier (clear message, explicit override); eco mode: auto-switch to free imagery when zoomed out (configurable, default z ≤ 15, **per-provider thresholds** ✅); Google hi-DPI 1024px tiles (1/16-cost captures; live map oversampled 2× — crisp mid-zoom imagery at ¼ cost); Mapbox/Esri disk tile cache (respect `cacheable`); **dead keys bench their basemap** ✅ (failed key test / auth-shaped provider rejection hides it until re-tested).-- **Google in the EEA** ✅ — Google stopped serving satellite tiles to EEA billing accounts (2025-07-08); shipped the **Maps JS widget basemap** (GoogleMutant under Leaflet, billed per map load, widget reused). It captures and **rotates like any other basemap** — same button, modes, frame and marquee — only its pixels come off the screen (one tab screenshot via the capture extension — no share prompt, fullscreen kept; attribution burned, `method:"screenshot"` + `framed` provenance) instead of stitched tiles, so the frame can't exceed the map view and there's no resolution multiplier. Without the extension the button explains and points at Settings. Details in [IMAGERY_PROVIDERS.md](IMAGERY_PROVIDERS.md).-- **Esri overzoom** ✅ — where World Imagery ends, upscale the parent tile instead of showing Esri's "not yet available" placeholder (live map + capture engine, noted in provenance).-- **Capture extension** ✅ — browser extension (MV3): screenshot the active map (Google Earth/Maps, …), parse coords/zoom from the URL, file into Azimut via a local ingest endpoint with provenance (ToS: user-initiated screenshot, attribution kept).-- **Copernicus easy link / viewer** — quick link into `browser.dataspace.copernicus.eu` (grows Satellite Compare).-- **Sat-vs-screen compare** — overlay/swipe/pixel-diff alignment aid; assist, never an auto-verdict (principle 5). Grows Image Compare.-- **Weather / METAR history** — corroborate a claimed date+coords from free archives; pairs with Shadow Clock into a chronolocation panel.-- **GIF maker** — before/after with annotations.-- **Tools links page** — a page of curated OSINT tool links.-- **Command palette** (Ctrl+K) — every tool/action one keystroke away, once the v2 tabs multiply.--**Toward v3 (investigation layer):**-- **Dependency-aware delete** ✅ — deleting a media that proofs/sessions/posts derive from: never cascade; confirm dialog lists dependents (needs real `derived-from` links written at save time); dependents keep a provenance tombstone (sha256 + source URL); Inspect opens missing sources as placeholders.-- **Downloader cookies** — optional `cookies.txt` (Settings, stored under the workspace root) passed to yt-dlp + gallery-dl for login-gated posts (sensitive/age-gated X, protected accounts), which today die on a bare `'Unavailable'` — surface the platform's real reason instead. Bytes still come from the platform, so sha256 provenance holds.-- **Archive-on-download** — optional Wayback push on URL import, archive URL into provenance (early Evidence Locker slice).-- **Extension for saving a web page** — web extension for saving a web page.-- **Case bundle export/import** — one-click **.zip** of the whole case a recipient opens in their own workbench; a zip, not a hosted link (principle 1).-- **Proof Composer free overlay layer** — **image as a first-class free element** (paste/drop, move/resize, floats or anchors to a panel) — must survive magic tweet-fit; carries the imported-screenshot source field (principle 6).-- **Callout / detail inset** — image-as-element wired to a circled feature by a color-matched arrow; optional **smart connector** that reflows when either end moves.-- **Audio analyzer** — local transcription (Whisper) + sound-pattern *hint* (gunfire/engine signatures).-- **Auto-translation → English** — local/offline (Whisper translate; Argos/OpusMT) for titles/descriptions/audio, stored beside the original. Pairs with the audio analyzer.--**Toward v4 (orchestration & advanced):**-- **AI-generated media detector** — a Manipulation *hint*, loudly labeled, never a judgment.-- **Measure-on-imagery** — draw a scale/distance line on a satellite capture to match feature sizes in-frame (focused Map Measures slice).--**After the MapLibre migration (§7):**-- **3D satellite capture** — pitch/terrain + oblique capture, pitch recorded in provenance.-- **Google Photorealistic 3D Tiles** — user-keyed 3D mesh basemap; needs a WebGL engine, and a 3D scene is not a flat capture.--**Unscheduled / undecided:**-- **Free-form montage editor** — likely unneeded once the free overlay layer lands; only with a crisp boundary vs Proof Composer + Inspect collage (risk = paint-app scope-creep).+| Tool | What it does |+|------|--------------|+| **Search Orchestrator** | Run username/alias/email across services, analyst selects → entities. Integrations, not clones. |+| **OSM Query (Overpass)** | Form-based feature search → map, no Overpass QL. |+| **Viewshed / Line of Sight** | What terrain is visible from a point (public DEM tiles). |+| **Camera Resection (GCP)** | Mark matching points photo↔map → solve camera position, viewing azimuth and rough FOV (OpenCV solvePnP); saves the match as evidence. Inverse of Viewshed. |+| **Map Measures** | Distance, bearing/azimuth, area, FOV cone; includes measure-on-imagery. |+| **Déjà Vu** | Perceptual-hash index flags recycled footage (local first; community index later). |+| **Manipulation Hints** | ELA (in Inspect), JPEG quantization, noise, AI-media detector — all labeled as hints. |+| **Channel Monitor** | Watch Telegram channels, auto-archive media, queue for geolocation (rate limits, ToS care). |++Also toward v4: skyline/horizon matching against a DEM (semi-auto geoloc from a+terrain silhouette), photogrammetric measurement from a resected photo (real+sizes via the GCP camera pose), road-topology search via Overpass (sketch a+junction → candidate spots), satellite-pass finder (public TLEs → who imaged a+place+time).++### After the MapLibre migration++Leaflet → MapLibre GL. **Phase 1** = 2D iso-functional parity (same providers and+captures, zero 3D; existing capture tests stay green, asserting the captured+pixels). **Phase 2** = pitch + terrain + oblique **3D capture**, pitch recorded in+provenance alongside bearing. Then: 3D satellite capture, Google Photorealistic+3D Tiles (user-keyed).++## 7. Loose ideas++No version yet — one line each. Promote into a roadmap table when a workflow+firms up; delete when it stops making sense.++- **Free-form montage editor** — likely unneeded once the free overlay layer+ lands; only with a crisp boundary vs Proof Composer + Inspect collage.+- **In-app OSINT assistant** — a local-model assist layer, no API key and+ no-cloud by default: a chat panel (or opt-in bridge to the user's existing+ LLM chat session) plus a local vision model that *suggests* features/entities+ in a photo (signs, vehicles, landmarks, script) for the analyst to confirm.- _(add ideas here — keep them one-liners)_-### Explicit non-goals--- No cloud, no accounts, no hosted service, no telemetry.-- No automated geolocation "magic button" — Azimut prepares materials and files- facts; the analyst reasons and decides.-- No rebuilding of specialized OSINT services (email finders, people search, …) —- orchestrate them instead (principle 4).-- No scraping features designed to evade platform blocks; downloads use- yt-dlp and gallery-dl as-is and inherit their capabilities. Passing the- user's own session cookies is auth, not evasion, and stays in scope —- third-party downloader proxies (ssstwitter & co) do not: they re-encode the- media (breaking the sha256 chain) and leak the target to a stranger.-- No auto-posting to any platform — Azimut prepares posts, the human publishes.-- No paid API dependencies, ever, for core features.--## 7. Architecture--- **Backend**: Python 3.11+, FastAPI serving on `localhost`. All processing- (ffmpeg, yt-dlp, gallery-dl, OpenCV, pytesseract, …) runs in the backend.-- **Frontend**: web UI served by the backend, opened in the default browser- (pywebview window revisited later). Tabs on the left, tool canvas on the right,- case sidebar. **Svelte** + Leaflet (maps) + Konva/canvas (annotation) — decided,- the composer's interaction state is too rich for vanilla JS.- - **Planned map migration: Leaflet → MapLibre GL.** Phase 1 = **2D- iso-functional parity** (same providers, same captures, zero 3D) proven by- the existing capture tests staying green — parity asserts the *captured- pixels*, not just that the map renders (vector-tile compositing replaces- raster XYZ stitching). Phase 2 = pitch + terrain + oblique **3D capture**,- with **pitch recorded in provenance** alongside bearing so a tilted crop- stays auditable.-- ✅ **Settings & secrets**: an in-app options page, split into tabs —- **Preferences** (coordinate format DD/DMS/MGRS, metric/imperial units,- Satellite home view, default post mention, **signature** — your own PNG logo,- ≤ 2 MB, app-wide beside `settings.json`, reaching a case only as pixels in a- proof PNG you signed), **Imagery** (one **collapsible card per provider** ✅ —- closed it's a single line: what it unlocks, a status chip, and either its- cost or its usage meter; open it holds the key field, the setup steps, the- **editable free tier** ✅ and its eco threshold. Keys save on change, stored- locally and **never** bundled into a shared case. Per-provider **monthly- counters** ✅ track a keyed quota before it's hit — an allowance belongs to- the account and providers change it silently, so it's the user's to correct),- **About** (version, workspace path, license,- links, + **Downloaders** ✅ — one-click update for yt-dlp/gallery-dl, see- below). **Settings backup** ✅ — export `settings.json` to a file and import- it on another machine, so keys and preferences survive a machine move. Core features never require a key (principle 7); key-less providers- are always the default.- **Display preferences are presentation only**: artifacts keep decimal degrees- and metres on disk, so a case reads the same for every reader. A default- title/label is minted in the user's format at creation and **never rewritten**- when the format changes later.-- **UI direction & workspaces**: the rail holds a fixed set of workspaces in- investigation-pipeline order; tools are tabs/modes inside them; visual- language is the sober "pro desk" (dense, flat, one accent), not the AI- dashboard — direction, tables and rollout in [UI.md](UI.md).-- **Tool navigation & derivation chain**: cleaner switching between tools, with- linked tools surfacing their **derivation chain** (this proof ← this frame ←- this video ← this download) as breadcrumbs — the case's connections made- visible, an early slice of the v3 Relations view.-- **Distribution**: `pip install azimut` + `azimut` command for technical users;- PyInstaller single-file executables (Windows/Linux/macOS) for everyone else.-- **Dependencies** ✅ — two regimes, on purpose:-- | | Declared in `pyproject.toml` | Pinned in `uv.lock` | Why |- |---|---|---|---|- | Everything else | range, bounded at the next untested major | exact + hashed | a tag must rebuild the same program; CI proves the locked set |- | yt-dlp, gallery-dl | `>=`, **no upper bound** | pinned for the build only | they race sites that change; old = broken |-- CI runs the lock (Linux/Windows/macOS × py3.11–3.12) *and*, weekly, the newest- versions the ranges allow — so upstream breakage lands on us, not on a user.- The binary is the strongest guarantee: it freezes everything, no install step.-- **Scraper self-update** ✅ — which is also what makes freezing yt-dlp safe.- Settings → About fetches the latest pure-Python wheel from PyPI into- `~/Azimut/runtime/<dist>/`, hash-checked, and a meta-path finder prefers it- over the bundled copy (a `sys.path` entry can't win against PyInstaller's- importer). Network only on the button; **Revert** returns to the shipped- version. Keeps a months-old binary useful instead of quietly broken.-- **Storage**: plain files as described in §4. No database server; SQLite only for- rebuildable indexes/caches.-- **Security posture** ✅ (single-user localhost workbench):- - The server binds `127.0.0.1` and a middleware refuses non-loopback `Host`- headers (DNS rebinding) and cross-origin web `Origin`s; the token-gated- ingest island stays open to browser-extension origins only.- - `settings.json` and the workspace are chmod'd owner-only; Pillow decoding- is capped at 100 MP (decompression bombs).- - Accepted risks, on purpose: `GET /settings` returns keys in cleartext (the- Settings UI edits them in place; localhost + the guard above is the wall),- the scraper updater executes hash-verified code from PyPI, and the tile- proxy / media download fetch user-supplied URLs — SSRF only matters if the- localhost assumption is ever broken.--## 8. Milestones--1. ✅ **M0 — skeleton**: repo, FastAPI app, Svelte tab shell, case workspace CRUD +- scratch-case flow, entity schema v1 (`case.json` read/write).-2. ✅ **M1 — Media Library**: import + URL download (yt-dlp), metadata + sha256,- media entities in the sidebar.-3. ✅ **M2 — Satellite**: tile-provider abstraction, Esri crop with crosshair +- provenance, settings for user-supplied providers/keys.-4. ✅ **M3 — Proof Composer**: panels, mouse annotation, colors, comments, legend,- export PNG + re-editable spec. *The demo video (media → satellite → proof) is- the community launch.*-5. ✅ **M4 — Post Composer**, v1 Proof Studio complete + deep-linkable tools.-6. ✅ **M5 — Inspect** (Frame Extractor pulled early): scratch workspace, frame- extraction/adjustments, warp collage, reopenable sessions (M5.1 rework).-7. ✅ **M6 — polish pass** across all five tools: Media facet bar, Satellite- places/captures split + move-pin, Proof Composer curves/text/live-editable- elements, Post Composer proof picker, case rename/delete + unique names.-8. ✅ **M7 — Launch v1**: pip-installable package (frontend bundled in the wheel),- AGPL-3.0 `LICENSE`, cross-platform binaries via CI (Windows/Linux/macOS),- PyPI publish, `v0.1.0` GitHub release, demo video (media → satellite → proof).-9. **M8+**: v2 GEOINT suite (auto-panorama, reverse-search — see backlog) by- community demand, then the investigation layer.--## 9. Open questions--- **Decided: AGPL-3.0-only** ✅ (root `LICENSE` in place).-- Entity schema details: attribute vocabularies per type, `same-as` merge- semantics, confidence levels — draft during M0, freeze at v1 release.-- Proof spec JSON format: design fresh at M3 (the old compose_proof format is a- reference, not a constraint).-- **Decided: OSM ships for street context, and the tile cache is shared, not- per-case** ✅ (30-day TTL under the workspace, never Google — see- [IMAGERY_PROVIDERS.md](IMAGERY_PROVIDERS.md)). Sentinel-2 via a key-less WMTS- stays open.-- **Decided: one-shot scratch cases live under the workspace `scratch/`,- promotable to a named case; empty ones idle for 14 days are reaped at server- start** ✅ (a scratch holding any entity, link or file is never touched).-- Déjà Vu community index: needs infra + moderation; out of scope until v4.-- Name/handle availability check: GitHub org/repo `azimut`, x.com handle, domain.+## 8. Explicit non-goals++- No cloud, accounts, hosted service, or telemetry.+- No automated geolocation "magic button" — Azimut files facts, the analyst decides.+- No rebuilding specialized OSINT services — orchestrate them (principle 4).+- No block-evasion scraping; yt-dlp/gallery-dl as-is. Own session cookies = auth+ (in scope); third-party downloader proxies (ssstwitter & co) are out — they+ re-encode media and leak the target.+- No auto-posting by default. An optional, opt-in X/Twitter API key (Settings,+ like the imagery keys) may enable auto-publish from Post Composer, quota+ shown alongside it; Post Composer's default opens X prefilled and never+ posts on its own. No paid API dependency, ever, for core features.++## 9. Architecture++- **Backend**: Python 3.11+, FastAPI on `localhost`; all processing (ffmpeg,+ yt-dlp, gallery-dl, OpenCV, tesseract) runs server-side.+- **Frontend**: Svelte + Leaflet (→ MapLibre) + Konva/canvas, served by the+ backend, opened in the default browser. Rail = workspaces in pipeline order,+ tools are tabs inside them (see [UI.md](UI.md)).+- **Settings & secrets** ✅: in-app tabs (Preferences / Imagery / About), keys+ stored locally and never bundled into a shared case, monthly usage counters,+ backup export/import. Display prefs are presentation only — artifacts keep+ decimal degrees + metres on disk.+- **Distribution**: `pip install azimut` + PyInstaller single-file binaries+ (Windows/Linux/macOS).+- **Dependencies** ✅: ranges in `pyproject.toml`, exact pins in `uv.lock`; yt-dlp+ + gallery-dl unbounded on purpose; scraper self-update keeps an old binary useful.+- **Storage**: plain files (§3); SQLite only for rebuildable caches.+- **Security posture** ✅ (single-user localhost): `127.0.0.1` bind + Host/Origin+ guard (DNS rebinding), 0600/0700 perms, 100 MP Pillow clamp, token-gated ingest+ island for the extension. Accepted risks recorded here: cleartext keys over+ localhost, the hash-verified scraper updater, and tile/media URL fetches (SSRF+ only matters if the localhost assumption breaks).++## 10. Open questions++- Entity attribute vocabularies, `same-as` merge semantics, confidence levels —+ freeze at v1 release.+- Déjà Vu community index: needs infra + moderation, out of scope until v4.+- Name/handle availability: GitHub org/repo `azimut`, x.com handle, domain.diff --git a/docs/UI.md b/docs/UI.mdindex 1149345..d0fc4f1 100644--- a/docs/UI.md+++ b/docs/UI.md@@ -1,7 +1,7 @@# Azimut — UI & UX referenceHow the interface is organized (UX) and styled (UI). This is the contract new-tools and future agents follow — not a roadmap. Feature phasing lives in+tools and future works follow — not a roadmap. Feature phasing lives in[SPEC.md](SPEC.md).## Layout anatomy@@ -21,7 +21,7 @@ entry**; it registers in `frontend/src/lib/workspaces.js`.| Workspace | Tools today | Future tools land here ||---|---|---|-| **Collect** | Media Library | Reverse Search, Channel Monitor, Evidence Locker |+| **Collect** | Media Library, Files | Reverse Search, Channel Monitor, Evidence Locker || **Examine** | Inspect (Selection / Frame / Collage / Analyze) | EXIF, OCR, Image Compare, Hints, Shadow Clock, audio || **Map** | Satellite | **one map, many modes**: Compare, Ground Imagery, Coordinates, Measures, Viewshed, OSM Query, Map Board || **Compose** | Proof Composer, Post Composer | Report Builder, GIF maker |@@ -51,10 +51,14 @@ double-click resets, width persists).- **My work** — every saved artifact: the analyst's nested folders (the onlyuser-owned taxonomy) plus an **Unfiled** inbox for the rest. File bydragging a row onto a folder or from the details panel (folder field).- Unfiling deletes nothing.+ Unfiling deletes nothing. The **Files** tab (Collect) opens this same tree+ as a desktop surface — small tiles, rubber-band select, drag several at once,+ right-click a file or folder for Move to Unfiled / Delete.- **Details** — selection editor for any artifact: preview, title/notes,- provenance (created by/at, source), My-work folder, open-in-tool /- open-file / go-to-coords, Delete everywhere (danger confirm).+ provenance (created by/at, source), the derivation chain (made-from /+ used-by), My-work folder, open-in-tool / open-file / go-to-coords, Delete+ everywhere (danger confirm). One shared body (`EntityDetails.svelte`) — the+ sidebar panel and the Media Library's info modal render the same editor.## Visual language (UI)@@ -82,7 +86,7 @@ sober instruments.`frontend/src/assets/logo-source.svg`; favicon derives from the same rose.No other place uses brand lettering.-## Adding a tool (checklist for future agents)+## Adding a tool (checklist for future work)1. Add the component under `frontend/src/tools/`, register it in`App.svelte`'s `TOOLS` and in its workspace's `tools` arraydiff --git a/extension/README.md b/extension/README.mdindex 596c0a2..c84431a 100644--- a/extension/README.md+++ b/extension/README.md@@ -19,8 +19,10 @@ It serves two flows:whatever Azimut learns to recognize later. Click the toolbar icon (or`Alt+Shift+A`): a popup shows what Azimut parsed from the URL (correctable),a case picker, and one button — drag the area to capture. The result- appears in the open app instantly. On any other kind of site the extension- refuses: it is for maps only.+ appears in the open app instantly.+- **Any other page** — no screenshot (capture is maps only), but the popup+ offers to file the page as a **bookmark**: a saved link with its title and+ source site, nothing downloaded. It lands in the case as a `bookmark` entity.- **Azimut's own Google (Maps JS) basemap** — the app's Capture button asksthe extension for the tab's pixels instead of prompting for a screen share.No pairing needed for this: the app files everything itself, same-origin.diff --git a/extension/manifest.json b/extension/manifest.jsonindex 84c7b84..1b5ab7e 100644--- a/extension/manifest.json+++ b/extension/manifest.json@@ -1,8 +1,8 @@{"manifest_version": 3,"name": "Azimut Capture",- "version": "0.1.0",- "description": "File the map you are looking at into Azimut: one user-initiated screenshot, coordinates parsed from the URL, provenance kept.",+ "version": "0.2.0",+ "description": "File into Azimut: screenshot the map you are looking at (coordinates from the URL), or save any other page as a bookmark.","permissions": ["activeTab", "scripting", "storage", "notifications"],"host_permissions": ["http://127.0.0.1/*", "http://localhost/*"],"background": {diff --git a/extension/popup.html b/extension/popup.htmlindex 3873f16..52f678d 100644--- a/extension/popup.html+++ b/extension/popup.html@@ -13,12 +13,23 @@<!-- one of these three states shows at a time --><section id="state-nomap" hidden>- <p>This doesn't look like a map site.</p>+ <p>Not a map site — no screenshot here.</p><p class="muted">- Azimut Capture only works on the map sites Azimut recognizes (Google- Maps/Earth, Bing, Yandex, OSM, Apple Maps, Zoom Earth, Copernicus, …) —- one screenshot per click, coordinates read from the page URL by the app.+ Screen capture is maps only (Google Maps/Earth, Bing, Yandex, OSM, Apple+ Maps, Zoom Earth, Copernicus). You can still file this page as a bookmark:+ a saved link, nothing downloaded.</p>+ <div class="row">+ <label>Case</label>+ <select id="bm-case"></select>+ </div>+ <div class="row">+ <label>Title</label>+ <input id="bm-title" type="text" placeholder="optional" />+ </div>+ <div class="actions">+ <button id="save-bookmark" class="primary">Save this page as a bookmark</button>+ </div></section><section id="state-azimut" hidden>diff --git a/extension/popup.js b/extension/popup.jsindex ba45a66..49a3ecd 100644--- a/extension/popup.js+++ b/extension/popup.js@@ -114,7 +114,32 @@ async function init() {}if (!parsed.site) {+ // Not a map: capture is out, but the page can still be filed as a bookmark+ // (a saved link, nothing downloaded). Same token, its own ingest route.$("state-nomap").hidden = false;+ if (tab.title) $("bm-title").value = tab.title;+ const paired = await loadCases($("bm-case"), stored);+ $("save-bookmark").addEventListener("click", async () => {+ if (!paired) return;+ $("save-bookmark").disabled = true;+ const body = new FormData();+ body.append("url", tab.url);+ body.append("case_id", $("bm-case").value);+ body.append("title", $("bm-title").value.trim());+ try {+ const r = await fetch(`${stored.backendUrl}/api/ingest/bookmark`, {+ method: "POST",+ headers: { "X-Azimut-Token": stored.token },+ body,+ });+ if (!r.ok) throw new Error((await r.json().catch(() => ({}))).detail || `HTTP ${r.status}`);+ status("Bookmark saved.", "ok");+ setTimeout(() => window.close(), 700);+ } catch (e) {+ $("save-bookmark").disabled = false;+ status(`Could not save: ${e.message}`, "error");+ }+ });return;}diff --git a/frontend/package.json b/frontend/package.jsonindex 0f52e2b..c1d39a8 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -1,7 +1,7 @@{"name": "azimut-frontend","private": true,- "version": "0.1.1",+ "version": "0.1.2","type": "module","scripts": {"dev": "vite",diff --git a/frontend/src/App.svelte b/frontend/src/App.svelteindex cded13d..7d27760 100644--- a/frontend/src/App.svelte+++ b/frontend/src/App.svelte@@ -9,6 +9,7 @@import CaseSidebar from './components/CaseSidebar.svelte';import Toasts from './components/Toasts.svelte';import MediaLibrary from './tools/MediaLibrary.svelte';+ import Files from './tools/Files.svelte';import Satellite from './tools/Satellite.svelte';import ProofComposer from './tools/ProofComposer.svelte';import PostComposer from './tools/PostComposer.svelte';@@ -20,6 +21,7 @@// of the working flow.const TOOLS = [{ id: 'media', label: 'Media', component: MediaLibrary },+ { id: 'files', label: 'Files', component: Files },{ id: 'inspect', label: 'Inspect', component: Inspector },{ id: 'satellite', label: 'Satellite', component: Satellite },{ id: 'proof', label: 'Proof', component: ProofComposer },@@ -70,6 +72,10 @@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();+ });</script><div class="shell">diff --git a/frontend/src/components/CaseSidebar.svelte b/frontend/src/components/CaseSidebar.svelteindex cd93cdf..c95f126 100644--- a/frontend/src/components/CaseSidebar.svelte+++ b/frontend/src/components/CaseSidebar.svelte@@ -10,10 +10,13 @@} from '../lib/state.svelte.js';import { DEFAULT_W } from '../lib/sidebar.js';import { buildTree, subtreeCount, flattenPaths, folderOf } from '../lib/folderTree.js';- import { chainOf, deletePlan, DEPENDS_ON } from '../lib/chain.js';+ import { assignFolder as fileEntity } from '../lib/filing.js';+ import { deletePlan } from '../lib/chain.js';+ import { openEntity, gotoCapture, ENTITY_TOOL } from '../lib/navigate.js';import Icon from './Icon.svelte';import Modal from './Modal.svelte';import ConfirmDialog from './ConfirmDialog.svelte';+ import EntityDetails from './EntityDetails.svelte';const ENTITY_ICONS = {person: 'user',@@ -35,11 +38,6 @@'inspect-session': 'inspect',};- // Tool to open when clicking a given entity type- const ENTITY_TOOL = {- media: 'media', proof: 'proof', place: 'satellite', post: 'post', 'inspect-session': 'inspect',- };-// Entity types backed by a file on disk — deleting them everywhere drops the file.const FILE_BACKED = new Set(['media', 'capture', 'proof', 'post', 'inspect-session']);@@ -115,71 +113,8 @@openEntity(entity);}- function openEntity(entity) {- if (entity.type === 'proof') {- // load the proof spec into the composer, then switch tab- const spec = entity.attrs?.spec ?? '';- const name = spec.replace(/^proofs\//, '').replace(/\.json$/, '');- if (name) uiState.openProof = name;- uiState.tool = 'proof';- return;- }- if (entity.type === 'post') {- // load the draft into the Post Composer, then switch tab- const draft = entity.attrs?.draft ?? '';- const name = draft.replace(/^exports\//, '').replace(/\.json$/, '');- if (name) uiState.openDraft = name;- uiState.tool = 'post';- return;- }- if (entity.type === 'inspect-session') {- // reopen the whole Inspect workspace (frames, adjustments, collage)- const spec = entity.attrs?.spec ?? '';- const name = spec.replace(/^inspect\//, '').replace(/\.json$/, '');- if (name) uiState.openInspect = name;- uiState.tool = 'inspect';- return;- }- if (entity.type === 'place') {- // fly the Satellite map to the point at the capture's own zoom/bearing- const lat = Number(entity.attrs?.lat);- const lon = Number(entity.attrs?.lon);- if (Number.isFinite(lat) && Number.isFinite(lon)) {- uiState.gotoCoords = {- lat,- lon,- zoom: Number(entity.attrs?.zoom),- bearing: Number(entity.attrs?.bearing),- };- }- uiState.tool = 'satellite';- return;- }- if (entity.type === 'media') {- // switch to the Media Library and flag the item so it's highlighted there- if (entity.attrs?.path) uiState.focusMedia = entity.attrs.path;- uiState.tool = 'media';- return;- }- const tool = ENTITY_TOOL[entity.type];- if (tool) uiState.tool = tool;- }-- // Fly the Satellite map to a capture's recorded coordinates (its marker),- // matching its own zoom/bearing — the capture stays an image, this just- // navigates. Mirrors the "Go to" button in the Satellite panel.- function gotoCapture(entity) {- const lat = Number(entity.attrs?.lat);- const lon = Number(entity.attrs?.lon);- if (!Number.isFinite(lat) || !Number.isFinite(lon)) return;- uiState.gotoCoords = {- lat,- lon,- zoom: Number(entity.attrs?.zoom),- bearing: Number(entity.attrs?.bearing),- };- uiState.tool = 'satellite';- }+ // openEntity / gotoCapture live in lib/navigate.js — the case sidebar and the+ // Details editor send an analyst to the same place.// ── My work: the analyst's own nested folder tree ('/'-separated paths) ────let newFolder = $state(''); // top-level create input@@ -250,20 +185,11 @@await createFolder(parent ? `${parent}/${name}` : name);}- // File (or unfile, with folder='') an entity into a My-work folder. Media- // keeps its sidecar in sync via its own endpoint.+ // File (or unfile, with folder='') an entity into a My-work folder, then+ // refresh. Routing lives in lib/filing.js so the desktop organizer files+ // items the same way.async function assignFolder(entity, folder) {- const val = folder || '';- if ((entity.type === 'media' || entity.type === 'capture') && entity.attrs?.path) {- await api.patch(`/api/cases/${caseState.current.id}/media`, {- path: entity.attrs.path,- folder: val,- });- } else {- await api.patch(`/api/cases/${caseState.current.id}/entities/${entity.id}`, {- attrs: { folder: val },- });- }+ await fileEntity(caseState.current.id, entity, folder);await reloadCase();}@@ -364,120 +290,16 @@};}- // ── details panel (selection info + editor, docs/UI.md §4) ────────────────+ // ── details panel (docs/UI.md §4) ─────────────────────────────────────────+ // The editor body lives in EntityDetails.svelte (shared with the Media+ // Library modal). The sidebar only tracks which entity is selected and+ // scrolls it into view.let infoEntity = $state(null);- let infoData = $state(null); // resolved media/satellite listing item (or null)- let infoLoading = $state(false);- // editable fields (title + notes), like the dedicated tool's editor- let infoTitle = $state('');- let infoNotes = $state('');- let infoFolder = $state('');- let infoSaving = $state(false);let detailsEl = $state(null);- const detailsFilePath = $derived(- infoData?.path ?? (infoEntity?.type === 'capture' ? infoEntity.attrs?.path : null)- );- // Every artifact type gets the title/notes editor (UI.md §4). Media and- // captures go through their sidecar PATCH; the rest edit the entity itself.- const EDITABLE = new Set([- 'capture',- 'place',- 'media',- 'proof',- 'post',- 'inspect-session',- 'note',- ]);- // The derivation chain around the selection: what it was made from, what was- // made from it, and the sources it has outlived (ONTOLOGY §3). An entity with- // no chain at all hides the section rather than showing an empty shell.- const chain = $derived(infoEntity ? chainOf(entities, links, infoEntity.id) : null);- const ENTITY_ICON = {- media: 'media',- capture: 'satellite',- place: 'pin',- proof: 'proof',- post: 'post',- 'inspect-session': 'inspect',- note: 'note',- };-- async function openInfo(entity) {+ function openInfo(entity) {infoEntity = entity;- infoData = null;- infoTitle = entity.label ?? '';- infoNotes = entity.attrs?.notes ?? '';- infoFolder = folderOf(entity) ?? '';requestAnimationFrame(() => detailsEl?.scrollIntoView({ behavior: 'smooth', block: 'start' }));- const endpoint =- entity.type === 'media' ? 'media' : entity.type === 'capture' ? 'satellite' : null;- if (endpoint && entity.attrs?.path) {- infoLoading = true;- try {- const list = await api.get(`/api/cases/${caseState.current.id}/${endpoint}`);- infoData = list.find((m) => m.path === entity.attrs.path) ?? null;- if (infoData) {- infoTitle = infoData.title ?? entity.label ?? '';- infoNotes = infoData.notes ?? infoNotes;- }- } catch {- infoData = null;- } finally {- infoLoading = false;- }- }- }-- async function saveInfo() {- if (!infoEntity || infoSaving) return;- infoSaving = true;- const cid = caseState.current.id;- try {- if (infoEntity.type === 'capture') {- // the satellite PATCH keeps the sidecar (title/notes) and the mirrored- // entity label in sync — the same path the Satellite tool uses- await api.patch(`/api/cases/${cid}/satellite`, {- path: infoEntity.attrs.path,- title: infoTitle,- notes: infoNotes,- });- } else if (infoEntity.type === 'media') {- // the media PATCH writes the sidecar (title/notes) and mirrors the- // title onto the entity label, so the Media tab reflects it too- await api.patch(`/api/cases/${cid}/media`, {- path: infoEntity.attrs.path,- title: infoTitle.trim(),- notes: infoNotes,- });- } else if (EDITABLE.has(infoEntity.type)) {- // place (or any bare entity): retitle + note on the entity itself- await api.patch(`/api/cases/${cid}/entities/${infoEntity.id}`, {- label: infoTitle.trim() || infoEntity.label,- attrs: { notes: infoNotes.trim() },- });- }- // filing is part of the same Save: My work folder from the picker- if ((infoFolder.trim() || '') !== (folderOf(infoEntity) ?? '')) {- await assignFolder(infoEntity, infoFolder.trim());- }- await reloadCase();- // the panel stays open on the fresh entity (reload replaced the objects)- infoEntity = (caseState.current?.entities ?? []).find((x) => x.id === infoEntity.id) ?? null;- toast('Saved', 'ok', 1600);- } catch (e) {- toast(e.message, 'danger');- } finally {- infoSaving = false;- }- }-- function fmtSize(bytes) {- if (bytes == null) return '';- if (bytes >= 1 << 30) return (bytes / (1 << 30)).toFixed(1) + ' GB';- if (bytes >= 1 << 20) return (bytes / (1 << 20)).toFixed(1) + ' MB';- if (bytes >= 1 << 10) return (bytes / (1 << 10)).toFixed(0) + ' KB';- return bytes + ' B';}// ── note entities ─────────────────────────────────────────────────────────@@ -706,198 +528,25 @@{/if}- <!-- 4 · Details (selection info + editor — docs/UI.md §4) -->+ <!-- 4 · Details (selection editor — docs/UI.md §4; shared body) -->{#if infoEntity}<div bind:this={detailsEl}>- <div class="section-head-row">- <div class="section-head static">- <Icon name="note" size={13} />- <span>Details</span>- </div>- <button class="btn btn-ghost btn-sm" title="Close details" onclick={() => (infoEntity = null)}>- <Icon name="x" size={13} />- </button>- </div>- <div class="details">- {#if infoLoading}- <div class="info-loading">Loading…</div>- {/if}-- {#if infoData?.kind === 'image' && infoData.thumbnail}- <div class="info-preview">- <img src={`/files/${caseState.current.id}/${infoData.path}`} alt={infoEntity.label} />- </div>- {:else if infoData?.kind === 'video'}- <div class="info-preview">- <!-- svelte-ignore a11y_media_has_caption -->- <video src={`/files/${caseState.current.id}/${infoData.path}`} controls preload="metadata"></video>- </div>- {:else if infoEntity.type === 'capture' && infoEntity.attrs?.path}- <div class="info-preview">- <img src={`/files/${caseState.current.id}/${infoEntity.attrs.path}`} alt={infoEntity.label} />- </div>- {/if}-- {#if EDITABLE.has(infoEntity.type)}- <label class="modal-label" for="info-title">Title</label>- <input- id="info-title"- class="input"- bind:value={infoTitle}- placeholder={infoEntity.attrs?.coords ?? 'Title'}- />- {:else}- <div class="details-title">{infoEntity.label}</div>- {/if}-- <div class="info-rows">- <div class="info-row"><span class="info-k">Type</span><span>{infoEntity.type}</span></div>- {#if infoEntity.provenance?.by}- <div class="info-row"><span class="info-k">Created by</span><span>{infoEntity.provenance.by}</span></div>- {/if}- {#if infoEntity.provenance?.at}- <div class="info-row"><span class="info-k">Created</span><span class="mono">{infoEntity.provenance.at.slice(0, 10)}</span></div>- {/if}- {#if infoEntity.type === 'media' && infoData}- <div class="info-row"><span class="info-k">Kind</span><span>{infoData.kind}</span></div>- <div class="info-row"><span class="info-k">Size</span><span>{fmtSize(infoData.size)}</span></div>- {#if infoData.sha256}- <div class="info-row"><span class="info-k">SHA-256</span><span class="mono hash" title={infoData.sha256}>{infoData.sha256}</span></div>- {/if}- {#if infoData.source?.title}- <div class="info-row"><span class="info-k">Title</span><span>{infoData.source.title}</span></div>- {/if}- {#if infoData.source?.uploader}- <div class="info-row"><span class="info-k">Uploader</span><span>{infoData.source.uploader}</span></div>- {/if}- {#if infoData.source?.upload_date}- <div class="info-row"><span class="info-k">Published</span><span class="mono">{infoData.source.upload_date}</span></div>- {/if}- {#if infoData.source?.webpage_url ?? infoData.source?.url}- <div class="info-row">- <span class="info-k">Source</span>- <a class="mono src" href={infoData.source.webpage_url ?? infoData.source.url} target="_blank" rel="noreferrer">- {infoData.source.webpage_url ?? infoData.source.url}- </a>- </div>- {/if}- {:else if infoEntity.type === 'capture'}- {#if infoData?.provider_label}- <div class="info-row"><span class="info-k">Provider</span><span>{infoData.provider_label}</span></div>- {/if}- {#if infoEntity.attrs?.zoom != null}- <div class="info-row"><span class="info-k">Zoom</span><span>z{infoEntity.attrs.zoom}</span></div>- {/if}- {#if infoData?.fetched_at}- <div class="info-row"><span class="info-k">Captured</span><span class="mono">{infoData.fetched_at.slice(0, 10)}</span></div>- {/if}- {#if infoData?.imagery_date}- <div class="info-row"><span class="info-k">Imagery</span><span class="mono">{infoData.imagery_date}</span></div>- {/if}- {:else if infoEntity.attrs?.content}- <div class="info-note-body">{infoEntity.attrs.content}</div>- {/if}- {#if infoEntity.attrs?.coords}- <div class="info-row"><span class="info-k">Coords</span><span class="mono">{infoEntity.attrs.coords}</span></div>- {/if}- </div>-- <!-- derivation chain: click a row to walk to that entity's details -->- {#if chain && !chain.empty}- <div class="chain">- {#if chain.sources.length || chain.lost.length}- <div class="chain-h">Made from</div>- {#each chain.sources as { entity, type } (entity.id)}- <button class="chain-row" onclick={() => openInfo(entity)}>- <Icon name={ENTITY_ICON[entity.type] ?? 'file'} size={12} />- <span class="chain-label">{entity.label}</span>- {#if type === DEPENDS_ON}- <span class="chain-tag" title="This is a view over that item — it cannot outlive it">needs</span>- {/if}- </button>- {/each}- {#each chain.lost as lost (lost.path)}- <div class="chain-row gone" title={`Deleted on ${lost.at?.slice(0, 10) ?? 'an unknown date'}${lost.sha256 ? ` · sha256 ${lost.sha256}` : ''}`}>- <Icon name="alert" size={12} />- <span class="chain-label">{lost.label ?? lost.path}</span>- <span class="chain-tag">deleted</span>- </div>- {/each}- {#each chain.lost as lost (lost.path + '-src')}- {#if lost.source_url}- <a class="chain-src mono" href={lost.source_url} target="_blank" rel="noreferrer">{lost.source_url}</a>- {/if}- {/each}- {/if}- {#if chain.dependents.length}- <div class="chain-h">Used by</div>- {#each chain.dependents as { entity, type } (entity.id)}- <button class="chain-row" onclick={() => openInfo(entity)}>- <Icon name={ENTITY_ICON[entity.type] ?? 'file'} size={12} />- <span class="chain-label">{entity.label}</span>- {#if type === DEPENDS_ON}- <span class="chain-tag warn" title="Deleting this item deletes that one too">goes with it</span>- {/if}- </button>- {/each}- {/if}+ <div class="section-head-row">+ <div class="section-head static">+ <Icon name="note" size={13} />+ <span>Details</span></div>- {/if}-- {#if EDITABLE.has(infoEntity.type)}- <label class="modal-label" for="info-notes">Notes</label>- <textarea- id="info-notes"- class="textarea"- rows="3"- bind:value={infoNotes}- placeholder="Add observations, links, context…"- ></textarea>- {/if}-- <label class="modal-label" for="info-folder">Folder (My work)</label>- <input- id="info-folder"- class="input"- bind:value={infoFolder}- placeholder="none"- list="info-folder-suggestions"- />- <datalist id="info-folder-suggestions">- {#each allFolders as f (f)}<option value={f}></option>{/each}- </datalist>-- <div class="details-actions">- {#if detailsFilePath}- <a class="btn btn-ghost btn-sm" href={`/files/${caseState.current.id}/${detailsFilePath}`} target="_blank" rel="noreferrer">- <Icon name="external" size={13} /> Open file- </a>- {/if}- {#if ENTITY_TOOL[infoEntity.type]}- <button class="btn btn-ghost btn-sm" onclick={() => openEntity(infoEntity)}>- <Icon name="arrowRight" size={13} /> Open in tool- </button>- {/if}- {#if infoEntity.type === 'capture' && infoEntity.attrs?.lat != null}- <button class="btn btn-ghost btn-sm" onclick={() => gotoCapture(infoEntity)}>- <Icon name="crosshair" size={13} /> Go to coords- </button>- {/if}- </div>- <div class="details-actions">- <button- class="btn btn-ghost btn-sm del"- title="Delete everywhere: removes the item and its file(s) from the case"- onclick={() => askDeleteEverywhere(infoEntity, () => (infoEntity = null))}- >- <Icon name="trash" size={13} /> Delete- </button>- <div style="flex:1"></div>- <button class="btn btn-primary btn-sm" onclick={saveInfo} disabled={infoSaving}>- {infoSaving ? 'Saving…' : 'Save'}+ <button class="btn btn-ghost btn-sm" title="Close details" onclick={() => (infoEntity = null)}>+ <Icon name="x" size={13} /></button></div>- </div>+ <div class="details">+ <EntityDetails+ entityId={infoEntity.id}+ onclose={() => (infoEntity = null)}+ ondeleted={() => (infoEntity = null)}+ />+ </div></div>{/if}@@ -1272,86 +921,6 @@border-bottom: 1px solid var(--border);font-size: var(--fs-sm);}- .details-title {- font-weight: 600;- margin-bottom: 6px;- overflow-wrap: anywhere;- }- .details-actions {- display: flex;- align-items: center;- gap: 4px;- flex-wrap: wrap;- margin-top: 8px;- }- .details-actions .del { color: var(--danger); }.note-content { width: 100%; resize: vertical; font-family: var(--font-mono); font-size: var(--fs-xs); }.modal-row { display: flex; align-items: center; gap: 8px; margin-top: 14px; }- /* info modal */- .info-loading { font-size: var(--fs-sm); color: var(--text-3); padding: 6px 0; }- .info-preview {- border-radius: var(--r);- overflow: hidden;- background: var(--bg-2);- margin-bottom: 14px;- max-height: 240px;- display: flex;- align-items: center;- justify-content: center;- }- .info-preview img, .info-preview video { max-width: 100%; max-height: 240px; object-fit: contain; display: block; }- .info-rows { display: flex; flex-direction: column; gap: 6px; }- .info-row { display: flex; gap: 10px; font-size: var(--fs-sm); align-items: baseline; min-width: 0; }- .info-k { color: var(--text-3); font-size: var(--fs-xs); min-width: 68px; flex-shrink: 0; }- .hash { font-size: 11px; word-break: break-all; color: var(--text-2); }- .src { font-size: var(--fs-xs); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }- .info-note-body { white-space: pre-wrap; font-size: var(--fs-sm); color: var(--text-2); }-- /* derivation chain rows (ONTOLOGY §3) */- .chain { margin-top: 14px; display: flex; flex-direction: column; gap: 2px; }- .chain-h {- font-size: var(--fs-xs);- color: var(--text-3);- text-transform: uppercase;- letter-spacing: 0.04em;- margin: 6px 0 3px;- }- .chain-row {- display: flex;- align-items: center;- gap: 7px;- width: 100%;- padding: 5px 6px;- border: 0;- border-radius: var(--r-sm);- background: transparent;- color: var(--text-2);- font-size: var(--fs-sm);- text-align: left;- min-width: 0;- }- button.chain-row { cursor: pointer; }- button.chain-row:hover { background: var(--bg-2); color: var(--text-1); }- .chain-row.gone { color: var(--text-3); }- .chain-label { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }- .chain-tag {- flex-shrink: 0;- font-size: 10px;- padding: 1px 5px;- border-radius: 999px;- background: var(--bg-2);- color: var(--text-3);- }- .chain-tag.warn {- background: color-mix(in srgb, var(--danger, #e5484d) 14%, transparent);- color: color-mix(in srgb, var(--danger, #e5484d) 80%, var(--text-2));- }- .chain-src {- font-size: 10px;- color: var(--text-3);- padding: 0 6px 4px 25px;- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;- }</style>diff --git a/frontend/src/components/EntityDetails.svelte b/frontend/src/components/EntityDetails.sveltenew file mode 100644index 0000000..f91440f--- /dev/null+++ b/frontend/src/components/EntityDetails.svelte@@ -0,0 +1,542 @@+<script>+ /**+ * The selection editor for any artifact (docs/UI.md §4): preview, provenance,+ * the derivation chain, and an inline title/notes/folder editor with the+ * open/delete actions. One body, two homes — the case sidebar's Details+ * section and the Media Library's info modal both render this, so the two can+ * never drift apart again.+ *+ * Driven by an entity id: the live entity is derived from the open case, so a+ * reload after Save (or a folder move) shows the fresh object with no prop+ * juggling. Clicking a chain row walks the details to that entity in place.+ */+ import { api } from '../lib/api.js';+ import { caseState, reloadCase, toast } from '../lib/state.svelte.js';+ import { buildTree, flattenPaths, folderOf } from '../lib/folderTree.js';+ import { assignFolder as fileEntity } from '../lib/filing.js';+ import { chainOf, deletePlan, DEPENDS_ON } from '../lib/chain.js';+ import { openEntity, gotoCapture, ENTITY_TOOL } from '../lib/navigate.js';+ import Icon from './Icon.svelte';+ import ConfirmDialog from './ConfirmDialog.svelte';++ let { entityId, onclose, ondeleted } = $props();++ // Chain rows walk the details to another entity in place; that override sticks+ // until the host selects a different entity, when it clears back to the prop.+ let walkedId = $state(null);+ let lastProp; // seeded on the first effect run+ $effect(() => {+ if (entityId !== lastProp) {+ lastProp = entityId;+ walkedId = null;+ }+ });+ const currentId = $derived(walkedId ?? entityId);++ const entities = $derived(caseState.current?.entities ?? []);+ const links = $derived(caseState.current?.links ?? []);+ const entity = $derived(entities.find((e) => e.id === currentId) ?? null);++ const confirmed = $derived(entities.filter((e) => e.provenance?.status !== 'suggested'));+ const allFolders = $derived(flattenPaths(buildTree(caseState.current?.folders ?? [], confirmed)));++ // Entity types backed by a file on disk — deleting them drops the file.+ const FILE_BACKED = new Set(['media', 'capture', 'proof', 'post', 'inspect-session']);+ // Every artifact type gets the title/notes editor. Media/captures go through+ // their sidecar PATCH; the rest edit the entity itself.+ const EDITABLE = new Set(['capture', 'place', 'media', 'proof', 'post', 'inspect-session', 'note', 'bookmark']);+ const ENTITY_ICON = {+ media: 'media', capture: 'satellite', place: 'pin', proof: 'proof',+ post: 'post', 'inspect-session': 'inspect', note: 'note', bookmark: 'link',+ };++ const chain = $derived(entity ? chainOf(entities, links, entity.id) : null);++ // ── resolved listing item (media/satellite) + editable fields ──────────────+ let infoData = $state(null);+ let infoLoading = $state(false);+ let infoTitle = $state('');+ let infoNotes = $state('');+ let infoFolder = $state('');+ let infoSaving = $state(false);+ let seededId = null; // the id whose fields are currently loaded++ const detailsFilePath = $derived(+ infoData?.path ?? (entity?.type === 'capture' ? entity.attrs?.path : null)+ );++ $effect(() => {+ const e = entity;+ caseState.rev; // re-resolve preview/metadata after a reload…+ if (!e) {+ infoData = null;+ seededId = null;+ return;+ }+ const firstSeed = seededId !== e.id; // …but only re-seed fields on a new selection+ if (firstSeed) {+ seededId = e.id;+ infoTitle = e.label ?? '';+ infoNotes = e.attrs?.notes ?? '';+ infoFolder = folderOf(e) ?? '';+ infoData = null;+ }+ resolve(e, firstSeed);+ });++ async function resolve(e, seedFields) {+ const endpoint = e.type === 'media' ? 'media' : e.type === 'capture' ? 'satellite' : null;+ if (!endpoint || !e.attrs?.path) {+ infoData = null;+ return;+ }+ infoLoading = true;+ try {+ const list = await api.get(`/api/cases/${caseState.current.id}/${endpoint}`);+ if (seededId !== e.id) return; // selection moved on mid-fetch+ infoData = list.find((m) => m.path === e.attrs.path) ?? null;+ if (infoData && seedFields) {+ infoTitle = infoData.title ?? e.label ?? '';+ infoNotes = infoData.notes ?? infoNotes;+ }+ } catch {+ infoData = null;+ } finally {+ infoLoading = false;+ }+ }++ async function saveInfo() {+ if (!entity || infoSaving) return;+ infoSaving = true;+ const cid = caseState.current.id;+ try {+ if (entity.type === 'capture') {+ await api.patch(`/api/cases/${cid}/satellite`, {+ path: entity.attrs.path, title: infoTitle, notes: infoNotes,+ });+ } else if (entity.type === 'media') {+ await api.patch(`/api/cases/${cid}/media`, {+ path: entity.attrs.path, title: infoTitle.trim(), notes: infoNotes,+ });+ } else if (EDITABLE.has(entity.type)) {+ await api.patch(`/api/cases/${cid}/entities/${entity.id}`, {+ label: infoTitle.trim() || entity.label, attrs: { notes: infoNotes.trim() },+ });+ }+ if ((infoFolder.trim() || '') !== (folderOf(entity) ?? '')) {+ await fileEntity(cid, entity, infoFolder.trim());+ }+ await reloadCase();+ toast('Saved', 'ok', 1600);+ } catch (e) {+ toast(e.message, 'danger');+ } finally {+ infoSaving = false;+ }+ }++ // ── delete everywhere (irreversible; spells out what it touches) ───────────+ let confirmState = $state(null);+ let confirmBusy = $state(false);++ function askDeleteEverywhere() {+ const e = entity;+ if (!e) return;+ confirmState = {+ title: 'Delete everywhere?',+ message: `“${e.label}” will be removed from the case and its tool.`,+ detail: FILE_BACKED.has(e.type)+ ? 'This permanently deletes the underlying file(s) on disk — it cannot be undone.'+ : 'This permanently removes it from the case — it cannot be undone.',+ consequences: deletePlan(entities, links, e.id),+ action: async () => {+ await api.del(`/api/cases/${caseState.current.id}/entities/${e.id}`);+ await reloadCase();+ toast(`Deleted "${e.label}"`, 'info');+ ondeleted?.();+ },+ };+ }++ async function runConfirm() {+ const s = confirmState;+ if (!s) return;+ confirmBusy = true;+ try {+ await s.action();+ } catch (e) {+ toast(e.message, 'danger');+ } finally {+ confirmBusy = false;+ confirmState = null;+ }+ }++ function fmtSize(bytes) {+ if (bytes == null) return '';+ if (bytes >= 1 << 30) return (bytes / (1 << 30)).toFixed(1) + ' GB';+ if (bytes >= 1 << 20) return (bytes / (1 << 20)).toFixed(1) + ' MB';+ if (bytes >= 1 << 10) return (bytes / (1 << 10)).toFixed(0) + ' KB';+ return bytes + ' B';+ }+</script>++{#if entity}+ <div class="ed">+ {#if infoLoading}+ <div class="info-loading">Loading…</div>+ {/if}++ {#if infoData?.kind === 'image' && infoData.thumbnail}+ <div class="info-preview">+ <img src={`/files/${caseState.current.id}/${infoData.path}`} alt={entity.label} />+ </div>+ {:else if infoData?.kind === 'video'}+ <div class="info-preview">+ <!-- svelte-ignore a11y_media_has_caption -->+ <video src={`/files/${caseState.current.id}/${infoData.path}`} controls preload="metadata"></video>+ </div>+ {:else if entity.type === 'capture' && entity.attrs?.path}+ <div class="info-preview">+ <img src={`/files/${caseState.current.id}/${entity.attrs.path}`} alt={entity.label} />+ </div>+ {/if}++ {#if EDITABLE.has(entity.type)}+ <label class="modal-label" for="ed-title">Title</label>+ <input id="ed-title" class="input" bind:value={infoTitle} placeholder={entity.attrs?.coords ?? 'Title'} />+ {:else}+ <div class="details-title">{entity.label}</div>+ {/if}++ <div class="info-rows">+ <div class="info-row"><span class="info-k">Type</span><span>{entity.type}</span></div>+ {#if entity.provenance?.by}+ <div class="info-row"><span class="info-k">Created by</span><span>{entity.provenance.by}</span></div>+ {/if}+ {#if entity.provenance?.at}+ <div class="info-row"><span class="info-k">Created</span><span class="mono">{entity.provenance.at.slice(0, 10)}</span></div>+ {/if}+ {#if entity.type === 'media' && infoData}+ <div class="info-row"><span class="info-k">Kind</span><span>{infoData.kind}</span></div>+ <div class="info-row"><span class="info-k">Size</span><span>{fmtSize(infoData.size)}</span></div>+ {#if infoData.sha256}+ <div class="info-row"><span class="info-k">SHA-256</span><span class="mono hash" title={infoData.sha256}>{infoData.sha256}</span></div>+ {/if}+ {#if infoData.source?.title}+ <div class="info-row"><span class="info-k">Title</span><span>{infoData.source.title}</span></div>+ {/if}+ {#if infoData.source?.uploader}+ <div class="info-row"><span class="info-k">Uploader</span><span>{infoData.source.uploader}</span></div>+ {/if}+ {#if infoData.source?.upload_date}+ <div class="info-row"><span class="info-k">Published</span><span class="mono">{infoData.source.upload_date}</span></div>+ {/if}+ {#if infoData.source?.duration}+ <div class="info-row"><span class="info-k">Duration</span><span>{infoData.source.duration}s</span></div>+ {/if}+ {#if infoData.source?.webpage_url ?? infoData.source?.url}+ <div class="info-row">+ <span class="info-k">Source</span>+ <a class="mono src" href={infoData.source.webpage_url ?? infoData.source.url} target="_blank" rel="noreferrer">+ {infoData.source.webpage_url ?? infoData.source.url}+ </a>+ </div>+ {/if}+ {#if infoData.source?.description}+ <div class="info-row"><span class="info-k">Description</span><span class="description">{infoData.source.description}</span></div>+ {/if}+ {:else if entity.type === 'capture'}+ {#if infoData?.provider_label}+ <div class="info-row"><span class="info-k">Provider</span><span>{infoData.provider_label}</span></div>+ {/if}+ {#if entity.attrs?.zoom != null}+ <div class="info-row"><span class="info-k">Zoom</span><span>z{entity.attrs.zoom}</span></div>+ {/if}+ {#if infoData?.fetched_at}+ <div class="info-row"><span class="info-k">Captured</span><span class="mono">{infoData.fetched_at.slice(0, 10)}</span></div>+ {/if}+ {#if infoData?.imagery_date}+ <div class="info-row"><span class="info-k">Imagery</span><span class="mono">{infoData.imagery_date}</span></div>+ {/if}+ {:else if entity.type === 'bookmark' && entity.attrs?.url}+ <div class="info-row">+ <span class="info-k">URL</span>+ <a class="mono src" href={entity.attrs.url} target="_blank" rel="noreferrer">{entity.attrs.url}</a>+ </div>+ {:else if entity.attrs?.content}+ <div class="info-note-body">{entity.attrs.content}</div>+ {/if}+ {#if entity.attrs?.coords}+ <div class="info-row"><span class="info-k">Coords</span><span class="mono">{entity.attrs.coords}</span></div>+ {/if}+ </div>++ <!-- derivation chain: click a row to walk to that entity's details -->+ {#if chain && !chain.empty}+ <div class="chain">+ {#if chain.sources.length || chain.lost.length}+ <div class="chain-h">Made from</div>+ {#each chain.sources as { entity: src, type } (src.id)}+ <button class="chain-row" onclick={() => (walkedId = src.id)}>+ <Icon name={ENTITY_ICON[src.type] ?? 'file'} size={12} />+ <span class="chain-label">{src.label}</span>+ {#if type === DEPENDS_ON}+ <span class="chain-tag" title="This is a view over that item — it cannot outlive it">needs</span>+ {/if}+ </button>+ {/each}+ {#each chain.lost as lost (lost.path)}+ <div class="chain-row gone" title={`Deleted on ${lost.at?.slice(0, 10) ?? 'an unknown date'}${lost.sha256 ? ` · sha256 ${lost.sha256}` : ''}`}>+ <Icon name="alert" size={12} />+ <span class="chain-label">{lost.label ?? lost.path}</span>+ <span class="chain-tag">deleted</span>+ </div>+ {/each}+ {#each chain.lost as lost (lost.path + '-src')}+ {#if lost.source_url}+ <a class="chain-src mono" href={lost.source_url} target="_blank" rel="noreferrer">{lost.source_url}</a>+ {/if}+ {/each}+ {/if}+ {#if chain.dependents.length}+ <div class="chain-h">Used by</div>+ {#each chain.dependents as { entity: dep, type } (dep.id)}+ <button class="chain-row" onclick={() => (walkedId = dep.id)}>+ <Icon name={ENTITY_ICON[dep.type] ?? 'file'} size={12} />+ <span class="chain-label">{dep.label}</span>+ {#if type === DEPENDS_ON}+ <span class="chain-tag warn" title="Deleting this item deletes that one too">goes with it</span>+ {/if}+ </button>+ {/each}+ {/if}+ </div>+ {/if}++ {#if EDITABLE.has(entity.type)}+ <label class="modal-label" for="ed-notes">Notes</label>+ <textarea id="ed-notes" class="textarea" rows="3" bind:value={infoNotes} placeholder="Add observations, links, context…"></textarea>+ {/if}++ <label class="modal-label" for="ed-folder">Folder (My work)</label>+ <input id="ed-folder" class="input" bind:value={infoFolder} placeholder="none" list="ed-folder-suggestions" />+ <datalist id="ed-folder-suggestions">+ {#each allFolders as f (f)}<option value={f}></option>{/each}+ </datalist>++ <div class="details-actions">+ {#if detailsFilePath}+ <a class="btn btn-ghost btn-sm" href={`/files/${caseState.current.id}/${detailsFilePath}`} target="_blank" rel="noreferrer">+ <Icon name="external" size={13} /> Open file+ </a>+ {/if}+ {#if entity.type === 'bookmark' && entity.attrs?.url}+ <a class="btn btn-ghost btn-sm" href={entity.attrs.url} target="_blank" rel="noreferrer">+ <Icon name="external" size={13} /> Open link+ </a>+ {/if}+ {#if ENTITY_TOOL[entity.type]}+ <button class="btn btn-ghost btn-sm" onclick={() => { openEntity(entity); onclose?.(); }}>+ <Icon name="arrowRight" size={13} /> Open in tool+ </button>+ {/if}+ {#if entity.type === 'capture' && entity.attrs?.lat != null}+ <button class="btn btn-ghost btn-sm" onclick={() => { gotoCapture(entity); onclose?.(); }}>+ <Icon name="crosshair" size={13} /> Go to coords+ </button>+ {/if}+ </div>+ <div class="details-actions">+ <button+ class="btn btn-ghost btn-sm del"+ title="Delete everywhere: removes the item and its file(s) from the case"+ onclick={askDeleteEverywhere}+ >+ <Icon name="trash" size={13} /> Delete+ </button>+ <div style="flex:1"></div>+ <button class="btn btn-primary btn-sm" onclick={saveInfo} disabled={infoSaving}>+ {infoSaving ? 'Saving…' : 'Save'}+ </button>+ </div>+ </div>+{/if}++{#if confirmState}+ <ConfirmDialog+ title={confirmState.title}+ message={confirmState.message}+ detail={confirmState.detail}+ consequences={confirmState.consequences}+ confirmLabel="Delete everywhere"+ tone="danger"+ icon="trash"+ busy={confirmBusy}+ onconfirm={runConfirm}+ oncancel={() => (confirmState = null)}+ />+{/if}++<style>+ .ed {+ font-size: var(--fs-sm);+ }+ .modal-label {+ display: block;+ font-size: var(--fs-xs);+ color: var(--text-3);+ margin: 8px 0 4px;+ }+ .details-title {+ font-weight: 600;+ margin-bottom: 6px;+ overflow-wrap: anywhere;+ }+ .details-actions {+ display: flex;+ align-items: center;+ gap: 4px;+ flex-wrap: wrap;+ margin-top: 8px;+ }+ .details-actions .del {+ color: var(--danger);+ }+ .info-loading {+ font-size: var(--fs-sm);+ color: var(--text-3);+ padding: 6px 0;+ }+ .info-preview {+ border-radius: var(--r);+ overflow: hidden;+ background: var(--bg-2);+ margin-bottom: 14px;+ max-height: 240px;+ display: flex;+ align-items: center;+ justify-content: center;+ }+ .info-preview img,+ .info-preview video {+ max-width: 100%;+ max-height: 240px;+ object-fit: contain;+ display: block;+ }+ .info-rows {+ display: flex;+ flex-direction: column;+ gap: 6px;+ }+ .info-row {+ display: flex;+ gap: 10px;+ font-size: var(--fs-sm);+ align-items: baseline;+ min-width: 0;+ }+ .info-k {+ color: var(--text-3);+ font-size: var(--fs-xs);+ min-width: 68px;+ flex-shrink: 0;+ }+ .hash {+ font-size: 11px;+ word-break: break-all;+ color: var(--text-2);+ }+ .src {+ font-size: var(--fs-xs);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .description {+ flex: 1;+ min-width: 0;+ font-size: var(--fs-xs);+ color: var(--text-2);+ white-space: pre-wrap;+ word-break: break-word;+ max-height: 8.5em;+ overflow-y: auto;+ }+ .info-note-body {+ white-space: pre-wrap;+ font-size: var(--fs-sm);+ color: var(--text-2);+ }+ .textarea {+ width: 100%;+ resize: vertical;+ }++ /* derivation chain rows (ONTOLOGY §3) */+ .chain {+ margin-top: 14px;+ display: flex;+ flex-direction: column;+ gap: 2px;+ }+ .chain-h {+ font-size: var(--fs-xs);+ color: var(--text-3);+ text-transform: uppercase;+ letter-spacing: 0.04em;+ margin: 6px 0 3px;+ }+ .chain-row {+ display: flex;+ align-items: center;+ gap: 7px;+ width: 100%;+ padding: 5px 6px;+ border: 0;+ border-radius: var(--r-sm);+ background: transparent;+ color: var(--text-2);+ font-size: var(--fs-sm);+ text-align: left;+ min-width: 0;+ }+ button.chain-row {+ cursor: pointer;+ }+ button.chain-row:hover {+ background: var(--bg-2);+ color: var(--text-1);+ }+ .chain-row.gone {+ color: var(--text-3);+ }+ .chain-label {+ flex: 1;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .chain-tag {+ flex-shrink: 0;+ font-size: 10px;+ padding: 1px 5px;+ border-radius: 999px;+ background: var(--bg-2);+ color: var(--text-3);+ }+ .chain-tag.warn {+ background: color-mix(in srgb, var(--danger, #e5484d) 14%, transparent);+ color: color-mix(in srgb, var(--danger, #e5484d) 80%, var(--text-2));+ }+ .chain-src {+ font-size: 10px;+ color: var(--text-3);+ padding: 0 6px 4px 25px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+</style>diff --git a/frontend/src/lib/bookmarks.js b/frontend/src/lib/bookmarks.jsnew file mode 100644index 0000000..fc8901e--- /dev/null+++ b/frontend/src/lib/bookmarks.js@@ -0,0 +1,22 @@+/**+ * Creating a bookmark entity. A bookmark is just an entity of type `bookmark`+ * whose target lives in `attrs.url`; `attrs.folder` files it into a My-work+ * folder (''=unfiled) and `attrs.notes` holds a one-line context. The mirror of+ * notes.js — the extension files the same shape over /api/ingest/bookmark when+ * the open page isn't a map site.+ *+ * Does not reload the case: the caller refetches once it returns.+ */+import { api } from './api.js';++export async function createBookmark(caseId, { title, url, folder = '', notes = '' }) {+ const label = (title ?? '').trim();+ const target = (url ?? '').trim();+ if (!label) throw new Error('Title required');+ if (!/^https?:\/\//i.test(target)) throw new Error('Enter an http(s) URL');+ await api.post(`/api/cases/${caseId}/entities`, {+ type: 'bookmark',+ label,+ attrs: { url: target, notes: (notes ?? '').trim(), folder: (folder ?? '').trim() },+ });+}diff --git a/frontend/src/lib/bookmarks.test.js b/frontend/src/lib/bookmarks.test.jsnew file mode 100644index 0000000..cf675cf--- /dev/null+++ b/frontend/src/lib/bookmarks.test.js@@ -0,0 +1,45 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { api } from './api.js';+import { createBookmark } from './bookmarks.js';++vi.mock('./api.js', () => ({ api: { post: vi.fn(async () => ({})) } }));++beforeEach(() => api.post.mockClear());++describe('createBookmark', () => {+ it('posts a bookmark entity with url, notes and filing folder', async () => {+ await createBookmark('case-1', {+ title: 'Leak site', url: 'https://example.com/x', folder: 'Sources', notes: 'seen once',+ });+ expect(api.post).toHaveBeenCalledWith('/api/cases/case-1/entities', {+ type: 'bookmark',+ label: 'Leak site',+ attrs: { url: 'https://example.com/x', notes: 'seen once', folder: 'Sources' },+ });+ });++ it('trims the title, url, folder and notes', async () => {+ await createBookmark('case-1', {+ title: ' Leak site ', url: ' https://example.com/x ', folder: ' Sources ',+ });+ expect(api.post).toHaveBeenCalledWith('/api/cases/case-1/entities', {+ type: 'bookmark',+ label: 'Leak site',+ attrs: { url: 'https://example.com/x', notes: '', folder: 'Sources' },+ });+ });++ it('rejects a blank title without hitting the API', async () => {+ await expect(createBookmark('case-1', { title: ' ', url: 'https://x.com' })).rejects.toThrow(+ 'Title required'+ );+ expect(api.post).not.toHaveBeenCalled();+ });++ it('rejects a non-http URL without hitting the API', async () => {+ await expect(+ createBookmark('case-1', { title: 'Bad', url: 'javascript:alert(1)' })+ ).rejects.toThrow('http(s) URL');+ expect(api.post).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/lib/composer.js b/frontend/src/lib/composer.jsindex d4911ca..eec9402 100644--- a/frontend/src/lib/composer.js+++ b/frontend/src/lib/composer.js@@ -39,6 +39,33 @@ export function newId(prefix) {return `${prefix}${Date.now().toString(36)}${(idSeq++).toString(36)}`;}+// Title a fresh proof carries until the analyst renames it. Two proofs left at+// this title auto-number on save (see uniqueProofName) instead of clobbering.+export const DEFAULT_PROOF_TITLE = 'Untitled proof';++/** URL-safe proof filename from free text — mirror of the backend `_slug`. */+export function proofSlug(text) {+ const slug = (text ?? '')+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '');+ return slug.slice(0, 80) || 'proof';+}++/**+ * A proof title that doesn't collide with `taken` (existing proof titles):+ * `base` when free, else `base 2`, `base 3`, … A new proof left at the default+ * title gets numbered so two never-renamed proofs read apart in the case, and+ * the filename simply follows the title (proofSlug). `taken` is a Set or array.+ */+export function uniqueProofTitle(base, taken) {+ const set = taken instanceof Set ? taken : new Set(taken);+ if (!set.has(base)) return base;+ let n = 2;+ while (set.has(`${base} ${n}`)) n += 1;+ return `${base} ${n}`;+}+export const CAPTION_SIZE = 20; // default caption font size (px, editable per proof)export const LEGEND_SIZE = 20; // default legend text sizeexport const FOOTER_SIZE = 15; // default footer / attribution text sizediff --git a/frontend/src/lib/composer.test.js b/frontend/src/lib/composer.test.jsindex ec41931..d34a279 100644--- a/frontend/src/lib/composer.test.js+++ b/frontend/src/lib/composer.test.js@@ -8,6 +8,7 @@ import {proofCoordsText, proofSource, orderedFeatureColors, legendLines,dedupeBySrc, isSatelliteCapture, satPanelInput, mediaPanelInput,SIG_MARGIN, SIG_SCALE, newSignature, signatureBox, signatureOffset,+ proofSlug, uniqueProofTitle, DEFAULT_PROOF_TITLE,} from './composer.js';// natural is [width, height]; PANEL_H drives the per-row scale.@@ -777,3 +778,35 @@ describe('signatureOffset — a drag round-trips through the anchor', () => {}});});++describe('proofSlug — mirrors the backend _slug', () => {+ it('lowercases, hyphenates runs of non-alphanumerics, trims edges', () => {+ expect(proofSlug('Untitled proof')).toBe('untitled-proof');+ expect(proofSlug(' Rooftop! @ 12:30 ')).toBe('rooftop-12-30');+ expect(proofSlug('Café déjà')).toBe('caf-d-j');+ });++ it('falls back to "proof" when nothing survives, and caps at 80 chars', () => {+ expect(proofSlug('')).toBe('proof');+ expect(proofSlug('!!!')).toBe('proof');+ expect(proofSlug(null)).toBe('proof');+ expect(proofSlug('a'.repeat(200))).toHaveLength(80);+ });+});++describe('uniqueProofTitle — a fresh proof reads apart from the case', () => {+ it('returns the base when no proof carries it', () => {+ expect(uniqueProofTitle(DEFAULT_PROOF_TITLE, new Set())).toBe('Untitled proof');+ expect(uniqueProofTitle(DEFAULT_PROOF_TITLE, ['Rooftop'])).toBe('Untitled proof');+ });++ it('numbers past the base and any run already taken', () => {+ expect(uniqueProofTitle(DEFAULT_PROOF_TITLE, new Set(['Untitled proof']))).toBe('Untitled proof 2');+ const taken = ['Untitled proof', 'Untitled proof 2', 'Untitled proof 3'];+ expect(uniqueProofTitle(DEFAULT_PROOF_TITLE, taken)).toBe('Untitled proof 4');+ });++ it('the numbered title still slugs to a distinct filename', () => {+ expect(proofSlug(uniqueProofTitle(DEFAULT_PROOF_TITLE, ['Untitled proof']))).toBe('untitled-proof-2');+ });+});diff --git a/frontend/src/lib/extBridge.js b/frontend/src/lib/extBridge.jsindex e0e3c19..556a59b 100644--- a/frontend/src/lib/extBridge.js+++ b/frontend/src/lib/extBridge.js@@ -20,6 +20,22 @@ export function extensionVersion(doc = document) {return doc.documentElement.dataset.azimutCaptureExtension || null;}+/**+ * Is `bundled` a newer extension than `installed`? Numeric per-part compare, so+ * 0.1.10 beats 0.1.9 and a `v` prefix or pre-release suffix doesn't fool it.+ * False when either side is missing — nothing to update to, or nothing to+ * update. Mirrors the app-side check in engine/updates.py.+ */+export function extensionOutdated(installed, bundled) {+ if (!installed || !bundled) return false;+ const parse = (v) => String(v).replace(/^v/i, '').split('.').map((n) => parseInt(n, 10) || 0);+ const [a, b] = [parse(bundled), parse(installed)];+ for (let i = 0; i < Math.max(a.length, b.length); i++) {+ if ((a[i] || 0) !== (b[i] || 0)) return (a[i] || 0) > (b[i] || 0);+ }+ return false;+}+let seq = 0;/**diff --git a/frontend/src/lib/extBridge.test.js b/frontend/src/lib/extBridge.test.jsindex 42b76a0..b6de892 100644--- a/frontend/src/lib/extBridge.test.js+++ b/frontend/src/lib/extBridge.test.js@@ -1,6 +1,6 @@// @vitest-environment happy-domimport { describe, it, expect, afterEach } from 'vitest';-import { extensionVersion, captureTab, onActivated } from './extBridge.js';+import { extensionVersion, extensionOutdated, captureTab, onActivated } from './extBridge.js';// The bridge protocol is the app's only path to widget pixels, so what these// tests pin is the contract: detection reads the content script's marker, and@@ -19,6 +19,20 @@ describe('extensionVersion', () => {});});+describe('extensionOutdated', () => {+ it('flags a newer bundled version against the installed one', () => {+ expect(extensionOutdated('0.1.0', '0.2.0')).toBe(true);+ expect(extensionOutdated('0.1.0', 'v0.1.1')).toBe(true);+ expect(extensionOutdated('0.1.9', '0.1.10')).toBe(true); // numeric, not lexical+ });+ it('is false when equal, older, or either side is missing', () => {+ expect(extensionOutdated('0.1.0', '0.1.0')).toBe(false);+ expect(extensionOutdated('0.2.0', '0.1.0')).toBe(false);+ expect(extensionOutdated(null, '0.2.0')).toBe(false);+ expect(extensionOutdated('0.1.0', '')).toBe(false);+ });+});+// A fake bridge.js: answers capture requests on the window like the content// script does. Returns a disposer.function fakeBridge(answer) {diff --git a/frontend/src/lib/filing.js b/frontend/src/lib/filing.jsnew file mode 100644index 0000000..89eb82e--- /dev/null+++ b/frontend/src/lib/filing.js@@ -0,0 +1,24 @@+/**+ * Filing an artifact into a My-work folder. Media and captures keep their+ * sidecar in sync through the media endpoint; every other entity stores the+ * folder on the entity itself. Same routing the case sidebar has always used —+ * lifted here so the desktop organizer files items the exact same way.+ *+ * Neither call reloads the case: the caller decides when to refetch (once after+ * a batch, not once per item).+ */+import { api } from './api.js';++export async function assignFolder(caseId, entity, folder) {+ const val = folder || '';+ if ((entity.type === 'media' || entity.type === 'capture') && entity.attrs?.path) {+ await api.patch(`/api/cases/${caseId}/media`, { path: entity.attrs.path, folder: val });+ } else {+ await api.patch(`/api/cases/${caseId}/entities/${entity.id}`, { attrs: { folder: val } });+ }+}++/** File several entities into one folder, in order. */+export async function assignFolderBatch(caseId, entities, folder) {+ for (const entity of entities) await assignFolder(caseId, entity, folder);+}diff --git a/frontend/src/lib/filing.test.js b/frontend/src/lib/filing.test.jsnew file mode 100644index 0000000..27f5e34--- /dev/null+++ b/frontend/src/lib/filing.test.js@@ -0,0 +1,58 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { api } from './api.js';+import { assignFolder, assignFolderBatch } from './filing.js';++vi.mock('./api.js', () => ({ api: { patch: vi.fn(async () => ({})) } }));++beforeEach(() => api.patch.mockClear());++const media = { id: 'm1', type: 'media', attrs: { path: 'media/a.jpg' } };+const capture = { id: 'c1', type: 'capture', attrs: { path: 'media/cap.png' } };+const note = { id: 'n1', type: 'note', attrs: {} };++describe('assignFolder', () => {+ it('files media through the media sidecar endpoint (path + folder)', async () => {+ await assignFolder('case-1', media, 'Sources/Telegram');+ expect(api.patch).toHaveBeenCalledWith('/api/cases/case-1/media', {+ path: 'media/a.jpg',+ folder: 'Sources/Telegram',+ });+ });++ it('files captures through the media endpoint too (they live in media/)', async () => {+ await assignFolder('case-1', capture, 'Places');+ expect(api.patch).toHaveBeenCalledWith('/api/cases/case-1/media', {+ path: 'media/cap.png',+ folder: 'Places',+ });+ });++ it('files other entities on the entity itself (attrs.folder)', async () => {+ await assignFolder('case-1', note, 'Timeline');+ expect(api.patch).toHaveBeenCalledWith('/api/cases/case-1/entities/n1', {+ attrs: { folder: 'Timeline' },+ });+ });++ it('unfiles with an empty string when folder is falsy', async () => {+ await assignFolder('case-1', media, '');+ expect(api.patch).toHaveBeenCalledWith('/api/cases/case-1/media', {+ path: 'media/a.jpg',+ folder: '',+ });+ });+});++describe('assignFolderBatch', () => {+ it('files every entity into the target folder', async () => {+ await assignFolderBatch('case-1', [media, note], 'Box');+ expect(api.patch).toHaveBeenCalledTimes(2);+ expect(api.patch).toHaveBeenNthCalledWith(1, '/api/cases/case-1/media', {+ path: 'media/a.jpg',+ folder: 'Box',+ });+ expect(api.patch).toHaveBeenNthCalledWith(2, '/api/cases/case-1/entities/n1', {+ attrs: { folder: 'Box' },+ });+ });+});diff --git a/frontend/src/lib/gridSelect.js b/frontend/src/lib/gridSelect.jsnew file mode 100644index 0000000..4e60d6a--- /dev/null+++ b/frontend/src/lib/gridSelect.js@@ -0,0 +1,55 @@+/**+ * Pure selection math for the desktop organizer's tile grid — kept out of the+ * component so it's unit-tested without a DOM. The component measures tile+ * rects (getBoundingClientRect) and drives these; nothing here touches the DOM.+ */++/**+ * Ids of tiles whose rect intersects the marquee rectangle. Rects and the+ * marquee are `{id, left, top, right, bottom}` / `{left, top, right, bottom}`+ * in the same coordinate space. Edge contact counts as a hit; a zero-area+ * marquee (a click that never dragged) selects nothing.+ */+export function marqueeHits(rects, marquee) {+ const { left, top, right, bottom } = marquee;+ if (right <= left || bottom <= top) return [];+ return rects+ .filter((r) => r.left <= right && r.right >= left && r.top <= bottom && r.bottom >= top)+ .map((r) => r.id);+}++/** Normalize a drag's two corners into a {left,top,right,bottom} rectangle. */+export function marqueeRect(x0, y0, x1, y1) {+ return {+ left: Math.min(x0, x1),+ top: Math.min(y0, y1),+ right: Math.max(x0, x1),+ bottom: Math.max(y0, y1),+ };+}++/**+ * Next selection after clicking `id`, given the modifier keys and the current+ * visual `order` of ids (used for shift-range).+ * - meta/ctrl: toggle `id` in/out of the set.+ * - shift: select the contiguous range from the anchor to `id`.+ * - plain: select just `id`.+ * Returns `{ selected: string[], anchor: string }`; pass the returned anchor+ * back in as `anchor` on the next call.+ */+export function toggleSelection(selected, id, { shift = false, meta = false } = {}, order = [], anchor = null) {+ const set = new Set(selected);+ if (meta) {+ set.has(id) ? set.delete(id) : set.add(id);+ return { selected: [...set], anchor: id };+ }+ if (shift && anchor && order.length) {+ const a = order.indexOf(anchor);+ const b = order.indexOf(id);+ if (a !== -1 && b !== -1) {+ const [lo, hi] = a <= b ? [a, b] : [b, a];+ return { selected: order.slice(lo, hi + 1), anchor };+ }+ }+ return { selected: [id], anchor: id };+}diff --git a/frontend/src/lib/gridSelect.test.js b/frontend/src/lib/gridSelect.test.jsnew file mode 100644index 0000000..f2dc9f2--- /dev/null+++ b/frontend/src/lib/gridSelect.test.js@@ -0,0 +1,78 @@+import { describe, it, expect } from 'vitest';+import { marqueeHits, marqueeRect, toggleSelection } from './gridSelect.js';++const rect = (id, left, top, right, bottom) => ({ id, left, top, right, bottom });++describe('marqueeRect', () => {+ it('normalizes either drag direction into a positive rect', () => {+ expect(marqueeRect(30, 40, 10, 20)).toEqual({ left: 10, top: 20, right: 30, bottom: 40 });+ expect(marqueeRect(10, 20, 30, 40)).toEqual({ left: 10, top: 20, right: 30, bottom: 40 });+ });+});++describe('marqueeHits', () => {+ const tiles = [+ rect('a', 0, 0, 50, 50),+ rect('b', 60, 0, 110, 50),+ rect('c', 0, 60, 50, 110),+ ];++ it('selects tiles the marquee overlaps', () => {+ expect(marqueeHits(tiles, marqueeRect(10, 10, 70, 10 + 1))).toEqual(['a', 'b']);+ });++ it('counts edge contact as a hit', () => {+ // marquee's right edge just touches tile b's left edge (x=60); it starts+ // past tile a's right edge (x=50), so only b is grazed+ expect(marqueeHits(tiles, { left: 55, top: 0, right: 60, bottom: 40 })).toEqual(['b']);+ });++ it('a zero-area marquee (a plain click) selects nothing', () => {+ expect(marqueeHits(tiles, { left: 10, top: 10, right: 10, bottom: 10 })).toEqual([]);+ });++ it('returns nothing when the marquee misses every tile', () => {+ expect(marqueeHits(tiles, marqueeRect(200, 200, 260, 260))).toEqual([]);+ });+});++describe('toggleSelection', () => {+ const order = ['a', 'b', 'c', 'd'];++ it('plain click selects just that id and anchors it', () => {+ expect(toggleSelection(['a', 'b'], 'c', {}, order, 'a')).toEqual({+ selected: ['c'],+ anchor: 'c',+ });+ });++ it('meta-click toggles one in and out, keeping the rest', () => {+ expect(toggleSelection(['a'], 'b', { meta: true }, order, 'a')).toEqual({+ selected: ['a', 'b'],+ anchor: 'b',+ });+ expect(toggleSelection(['a', 'b'], 'b', { meta: true }, order, 'a').selected).toEqual(['a']);+ });++ it('shift-click selects the contiguous range from the anchor', () => {+ expect(toggleSelection(['b'], 'd', { shift: true }, order, 'b')).toEqual({+ selected: ['b', 'c', 'd'],+ anchor: 'b',+ });+ });++ it('shift-click works when the target sits before the anchor', () => {+ expect(toggleSelection(['c'], 'a', { shift: true }, order, 'c').selected).toEqual([+ 'a',+ 'b',+ 'c',+ ]);+ });++ it('shift with no anchor falls back to a plain single select', () => {+ expect(toggleSelection([], 'c', { shift: true }, order, null)).toEqual({+ selected: ['c'],+ anchor: 'c',+ });+ });+});diff --git a/frontend/src/lib/navigate.js b/frontend/src/lib/navigate.jsnew file mode 100644index 0000000..ea7b2bb--- /dev/null+++ b/frontend/src/lib/navigate.js@@ -0,0 +1,76 @@+/**+ * Opening a saved artifact back in its tool — the "navigation follows the+ * object" glue (docs/UI.md). Every jump is a cross-tool handoff written onto+ * uiState; the target tool consumes it on mount. Shared so the case sidebar and+ * the Details editor send an analyst to the same place.+ */+import { uiState } from './state.svelte.js';++/** Tool a given entity type opens in (also gates the "Open in tool" button). */+export const ENTITY_TOOL = {+ media: 'media',+ proof: 'proof',+ place: 'satellite',+ post: 'post',+ 'inspect-session': 'inspect',+};++/** Reopen an artifact in its tool, loading whatever spec/draft it carries. */+export function openEntity(entity) {+ if (entity.type === 'proof') {+ const spec = entity.attrs?.spec ?? '';+ const name = spec.replace(/^proofs\//, '').replace(/\.json$/, '');+ if (name) uiState.openProof = name;+ uiState.tool = 'proof';+ return;+ }+ if (entity.type === 'post') {+ const draft = entity.attrs?.draft ?? '';+ const name = draft.replace(/^exports\//, '').replace(/\.json$/, '');+ if (name) uiState.openDraft = name;+ uiState.tool = 'post';+ return;+ }+ if (entity.type === 'inspect-session') {+ const spec = entity.attrs?.spec ?? '';+ const name = spec.replace(/^inspect\//, '').replace(/\.json$/, '');+ if (name) uiState.openInspect = name;+ uiState.tool = 'inspect';+ return;+ }+ if (entity.type === 'place') {+ const lat = Number(entity.attrs?.lat);+ const lon = Number(entity.attrs?.lon);+ if (Number.isFinite(lat) && Number.isFinite(lon)) {+ uiState.gotoCoords = {+ lat,+ lon,+ zoom: Number(entity.attrs?.zoom),+ bearing: Number(entity.attrs?.bearing),+ };+ }+ uiState.tool = 'satellite';+ return;+ }+ if (entity.type === 'media') {+ if (entity.attrs?.path) uiState.focusMedia = entity.attrs.path;+ uiState.tool = 'media';+ return;+ }+ const tool = ENTITY_TOOL[entity.type];+ if (tool) uiState.tool = tool;+}++/** Fly the Satellite map to a capture's recorded coordinates (its marker). */+export function gotoCapture(entity) {+ const lat = Number(entity.attrs?.lat);+ const lon = Number(entity.attrs?.lon);+ if (!Number.isFinite(lat) || !Number.isFinite(lon)) return;+ uiState.gotoCoords = {+ lat,+ lon,+ zoom: Number(entity.attrs?.zoom),+ bearing: Number(entity.attrs?.bearing),+ };+ uiState.tool = 'satellite';+}diff --git a/frontend/src/lib/notes.js b/frontend/src/lib/notes.jsnew file mode 100644index 0000000..bc74db5--- /dev/null+++ b/frontend/src/lib/notes.js@@ -0,0 +1,19 @@+/**+ * Creating a note entity. A note is just an entity of type `note` whose body+ * lives in `attrs.content`; `attrs.folder` files it into a My-work folder+ * (''=unfiled). Lifted out of the case sidebar so the desktop organizer's+ * right-click menu can create notes the same way.+ *+ * Does not reload the case: the caller refetches once it returns.+ */+import { api } from './api.js';++export async function createNote(caseId, { title, folder = '', content = '' }) {+ const label = (title ?? '').trim();+ if (!label) throw new Error('Title required');+ await api.post(`/api/cases/${caseId}/entities`, {+ type: 'note',+ label,+ attrs: { content: content ?? '', folder: (folder ?? '').trim() },+ });+}diff --git a/frontend/src/lib/notes.test.js b/frontend/src/lib/notes.test.jsnew file mode 100644index 0000000..90d33eb--- /dev/null+++ b/frontend/src/lib/notes.test.js@@ -0,0 +1,41 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { api } from './api.js';+import { createNote } from './notes.js';++vi.mock('./api.js', () => ({ api: { post: vi.fn(async () => ({})) } }));++beforeEach(() => api.post.mockClear());++describe('createNote', () => {+ it('posts a note entity with content and filing folder', async () => {+ await createNote('case-1', { title: 'Lead', folder: 'Research', content: 'body' });+ expect(api.post).toHaveBeenCalledWith('/api/cases/case-1/entities', {+ type: 'note',+ label: 'Lead',+ attrs: { content: 'body', folder: 'Research' },+ });+ });++ it('trims the title and folder, and defaults content to empty', async () => {+ await createNote('case-1', { title: ' Lead ', folder: ' Research ' });+ expect(api.post).toHaveBeenCalledWith('/api/cases/case-1/entities', {+ type: 'note',+ label: 'Lead',+ attrs: { content: '', folder: 'Research' },+ });+ });++ it('leaves the note unfiled when no folder is given', async () => {+ await createNote('case-1', { title: 'Lead' });+ expect(api.post).toHaveBeenCalledWith('/api/cases/case-1/entities', {+ type: 'note',+ label: 'Lead',+ attrs: { content: '', folder: '' },+ });+ });++ it('rejects a blank title without hitting the API', async () => {+ await expect(createNote('case-1', { title: ' ' })).rejects.toThrow('Title required');+ expect(api.post).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/lib/workspaces.js b/frontend/src/lib/workspaces.jsindex 35e5a75..70be87c 100644--- a/frontend/src/lib/workspaces.js+++ b/frontend/src/lib/workspaces.js@@ -10,7 +10,7 @@* layer (today the case sidebar covers it).*/export const WORKSPACES = [- { id: 'collect', label: 'Collect', icon: 'download', tools: ['media'] },+ { id: 'collect', label: 'Collect', icon: 'download', tools: ['media', 'files'] },{ id: 'examine', label: 'Examine', icon: 'inspect', tools: ['inspect'] },{ id: 'map', label: 'Map', icon: 'satellite', tools: ['satellite'] },{ id: 'compose', label: 'Compose', icon: 'proof', tools: ['proof', 'post'] },diff --git a/frontend/src/lib/workspaces.test.js b/frontend/src/lib/workspaces.test.jsindex c871995..d8132be 100644--- a/frontend/src/lib/workspaces.test.js+++ b/frontend/src/lib/workspaces.test.js@@ -1,17 +1,22 @@import { describe, it, expect } from 'vitest';import { WORKSPACES, workspaceOf, toolFromHash } from './workspaces.js';-const ALL_TOOLS = ['media', 'inspect', 'satellite', 'proof', 'post', 'settings'];+const ALL_TOOLS = ['media', 'files', 'inspect', 'satellite', 'proof', 'post', 'settings'];describe('workspaceOf', () => {it('maps every rail tool to exactly one workspace', () => {- for (const tool of ['media', 'inspect', 'satellite', 'proof', 'post']) {+ for (const tool of ['media', 'files', 'inspect', 'satellite', 'proof', 'post']) {const owners = WORKSPACES.filter((w) => w.tools.includes(tool));expect(owners).toHaveLength(1);expect(workspaceOf(tool)).toBe(owners[0]);}});+ it('groups media and files under collect', () => {+ expect(workspaceOf('media').id).toBe('collect');+ expect(workspaceOf('files').id).toBe('collect');+ });+it('groups proof and post under compose', () => {expect(workspaceOf('proof').id).toBe('compose');expect(workspaceOf('post').id).toBe('compose');@@ -38,6 +43,7 @@ describe('toolFromHash', () => {it('accepts workspace/tab form', () => {expect(toolFromHash('#compose/post', ALL_TOOLS)).toBe('post');expect(toolFromHash('#compose/proof', ALL_TOOLS)).toBe('proof');+ expect(toolFromHash('#collect/files', ALL_TOOLS)).toBe('files');});it('falls back to the first tool on an unknown tab', () => {diff --git a/frontend/src/tools/Files.svelte b/frontend/src/tools/Files.sveltenew file mode 100644index 0000000..b030b82--- /dev/null+++ b/frontend/src/tools/Files.svelte@@ -0,0 +1,1173 @@+<script>+ /**+ * Files — the desktop view of My work. The case sidebar's folder tree, opened+ * up into a Finder-style surface: navigate folders, rubber-band-select several+ * items at once, and drag the lot into a folder. Reads every saved artifact+ * (media, captures, notes, proofs, posts, places, sessions), not just media.+ *+ * The tree and the filing routing are the sidebar's own (lib/folderTree.js,+ * lib/filing.js); the selection math is pure and unit-tested (lib/gridSelect.js).+ */+ import { api } from '../lib/api.js';+ import { caseState, reloadCase, toast } from '../lib/state.svelte.js';+ import { buildTree, subtreeCount, folderOf, flattenPaths } from '../lib/folderTree.js';+ import { assignFolderBatch } from '../lib/filing.js';+ import { createNote } from '../lib/notes.js';+ import { createBookmark } from '../lib/bookmarks.js';+ import { marqueeRect, marqueeHits, toggleSelection } from '../lib/gridSelect.js';+ import { deletePlan } from '../lib/chain.js';+ import Icon from '../components/Icon.svelte';+ import Modal from '../components/Modal.svelte';+ import ConfirmDialog from '../components/ConfirmDialog.svelte';+ import EntityDetails from '../components/EntityDetails.svelte';++ const TYPE_ICON = {+ media: 'image', capture: 'satellite', note: 'note', proof: 'proof',+ post: 'post', place: 'pin', 'inspect-session': 'inspect', bookmark: 'link',+ };+ const VIDEO_EXTS = new Set(['mp4', 'mov', 'webm', 'mkv', 'avi', 'm4v']);+ // Entity types backed by a file on disk — deleting them drops the file too.+ const FILE_BACKED = new Set(['media', 'capture', 'proof', 'post', 'inspect-session']);++ // ── case data ──────────────────────────────────────────────────────────────+ const confirmed = $derived(+ (caseState.current?.entities ?? []).filter((e) => e.provenance?.status !== 'suggested')+ );+ const links = $derived(caseState.current?.links ?? []);+ const tree = $derived(buildTree(caseState.current?.folders ?? [], confirmed));+ const allFolders = $derived(flattenPaths(tree));+ const unfiled = $derived(confirmed.filter((e) => !folderOf(e)));++ // Thumbnails: the media + satellite shelves, indexed by path. Same lists the+ // Media Library reads — a local call to our own backend, nothing external.+ let pathInfo = $state(new Map());+ $effect(() => {+ const id = caseState.current?.id;+ caseState.rev; // refetch after a save/move elsewhere+ if (!id) {+ pathInfo = new Map();+ return;+ }+ loadThumbs(id);+ });+ async function loadThumbs(id) {+ try {+ const [media, sat] = await Promise.all([+ api.get(`/api/cases/${id}/media`),+ api.get(`/api/cases/${id}/satellite`),+ ]);+ const m = new Map();+ for (const it of [...media, ...sat]) m.set(it.path, { thumbnail: it.thumbnail, kind: it.kind });+ pathInfo = m;+ } catch {+ pathInfo = new Map();+ }+ }++ function tileIcon(e) {+ if (e.type === 'media') {+ const kind = pathInfo.get(e.attrs?.path)?.kind;+ if (kind === 'video') return 'video';+ const ext = e.attrs?.path?.split('.').pop()?.toLowerCase();+ if (ext && VIDEO_EXTS.has(ext)) return 'video';+ }+ return TYPE_ICON[e.type] ?? 'file';+ }+ const tileThumb = (e) => pathInfo.get(e.attrs?.path)?.thumbnail ?? null;++ // ── navigation ──────────────────────────────────────────────────────────────+ let cwd = $state(''); // '' = root ("All")+ let showUnfiled = $state(false);++ function nodeAt(path) {+ if (!path) return { path: '', children: tree, entities: [] };+ let nodes = tree,+ node = null;+ for (const seg of path.split('/')) {+ node = nodes.find((n) => n.name === seg);+ if (!node) return { path, children: [], entities: [] };+ nodes = node.children;+ }+ return node;+ }++ // free-text search spans the whole of My work, not just the open folder+ let query = $state('');+ const searching = $derived(!!query.trim());+ function matches(e) {+ const q = query.trim().toLowerCase();+ return (+ (e.label ?? '').toLowerCase().includes(q) ||+ e.type.toLowerCase().includes(q) ||+ (folderOf(e) ?? '').toLowerCase().includes(q)+ );+ }++ const current = $derived(showUnfiled ? { path: '', children: [], entities: unfiled } : nodeAt(cwd));+ const curFolders = $derived(searching ? [] : current.children);+ const curEntities = $derived(searching ? confirmed.filter(matches) : current.entities);+ const entityOrder = $derived(curEntities.map((e) => e.id));+ const crumbs = $derived(cwd ? cwd.split('/') : []);+ // the Unfiled bucket shows as a tile at the root, even when empty (drop here+ // 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);++ function openFolder(path) {+ showUnfiled = false;+ cwd = path;+ }+ function openUnfiled() {+ showUnfiled = true;+ }++ // ── selection ────────────────────────────────────────────────────────────────+ let selected = $state([]);+ let anchor = null;+ // clear the selection whenever the view changes+ $effect(() => {+ cwd;+ showUnfiled;+ query;+ selected = [];+ anchor = null;+ });++ function onTileClick(e, id) {+ const r = toggleSelection(selected, id, { shift: e.shiftKey, meta: e.metaKey || e.ctrlKey }, entityOrder, anchor);+ selected = r.selected;+ anchor = r.anchor;+ }++ // ── marquee (rubber-band) ─────────────────────────────────────────────────────+ let gridEl = $state(null);+ let marquee = $state(null); // {left, top, width, height} in the grid's content space++ function onGridPointerDown(e) {+ if (e.button !== 0 || e.target.closest('.tile')) return;+ const rect = gridEl.getBoundingClientRect();+ const additive = e.shiftKey || e.metaKey || e.ctrlKey;+ const base = additive ? [...selected] : [];+ if (!additive) {+ selected = [];+ anchor = null;+ }+ const at = (ev) => ({+ x: ev.clientX - rect.left + gridEl.scrollLeft,+ y: ev.clientY - rect.top + gridEl.scrollTop,+ });+ const start = at(e);+ const move = (ev) => {+ const cur = at(ev);+ const mr = marqueeRect(start.x, start.y, cur.x, cur.y);+ marquee = { left: mr.left, top: mr.top, width: mr.right - mr.left, height: mr.bottom - mr.top };+ selected = [...new Set([...base, ...marqueeHits(tileRects(rect), mr)])];+ };+ const up = () => {+ marquee = null;+ window.removeEventListener('pointermove', move);+ window.removeEventListener('pointerup', up);+ };+ window.addEventListener('pointermove', move);+ window.addEventListener('pointerup', up);+ }++ function tileRects(gridRect) {+ return [...gridEl.querySelectorAll('.tile.entity')].map((el) => {+ const r = el.getBoundingClientRect();+ return {+ id: el.dataset.id,+ left: r.left - gridRect.left + gridEl.scrollLeft,+ top: r.top - gridRect.top + gridEl.scrollTop,+ right: r.right - gridRect.left + gridEl.scrollLeft,+ bottom: r.bottom - gridRect.top + gridEl.scrollTop,+ };+ });+ }++ // ── drag to move ──────────────────────────────────────────────────────────────+ let draggingIds = $state([]);+ const UNFILED = Symbol('unfiled'); // drop-target marker for the Unfiled bucket+ let dropTarget = $state(null); // a folder path, UNFILED, or '' for unfile++ function onTileDragStart(ev, id) {+ if (!selected.includes(id)) {+ selected = [id];+ anchor = id;+ }+ draggingIds = [...selected];+ ev.dataTransfer.effectAllowed = 'move';+ ev.dataTransfer.setData('text/plain', draggingIds.join(','));+ }++ async function dropInto(folder) {+ const ids = draggingIds;+ draggingIds = [];+ dropTarget = null;+ if (!ids.length) return;+ const ents = confirmed.filter((e) => ids.includes(e.id));+ // no-op when dropped on the folder they already sit in+ if (ents.every((e) => (folderOf(e) ?? '') === folder)) return;+ try {+ await assignFolderBatch(caseState.current.id, ents, folder);+ await reloadCase();+ selected = [];+ toast(`Moved ${ents.length} item${ents.length > 1 ? 's' : ''}`, 'ok', 1600);+ } catch (e) {+ toast(e.message, 'danger');+ }+ }++ // ── folders ────────────────────────────────────────────────────────────────+ let newFolder = $state('');+ // create `leaf` under `parent` ('' = top level)+ async function createFolderAt(parent, leaf) {+ const name = (parent ? `${parent}/` : '') + leaf.trim();+ try {+ await api.post(`/api/cases/${caseState.current.id}/folders`, { name });+ await reloadCase();+ } catch (e) {+ toast(e.message, 'danger');+ }+ }+ function createFolder() {+ const leaf = newFolder.trim();+ if (!leaf) return;+ newFolder = '';+ createFolderAt(searching || 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.+ 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',+ 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 = '';+ },+ };+ }++ // ── delete (irreversible; spells out what it touches) ─────────────────────+ let confirmState = $state(null); // { title, message, detail, consequences, confirmLabel, tone, icon, action }+ let confirmBusy = $state(false);++ async function runConfirm() {+ const s = confirmState;+ if (!s) return;+ confirmBusy = true;+ try {+ await s.action();+ } catch (e) {+ toast(e.message, 'danger');+ } finally {+ confirmBusy = false;+ confirmState = null;+ }+ }++ function askDeleteEntities(ids) {+ const ents = confirmed.filter((e) => ids.includes(e.id));+ if (!ents.length) return;+ const multi = ents.length > 1;+ confirmState = {+ title: multi ? `Delete ${ents.length} items?` : 'Delete everywhere?',+ message: multi+ ? `${ents.length} items will be removed from the case and their tools.`+ : `“${ents[0].label}” will be removed from the case and its tool.`,+ detail: ents.some((e) => FILE_BACKED.has(e.type))+ ? 'This permanently deletes the underlying file(s) on disk — it cannot be undone.'+ : 'This permanently removes it from the case — it cannot be undone.',+ consequences: multi ? null : deletePlan(confirmed, links, ents[0].id),+ confirmLabel: multi ? 'Delete all' : 'Delete everywhere',+ tone: 'danger',+ icon: 'trash',+ action: async () => {+ for (const e of ents) await api.del(`/api/cases/${caseState.current.id}/entities/${e.id}`);+ await reloadCase();+ selected = [];+ toast(multi ? `Deleted ${ents.length} items` : `Deleted “${ents[0].label}”`, 'info');+ },+ };+ }++ // 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 }+ let ctxName = $state('');+ function openCtx(e, parent, isFolder = false) {+ e.preventDefault();+ e.stopPropagation();+ ctx = { x: e.clientX, y: e.clientY, parent, mode: 'menu', isFolder };+ ctxName = '';+ }+ function ctxNewFolder() {+ ctx = { ...ctx, mode: 'folder' };+ ctxName = '';+ }+ 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 ?? '';+ ctx = null;+ openNewBookmark(parent);+ }++ function ctxDeleteFolder() {+ const path = ctx?.parent;+ ctx = null;+ if (path) askDeleteFolder(path);+ }++ // right-click on a file tile: select it (unless it's part of the current+ // selection already) and open the file-specific menu instead.+ function openEntityCtx(e, entity) {+ e.preventDefault();+ e.stopPropagation();+ if (!selected.includes(entity.id)) {+ selected = [entity.id];+ anchor = entity.id;+ }+ ctx = { x: e.clientX, y: e.clientY, kind: 'entity', ids: [...selected] };+ }+ 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);+ }++ // ── notes ────────────────────────────────────────────────────────────────+ let noteModal = $state(null); // { folder, title, content }+ let noteSaving = $state(false);+ function openNewNote(folder) {+ noteModal = { folder: folder ?? '', title: '', content: '' };+ }+ async function saveNote() {+ if (!noteModal || !noteModal.title.trim()) {+ toast('Title required', 'warn');+ return;+ }+ noteSaving = true;+ try {+ await createNote(caseState.current.id, noteModal);+ await reloadCase();+ toast('Note created', 'ok', 1600);+ noteModal = null;+ } catch (e) {+ toast(e.message, 'danger');+ } finally {+ noteSaving = false;+ }+ }++ // ── bookmarks ────────────────────────────────────────────────────────────+ let bookmarkModal = $state(null); // { folder, title, url, notes }+ let bookmarkSaving = $state(false);+ function openNewBookmark(folder) {+ bookmarkModal = { folder: folder ?? '', title: '', url: '', notes: '' };+ }+ async function saveBookmark() {+ if (!bookmarkModal) return;+ bookmarkSaving = true;+ try {+ await createBookmark(caseState.current.id, bookmarkModal);+ await reloadCase();+ toast('Bookmark saved', 'ok', 1600);+ bookmarkModal = null;+ } catch (e) {+ toast(e.message, 'danger');+ } finally {+ bookmarkSaving = false;+ }+ }++ // ── tree rail ────────────────────────────────────────────────────────────────+ let expanded = $state({});+ const isExpanded = (p) => expanded[p] === true;+ function toggle(p) {+ expanded[p] = !isExpanded(p);+ }++ // ── details ────────────────────────────────────────────────────────────────+ let infoEntityId = $state(null);+ let dense = $state(true); // small thumbnails by default — this view's whole point+</script>++<div class="tool">+ <div class="tool-header">+ <h2>Files</h2>+ <span class="sub">Organize My work</span>+ <div class="spacer"></div>+ <div class="search-box">+ <Icon name="search" size={13} />+ <input class="search-input" placeholder="Search My work…" bind:value={query} />+ {#if query}+ <button class="search-clear" onclick={() => (query = '')} aria-label="Clear search">+ <Icon name="x" size={12} />+ </button>+ {/if}+ </div>+ <button+ class="btn btn-ghost btn-sm"+ title={dense ? 'Larger thumbnails' : 'Smaller thumbnails'}+ onclick={() => (dense = !dense)}+ >+ <Icon name="grip" size={15} /> {dense ? 'Small' : 'Large'}+ </button>+ <form class="new-folder" onsubmit={(e) => { e.preventDefault(); createFolder(); }}>+ <input class="input" placeholder="New folder…" bind:value={newFolder} />+ <button class="btn" type="submit" disabled={!newFolder.trim()}>+ <Icon name="folder" size={14} /> Add+ </button>+ </form>+ </div>++ {#if !caseState.current}+ <div class="empty" style="height: 100%">+ <div class="empty-icon"><Icon name="folder" size={42} /></div>+ <h3>No case open</h3>+ <p>Create or open a case to organize its files.</p>+ </div>+ {:else}+ <div class="workbench">+ <!-- left: folder tree (navigation + drop targets) -->+ <aside class="tree-rail">+ <div+ class="trow"+ class:active={cwd === '' && !showUnfiled}+ class:dropping={dropTarget === ''}+ role="button"+ tabindex="0"+ onclick={() => openFolder('')}+ onkeydown={(e) => e.key === 'Enter' && openFolder('')}+ oncontextmenu={(e) => openCtx(e, '')}+ ondragover={(e) => { e.preventDefault(); dropTarget = ''; }}+ ondragleave={() => (dropTarget = dropTarget === '' ? null : dropTarget)}+ ondrop={(e) => { e.preventDefault(); dropInto(''); }}+ >+ <Icon name="layers" size={14} />+ <span class="tname">All</span>+ <span class="tcount">{confirmed.length}</span>+ </div>++ {#each tree as node (node.path)}+ {@render treeNode(node, 0)}+ {/each}++ <!-- Unfiled stays even when empty: a place to drop files back into -->+ <div+ class="trow"+ class:active={showUnfiled}+ class:dropping={dropTarget === UNFILED}+ role="button"+ tabindex="0"+ onclick={openUnfiled}+ onkeydown={(e) => e.key === 'Enter' && openUnfiled()}+ ondragover={(e) => { e.preventDefault(); dropTarget = UNFILED; }}+ ondragleave={() => (dropTarget = dropTarget === UNFILED ? null : dropTarget)}+ ondrop={(e) => { e.preventDefault(); dropInto(''); }}+ >+ <Icon name="file" size={14} />+ <span class="tname">Unfiled</span>+ <span class="tcount">{unfiled.length}</span>+ </div>+ </aside>++ <!-- right: the desktop surface -->+ <section class="grid-pane">+ <div class="crumbs">+ <button class="crumb" onclick={() => openFolder('')}>All</button>+ {#if showUnfiled}+ <Icon name="chevronRight" size={12} />+ <span class="crumb here">Unfiled</span>+ {:else}+ {#each crumbs as seg, i (i)}+ <Icon name="chevronRight" size={12} />+ {#if i === crumbs.length - 1}+ <span class="crumb here">{seg}</span>+ {:else}+ <button class="crumb" onclick={() => openFolder(crumbs.slice(0, i + 1).join('/'))}>{seg}</button>+ {/if}+ {/each}+ {/if}+ <div class="spacer"></div>+ {#if selected.length}+ <span class="sel-count">{selected.length} selected</span>+ {/if}+ </div>++ <!-- svelte-ignore a11y_no_static_element_interactions -->+ <div+ class="grid"+ class:dense+ bind:this={gridEl}+ onpointerdown={onGridPointerDown}+ oncontextmenu={(e) => openCtx(e, ctxParent)}+ >+ {#if !showUnfiled}+ {#each curFolders as node (node.path)}+ <div+ class="tile folder"+ class:dropping={dropTarget === node.path}+ role="button"+ tabindex="0"+ title={node.name}+ ondblclick={() => openFolder(node.path)}+ onkeydown={(e) => e.key === 'Enter' && openFolder(node.path)}+ oncontextmenu={(e) => openCtx(e, node.path, true)}+ ondragover={(e) => { e.preventDefault(); dropTarget = node.path; }}+ ondragleave={() => (dropTarget = dropTarget === node.path ? null : dropTarget)}+ ondrop={(e) => { e.preventDefault(); dropInto(node.path); }}+ >+ <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>+ </div>+ {/each}++ {#if showRootUnfiled}+ <div+ class="tile folder"+ class:dropping={dropTarget === UNFILED}+ role="button"+ tabindex="0"+ title="Unfiled"+ ondblclick={openUnfiled}+ onkeydown={(e) => e.key === 'Enter' && openUnfiled()}+ ondragover={(e) => { e.preventDefault(); dropTarget = UNFILED; }}+ ondragleave={() => (dropTarget = dropTarget === UNFILED ? null : dropTarget)}+ ondrop={(e) => { e.preventDefault(); dropInto(''); }}+ >+ <div class="thumb folder-thumb unfiled"><Icon name="file" size={dense ? 26 : 38} /></div>+ <span class="tile-name">Unfiled</span>+ <span class="tile-sub">{unfiled.length} item{unfiled.length === 1 ? '' : 's'}</span>+ </div>+ {/if}+ {/if}++ {#each curEntities as e (e.id)}+ <div+ class="tile entity"+ class:selected={selected.includes(e.id)}+ data-id={e.id}+ draggable="true"+ role="button"+ tabindex="0"+ title={e.label}+ onclick={(ev) => onTileClick(ev, e.id)}+ ondblclick={() => (infoEntityId = e.id)}+ onkeydown={(ev) => ev.key === 'Enter' && (infoEntityId = e.id)}+ oncontextmenu={(ev) => openEntityCtx(ev, e)}+ ondragstart={(ev) => onTileDragStart(ev, e.id)}+ ondragend={() => { draggingIds = []; dropTarget = null; }}+ >+ <div class="thumb">+ {#if tileThumb(e)}+ <img src={`/files/${caseState.current.id}/${tileThumb(e)}`} alt={e.label} loading="lazy" />+ {:else}+ <Icon name={tileIcon(e)} size={dense ? 24 : 34} />+ {/if}+ </div>+ <span class="tile-name">{e.label}</span>+ <span class="tile-sub">{e.type}</span>+ <button+ class="tile-info btn btn-ghost btn-sm"+ title="Details"+ onclick={(ev) => { ev.stopPropagation(); infoEntityId = e.id; }}+ >+ <Icon name="note" size={13} />+ </button>+ </div>+ {/each}++ {#if !curFolders.length && !curEntities.length && !showRootUnfiled}+ <div class="grid-empty">+ <Icon name="folder" size={34} />+ <p>+ {#if searching}No files match “{query.trim()}”.+ {:else if showUnfiled}Nothing unfiled.+ {:else}This folder is empty. Drag items here, or right-click to add a subfolder or note.{/if}+ </p>+ </div>+ {/if}++ {#if marquee}+ <div+ class="marquee"+ style="left:{marquee.left}px; top:{marquee.top}px; width:{marquee.width}px; height:{marquee.height}px"+ ></div>+ {/if}+ </div>+ </section>+ </div>+ {/if}+</div>++<!-- one tree node + subtree (navigation + drop target) -->+{#snippet treeNode(node, depth)}+ <div+ class="trow"+ class:active={!showUnfiled && cwd === node.path}+ class:dropping={dropTarget === node.path}+ style="padding-left: {8 + depth * 14}px"+ role="button"+ tabindex="0"+ onclick={() => openFolder(node.path)}+ onkeydown={(e) => e.key === 'Enter' && openFolder(node.path)}+ oncontextmenu={(e) => openCtx(e, node.path, true)}+ ondragover={(e) => { e.preventDefault(); dropTarget = node.path; }}+ ondragleave={() => (dropTarget = dropTarget === node.path ? null : dropTarget)}+ ondrop={(e) => { e.preventDefault(); dropInto(node.path); }}+ >+ {#if node.children.length}+ <span+ class="tchevron"+ role="button"+ tabindex="0"+ title="Expand"+ onclick={(e) => { e.stopPropagation(); toggle(node.path); }}+ onkeydown={(e) => e.key === 'Enter' && (e.stopPropagation(), toggle(node.path))}+ >+ <Icon name={isExpanded(node.path) ? 'chevronDown' : 'chevronRight'} size={12} />+ </span>+ {:else}+ <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>+ </div>+ {#if isExpanded(node.path)}+ {#each node.children as child (child.path)}+ {@render treeNode(child, depth + 1)}+ {/each}+ {/if}+{/snippet}++<!-- right-click menu: create a folder or a note under whatever was clicked -->+{#if ctx}+ <div+ class="ctx-backdrop"+ role="presentation"+ onpointerdown={() => (ctx = null)}+ 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()}>+ {#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}>+ <Icon name="folderMinus" size={14} /> Move to Unfiled+ </button>+ {/if}+ <button class="ctx-item danger" onclick={ctxDeleteEntities}>+ <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>+ <form onsubmit={(e) => { e.preventDefault(); ctxCreate(); }}>+ <!-- svelte-ignore a11y_autofocus -->+ <input+ class="input"+ placeholder="Folder name…"+ bind:value={ctxName}+ autofocus+ onkeydown={(e) => e.key === 'Escape' && (ctx = null)}+ />+ <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+ </button>+ <button class="ctx-item" onclick={ctxNewNote}>+ <Icon name="note" size={14} /> New note+ </button>+ <button class="ctx-item" onclick={ctxNewBookmark}>+ <Icon name="link" size={14} /> New bookmark+ </button>+ {#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>+ {/if}+ {/if}+ </div>+{/if}++<!-- delete confirmation (entities or a folder) -->+{#if confirmState}+ <ConfirmDialog+ title={confirmState.title}+ message={confirmState.message}+ detail={confirmState.detail}+ consequences={confirmState.consequences}+ confirmLabel={confirmState.confirmLabel}+ tone={confirmState.tone}+ icon={confirmState.icon}+ busy={confirmBusy}+ onconfirm={runConfirm}+ oncancel={() => (confirmState = null)}+ />+{/if}++<!-- new-note modal (same shape the case sidebar uses) -->+{#if noteModal}+ <Modal title="New note" onclose={() => (noteModal = null)} width="580px">+ <label class="modal-label" for="fnote-title">Title</label>+ <input id="fnote-title" class="input" placeholder="Note title…" bind:value={noteModal.title} />++ <label class="modal-label" for="fnote-folder" style="margin-top:10px">Folder (in My work)</label>+ <input+ id="fnote-folder"+ class="input"+ placeholder="e.g. research, timeline, sources…"+ bind:value={noteModal.folder}+ list="fnote-folder-suggestions"+ />+ <datalist id="fnote-folder-suggestions">+ {#each allFolders as f (f)}<option value={f}></option>{/each}+ </datalist>++ <label class="modal-label" for="fnote-content" style="margin-top:10px">Content</label>+ <textarea+ id="fnote-content"+ class="textarea note-content"+ rows="14"+ placeholder="Write your notes in markdown…"+ bind:value={noteModal.content}+ ></textarea>++ <div class="modal-row">+ <div style="flex:1"></div>+ <button class="btn" onclick={() => (noteModal = null)}>Cancel</button>+ <button class="btn btn-primary" onclick={saveNote} disabled={noteSaving}>+ {noteSaving ? 'Saving…' : 'Create'}+ </button>+ </div>+ </Modal>+{/if}++<!-- new-bookmark modal: save a link to a web page (no screenshot) -->+{#if bookmarkModal}+ <Modal title="New bookmark" onclose={() => (bookmarkModal = null)} width="580px">+ <label class="modal-label" for="fbm-url">URL</label>+ <input id="fbm-url" class="input" placeholder="https://…" bind:value={bookmarkModal.url} />++ <label class="modal-label" for="fbm-title" style="margin-top:10px">Title</label>+ <input id="fbm-title" class="input" placeholder="Bookmark title…" bind:value={bookmarkModal.title} />++ <label class="modal-label" for="fbm-folder" style="margin-top:10px">Folder (in My work)</label>+ <input+ id="fbm-folder"+ class="input"+ placeholder="e.g. research, sources…"+ bind:value={bookmarkModal.folder}+ list="fbm-folder-suggestions"+ />+ <datalist id="fbm-folder-suggestions">+ {#each allFolders as f (f)}<option value={f}></option>{/each}+ </datalist>++ <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>++ <div class="modal-row">+ <div style="flex:1"></div>+ <button class="btn" onclick={() => (bookmarkModal = null)}>Cancel</button>+ <button class="btn btn-primary" onclick={saveBookmark} disabled={bookmarkSaving}>+ {bookmarkSaving ? 'Saving…' : 'Save'}+ </button>+ </div>+ </Modal>+{/if}++<!-- details editor: the shared body, same as the sidebar and Media modal -->+{#if infoEntityId}+ <Modal title="Details" onclose={() => (infoEntityId = null)} width="520px">+ <EntityDetails+ entityId={infoEntityId}+ onclose={() => (infoEntityId = null)}+ ondeleted={() => (infoEntityId = null)}+ />+ </Modal>+{/if}++<style>+ .spacer {+ flex: 1;+ }+ .new-folder {+ display: flex;+ gap: 6px;+ }+ .new-folder .input {+ width: 160px;+ font-size: var(--fs-sm);+ }+ .search-box {+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 4px 8px;+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ background: var(--bg-2);+ color: var(--text-3);+ }+ .search-box:focus-within {+ border-color: var(--accent);+ }+ .search-input {+ width: 160px;+ border: none;+ background: none;+ outline: none;+ color: var(--text-1);+ font-size: var(--fs-xs);+ }+ .search-clear {+ display: inline-flex;+ color: var(--text-3);+ padding: 1px;+ border-radius: 50%;+ }+ .search-clear:hover {+ color: var(--text-1);+ background: var(--bg-3);+ }++ /* right-click new-folder menu */+ .ctx-backdrop {+ position: fixed;+ inset: 0;+ z-index: 40;+ }+ .ctx-menu {+ position: fixed;+ z-index: 41;+ width: 220px;+ padding: 8px;+ background: var(--bg-1);+ border: 1px solid var(--border-strong);+ border-radius: var(--r);+ box-shadow: var(--shadow-2);+ }+ .ctx-head {+ font-size: var(--fs-xs);+ color: var(--text-3);+ margin: 2px 2px 6px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .ctx-menu form {+ display: flex;+ gap: 6px;+ }+ .ctx-menu .input {+ flex: 1;+ font-size: var(--fs-sm);+ }+ .ctx-item {+ display: flex;+ align-items: center;+ gap: 8px;+ width: 100%;+ padding: 7px 8px;+ border-radius: var(--r-sm);+ color: var(--text-1);+ font-size: var(--fs-sm);+ text-align: left;+ }+ .ctx-item:hover {+ background: var(--bg-2);+ }+ .ctx-item > :global(svg) {+ color: var(--text-3);+ flex-shrink: 0;+ }+ .ctx-item.danger {+ color: var(--danger, #e5484d);+ }+ .ctx-item.danger > :global(svg) {+ color: inherit;+ }+ .ctx-sep {+ height: 1px;+ margin: 6px 2px;+ background: var(--border);+ }++ /* new-note modal */+ .modal-label {+ display: block;+ font-size: var(--fs-xs);+ color: var(--text-3);+ margin: 8px 0 4px;+ }+ .note-content {+ width: 100%;+ resize: vertical;+ font-family: var(--font-mono);+ font-size: var(--fs-xs);+ }+ .modal-row {+ display: flex;+ align-items: center;+ gap: 8px;+ margin-top: 14px;+ }++ .workbench {+ flex: 1;+ min-height: 0;+ display: flex;+ }++ /* left tree rail */+ .tree-rail {+ width: 200px;+ flex-shrink: 0;+ border-right: 1px solid var(--border);+ background: var(--bg-1);+ overflow-y: auto;+ padding: 8px 6px;+ }+ .trow {+ display: flex;+ align-items: center;+ gap: 6px;+ width: 100%;+ padding: 6px 8px;+ border-radius: var(--r-sm);+ border: 1px solid transparent;+ color: var(--text-2);+ font-size: var(--fs-sm);+ cursor: pointer;+ text-align: left;+ }+ .trow:hover {+ background: var(--bg-2);+ }+ .trow.active {+ background: var(--bg-3);+ color: var(--text-1);+ }+ .trow.dropping {+ border-color: var(--accent);+ background: var(--accent-soft);+ }+ .trow > :global(svg) {+ color: var(--text-3);+ flex-shrink: 0;+ }+ .tchevron {+ display: flex;+ width: 12px;+ flex-shrink: 0;+ color: var(--text-3);+ }+ .tchevron.spacer-icon {+ width: 12px;+ }+ .tname {+ flex: 1;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .tcount {+ color: var(--text-3);+ font-size: var(--fs-xs);+ font-weight: 600;+ }++ /* right desktop surface */+ .grid-pane {+ flex: 1;+ min-width: 0;+ display: flex;+ flex-direction: column;+ }+ .crumbs {+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 8px 16px;+ border-bottom: 1px solid var(--border);+ flex-shrink: 0;+ }+ .crumb {+ font-size: var(--fs-sm);+ color: var(--text-3);+ padding: 2px 4px;+ border-radius: var(--r-sm);+ }+ button.crumb:hover {+ color: var(--text-1);+ background: var(--bg-2);+ }+ .crumb.here {+ color: var(--text-1);+ font-weight: 600;+ }+ .crumbs > :global(svg) {+ color: var(--text-3);+ }+ .sel-count {+ font-size: var(--fs-xs);+ color: var(--accent);+ font-weight: 600;+ }++ .grid {+ position: relative;+ flex: 1;+ min-height: 0;+ overflow: auto;+ padding: 14px 16px;+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));+ gap: 12px;+ align-content: start;+ user-select: none;+ }+ .grid.dense {+ grid-template-columns: repeat(auto-fill, minmax(96px, 1fr));+ gap: 8px;+ }++ .tile {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 4px;+ padding: 8px 6px;+ border-radius: var(--r);+ border: 1px solid transparent;+ position: relative;+ cursor: pointer;+ }+ .tile:hover {+ background: var(--bg-1);+ }+ .tile.folder:hover {+ border-color: var(--border-strong);+ }+ .tile.entity.selected {+ background: var(--accent-soft);+ border-color: var(--accent);+ }+ .tile.dropping {+ border-color: var(--accent);+ background: var(--accent-soft);+ }+ .thumb {+ width: 100%;+ aspect-ratio: 1 / 1;+ border-radius: var(--r-sm);+ background: var(--bg-2);+ display: flex;+ align-items: center;+ justify-content: center;+ color: var(--text-3);+ overflow: hidden;+ }+ .grid:not(.dense) .thumb {+ aspect-ratio: 4 / 3;+ }+ .thumb img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ }+ .folder-thumb {+ background: transparent;+ color: var(--accent);+ }+ .folder-thumb.unfiled {+ color: var(--text-3);+ }+ .tile-name {+ font-size: var(--fs-xs);+ color: var(--text-1);+ max-width: 100%;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ text-align: center;+ }+ .tile-sub {+ font-size: 10px;+ color: var(--text-3);+ }+ .tile-info {+ position: absolute;+ top: 4px;+ right: 4px;+ opacity: 0;+ background: rgba(16, 16, 16, 0.6);+ backdrop-filter: blur(3px);+ }+ .tile.entity:hover .tile-info {+ opacity: 1;+ }++ .marquee {+ position: absolute;+ border: 1px solid var(--accent);+ background: var(--accent-soft);+ pointer-events: none;+ z-index: 3;+ }+ .grid-empty {+ grid-column: 1 / -1;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 10px;+ padding: 48px 0;+ color: var(--text-3);+ font-size: var(--fs-sm);+ }+</style>diff --git a/frontend/src/tools/Inspector.svelte b/frontend/src/tools/Inspector.svelteindex 5a4ecb2..bf055dc 100644--- a/frontend/src/tools/Inspector.svelte+++ b/frontend/src/tools/Inspector.svelte@@ -48,6 +48,9 @@let openedSession = $state(null);const sessionModal = $state({ open: false, mode: 'save', name: null, title: '', list: [], busy: false });let discardConfirm = $state(false);+ // openSession fetches the spec then re-renders every frame and collage node+ // one at a time — slow enough on a heavy session that the tool needs to say so.+ let sessionLoading = $state(false);// A fresh, empty collage. A session can hold several — the Collage tab edits// one at a time (session.activeCollageId) and each is saved as its own PNG.@@ -779,71 +782,76 @@}async function openSession(name) {- await ensureOps();- if (!mediaList.length) await refresh();- let spec;- try {- spec = await api.get(`/api/cases/${caseState.current.id}/inspect/sessions/${name}`);- } catch (e) {- toast(e.message, 'danger');- return;- }- resetSession();- const src = mediaList.find((m) => m.path === spec.source.path) ?? spec.source;- session.source = src;+ sessionLoading = true;+ sessionModal.open = false;try {- probeInfo = await api.get(- `/api/cases/${caseState.current.id}/inspect/probe?path=${encodeURIComponent(src.path)}`- );- } catch {- probeInfo = { kind: src.kind };- }- session.videoAdjust = spec.videoAdjust ?? adjustDefaults(videoFilters);- for (const f of spec.frames ?? []) {+ await ensureOps();+ if (!mediaList.length) await refresh();+ let spec;try {- const url = await renderUrl(f.path, f.time, []);- session.frames.push({ ...f, url });+ spec = await api.get(`/api/cases/${caseState.current.id}/inspect/sessions/${name}`);+ } catch (e) {+ toast(e.message, 'danger');+ return;+ }+ resetSession();+ const src = mediaList.find((m) => m.path === spec.source.path) ?? spec.source;+ session.source = src;+ try {+ probeInfo = await api.get(+ `/api/cases/${caseState.current.id}/inspect/probe?path=${encodeURIComponent(src.path)}`+ );} catch {- /* skip a frame whose source is gone */+ probeInfo = { kind: src.kind };}- }- session.activeFrameId = spec.activeFrameId ?? session.frames[0]?.id ?? null;- // Back-compat: older sessions stored a single `collage`; newer ones an array.- const specCollages = spec.collages ?? (spec.collage ? [spec.collage] : []);- const collages = [];- for (const sc of specCollages) {- const nodes = [];- for (const n of sc.nodes ?? []) {+ session.videoAdjust = spec.videoAdjust ?? adjustDefaults(videoFilters);+ for (const f of spec.frames ?? []) {try {- // frameOps = the snapshot without the collage crop; baseUrl feeds the- // crop editor, url is the (possibly cropped) piece shown on the canvas.- const frameOps = n.frameOps ?? n.save.ops ?? [];- const crop = n.crop ?? null;- const baseUrl = await renderUrl(n.save.path, n.save.time, frameOps);- const url = crop ? await renderUrl(n.save.path, n.save.time, n.save.ops) : baseUrl;- nodes.push({ ...n, frameOps, crop, baseUrl, url });+ const url = await renderUrl(f.path, f.time, []);+ session.frames.push({ ...f, url });} catch {- /* skip a node whose source is gone */+ /* skip a frame whose source is gone */}}- collages.push({- id: sc.id ?? uid('cl'),- name: sc.name ?? `Collage ${collages.length + 1}`,- width: sc.width ?? 1600,- height: sc.height ?? 800,- background: sc.background ?? '#12141c',- transparent: sc.transparent ?? false,- nodes,- });+ session.activeFrameId = spec.activeFrameId ?? session.frames[0]?.id ?? null;+ // Back-compat: older sessions stored a single `collage`; newer ones an array.+ const specCollages = spec.collages ?? (spec.collage ? [spec.collage] : []);+ const collages = [];+ for (const sc of specCollages) {+ const nodes = [];+ for (const n of sc.nodes ?? []) {+ try {+ // frameOps = the snapshot without the collage crop; baseUrl feeds the+ // crop editor, url is the (possibly cropped) piece shown on the canvas.+ const frameOps = n.frameOps ?? n.save.ops ?? [];+ const crop = n.crop ?? null;+ const baseUrl = await renderUrl(n.save.path, n.save.time, frameOps);+ const url = crop ? await renderUrl(n.save.path, n.save.time, n.save.ops) : baseUrl;+ nodes.push({ ...n, frameOps, crop, baseUrl, url });+ } catch {+ /* skip a node whose source is gone */+ }+ }+ collages.push({+ id: sc.id ?? uid('cl'),+ name: sc.name ?? `Collage ${collages.length + 1}`,+ width: sc.width ?? 1600,+ height: sc.height ?? 800,+ background: sc.background ?? '#12141c',+ transparent: sc.transparent ?? false,+ nodes,+ });+ }+ if (!collages.length) collages.push(makeCollage('Collage 1'));+ session.collages = collages;+ session.activeCollageId =+ collages.find((c) => c.id === spec.activeCollageId)?.id ?? collages[0].id;+ openedSession = { name, title: spec.title || name };+ activeTab = src.kind === 'video' ? 'selection' : 'frame';+ anchorCollageHistory();+ } finally {+ sessionLoading = false;}- if (!collages.length) collages.push(makeCollage('Collage 1'));- session.collages = collages;- session.activeCollageId =- collages.find((c) => c.id === spec.activeCollageId)?.id ?? collages[0].id;- openedSession = { name, title: spec.title || name };- activeTab = src.kind === 'video' ? 'selection' : 'frame';- sessionModal.open = false;- anchorCollageHistory();}function discardSession() {@@ -903,6 +911,11 @@<p>Open a case and add media to start inspecting.</p><button class="btn" onclick={() => (uiState.tool = 'media')}>Go to Media Library</button></div>+ {:else if sessionLoading}+ <div class="empty">+ <span class="spinner"></span>+ <p>Loading session…</p>+ </div>{:else if !session.source}<div class="empty"><Icon name="inspect" size={40} />@@ -1119,11 +1132,11 @@<div class="session-list">{#each sessionModal.list as s (s.name)}<div class="session-row">- <button class="session-open" onclick={() => openSession(s.name)}>+ <button class="session-open" disabled={sessionLoading} onclick={() => openSession(s.name)}><span class="session-title">{s.title}</span><span class="session-meta">{s.frames} frame{s.frames === 1 ? '' : 's'} · {s.collage} collage piece{s.collage === 1 ? '' : 's'}</span></button>- <button class="btn btn-ghost btn-xs" onclick={() => deleteSession(s.name)} aria-label="Delete session">+ <button class="btn btn-ghost btn-xs" disabled={sessionLoading} onclick={() => deleteSession(s.name)} aria-label="Delete session"><Icon name="trash" size={14} /></button></div>@@ -1179,6 +1192,19 @@max-width: 260px;font-size: var(--fs-sm);}+ .spinner {+ width: 24px;+ height: 24px;+ border: 3px solid var(--border);+ border-top-color: var(--accent);+ border-radius: 50%;+ animation: spin 0.7s linear infinite;+ }+ @keyframes spin {+ to {+ transform: rotate(360deg);+ }+ }.gone-banner {display: flex;align-items: flex-start;@@ -1419,6 +1445,10 @@.session-open:hover {border-color: var(--accent);}+ .session-open:disabled {+ opacity: 0.55;+ cursor: default;+ }.session-title {font-size: var(--fs-sm);font-weight: 600;diff --git a/frontend/src/tools/MediaLibrary.svelte b/frontend/src/tools/MediaLibrary.svelteindex 0257d3f..e5426bb 100644--- a/frontend/src/tools/MediaLibrary.svelte+++ b/frontend/src/tools/MediaLibrary.svelte@@ -5,6 +5,7 @@import Icon from '../components/Icon.svelte';import Modal from '../components/Modal.svelte';import ConfirmDialog from '../components/ConfirmDialog.svelte';+ import EntityDetails from '../components/EntityDetails.svelte';const KIND_ICONS = { image: 'image', video: 'video', audio: 'audio', file: 'file' };@@ -61,11 +62,8 @@}));- // --- info/edit modal ---- let editItem = $state(null);- let editNotes = $state('');- let editTitle = $state('');- let editSaving = $state(false);+ // --- details modal (shared EntityDetails, keyed by the file's entity id) ---+ let infoEntityId = $state(null);// --- lightbox (←/→ flips through the filtered images) ---let lightboxItem = $state(null);@@ -259,44 +257,18 @@return bytes + ' B';}- function fmtDate(iso) {- if (!iso) return '';- return iso.slice(0, 10);- }-function onDrop(e) {e.preventDefault();dragOver = false;importFiles(e.dataTransfer.files);}- // --- info modal actions ---+ // Open the shared details editor (same body as the case sidebar) for this+ // file's case entity — full provenance, derivation chain, title/notes/folder.function openInfo(item) {- editItem = item;- editNotes = item.notes ?? '';- editTitle = item.title ?? '';- }-- async function saveInfo() {- if (!editItem) return;- editSaving = true;- try {- const updated = await api.patch(`/api/cases/${caseState.current.id}/media`, {- path: editItem.path,- notes: editNotes,- title: editTitle,- });- const idx = items.findIndex((i) => i.path === editItem.path);- if (idx !== -1) items[idx] = updated;- editItem = null;- // mirror the title/notes onto the case sidebar entity live- await reloadCase();- toast('Saved', 'ok', 1600);- } catch (e) {- toast(e.message, 'danger');- } finally {- editSaving = false;- }+ const ent = (caseState.current?.entities ?? []).find((e) => e.attrs?.path === item.path);+ if (ent) infoEntityId = ent.id;+ else toast('This file has no case entity yet', 'warn');}</script>@@ -578,123 +550,15 @@</Modal>{/if}-<!-- info / edit modal -->-{#if editItem}- <Modal title={editTitle.trim() || editItem.filename} onclose={() => (editItem = null)} width="520px">- <!-- preview -->- {#if editItem.kind === 'image' && editItem.thumbnail}- <div class="modal-preview">- <img- src={`/files/${caseState.current.id}/${editItem.path}`}- alt={editItem.filename}- />- </div>- {:else if editItem.kind === 'video'}- <div class="modal-preview">- <!-- svelte-ignore a11y_media_has_caption -->- <video- src={`/files/${caseState.current.id}/${editItem.path}`}- controls- preload="metadata"- ></video>- </div>- {/if}-- <!-- metadata section -->- <div class="info-rows">- <div class="info-row">- <span class="info-label">Kind</span>- <span>{editItem.kind}</span>- </div>- <div class="info-row">- <span class="info-label">Size</span>- <span>{fmtSize(editItem.size)}</span>- </div>- <div class="info-row">- <span class="info-label">Added</span>- <span>{fmtDate(editItem.added_at)}</span>- </div>- <div class="info-row">- <span class="info-label">SHA-256</span>- <span class="mono hash" title={editItem.sha256}>{editItem.sha256}</span>- </div>- {#if editItem.source?.type === 'download'}- {#if editItem.source.title}- <div class="info-row">- <span class="info-label">Title</span>- <span>{editItem.source.title}</span>- </div>- {/if}- {#if editItem.source.uploader}- <div class="info-row">- <span class="info-label">Uploader</span>- <span>{editItem.source.uploader}</span>- </div>- {/if}- {#if editItem.source.upload_date}- <div class="info-row">- <span class="info-label">Published</span>- <span class="mono">{editItem.source.upload_date}</span>- </div>- {/if}- {#if editItem.source.duration}- <div class="info-row">- <span class="info-label">Duration</span>- <span>{editItem.source.duration}s</span>- </div>- {/if}- {#if editItem.source.webpage_url ?? editItem.source.url}- <div class="info-row">- <span class="info-label">Source</span>- <a- href={editItem.source.webpage_url ?? editItem.source.url}- target="_blank"- rel="noreferrer"- class="mono source-link"- >{editItem.source.webpage_url ?? editItem.source.url}</a>- </div>- {/if}- {#if editItem.source.description}- <div class="info-row">- <span class="info-label">Description</span>- <span class="description">{editItem.source.description}</span>- </div>- {/if}- {/if}- </div>-- <hr class="divider" />-- <!-- editable fields -->- <label class="field-label" for="edit-title">Title</label>- <input- id="edit-title"- class="input"- placeholder={editItem.filename}- bind:value={editTitle}+<!-- details modal: the same editor body as the case sidebar (provenance,+ derivation chain, title/notes/folder) so both stay in step -->+{#if infoEntityId}+ <Modal title="Details" onclose={() => (infoEntityId = null)} width="520px">+ <EntityDetails+ entityId={infoEntityId}+ onclose={() => (infoEntityId = null)}+ ondeleted={() => (infoEntityId = null)}/>-- <label class="field-label" for="edit-notes" style="margin-top: 12px;">Notes</label>- <textarea- id="edit-notes"- class="textarea"- rows="4"- placeholder="Add context, observations, links…"- bind:value={editNotes}- ></textarea>-- <div class="modal-actions">- {#if editItem.kind === 'image'}- <button class="btn btn-ghost btn-sm" onclick={() => { sendToComposer(editItem); editItem = null; }}>- <Icon name="proof" size={14} /> Send to Composer- </button>- {/if}- <div style="flex:1"></div>- <button class="btn" onclick={() => (editItem = null)}>Cancel</button>- <button class="btn btn-primary" onclick={saveInfo} disabled={editSaving}>- {editSaving ? 'Saving…' : 'Save'}- </button>- </div></Modal>{/if}@@ -1015,80 +879,7 @@background: var(--accent-soft);}- /* info modal */- .modal-preview {- border-radius: var(--r);- overflow: hidden;- background: var(--bg-2);- margin-bottom: 14px;- max-height: 260px;- display: flex;- align-items: center;- justify-content: center;- }- .modal-preview img,- .modal-preview video {- max-width: 100%;- max-height: 260px;- object-fit: contain;- display: block;- }- .info-rows {- display: flex;- flex-direction: column;- gap: 6px;- margin-bottom: 4px;- }- .info-row {- display: flex;- gap: 10px;- font-size: var(--fs-sm);- align-items: baseline;- min-width: 0;- }- .info-label {- color: var(--text-3);- font-size: var(--fs-xs);- min-width: 70px;- flex-shrink: 0;- }- .hash {- font-size: 11px;- word-break: break-all;- color: var(--text-2);- }- .source-link {- font-size: var(--fs-xs);- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;- }- .description {- flex: 1;- min-width: 0;- font-size: var(--fs-xs);- color: var(--text-2);- white-space: pre-wrap;- word-break: break-word;- max-height: 8.5em;- overflow-y: auto;- }- .divider {- border: none;- border-top: 1px solid var(--border);- margin: 14px 0 12px;- }- .field-label {- display: block;- font-size: var(--fs-xs);- color: var(--text-3);- margin-bottom: 5px;- }- .textarea {- width: 100%;- resize: vertical;- min-height: 80px;- }+ /* shared across picker + details modals */.modal-actions {display: flex;align-items: center;diff --git a/frontend/src/tools/PostComposer.svelte b/frontend/src/tools/PostComposer.svelteindex 21c4602..ff039b8 100644--- a/frontend/src/tools/PostComposer.svelte+++ b/frontend/src/tools/PostComposer.svelte@@ -1,7 +1,7 @@<script>import { api } from '../lib/api.js';import { caseState, uiState, toast, reloadCase, prefs } from '../lib/state.svelte.js';- import { proofCoordsText, proofSource } from '../lib/composer.js';+ import { proofCoordsText, proofSource, DEFAULT_PROOF_TITLE } from '../lib/composer.js';import { bidiSafe } from '../lib/bidi.js';import Icon from '../components/Icon.svelte';import Modal from '../components/Modal.svelte';@@ -79,7 +79,7 @@const p = uiState.postProof;if (!p) return;uiState.postProof = null;- description = p.title === 'Untitled proof' ? '' : (p.title ?? '');+ description = p.title === DEFAULT_PROOF_TITLE ? '' : (p.title ?? '');source = p.source ?? p.sources?.[0] ?? '';setProof(p.png ?? null);tweet1Edited = false;@@ -268,7 +268,7 @@async function pickProof(item) {setProof(item.png);proofPickerOpen = false;- if (!description.trim() && item.title && item.title !== 'Untitled proof') {+ if (!description.trim() && item.title && item.title !== DEFAULT_PROOF_TITLE) {description = item.title;}// Pull the proof's coordinates + source into the post so the fields fill in.diff --git a/frontend/src/tools/ProofComposer.svelte b/frontend/src/tools/ProofComposer.svelteindex 300dbc5..bdca37d 100644--- a/frontend/src/tools/ProofComposer.svelte+++ b/frontend/src/tools/ProofComposer.svelte@@ -16,6 +16,7 @@toSpec, newId, loadImage, orderedFeatureColors, notesFromShapes,copyShapeSpec, dedupeBySrc, isSatelliteCapture, satPanelInput, mediaPanelInput,SIG_ANCHORS, newSignature, signatureBox, signatureOffset,+ DEFAULT_PROOF_TITLE, proofSlug, uniqueProofTitle,} from '../lib/composer.js';import { createHistory } from '../lib/history.js';@@ -37,7 +38,7 @@// `notes` holds the legend text per color (annotations are written by color,// not per element); `shapes` are the drawn geometry bound to a panel.const proof = $state({- title: 'Untitled proof', panels: [], shapes: [], notes: {}, legendOrder: [],+ title: DEFAULT_PROOF_TITLE, panels: [], shapes: [], notes: {}, legendOrder: [],coordsText: '', source: '', // '' → auto-derived from panels; non-empty → manual overridecaptionSize: CAPTION_SIZE, legendSize: LEGEND_SIZE, footerSize: FOOTER_SIZE, footer: '',layout: 'grid', // 'grid' (rows) | 'free' (drag panels anywhere, overlap allowed)@@ -59,6 +60,10 @@let advancedOpen = $state(false);let collapsed = $state({ panels: false, annotations: false, elements: false });let savedName = $state(null);+ // Whether the analyst edited the title on this document (vs the auto-assigned+ // default). An untouched default renumbers on a name clash; a title they typed+ // asks before overwriting an existing proof. Reset on open/discard.+ let titleTouched = $state(false);let dirty = $state(false);// Kept in step with deletes made anywhere else in the app. If the saved proof@@ -134,7 +139,7 @@const spec = JSON.parse(json);histBusy = true;if (pathDraft) finishPath(false);- proof.title = spec.title ?? 'Untitled proof';+ proof.title = spec.title ?? DEFAULT_PROOF_TITLE;proof.coordsText = spec.coordsText ?? '';proof.source = spec.source ?? '';proof.captionSize = spec.captionSize ?? CAPTION_SIZE;@@ -291,7 +296,7 @@docSize(proof.panels, proof.shapes, proof.notes, textOpts(), proof.legendOrder, proof.layout);function resetDoc() {- proof.title = 'Untitled proof';+ proof.title = freshTitle();proof.panels = [];proof.shapes = [];proof.notes = {};@@ -305,6 +310,7 @@proof.layout = 'grid';proof.signature = null;savedName = null;+ titleTouched = false;selectedId = null;selectedPanelId = null;dirty = false;@@ -1492,14 +1498,57 @@}}+ // Every proof already saved in this case, read off the filed entities: the+ // slugs (filename without `proofs/….json`) to catch a filename collision, and+ // the titles so a fresh proof can take a title that reads apart from them.+ function savedProofEntities() {+ return (caseState.current?.entities ?? []).filter((e) => {+ const s = e.attrs?.spec;+ return typeof s === 'string' && s.startsWith('proofs/') && s.endsWith('.json');+ });+ }+ const savedProofNames = () =>+ new Set(savedProofEntities().map((e) => e.attrs.spec.slice(7, -5)));+ const savedProofTitles = () => new Set(savedProofEntities().map((e) => e.label ?? ''));++ // Title of a saved proof by its slug, for the overwrite prompt.+ function savedProofTitle(name) {+ const e = savedProofEntities().find((x) => x.attrs.spec === `proofs/${name}.json`);+ return e?.label ?? name;+ }++ // Default title for a fresh proof, numbered past any already in the case so+ // the top-of-screen name reads apart ("Untitled proof 2"). Called on reset.+ const freshTitle = () => uniqueProofTitle(DEFAULT_PROOF_TITLE, savedProofTitles());++ let overwritePrompt = $state(null); // { name, andPost } when a first save hits a named proof+async function save({ andPost = false } = {}) {+ if (!proof.panels.length || saving) return;+ // A proof already bound to a saved name (opened, or saved once) writes back+ // over itself — no collision to resolve. On a first save the title is the+ // name: an untouched default title keeps itself unique/numbered (no prompt),+ // a title the analyst typed that lands on an existing proof asks before it+ // overwrites the one already under that name.+ if (!savedName) {+ if (!titleTouched) {+ proof.title = freshTitle();+ } else if (savedProofNames().has(proofSlug(proof.title))) {+ overwritePrompt = { name: proofSlug(proof.title), andPost };+ return;+ }+ }+ return performSave(savedName, andPost);+ }++ async function performSave(name, andPost = false) {if (!proof.panels.length || saving) return;saving = true;try {const c = await ensureCase();const dataUrl = exportPng();const result = await api.post(`/api/cases/${c.id}/proofs`, {- name: savedName,+ name,title: proof.title,spec: toSpec(proof),png_base64: dataUrl.split(',')[1],@@ -1545,6 +1594,10 @@async function openProof(entry) {const spec = await api.get(`/api/cases/${caseState.current.id}/proofs/${entry.name}`);resetDoc();+ // Bind the opened proof's name up front, before the panel images load: they+ // stream in one by one and enable the Save button as they arrive, so a Save+ // during the load has to write back over this proof, not file a new one.+ savedName = entry.name;proof.title = spec.title;proof.coordsText = spec.coordsText ?? '';proof.source = spec.source ?? '';@@ -1568,7 +1621,6 @@// legend text lives in `notes` (per color); migrate old per-shape commentsproof.notes = spec.notes ?? notesFromShapes(proof.shapes);proof.legendOrder = spec.legendOrder ?? [];- savedName = entry.name;openList = null;dirty = false;anchorHistory();@@ -1605,7 +1657,11 @@<div class="tool"><div class="tool-header"><h2>Proof Composer</h2>- <input class="input title-input" bind:value={proof.title} onchange={() => (dirty = true)} />+ <input+ class="input title-input"+ bind:value={proof.title}+ oninput={() => { dirty = true; titleTouched = true; }}+ />{#if dirty}<span class="badge">unsaved</span>{/if}<div class="spacer"></div>{#if caseState.current}@@ -2098,6 +2154,23 @@/>{/if}+{#if overwritePrompt}+ <ConfirmDialog+ title="Overwrite this proof?"+ message={`“${savedProofTitle(overwritePrompt.name)}” is already saved in this case.`}+ detail="Saving replaces its PNG and editable spec. Rename this proof to keep both."+ confirmLabel="Overwrite"+ tone="danger"+ icon="check"+ onconfirm={() => {+ const p = overwritePrompt;+ overwritePrompt = null;+ performSave(p.name, p.andPost);+ }}+ oncancel={() => (overwritePrompt = null)}+ />+{/if}+{#if deleteEntry}<ConfirmDialogtitle="Delete this proof?"diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelteindex 3c0266c..86da1ca 100644--- a/frontend/src/tools/Satellite.svelte+++ b/frontend/src/tools/Satellite.svelte@@ -1325,8 +1325,9 @@// One-click grab of the whole map view into the dialog's preview: the same// extension frame as a framed capture, minus the crop, at native resolution.- // The preview is what lets the user judge it before filing. Only offered- // when the extension is present — without it the dialog is paste/drop only.+ // The preview is what lets the user judge it before filing. The dialog itself+ // is only reachable with the extension present (no extension → the gate points+ // at Settings instead), so this grab is always available here.let shotGrabbing = $state(false);async function shotGrab() {if (shotGrabbing) return;@@ -2186,21 +2187,38 @@<div class="menu-row"><span class="menu-label">Source</span><div class="chips">- <button- class="chip"- onclick={() => {- sizeMenuOpen = false;- shotOpen = true;- }}- >- Paste a screenshot…- </button>+ {#if extensionVersion()}+ <button+ class="chip"+ onclick={() => {+ sizeMenuOpen = false;+ shotOpen = true;+ }}+ >+ Paste a screenshot…+ </button>+ {:else}+ <button+ class="chip"+ onclick={() => {+ sizeMenuOpen = false;+ extGateOpen = true;+ }}+ >+ Get the capture extension+ </button>+ {/if}</div></div><div class="menu-hint">- This basemap is captured from the screen (Google's terms allow nothing- programmatic out of it), so the frame can't go past the map view and screen- pixels are the ceiling.+ {#if extensionVersion()}+ This basemap is captured from the screen (Google's terms allow nothing+ programmatic out of it), so the frame can't go past the map view and screen+ pixels are the ceiling.+ {:else}+ This basemap is captured from the screen, so filing it needs the capture+ extension (Google's terms allow nothing programmatic out).+ {/if}</div>{:else}<div class="menu-row">@@ -2534,7 +2552,7 @@<p class="shot-hint">The <strong>Capture</strong> button already crops this basemap off the screenthrough the usual frame. Use this when it can't:- {#if extensionVersion()}grab the whole map view below, or paste{:else}paste{/if}+ grab the whole map view below, or paste(<span class="mono">Ctrl+V</span>) / drop your own OS screenshot.Unlike a framed capture, this is filed at the current <em>view</em>(<span class="mono">{fmtCoords(center.lat, center.lon)}</span>, z{center.zoom}) —@@ -2542,14 +2560,12 @@is burned into a footer either way; keep Google's on-screen credits inside theframe too.</p>- {#if extensionVersion()}- <div style="display:flex;justify-content:center;margin-bottom:10px">- <button class="btn btn-primary" onclick={shotGrab} disabled={shotGrabbing}>- {#if shotGrabbing}<span class="spinner"></span> Grabbing…{:else}- <Icon name="satellite" size={14} /> Capture the view{/if}- </button>- </div>- {/if}+ <div style="display:flex;justify-content:center;margin-bottom:10px">+ <button class="btn btn-primary" onclick={shotGrab} disabled={shotGrabbing}>+ {#if shotGrabbing}<span class="spinner"></span> Grabbing…{:else}+ <Icon name="satellite" size={14} /> Capture the view{/if}+ </button>+ </div><divclass="shot-zone"class:has-image={!!shotPreview}@@ -2590,18 +2606,10 @@</p><p class="shot-hint">Install it from <strong>Settings → Capture extension</strong>, then reload- this tab. You can also paste an OS screenshot instead.+ this tab.</p><div style="display:flex;gap:8px;justify-content:flex-end;margin-top:12px">- <button- class="btn"- onclick={() => {- extGateOpen = false;- shotOpen = true;- }}- >- Paste a screenshot…- </button>+ <button class="btn" onclick={() => (extGateOpen = false)}>Cancel</button><buttonclass="btn btn-primary"onclick={() => {diff --git a/frontend/src/tools/Settings.svelte b/frontend/src/tools/Settings.svelteindex 2c5f900..b272fe7 100644--- a/frontend/src/tools/Settings.svelte+++ b/frontend/src/tools/Settings.svelte@@ -16,7 +16,7 @@FREE_TIER,} from '../lib/usage.js';import { probeKey, googleMapsLoadedKey } from '../lib/gmaps.js';- import { extensionVersion } from '../lib/extBridge.js';+ import { extensionVersion, extensionOutdated } from '../lib/extBridge.js';import Icon from '../components/Icon.svelte';// Imagery and Usage were the same four objects seen from two rooms: the key@@ -51,6 +51,11 @@placeholder: 'pk.…',help: 'https://account.mapbox.com/access-tokens/',usage: USAGE_LINKS.mapbox,+ steps: [+ 'Sign in (or create a free account) at mapbox.com.',+ 'Open Account → Tokens and copy the default public token, or create a new one.',+ 'No referrer restriction needed: Azimut calls Mapbox from its own backend, not the browser.',+ ],overage:'Past the tier, Mapbox bills extra tiles automatically; set a spending alert in your account.',},@@ -65,6 +70,11 @@usage: USAGE_LINKS.google,warning:'EEA billing accounts: since 8 July 2025 Google no longer serves satellite tiles to Europe (403). Use a Maps JavaScript API key instead.',+ steps: [+ 'In the Google Cloud Console, enable the "Map Tiles API" on your project.',+ 'Create an API key (Credentials) and restrict it to that API.',+ 'Use an IP restriction, not a referrer one: Azimut calls Google from its own backend, not the browser.',+ ],overage:'Extra tiles are billed to your Cloud project; a quota cap in the Cloud Console makes it stop serving instead.',},@@ -151,7 +161,7 @@// helpers read; `tierEdits` is what's in the boxes.let tiers = $state(null);let tierEdits = $state(perProvider(() => ''));- let about = $state({ version: '', workspace_root: '' });+ let about = $state({ version: '', workspace_root: '', extension_version: '' });// --- capture extension: pairing token + detection (lib/extBridge.js) ---let ingestToken = $state('');@@ -160,6 +170,11 @@// mid-session install genuinely needs a tab reload (the text says so)const extDetected = extensionVersion();+ // Is the bundled extension newer than the one loaded in this browser? The app+ // can't reload an unpacked extension for the user (the browser won't let it),+ // so it flags the mismatch and points at the same re-download + reload steps.+ let extOutdated = $derived(extensionOutdated(extDetected, about.extension_version));+async function copyToken() {try {await ensureToken();@@ -247,6 +262,26 @@}}+ // App self-update check (engine/updates.py). The binary has no package+ // manager behind it; a pip/pipx user runs `pipx upgrade azimut` instead.+ // Opt-in and never on mount — local-first, like the downloader check.+ let appUpdate = $state(null); // { current, latest, update_available, url, error }+ let checkingApp = $state(false);++ async function checkAppUpdate() {+ if (checkingApp) return;+ checkingApp = true;+ try {+ appUpdate = await api.get('/api/settings/update?check=true');+ if (appUpdate.error) toast(`Could not reach GitHub: ${appUpdate.error}`, 'danger');+ else if (!appUpdate.update_available) toast('Azimut is up to date', 'ok');+ } catch (e) {+ toast(`Could not check for updates: ${e.message}`, 'danger');+ } finally {+ checkingApp = false;+ }+ }+async function updateScraper(dist) {if (updating[dist]) return;updating[dist] = true;@@ -301,7 +336,11 @@const v = s.free_tiers?.[k.id];return v === undefined || v === null ? '' : String(v);});- about = { version: s.version ?? '', workspace_root: s.workspace_root ?? '' };+ about = {+ version: s.version ?? '',+ workspace_root: s.workspace_root ?? '',+ extension_version: s.extension_version ?? '',+ };ingestToken = s.ingest_token ?? '';home = { lat: String(s.home_view.lat), lon: String(s.home_view.lon), zoom: String(s.home_view.zoom) };mention = s.post_mention ?? '';@@ -899,15 +938,26 @@<span class="row-hint">{#if extDetected}detected · <span class="mono">v{extDetected}</span>+ {#if extOutdated}+ · update bundled (<span class="mono">v{about.extension_version}</span>)+ {/if}{:else}not detected — after installing, reload this tab{/if}</span></div><a class="btn btn-sm btn-primary" href="/api/ingest/extension.zip" download>- <Icon name="download" size={13} /> Download extension (.zip)+ <Icon name="download" size={13} />+ {extOutdated ? 'Download update (.zip)' : 'Download extension (.zip)'}</a></div>+ {#if extOutdated}+ <p class="note warn">+ This Azimut ships a newer capture extension (v{about.extension_version}) than the+ v{extDetected} loaded here. Download it, replace the unpacked folder, then reload the+ extension in your browser's extensions page. Azimut can't reload it for you.+ </p>+ {/if}<p class="note">Unzip it somewhere permanent and load it as an unpacked extension, thenreload this tab. Step-by-step instructions are in the README inside the zip.@@ -970,6 +1020,39 @@</div></section>+ <section class="group">+ <h3>Updates</h3>+ <div class="row">+ <div class="row-label">+ <span>Check for a newer release</span>+ <span class="row-hint">+ {#if appUpdate?.update_available}+ <span class="mono">{appUpdate.latest}</span> is out — you have+ <span class="mono">{about.version}</span>+ {:else if appUpdate && !appUpdate.error}+ you're on the latest (<span class="mono">{about.version}</span>)+ {:else}+ looks at GitHub only when you press it+ {/if}+ </span>+ </div>+ {#if appUpdate?.update_available}+ <a class="btn btn-sm btn-primary" href={appUpdate.url} target="_blank" rel="noreferrer">+ <Icon name="download" size={13} /> Get {appUpdate.latest} <Icon name="external" size={11} />+ </a>+ {:else}+ <button class="btn btn-sm" onclick={checkAppUpdate} disabled={checkingApp}>+ {checkingApp ? 'Checking…' : 'Check for updates'}+ </button>+ {/if}+ </div>+ <p class="note">+ A <span class="mono">pip</span> or <span class="mono">pipx</span> install updates with+ <span class="mono">pipx upgrade azimut</span>. For the standalone binary, download the new+ release and replace the file — your cases under the workspace are untouched.+ </p>+ </section>+<section class="group"><h3>Backup</h3><p class="note">@@ -1260,6 +1343,9 @@line-height: 1.5;margin-top: 8px;}+ .note.warn {+ color: var(--warn, #d8a03d);+ }/* same voice as .note, but leading a group instead of trailing one */.intro {color: var(--text-3);diff --git a/pyproject.toml b/pyproject.tomlindex 34d4db0..06577d4 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "azimut"-version = "0.1.1"+version = "0.1.2"description = "The OSINT investigator's workbench — local-first media, geolocation proofs and case management."readme = "README.md"requires-python = ">=3.11"diff --git a/src/azimut/__init__.py b/src/azimut/__init__.pyindex 3a37e0e..f1fef05 100644--- a/src/azimut/__init__.py+++ b/src/azimut/__init__.py@@ -2,7 +2,7 @@from PIL import Image as _Image-__version__ = "0.1.1"+__version__ = "0.1.2"# Cap the pixels Pillow will decode from a file, process-wide. A tiny,# highly-compressed image can otherwise expand to gigabytes in memory and takediff --git a/src/azimut/api/ingest.py b/src/azimut/api/ingest.pyindex 98a0831..9625e21 100644--- a/src/azimut/api/ingest.py+++ b/src/azimut/api/ingest.py@@ -22,6 +22,7 @@ treatment the widget screenshot endpoint applies.from __future__ import annotationsimport io+import jsonimport secretsimport zipfilefrom datetime import datetime, timezone@@ -266,6 +267,39 @@ async def ingest_screenshot(}[email protected]("/bookmark", dependencies=[Depends(require_token)])+def ingest_bookmark(+ url: str = Form(min_length=1, max_length=4000),+ case_id: str = Form(default=""),+ title: str = Form(default="", max_length=200),+) -> dict[str, Any]:+ """File a web page as a ``bookmark`` entity — a saved link, no screenshot.++ The capture flow is maps-only (legal rails); this is the other half of the+ extension popup, offered when the open page is *not* a recognized map site.+ Nothing is fetched: we store the URL the user is already on, its title and+ the source site — a pointer, not a copy. An empty ``case_id`` opens a fresh+ scratch session, the same as a screenshot ingest.+ """+ split = urlsplit(url)+ if split.scheme not in ("http", "https") or not split.hostname:+ raise HTTPException(status_code=422, detail="bookmark needs an http(s) URL")++ case = get_case(case_id) if case_id else Case.create("Scratch session", scratch=True)+ label = title.strip() or split.hostname+ entity = case.add_entity(+ "bookmark",+ label,+ {"url": url, "site": split.hostname, "folder": ""},+ by="ingest",+ )+ events.publish(+ {"type": "bookmark", "case_id": case.id, "entity_id": entity["id"],+ "title": label, "url": url}+ )+ return {"entity_id": entity["id"], "case_id": case.id, "title": label, "url": url}++# ---- extension download: the packaged source, zipped on request ---------------# Repo checkout first (development), then the copy hatchling ships inside the@@ -287,6 +321,22 @@ def _extension_dir() -> Path | None:return None+def bundled_extension_version() -> str | None:+ """The ``version`` of the extension this Azimut build ships. Settings+ compares it to the version stamped by the *installed* extension+ (lib/extBridge.js) so it can flag "an update is bundled — re-download and+ reload". None if no extension is bundled (unusual builds)."""+ src = _extension_dir()+ if src is None:+ return None+ try:+ manifest = json.loads((src / "manifest.json").read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ return None+ version = manifest.get("version")+ return str(version) if version else None++@router.get("/extension.zip")def extension_zip() -> Response:"""The capture extension, zipped for Settings' install flow.diff --git a/src/azimut/api/settings.py b/src/azimut/api/settings.pyindex 8b5d2b2..0fabd83 100644--- a/src/azimut/api/settings.py+++ b/src/azimut/api/settings.py@@ -19,7 +19,8 @@ from fastapi.responses import FileResponsefrom pydantic import BaseModel, Fieldfrom .. import __version__, config-from ..engine import google_tiles, scrapers, sentinel, tiles+from ..engine import google_tiles, scrapers, sentinel, tiles, updates+from .ingest import bundled_extension_versionrouter = APIRouter(prefix="/api", tags=["settings"])@@ -118,6 +119,9 @@ def get_settings() -> dict[str, Any]:# About tab: what this build is, and where it keeps its files"version": __version__,"workspace_root": str(config.workspace_root()),+ # the capture-extension version this build ships — Settings compares it+ # to the installed one (lib/extBridge.js) to flag a stale extension+ "extension_version": bundled_extension_version(),# capture-extension pairing token (api/ingest.py) — reported only if it# already exists; loading Settings no longer mints a credential (POST# /settings/ingest-token does, on the user's explicit reveal/copy)@@ -390,6 +394,19 @@ def get_scrapers(check: bool = False) -> dict[str, Any]:return {"scrapers": scrapers.status(check_pypi=check)}[email protected]("/settings/update")+def check_app_update(check: bool = False) -> dict[str, Any]:+ """This build's version, and — with ``check=true`` — whether GitHub has a+ newer release. For the binary, which has no package manager to ask.++ Opt-in and user-triggered like the scraper check: without ``check`` it+ reports the current version and touches no network (engine/updates.py).+ """+ if not check:+ return {"current": __version__, "latest": None, "update_available": False}+ return updates.check(__version__)++@router.post("/settings/scrapers/{dist}/update")def update_scraper(dist: str) -> dict[str, Any]:"""Fetch the latest wheel for one scraper into the workspace.diff --git a/src/azimut/config.py b/src/azimut/config.pyindex 39997e3..ab47750 100644--- a/src/azimut/config.py+++ b/src/azimut/config.py@@ -23,7 +23,16 @@ from datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Callable+# On-disk schema for settings.json — the app-wide sibling of case.json's+# CASE_SCHEMA (workspace.py). An older file is migrated up to this on load; a+# newer file is left alone, since update() below preserves keys this Azimut+# doesn't know. Bump it in the same change that adds a SETTINGS_MIGRATIONS entry.+SETTINGS_SCHEMA = 1+DEFAULT_SETTINGS: dict[str, Any] = {+ # Schema version this build writes. Read back through _settings_schema() so+ # a future breaking rename is migrated rather than silently dropped.+ "schema": SETTINGS_SCHEMA,# Extra XYZ tile providers added by the user (spec §6 v1 notes).# Each: {"id", "label", "url" ({x}/{y}/{z} template), "attribution", "max_zoom"}"tile_providers": [],@@ -165,6 +174,16 @@ def ensure_workspace() -> None:_restrict(workspace_root(), 0o700)if not settings_path().exists():save_settings(DEFAULT_SETTINGS)+ return+ # Upgrade an older settings.json in place, once, so the file on disk matches+ # the shape the rest of the app expects. load_settings() also migrates in+ # memory, so a read is safe even before this runs.+ try:+ raw = json.loads(settings_path().read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ return+ if _settings_schema(raw) < SETTINGS_SCHEMA:+ save_settings(migrate_settings(raw))def _restrict(path: Path, mode: int) -> None:@@ -175,6 +194,33 @@ def _restrict(path: Path, mode: int) -> None:pass+# from_version -> function(data) returning settings reshaped for from_version+1.+# The runner (migrate_settings) stamps the new number, so a migration only+# rewrites fields. Empty while we're on the first schema.+SETTINGS_MIGRATIONS: dict[int, Callable[[dict[str, Any]], dict[str, Any]]] = {}+++def _settings_schema(data: dict[str, Any]) -> int:+ """The schema a loaded settings.json declares. Files predating the tag are+ the first schema."""+ value = data.get("schema")+ return value if isinstance(value, int) else 1+++def migrate_settings(data: dict[str, Any]) -> dict[str, Any]:+ """Upgrade a raw settings dict to ``SETTINGS_SCHEMA`` in memory.++ A newer file is returned untouched — update() in load_settings keeps keys+ this build doesn't recognise, so there is nothing to lose by loading it.+ Pure: it never writes. ensure_workspace() persists the result once at start.+ """+ version = _settings_schema(data)+ for step in range(version, SETTINGS_SCHEMA):+ data = SETTINGS_MIGRATIONS[step](data)+ data["schema"] = step + 1+ return data++def load_settings() -> dict[str, Any]:# deep copies: callers mutate nested dicts (usage counters, prefs), and a# shallow copy would let that leak into DEFAULT_SETTINGS itself@@ -183,7 +229,7 @@ def load_settings() -> dict[str, Any]:except (OSError, json.JSONDecodeError):return copy.deepcopy(DEFAULT_SETTINGS)merged = copy.deepcopy(DEFAULT_SETTINGS)- merged.update(data)+ merged.update(migrate_settings(data))return mergeddiff --git a/src/azimut/engine/updates.py b/src/azimut/engine/updates.pynew file mode 100644index 0000000..c5c9d69--- /dev/null+++ b/src/azimut/engine/updates.py@@ -0,0 +1,67 @@+"""Is a newer Azimut out? — a self-check for the binary, which has no package+manager behind it (a ``pip``/``pipx`` user runs ``pipx upgrade`` instead).++Local-first: this reaches the network only when the user presses "Check for+updates" (api/settings.py gates it behind ``?check=true``, the same opt-in the+scraper check uses). Nothing here runs on launch or on opening Settings.+"""++from __future__ import annotations++import re++import httpx++# The public releases feed. Latest *published, non-draft, non-prerelease* tag —+# exactly the assets the README's download table points at.+LATEST_RELEASE_URL = "https://api.github.com/repos/OsintMeThat/azimut/releases/latest"+RELEASES_PAGE_URL = "https://github.com/OsintMeThat/azimut/releases/latest"+++def _parse(version: str) -> tuple[int, ...]:+ """A tag like ``v0.1.2`` (or a bare ``0.1.2``) as a comparable tuple.++ Only the leading integer of each dotted part counts, so a ``0.2.0rc1``+ sorts as ``(0, 2, 0)`` — good enough to answer "is the release newer than+ what I'm running", which is all this decides."""+ parts = []+ for chunk in version.strip().lstrip("vV").split("."):+ match = re.match(r"\d+", chunk)+ parts.append(int(match.group()) if match else 0)+ return tuple(parts) or (0,)+++def is_newer(latest: str, current: str) -> bool:+ return _parse(latest) > _parse(current)+++def check(current: str, *, timeout: float = 6.0) -> dict[str, object]:+ """Ask GitHub for the latest release and compare it to ``current``.++ Never raises — a failed check is reported inline (``error``), like the+ scraper and API-key checks, so a flaky network never breaks Settings.+ """+ result: dict[str, object] = {+ "current": current,+ "latest": None,+ "update_available": False,+ "url": RELEASES_PAGE_URL,+ }+ try:+ resp = httpx.get(+ LATEST_RELEASE_URL,+ timeout=timeout,+ headers={"Accept": "application/vnd.github+json", "User-Agent": "azimut"},+ )+ resp.raise_for_status()+ body = resp.json()+ except (httpx.HTTPError, ValueError) as exc:+ result["error"] = str(exc)+ return result+ latest = str(body.get("tag_name") or "").strip()+ if latest:+ result["latest"] = latest+ result["update_available"] = is_newer(latest, current)+ if body.get("html_url"):+ result["url"] = str(body["html_url"])+ return resultdiff --git a/src/azimut/workspace.py b/src/azimut/workspace.pyindex 6806c60..566d281 100644--- a/src/azimut/workspace.py+++ b/src/azimut/workspace.py@@ -23,12 +23,33 @@ import timeimport uuidfrom datetime import datetime, timezonefrom pathlib import Path-from typing import Any, Literal+from typing import Any, Callable, Literalfrom . import configCASE_SUBDIRS = ("media", "proofs", "exports", "inspect")+# On-disk schema for case.json. A newer Azimut opens an older case by running+# the migrations below up to this number on first open; a case written by a+# *newer* Azimut (higher schema) is refused rather than mangled (spec §7,+# forward compatibility). Bump this in the same change that adds a migration.+CASE_SCHEMA = 1++# from_version -> function(data) returning data reshaped for from_version + 1.+# The runner (Case.migrate) owns stamping the new schema number, so a migration+# only rewrites fields. Empty while we're on the first schema; each future+# breaking change to case.json lands one entry here plus a fixture pinning it.+CASE_MIGRATIONS: dict[int, Callable[[dict[str, Any]], dict[str, Any]]] = {}+++def _case_schema(data: dict[str, Any]) -> int:+ """The schema a loaded case.json declares. Legacy/untagged files predate the+ tag and are treated as the first schema."""+ meta = data.get("azimut")+ if isinstance(meta, dict) and isinstance(meta.get("schema"), int):+ return meta["schema"]+ return 1+# Empty scratch sessions older than this are reaped at startup (spec §9).SCRATCH_MAX_AGE_DAYS = 14@@ -64,6 +85,7 @@ EntityStatus = Literal["confirmed", "suggested"]ENTITY_TYPES = ("person", "organization", "alias", "account", "email", "phone", "domain","ip", "vehicle", "place", "capture", "event", "media", "proof", "note",+ "bookmark",)@@ -175,9 +197,48 @@ class Case:for parent in (config.cases_dir(), config.scratch_dir()):path = parent / case_idif (path / "case.json").exists():- return cls(path)+ case = cls(path)+ case.migrate()+ return caseraise CaseError(f"case '{case_id}' not found")+ def migrate(self) -> dict[str, Any]:+ """Bring case.json up to ``CASE_SCHEMA`` on open, and return the data.++ A case written by the same schema is returned untouched (the common+ path, so today this never rewrites anything). An older one is upgraded+ in order, backing the file up once before the first rewrite so a bad+ migration is recoverable. A *newer* one is refused: an old Azimut must+ not silently drop fields it was never taught, so the user is told to+ update instead (spec §7).+ """+ with self._lock:+ data = self.read()+ version = _case_schema(data)+ if version == CASE_SCHEMA:+ return data+ if version > CASE_SCHEMA:+ raise CaseError(+ f"case '{self.id}' was made with a newer Azimut "+ f"(schema {version} > {CASE_SCHEMA}); update Azimut to open it"+ )+ self._backup(f"pre-migrate-v{version}")+ for step in range(version, CASE_SCHEMA):+ migrate = CASE_MIGRATIONS.get(step)+ if migrate is None:+ raise CaseError(f"no migration for case schema {step}")+ data = migrate(data)+ data.setdefault("azimut", {})["schema"] = step + 1+ self._write_json(data)+ return data++ def _backup(self, tag: str) -> None:+ """Copy case.json aside once, under a ``tag``. Never overwrites an+ existing backup — a re-run of the same migration keeps the first copy."""+ dst = self.json_path.with_name(f"case.{tag}.json")+ if not dst.exists():+ shutil.copy2(self.json_path, dst)+@classmethoddef cleanup_scratch(cls, max_age_days: int = SCRATCH_MAX_AGE_DAYS) -> int:"""Delete scratch cases that hold nothing and haven't been touched indiff --git a/tests/test_ingest_api.py b/tests/test_ingest_api.pyindex 0ad4dfb..7a0a259 100644--- a/tests/test_ingest_api.py+++ b/tests/test_ingest_api.py@@ -208,6 +208,58 @@ def test_cors_opens_exactly_extension_origins_on_exactly_ingest_routes(client):assert "access-control-allow-origin" not in r.headers+def _bookmark(client, token=None, **overrides):+ data = {"url": "https://example.com/leak", "title": "A page"}+ data.update(overrides)+ data = {k: v for k, v in data.items() if v is not None}+ headers = {"X-Azimut-Token": token} if token else {}+ return client.post("/api/ingest/bookmark", data=data, headers=headers)+++def test_bookmark_needs_the_token(client):+ _token(client) # minted, but the request carries none+ assert _bookmark(client).status_code == 401+ assert _bookmark(client, token="wrong").status_code == 401+++def test_bookmark_files_a_link_entity_without_a_screenshot(client):+ token = _token(client)+ cid = client.post("/api/cases", json={"name": "Links"}).json()["id"]+ r = _bookmark(client, token=token, case_id=cid, title="Leak site")+ assert r.status_code == 200+ body = r.json()+ assert body["case_id"] == cid and body["title"] == "Leak site"+ ents = client.get(f"/api/cases/{cid}").json()["entities"]+ bm = [e for e in ents if e["type"] == "bookmark"]+ assert len(bm) == 1+ assert bm[0]["label"] == "Leak site"+ assert bm[0]["attrs"]["url"] == "https://example.com/leak"+ assert bm[0]["attrs"]["site"] == "example.com"+ # no image entity was created — a bookmark is a pointer, not a copy+ assert client.get(f"/api/cases/{cid}/media").json() == []+++def test_bookmark_falls_back_to_the_host_when_untitled(client):+ token = _token(client)+ cid = client.post("/api/cases", json={"name": "Untitled"}).json()["id"]+ body = _bookmark(client, token=token, case_id=cid, title="").json()+ assert body["title"] == "example.com"+++def test_bookmark_refuses_non_http_urls(client):+ token = _token(client)+ for bad in ("javascript:alert(1)", "file:///etc/passwd", "not a url"):+ assert _bookmark(client, token=token, url=bad).status_code == 422+++def test_bookmark_empty_case_files_into_a_scratch_session(client):+ token = _token(client)+ body = _bookmark(client, token=token).json()+ cases = client.get("/api/cases").json()+ match = [c for c in cases if c["id"] == body["case_id"]]+ assert match and match[0]["scratch"] is True++def test_extension_zip_serves_the_packaged_runtime_files(client):import zipfile as zfdiff --git a/tests/test_migrations.py b/tests/test_migrations.pynew file mode 100644index 0000000..3c40786--- /dev/null+++ b/tests/test_migrations.py@@ -0,0 +1,113 @@+"""Forward compatibility (spec §7): an older case.json / settings.json is+migrated up to the running schema on open, a newer one is refused rather than+mangled. The chains are empty today, so these tests register throwaway+migrations to prove the runners, and pin the "same schema doesn't rewrite" and+"newer is refused" invariants that hold with zero migrations."""++import json++import pytest++from azimut import config, workspace+from azimut.workspace import Case, CaseError+++# -- case.json ------------------------------------------------------------+++def test_open_current_schema_does_not_rewrite(tmp_workspace):+ """The common path: a case at the running schema is returned untouched, no+ backup file appears, updated_at is left alone."""+ case = Case.create("Investigation")+ before = case.read()["updated_at"]++ reopened = Case.open(case.id)++ assert reopened.read()["updated_at"] == before+ backups = list(case.path.glob("case.pre-migrate*.json"))+ assert backups == []+++def test_open_newer_schema_is_refused(tmp_workspace):+ case = Case.create("From the future")+ data = case.read()+ data["azimut"]["schema"] = workspace.CASE_SCHEMA + 5+ case._write_json(data)++ with pytest.raises(CaseError, match="newer Azimut"):+ Case.open(case.id)+++def test_open_older_schema_migrates_and_backs_up(tmp_workspace, monkeypatch):+ case = Case.create("Legacy") # written at schema 1++ def to_v2(data):+ data.setdefault("attrs", {})["migrated"] = True+ return data++ monkeypatch.setattr(workspace, "CASE_SCHEMA", 2)+ monkeypatch.setattr(workspace, "CASE_MIGRATIONS", {1: to_v2})++ migrated = Case.open(case.id).read()++ assert migrated["azimut"]["schema"] == 2+ assert migrated["attrs"]["migrated"] is True+ backup = case.path / "case.pre-migrate-v1.json"+ assert backup.exists()+ assert json.loads(backup.read_text())["azimut"]["schema"] == 1+++def test_migration_backup_is_not_overwritten(tmp_workspace, monkeypatch):+ """A second migration run keeps the first pre-migration copy."""+ case = Case.create("Legacy")+ monkeypatch.setattr(workspace, "CASE_SCHEMA", 2)+ monkeypatch.setattr(workspace, "CASE_MIGRATIONS", {1: lambda d: d})++ Case.open(case.id)+ backup = case.path / "case.pre-migrate-v1.json"+ first = backup.read_text()++ # Force another migration pass from the same starting schema.+ data = case.read()+ data["azimut"]["schema"] = 1+ case._write_json(data)+ Case.open(case.id)++ assert backup.read_text() == first+++# -- settings.json --------------------------------------------------------+++def test_migrate_settings_newer_is_left_alone():+ data = {"schema": config.SETTINGS_SCHEMA + 3, "unknown_future_key": 1}+ assert config.migrate_settings(dict(data)) == data+++def test_load_settings_untagged_file_is_first_schema(monkeypatch, tmp_path):+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))+ config.settings_path().parent.mkdir(parents=True, exist_ok=True)+ config.settings_path().write_text(json.dumps({"api_keys": {}}), encoding="utf-8")++ assert config.load_settings()["schema"] == 1+++def test_ensure_workspace_upgrades_settings_in_place(monkeypatch, tmp_path):+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))+ config.settings_path().parent.mkdir(parents=True, exist_ok=True)+ config.settings_path().write_text(+ json.dumps({"schema": 1, "post_mention": "@old"}), encoding="utf-8"+ )++ def to_v2(data):+ data["post_mention"] = "@new"+ return data++ monkeypatch.setattr(config, "SETTINGS_SCHEMA", 2)+ monkeypatch.setattr(config, "SETTINGS_MIGRATIONS", {1: to_v2})++ config.ensure_workspace()++ saved = json.loads(config.settings_path().read_text(encoding="utf-8"))+ assert saved["schema"] == 2+ assert saved["post_mention"] == "@new"diff --git a/tests/test_updates.py b/tests/test_updates.pynew file mode 100644index 0000000..d7309af--- /dev/null+++ b/tests/test_updates.py@@ -0,0 +1,117 @@+"""App self-update check (engine/updates.py, api/settings.py) and the bundled+capture-extension version Settings compares against the installed one.++Nothing here touches the network: GitHub's releases feed is faked, and the+opt-in gate (``?check=true``) is asserted by making the fake explode when it+shouldn't be reached."""++from __future__ import annotations++import httpx+import pytest++from azimut import __version__+from azimut.api.ingest import bundled_extension_version+from azimut.engine import updates+++class FakeResponse:+ def __init__(self, payload):+ self._payload = payload++ def raise_for_status(self):+ return None++ def json(self):+ return self._payload+++# -- version comparison ---------------------------------------------------+++ "latest,current,expected",+ [+ ("v0.2.0", "0.1.1", True),+ ("v0.1.2", "0.1.1", True),+ ("v0.1.1", "0.1.1", False),+ ("v0.1.0", "0.1.1", False),+ ("0.1.10", "0.1.9", True), # numeric, not lexical+ ("v0.2.0rc1", "0.1.9", True), # pre-release suffix ignored+ ],+)+def test_is_newer(latest, current, expected):+ assert updates.is_newer(latest, current) is expected+++# -- updates.check --------------------------------------------------------+++def test_check_reports_a_newer_release(monkeypatch):+ monkeypatch.setattr(+ updates.httpx,+ "get",+ lambda *a, **k: FakeResponse({"tag_name": "v9.9.9", "html_url": "https://x/rel"}),+ )+ result = updates.check("0.1.1")+ assert result == {+ "current": "0.1.1",+ "latest": "v9.9.9",+ "update_available": True,+ "url": "https://x/rel",+ }+++def test_check_up_to_date(monkeypatch):+ monkeypatch.setattr(+ updates.httpx, "get", lambda *a, **k: FakeResponse({"tag_name": "v0.1.1"})+ )+ result = updates.check("0.1.1")+ assert result["update_available"] is False+ assert result["latest"] == "v0.1.1"+++def test_check_never_raises_on_network_error(monkeypatch):+ def boom(*a, **k):+ raise httpx.ConnectError("offline")++ monkeypatch.setattr(updates.httpx, "get", boom)+ result = updates.check("0.1.1")+ assert result["update_available"] is False+ assert "offline" in result["error"]+++# -- endpoint (opt-in, local-first) ---------------------------------------+++def test_update_endpoint_without_check_touches_no_network(client, monkeypatch):+ def boom(*a, **k):+ raise AssertionError("must not reach the network without ?check=true")++ monkeypatch.setattr(updates.httpx, "get", boom)+ body = client.get("/api/settings/update").json()+ assert body == {"current": __version__, "latest": None, "update_available": False}+++def test_update_endpoint_with_check_queries_github(client, monkeypatch):+ monkeypatch.setattr(+ updates.httpx,+ "get",+ lambda *a, **k: FakeResponse({"tag_name": "v9.9.9", "html_url": "https://x/rel"}),+ )+ body = client.get("/api/settings/update?check=true").json()+ assert body["update_available"] is True+ assert body["latest"] == "v9.9.9"+++# -- bundled extension version --------------------------------------------+++def test_bundled_extension_version_matches_manifest():+ # The repo checkout's extension/manifest.json is the source of truth here.+ assert bundled_extension_version() == "0.2.0"+++def test_settings_reports_extension_version(client):+ body = client.get("/api/settings").json()+ assert body["extension_version"] == "0.2.0"diff --git a/uv.lock b/uv.lockindex 31dd0de..f3a3b6c 100644--- a/uv.lock+++ b/uv.lock@@ -39,7 +39,7 @@ wheels = [[[package]]name = "azimut"-version = "0.1.1"+version = "0.1.2"source = { editable = "." }dependencies = [{ name = "fastapi" },