Skip to content

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

JavaScript

M5.1: Inspect tool rework — scratch workspace, collage warp, session save

OsintMeThate8ff40c3f199
diff --git a/docs/SPEC.md b/docs/SPEC.md
index fba5fd5..937cbc7 100644
--- a/docs/SPEC.md
+++ b/docs/SPEC.md
@@ -146,11 +146,11 @@ 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) → clean local file + metadata JSON + sha256. Every media becomes a `media` entity. 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** | Open any photo or video to extract and work on imagery. **Frames**: scrub a video, step frame-by-frame, one-click capture, or scan for the *sharpest* frames per time bin. **Adjust**: non-destructive brightness/contrast/saturation/gamma/sharpness/grayscale/invert/rotate + interactive **crop**, live-previewed then baked to a new image. **Collage**: tile several frames/images into one contact sheet. **Analyze**: histogram, EXIF/metadata, ELA (labeled a *hint*). Every output is filed as new case media with provenance back to its source, so it flows straight into the composer. Built on two self-describing registries (filters + analyses) so new mini-tools are one function to add. |
-| **Satellite** | Enter/click coordinates: imagery crop centered on the point, crosshair marker, zoom control, **map rotation** (turn the view off-north; capture matches the on-screen heading, bearing recorded in provenance), provenance (provider, zoom, date, bearing, attribution) recorded — feeds the composer directly. XYZ tile-provider abstraction (see note below). Captures support **editable notes** via inline modal. |
+| **Inspect** | A scratch workspace over any photo/video — **nothing enters the case until Save**. **Selection** (video): scrub, step, scan *sharpest* frames, 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/rotate + interactive **crop**, live-previewed, with a fold-out **Analyze** (histogram, EXIF, ELA *hint*). **Collage**: drag/scale and **corner-warp** tray frames (thumbnails show each frame's current adjustments) on a canvas into a hand-made panorama; the canvas fill is a color or **transparent** (RGBA PNG export of just the pieces). Auto-stitch = later. **Save**: tick which of {enhanced video, adjusted frames, collage} to file — each re-derived full-res on the backend with provenance back to its source, into an optional folder; the collage shows a live miniature 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 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: imagery crop centered on the point, crosshair marker, zoom control, **map rotation** (turn the view off-north; capture matches the on-screen heading, bearing recorded in provenance), provenance (provider, zoom, date, bearing, attribution) recorded — feeds the composer directly. XYZ tile-provider abstraction (see note below). Each capture is one `place` entity with an **editable title + notes** via inline modal. |
| **Proof Composer** | The heart of v1. Compose panels side by side (frames, photos, satellite crops, imported screenshots); draw colored boxes/ellipses/lines/arrows with the mouse — same color = same feature across panels; per-shape and per-panel **comments/captions**; numbered feature legend; layout rows; export `proof.png` + re-editable JSON spec saved in `proofs/`. |
| **Post Composer** | Build a GeoConfirmed-style thread from a proof. Tweet 1 = `Place - Plus code`, description, decimal coordinates (6 digits), `@GeoConfirmed` mention, source. Tweet 2 = optional media (Video / Image(s), 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 — Ozimut never posts on your behalf. |
-| **Case sidebar** | Always visible: case notes (`notes.md`), media list, saved proofs, entity list (simple list view). Create/open/promote cases. |
+| **Case sidebar** | Always visible, three sections. **Case Notes** (`notes.md`). **Saved work** — every artifact, auto-grouped by the tool that produced it (Media Library / Inspect / Satellite / Proof Composer / Post Composer, from `provenance.by`); suggested entities pinned on top to confirm/dismiss; deleting here removes the item **everywhere** (drops its file — danger confirm). **My work** — the analyst's own **nested folders** (`/`-separated, e.g. `Sources/Telegram`), empty until you **drag** items in from Saved work; an item filed here stays in Saved work too (lives in both); deleting here only **unfiles** it (light confirm), and removing a folder cascades its subtree back to Saved work. Styled confirm dialogs, not browser popups. Create/open/promote cases. |
v1 notes:
@@ -169,6 +169,12 @@ v1 notes:
- 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 `place` entity (tied by file
+ path): the entity title defaults to the coordinates but is editable, and
+ deleting either side removes the other.
- 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)
diff --git a/frontend/src/components/CaseSidebar.svelte b/frontend/src/components/CaseSidebar.svelte
index 7fc1e9a..f69e0b3 100644
--- a/frontend/src/components/CaseSidebar.svelte
+++ b/frontend/src/components/CaseSidebar.svelte
@@ -3,6 +3,7 @@
import { caseState, uiState, reloadCase, toast } from '../lib/state.svelte.js';
import Icon from './Icon.svelte';
import Modal from './Modal.svelte';
+ import ConfirmDialog from './ConfirmDialog.svelte';
const ENTITY_ICONS = {
person: 'user',
@@ -20,17 +21,23 @@
ip: 'hash',
vehicle: 'grip',
note: 'note',
+ 'inspect-session': 'inspect',
};
// Tool to open when clicking a given entity type
- const ENTITY_TOOL = { media: 'media', proof: 'proof', place: 'satellite', post: 'post' };
+ 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', 'place', 'proof', 'post', 'inspect-session']);
// ── case notes (single notes.md) ─────────────────────────────────────────
let caseNotes = $state('');
let caseNotesLoadedFor = $state(null);
let saveTimer;
let saved = $state(true);
- let section = $state({ notes: false, folders: true, entities: true });
+ let section = $state({ notes: false, saved: true, mywork: true });
$effect(() => {
const id = caseState.current?.id;
@@ -59,6 +66,12 @@
}
// ── entities ─────────────────────────────────────────────────────────────
+ const entities = $derived(caseState.current?.entities ?? []);
+ const suggested = $derived(entities.filter((e) => e.provenance?.status === 'suggested'));
+ const confirmed = $derived(entities.filter((e) => e.provenance?.status !== 'suggested'));
+
+ const folderOf = (e) => e.attrs?.folder || null;
+
async function confirmEntity(entity) {
await api.patch(`/api/cases/${caseState.current.id}/entities/${entity.id}`, {
status: 'confirmed',
@@ -66,11 +79,11 @@
await reloadCase();
}
- async function removeEntity(entity) {
- if (!confirm(`Delete "${entity.label}"?`)) return;
+ // Dismiss a suggestion outright (quick triage — no heavy confirmation).
+ async function dismissSuggestion(entity) {
await api.del(`/api/cases/${caseState.current.id}/entities/${entity.id}`);
await reloadCase();
- toast(`Removed "${entity.label}"`, 'info');
+ toast(`Dismissed "${entity.label}"`, 'info');
}
function openEntity(entity) {
@@ -90,12 +103,25 @@
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, then switch tab
+ // 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 };
+ uiState.gotoCoords = {
+ lat,
+ lon,
+ zoom: Number(entity.attrs?.zoom),
+ bearing: Number(entity.attrs?.bearing),
+ };
}
uiState.tool = 'satellite';
return;
@@ -104,94 +130,130 @@
if (tool) uiState.tool = tool;
}
- const entities = $derived(caseState.current?.entities ?? []);
- const suggested = $derived(entities.filter((e) => e.provenance?.status === 'suggested'));
- const confirmed = $derived(entities.filter((e) => e.provenance?.status !== 'suggested'));
+ // ── Saved work: every artifact, grouped by the tool that produced it ──────
+ // The grouping is derived from provenance.by — the honest record of origin —
+ // so it fills itself as you work and needs no manual upkeep.
+ const TOOL_GROUPS = [
+ ['media-library', 'Media Library', 'image'],
+ ['inspect', 'Inspect', 'inspect'],
+ ['satellite', 'Satellite', 'satellite'],
+ ['proof-composer', 'Proof Composer', 'proof'],
+ ['post-composer', 'Post Composer', 'post'],
+ ['user', 'Notes & manual', 'note'],
+ ];
+ const KNOWN_TOOLS = new Set(TOOL_GROUPS.map(([k]) => k).filter((k) => k !== 'user'));
+ const groupKey = (by) => (KNOWN_TOOLS.has(by) ? by : 'user');
+
+ const savedGroups = $derived.by(() => {
+ const buckets = new Map(TOOL_GROUPS.map(([k]) => [k, []]));
+ for (const e of confirmed) buckets.get(groupKey(e.provenance?.by)).push(e);
+ return TOOL_GROUPS.map(([key, label, icon]) => ({
+ key,
+ label,
+ icon,
+ items: buckets.get(key),
+ })).filter((g) => g.items.length > 0);
+ });
- const folderOf = (e) => e.attrs?.folder || null;
+ let groupOpen = $state({}); // group key -> bool (absent = open)
+ const isGroupOpen = (k) => groupOpen[k] !== false;
+ const toggleGroup = (k) => (groupOpen[k] = !isGroupOpen(k));
- // ── folders (managed here, drag & drop assignment) ────────────────────────
- let folderFilter = $state(null); // null = all, '' = unfiled sentinel
- let newFolder = $state('');
+ // ── My work: the analyst's own nested folder tree ('/'-separated paths) ────
+ let newFolder = $state(''); // top-level create input
+ let addingUnder = $state(undefined); // folder path currently gaining a child
+ let newSubName = $state('');
+ let expanded = $state({}); // path -> bool (absent = expanded)
let dragEntityId = $state(null);
- let dragOverFolder = $state(undefined); // folder name or '' (unfiled) being hovered
+ let dragOverFolder = $state(undefined); // folder path being hovered
- // known folders = persisted case folders ∪ folders in use on entities
const caseFolders = $derived(caseState.current?.folders ?? []);
- const usedFolders = $derived(
- [...new Set(entities.map(folderOf).filter(Boolean))]
- );
- const allFolders = $derived(
- [...new Set([...caseFolders, ...usedFolders])].sort((a, b) =>
- a.toLowerCase().localeCompare(b.toLowerCase())
- )
- );
+ const filedCount = $derived(confirmed.filter((e) => folderOf(e)).length);
+
+ // Build a nested tree from flat '/'-separated folder paths + filed entities.
+ // Entities with no folder live only in Saved work, so they are ignored here.
+ function buildTree(folders, items) {
+ const root = { name: '', path: '', children: new Map(), entities: [] };
+ const ensure = (path) => {
+ let node = root, acc = '';
+ for (const seg of path.split('/')) {
+ acc = acc ? `${acc}/${seg}` : seg;
+ if (!node.children.has(seg))
+ node.children.set(seg, { name: seg, path: acc, children: new Map(), entities: [] });
+ node = node.children.get(seg);
+ }
+ return node;
+ };
+ for (const f of folders) if (f) ensure(f);
+ for (const e of items) {
+ const f = folderOf(e);
+ if (f) ensure(f).entities.push(e);
+ }
+ const sortNodes = (map) =>
+ [...map.values()]
+ .sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()))
+ .map((n) => ({ ...n, children: sortNodes(n.children) }));
+ return sortNodes(root.children);
+ }
- const filteredConfirmed = $derived(
- folderFilter === null
- ? confirmed
- : confirmed.filter((e) => (folderOf(e) ?? '') === folderFilter)
- );
- const filteredSuggested = $derived(
- folderFilter === null || folderFilter === ''
- ? suggested
- : []
+ const tree = $derived(buildTree(caseFolders, confirmed));
+ const allFolders = $derived(
+ (function flatten(nodes) {
+ return nodes.flatMap((n) => [n.path, ...flatten(n.children)]);
+ })(tree)
);
- function countInFolder(f) {
- return entities.filter((e) => (folderOf(e) ?? '') === f).length;
+ function subtreeCount(node) {
+ return node.entities.length + node.children.reduce((s, c) => s + subtreeCount(c), 0);
}
- async function createFolder() {
- const name = newFolder.trim();
+ const isExpanded = (path) => expanded[path] !== false;
+ function toggle(path) { expanded[path] = !isExpanded(path); }
+ function focus(node) { node.focus(); }
+
+ async function createFolder(fullName) {
+ const name = (fullName ?? newFolder).trim();
if (!name) return;
- newFolder = '';
+ if (fullName == null) newFolder = '';
try {
await api.post(`/api/cases/${caseState.current.id}/folders`, { name });
+ let acc = '';
+ for (const seg of name.split('/')) { acc = acc ? `${acc}/${seg}` : seg; expanded[acc] = true; }
await reloadCase();
- folderFilter = name;
} catch (e) {
toast(e.message, 'danger');
}
}
- async function assignFolder(entity, folder) {
- const val = folder || '';
- try {
- if (entity.type === 'media' && 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 reloadCase();
- } catch (e) {
- toast(e.message, 'danger');
- }
+ function startAddSub(path) {
+ addingUnder = path;
+ newSubName = '';
+ expanded[path] = true;
+ }
+ async function submitAddSub() {
+ const name = newSubName.trim();
+ const parent = addingUnder;
+ addingUnder = undefined;
+ newSubName = '';
+ if (!name || parent === undefined) return;
+ await createFolder(parent ? `${parent}/${name}` : name);
}
- async function deleteFolder(f) {
- if (!confirm(`Delete folder "${f}"? Items inside become unfiled.`)) return;
- const inside = entities.filter((e) => folderOf(e) === f);
- for (const e of inside) {
- // clear each entity's folder (keeps media sidecars in sync)
- if (e.type === 'media' && e.attrs?.path) {
- await api.patch(`/api/cases/${caseState.current.id}/media`, {
- path: e.attrs.path, folder: '',
- });
- } else {
- await api.patch(`/api/cases/${caseState.current.id}/entities/${e.id}`, {
- attrs: { folder: '' },
- });
- }
+ // File (or unfile, with folder='') an entity into a My-work folder. Media
+ // keeps its sidecar in sync via its own endpoint.
+ async function assignFolder(entity, folder) {
+ const val = folder || '';
+ if (entity.type === 'media' && 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 api.del(`/api/cases/${caseState.current.id}/folders?name=${encodeURIComponent(f)}`);
await reloadCase();
- if (folderFilter === f) folderFilter = null;
}
// drag & drop wiring
@@ -205,7 +267,85 @@
dragOverFolder = undefined;
const entity = entities.find((e) => e.id === dragEntityId);
dragEntityId = null;
- if (entity) assignFolder(entity, folder);
+ if (entity) assignFolder(entity, folder).catch((e) => toast(e.message, 'danger'));
+ }
+
+ // ── confirmation dialog (replaces browser confirm()) ──────────────────────
+ let confirmState = $state(null); // { title, message, detail, 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;
+ }
+ }
+
+ // Delete everywhere: removes the entity and its underlying file(s). Used from
+ // Saved work (and the note modal) — irreversible, danger tone.
+ function askDeleteEverywhere(entity, onDone) {
+ confirmState = {
+ title: 'Delete everywhere?',
+ message: `“${entity.label}” will be removed from Saved work and My work.`,
+ detail: FILE_BACKED.has(entity.type)
+ ? 'This permanently deletes the underlying file(s) on disk — it cannot be undone.'
+ : 'This permanently removes it from the case — it cannot be undone.',
+ confirmLabel: 'Delete everywhere',
+ tone: 'danger',
+ icon: 'trash',
+ action: async () => {
+ await api.del(`/api/cases/${caseState.current.id}/entities/${entity.id}`);
+ await reloadCase();
+ toast(`Deleted "${entity.label}"`, 'info');
+ onDone?.();
+ },
+ };
+ }
+
+ // Remove from My work: just clears the filing. The item stays in Saved work.
+ function askRemoveFromMyWork(entity) {
+ confirmState = {
+ title: 'Remove from My work?',
+ message: `“${entity.label}” goes back to Saved work — nothing is deleted.`,
+ detail: 'It stays available under its tool in Saved work. Only your filing here is cleared.',
+ confirmLabel: 'Remove from My work',
+ tone: 'default',
+ icon: 'folderMinus',
+ action: () => assignFolder(entity, ''),
+ };
+ }
+
+ function askDeleteFolder(path) {
+ const prefix = path + '/';
+ const inside = entities.filter((e) => {
+ const f = folderOf(e);
+ return f === path || (f && f.startsWith(prefix));
+ });
+ const subs = allFolders.filter((f) => f.startsWith(prefix)).length;
+ confirmState = {
+ title: 'Remove this folder?',
+ message: subs
+ ? `“${path}” and its ${subs} subfolder(s) will be removed from My work.`
+ : `“${path}” will be removed from My work.`,
+ detail: 'Items inside go back to Saved work — no files are deleted.',
+ confirmLabel: 'Remove folder',
+ tone: 'default',
+ icon: 'folderMinus',
+ action: async () => {
+ for (const e of inside) await assignFolder(e, '');
+ await api.del(
+ `/api/cases/${caseState.current.id}/folders?name=${encodeURIComponent(path)}`
+ );
+ await reloadCase();
+ },
+ };
}
// ── entity info modal (media details) ─────────────────────────────────────
@@ -243,7 +383,7 @@
let noteModalSaving = $state(false);
function openNewNote() {
- noteModal = { entity: null, title: '', folder: folderFilter || '', content: '' };
+ noteModal = { entity: null, title: '', folder: '', content: '' };
}
function openEditNote(entity) {
@@ -302,7 +442,7 @@
<div class="sections">
- <!-- Case Notes (single notes.md) -->
+ <!-- 1 · Case Notes (single notes.md) -->
<button class="section-head" onclick={() => (section.notes = !section.notes)}>
<Icon name={section.notes ? 'chevronDown' : 'chevronRight'} size={13} />
<span>Case Notes</span>
@@ -317,104 +457,23 @@
></textarea>
{/if}
- <!-- Folders -->
- <button class="section-head" onclick={() => (section.folders = !section.folders)}>
- <Icon name={section.folders ? 'chevronDown' : 'chevronRight'} size={13} />
- <span>Folders</span>
- <span class="count">{allFolders.length}</span>
- </button>
- {#if section.folders}
- <form class="new-folder" onsubmit={(e) => { e.preventDefault(); createFolder(); }}>
- <input class="input" placeholder="New folder…" bind:value={newFolder} />
- <button class="btn btn-sm" type="submit" title="Create folder" disabled={!newFolder.trim()}>
- <Icon name="plus" size={13} />
- </button>
- </form>
-
- <div class="folder-list">
- <!-- All -->
- <button
- class="frow"
- class:active={folderFilter === null}
- class:dropping={dragOverFolder === 'ALL_SENTINEL'}
- onclick={() => (folderFilter = null)}
- >
- <Icon name="layers" size={13} />
- <span class="fname">All items</span>
- <span class="fcount">{entities.length}</span>
- </button>
-
- <!-- Unfiled (drop target to clear folder) -->
- <button
- class="frow"
- class:active={folderFilter === ''}
- class:dropping={dragOverFolder === ''}
- ondragover={(e) => { e.preventDefault(); dragOverFolder = ''; }}
- ondragleave={() => (dragOverFolder = undefined)}
- ondrop={(e) => onDropFolder(e, '')}
- onclick={() => (folderFilter = '')}
- >
- <Icon name="folder" size={13} />
- <span class="fname">Unfiled</span>
- <span class="fcount">{countInFolder('')}</span>
- </button>
-
- {#each allFolders as f (f)}
- <button
- class="frow"
- class:active={folderFilter === f}
- class:dropping={dragOverFolder === f}
- ondragover={(e) => { e.preventDefault(); dragOverFolder = f; }}
- ondragleave={() => (dragOverFolder = undefined)}
- ondrop={(e) => onDropFolder(e, f)}
- onclick={() => (folderFilter = f)}
- >
- <Icon name="folderOpen" size={13} />
- <span class="fname">{f}</span>
- <span class="fcount">{countInFolder(f)}</span>
- <span
- class="fdel"
- role="button"
- tabindex="0"
- title="Delete folder"
- onclick={(e) => { e.stopPropagation(); deleteFolder(f); }}
- onkeydown={(e) => e.key === 'Enter' && (e.stopPropagation(), deleteFolder(f))}
- >
- <Icon name="trash" size={12} />
- </span>
- </button>
- {/each}
- </div>
- <div class="hint">Drag an entity onto a folder to file it.</div>
- {/if}
-
- <!-- Entities -->
+ <!-- 2 · Saved work (auto — grouped by the tool that produced each item) -->
<div class="section-head-row">
- <button class="section-head" onclick={() => (section.entities = !section.entities)}>
- <Icon name={section.entities ? 'chevronDown' : 'chevronRight'} size={13} />
- <span>Entities</span>
- <span class="count">{entities.length}</span>
+ <button class="section-head" onclick={() => (section.saved = !section.saved)}>
+ <Icon name={section.saved ? 'chevronDown' : 'chevronRight'} size={13} />
+ <span>Saved work</span>
+ <span class="count">{confirmed.length}</span>
</button>
<button class="btn btn-ghost btn-sm new-note-btn" title="New note" onclick={openNewNote}>
<Icon name="plus" size={13} /><Icon name="note" size={13} />
</button>
</div>
- {#if section.entities}
- {#if folderFilter !== null}
- <div class="active-folder">
- <Icon name={folderFilter === '' ? 'folder' : 'folderOpen'} size={12} />
- <span>{folderFilter === '' ? 'Unfiled' : folderFilter}</span>
- <button class="clear-filter" onclick={() => (folderFilter = null)} title="Clear filter">
- <Icon name="x" size={12} />
- </button>
- </div>
- {/if}
-
- <!-- suggested entities -->
- {#if filteredSuggested.length > 0}
+ {#if section.saved}
+ <!-- suggested entities (pinned — confirm or dismiss) -->
+ {#if suggested.length > 0}
<div class="suggest-note">Suggested — confirm or dismiss:</div>
- {#each filteredSuggested as e (e.id)}
+ {#each suggested as e (e.id)}
<div class="entity suggested">
<Icon name={ENTITY_ICONS[e.type] ?? 'note'} size={14} />
<div class="e-body">
@@ -424,66 +483,186 @@
<button class="btn btn-ghost btn-sm" title="Confirm" onclick={() => confirmEntity(e)}>
<Icon name="check" size={13} />
</button>
- <button class="btn btn-ghost btn-sm" title="Dismiss" onclick={() => removeEntity(e)}>
+ <button class="btn btn-ghost btn-sm" title="Dismiss" onclick={() => dismissSuggestion(e)}>
<Icon name="x" size={13} />
</button>
</div>
{/each}
{/if}
- <!-- confirmed entities -->
- {#each filteredConfirmed as e (e.id)}
- {@const isClickable = e.type === 'note' || !!ENTITY_TOOL[e.type]}
- <div
- class="entity"
- class:clickable={isClickable}
- class:dragging={dragEntityId === e.id}
- draggable="true"
- ondragstart={(ev) => onDragStart(ev, e)}
- ondragend={() => { dragEntityId = null; dragOverFolder = undefined; }}
- onclick={() => (e.type === 'note' ? openEditNote(e) : openEntity(e))}
- role={isClickable ? 'button' : undefined}
- tabindex={isClickable ? 0 : undefined}
- onkeydown={(ev) => ev.key === 'Enter' && (e.type === 'note' ? openEditNote(e) : openEntity(e))}
- >
- <Icon name="grip" size={13} />
- <Icon name={ENTITY_ICONS[e.type] ?? 'note'} size={14} />
- <div class="e-body">
- <span class="e-label">{e.label}</span>
- <span class="e-meta">
- {e.type}
- {#if folderOf(e)}· <Icon name="folder" size={10} />{folderOf(e)}{/if}
- </span>
- </div>
- <button
- class="btn btn-ghost btn-sm act"
- title="Info"
- onclick={(ev) => { ev.stopPropagation(); openInfo(e); }}
- >
- <Icon name="note" size={13} />
+ <div class="tree">
+ {#each savedGroups as g (g.key)}
+ <button class="grow" onclick={() => toggleGroup(g.key)}>
+ <Icon name={isGroupOpen(g.key) ? 'chevronDown' : 'chevronRight'} size={12} />
+ <Icon name={g.icon} size={13} />
+ <span class="fname">{g.label}</span>
+ <span class="fcount">{g.items.length}</span>
</button>
- <button
- class="btn btn-ghost btn-sm act del"
- title="Delete"
- onclick={(ev) => { ev.stopPropagation(); removeEntity(e); }}
- >
- <Icon name="trash" size={13} />
- </button>
- </div>
- {:else}
- {#if !filteredSuggested.length}
+ {#if isGroupOpen(g.key)}
+ {#each g.items as e (e.id)}
+ {@render entityRow(e, 1, 'saved')}
+ {/each}
+ {/if}
+ {/each}
+
+ {#if savedGroups.length === 0 && suggested.length === 0}
+ <div class="none">Tools file what you save here as you work.</div>
+ {/if}
+ </div>
+ {/if}
+
+ <!-- 3 · My work (manual — your own folders, filled by drag & drop) -->
+ <button class="section-head" onclick={() => (section.mywork = !section.mywork)}>
+ <Icon name={section.mywork ? 'chevronDown' : 'chevronRight'} size={13} />
+ <span>My work</span>
+ <span class="count">{filedCount}</span>
+ </button>
+
+ {#if section.mywork}
+ <!-- create a top-level folder -->
+ <form class="new-folder" onsubmit={(e) => { e.preventDefault(); createFolder(); }}>
+ <input class="input" placeholder="New folder…" bind:value={newFolder} />
+ <button class="btn btn-sm" type="submit" title="Create folder" disabled={!newFolder.trim()}>
+ <Icon name="plus" size={13} />
+ </button>
+ </form>
+
+ <div class="tree">
+ {#each tree as node (node.path)}
+ {@render folderNode(node, 0)}
+ {/each}
+
+ {#if tree.length === 0}
<div class="none">
- {folderFilter !== null ? 'No items in this folder.' : 'Tools file entities here as you work.'}
+ Create a folder, then drag items from Saved work here to organize your investigation.
</div>
{/if}
- {/each}
+ </div>
+ {#if tree.length > 0}
+ <div class="hint">Drag an item from Saved work onto a folder to file it here.</div>
+ {/if}
{/if}
-
</div>
{/if}
</aside>
+<!-- one folder node + its subtree (recursive) -->
+{#snippet folderNode(node, depth)}
+ <div
+ class="frow"
+ class:dropping={dragOverFolder === node.path}
+ style="padding-left: {8 + depth * 14}px"
+ role="button"
+ tabindex="0"
+ ondragover={(e) => { e.preventDefault(); dragOverFolder = node.path; }}
+ ondragleave={() => (dragOverFolder = undefined)}
+ ondrop={(e) => onDropFolder(e, node.path)}
+ onclick={() => toggle(node.path)}
+ onkeydown={(e) => e.key === 'Enter' && toggle(node.path)}
+ >
+ <Icon name={isExpanded(node.path) ? 'chevronDown' : 'chevronRight'} size={12} />
+ <Icon name={isExpanded(node.path) ? 'folderOpen' : 'folder'} size={13} />
+ <span class="fname">{node.name}</span>
+ <span class="fcount">{subtreeCount(node)}</span>
+ <span
+ class="fact"
+ role="button"
+ tabindex="0"
+ title="Add subfolder"
+ onclick={(e) => { e.stopPropagation(); startAddSub(node.path); }}
+ onkeydown={(e) => e.key === 'Enter' && (e.stopPropagation(), startAddSub(node.path))}
+ >
+ <Icon name="plus" size={12} />
+ </span>
+ <span
+ class="fact fdel"
+ role="button"
+ tabindex="0"
+ title="Remove folder"
+ onclick={(e) => { e.stopPropagation(); askDeleteFolder(node.path); }}
+ onkeydown={(e) => e.key === 'Enter' && (e.stopPropagation(), askDeleteFolder(node.path))}
+ >
+ <Icon name="folderMinus" size={12} />
+ </span>
+ </div>
+ {#if isExpanded(node.path)}
+ {#if addingUnder === node.path}
+ <form
+ class="new-folder sub"
+ style="padding-left: {8 + (depth + 1) * 14}px"
+ onsubmit={(e) => { e.preventDefault(); submitAddSub(); }}
+ >
+ <input
+ class="input"
+ placeholder="Subfolder…"
+ bind:value={newSubName}
+ use:focus
+ onkeydown={(e) => e.key === 'Escape' && (addingUnder = undefined)}
+ />
+ <button class="btn btn-sm" type="submit" title="Create" disabled={!newSubName.trim()}>
+ <Icon name="plus" size={13} />
+ </button>
+ </form>
+ {/if}
+ {#each node.children as child (child.path)}
+ {@render folderNode(child, depth + 1)}
+ {/each}
+ {#each node.entities as e (e.id)}
+ {@render entityRow(e, depth + 1, 'mywork')}
+ {/each}
+ {/if}
+{/snippet}
+
+<!-- one entity row. zone 'saved' → delete everywhere; 'mywork' → unfile only -->
+{#snippet entityRow(e, depth, zone)}
+ {@const isClickable = e.type === 'note' || !!ENTITY_TOOL[e.type]}
+ <div
+ class="entity"
+ class:clickable={isClickable}
+ class:dragging={dragEntityId === e.id}
+ style="padding-left: {8 + depth * 14}px"
+ draggable="true"
+ ondragstart={(ev) => onDragStart(ev, e)}
+ ondragend={() => { dragEntityId = null; dragOverFolder = undefined; }}
+ onclick={() => (e.type === 'note' ? openEditNote(e) : openEntity(e))}
+ role={isClickable ? 'button' : undefined}
+ tabindex={isClickable ? 0 : undefined}
+ onkeydown={(ev) => ev.key === 'Enter' && (e.type === 'note' ? openEditNote(e) : openEntity(e))}
+ >
+ <Icon name="grip" size={13} />
+ <Icon name={ENTITY_ICONS[e.type] ?? 'note'} size={14} />
+ <div class="e-body">
+ <span class="e-label">{e.label}</span>
+ <span class="e-meta">{e.type}</span>
+ </div>
+ <button
+ class="btn btn-ghost btn-sm act"
+ title="Info"
+ onclick={(ev) => { ev.stopPropagation(); openInfo(e); }}
+ >
+ <Icon name="note" size={13} />
+ </button>
+ {#if zone === 'mywork'}
+ <button
+ class="btn btn-ghost btn-sm act del"
+ title="Remove from My work"
+ onclick={(ev) => { ev.stopPropagation(); askRemoveFromMyWork(e); }}
+ >
+ <Icon name="folderMinus" size={13} />
+ </button>
+ {:else}
+ <button
+ class="btn btn-ghost btn-sm act del"
+ title="Delete everywhere"
+ onclick={(ev) => { ev.stopPropagation(); askDeleteEverywhere(e); }}
+ >
+ <Icon name="trash" size={13} />
+ </button>
+ {/if}
+ </div>
+{/snippet}
+
<!-- Note edit / create modal -->
{#if noteModal}
<Modal
@@ -499,7 +678,7 @@
bind:value={noteModal.title}
/>
- <label class="modal-label" for="note-folder" style="margin-top:10px">Folder</label>
+ <label class="modal-label" for="note-folder" style="margin-top:10px">Folder (in My work)</label>
<input
id="note-folder"
class="input"
@@ -525,7 +704,7 @@
<button
class="btn btn-ghost btn-sm"
style="color:var(--danger,#e55)"
- onclick={async () => { await removeEntity(noteModal.entity); noteModal = null; }}
+ onclick={() => askDeleteEverywhere(noteModal.entity, () => (noteModal = null))}
>
<Icon name="trash" size={13} /> Delete note
</button>
@@ -619,6 +798,21 @@
</Modal>
{/if}
+<!-- Confirmation dialog (delete everywhere / remove from My work / remove folder) -->
+{#if confirmState}
+ <ConfirmDialog
+ title={confirmState.title}
+ message={confirmState.message}
+ detail={confirmState.detail}
+ confirmLabel={confirmState.confirmLabel}
+ tone={confirmState.tone}
+ icon={confirmState.icon}
+ busy={confirmBusy}
+ onconfirm={runConfirm}
+ oncancel={() => (confirmState = null)}
+ />
+{/if}
+
<style>
.sidebar {
width: var(--sidebar-w);
@@ -672,14 +866,29 @@
margin: 0 4px 10px;
width: calc(100% - 8px);
}
- /* folder management */
+ /* tool group header (Saved work) */
+ .grow {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ width: 100%;
+ padding: 6px 8px;
+ border-radius: var(--r-sm);
+ color: var(--text-2);
+ font-size: var(--fs-sm);
+ text-align: left;
+ }
+ .grow:hover { background: var(--bg-2); color: var(--text-1); }
+ .grow > :global(svg:first-child) { color: var(--text-3); flex-shrink: 0; }
+ /* folder tree */
.new-folder { display: flex; gap: 6px; padding: 2px 8px 8px; }
+ .new-folder.sub { padding: 2px 8px 4px; }
.new-folder .input { flex: 1; font-size: var(--fs-xs); }
- .folder-list { display: flex; flex-direction: column; gap: 2px; padding: 0 4px 4px; }
+ .tree { display: flex; flex-direction: column; gap: 1px; padding: 0 4px 4px; }
.frow {
display: flex;
align-items: center;
- gap: 8px;
+ gap: 7px;
width: 100%;
padding: 6px 8px;
border-radius: var(--r-sm);
@@ -690,27 +899,15 @@
text-align: left;
}
.frow:hover { background: var(--bg-2); }
- .frow.active { background: var(--accent-soft); color: var(--accent); }
.frow.dropping { border-color: var(--accent); background: var(--accent-soft); }
+ .frow > :global(svg:first-child) { color: var(--text-3); flex-shrink: 0; }
.fname { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.fcount { color: var(--text-3); font-size: var(--fs-xs); font-weight: 600; }
- .fdel { opacity: 0; color: var(--text-3); display: flex; padding: 2px; border-radius: 4px; }
+ .fact { opacity: 0; color: var(--text-3); display: flex; padding: 2px; border-radius: 4px; flex-shrink: 0; }
+ .fact:hover { color: var(--text-1); }
.fdel:hover { color: var(--danger, #e55); }
- .frow:hover .fdel { opacity: 1; }
+ .frow:hover .fact { opacity: 1; }
.hint { font-size: var(--fs-xs); color: var(--text-3); padding: 2px 12px 8px; font-style: italic; }
- .active-folder {
- display: flex;
- align-items: center;
- gap: 5px;
- padding: 4px 10px;
- margin: 2px 4px 6px;
- border-radius: 999px;
- background: var(--accent-soft);
- color: var(--accent);
- font-size: var(--fs-xs);
- width: fit-content;
- }
- .clear-filter { display: flex; color: var(--accent); padding: 0; }
/* entities */
.entity {
display: flex;
@@ -748,7 +945,7 @@
.entity:hover .act { opacity: 1; }
.del:hover { color: var(--danger, #e55); }
.suggest-note { font-size: var(--fs-xs); color: var(--accent); padding: 2px 8px 6px; }
- .none { font-size: var(--fs-xs); color: var(--text-3); padding: 4px 8px 12px; }
+ .none { font-size: var(--fs-xs); color: var(--text-3); padding: 4px 8px 12px; line-height: 1.45; }
/* note modal */
.modal-label { display: block; font-size: var(--fs-xs); color: var(--text-3); margin-bottom: 5px; }
.note-content { width: 100%; resize: vertical; font-family: var(--font-mono); font-size: var(--fs-xs); }
@@ -773,4 +970,3 @@
.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); }
</style>
-
diff --git a/frontend/src/components/ConfirmDialog.svelte b/frontend/src/components/ConfirmDialog.svelte
new file mode 100644
index 0000000..0e9c2a9
--- /dev/null
+++ b/frontend/src/components/ConfirmDialog.svelte
@@ -0,0 +1,140 @@
+<script>
+ import Icon from './Icon.svelte';
+
+ // A small, styled confirmation dialog — replaces the browser confirm() popup.
+ // Tone drives the accent so a destructive action reads differently from a
+ // reversible one.
+ // tone: 'danger' → deletes everywhere (irreversible, drops files)
+ // tone: 'default' → reversible (unfile, remove a folder)
+ let {
+ title,
+ message,
+ detail = '',
+ confirmLabel = 'Confirm',
+ tone = 'default', // 'danger' | 'default'
+ icon = tone === 'danger' ? 'trash' : 'folderMinus',
+ busy = false,
+ onconfirm,
+ oncancel,
+ } = $props();
+
+ function onkeydown(e) {
+ if (e.key === 'Escape') oncancel?.();
+ else if (e.key === 'Enter') onconfirm?.();
+ }
+</script>
+
+<svelte:window {onkeydown} />
+
+<div
+ class="overlay"
+ onclick={(e) => e.target === e.currentTarget && oncancel?.()}
+ role="presentation"
+>
+ <div class="dialog fade-up" class:danger={tone === 'danger'} role="alertdialog" aria-label={title}>
+ <div class="head">
+ <span class="badge" class:danger={tone === 'danger'}>
+ <Icon name={icon} size={18} />
+ </span>
+ <div class="titles">
+ <h3>{title}</h3>
+ <p class="msg">{message}</p>
+ </div>
+ </div>
+ {#if detail}
+ <p class="detail" class:danger={tone === 'danger'}>{detail}</p>
+ {/if}
+ <div class="actions">
+ <button class="btn" onclick={oncancel} disabled={busy}>Cancel</button>
+ <button
+ class="btn {tone === 'danger' ? 'btn-danger' : 'btn-primary'}"
+ onclick={onconfirm}
+ disabled={busy}
+ >
+ {busy ? 'Working…' : confirmLabel}
+ </button>
+ </div>
+ </div>
+</div>
+
+<style>
+ .overlay {
+ position: fixed;
+ inset: 0;
+ background: rgba(4, 7, 12, 0.72);
+ backdrop-filter: blur(3px);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ z-index: 950;
+ }
+ .dialog {
+ background: var(--bg-1);
+ border: 1px solid var(--border-strong);
+ border-top: 3px solid var(--accent);
+ border-radius: var(--r-lg);
+ box-shadow: var(--shadow-2);
+ width: 400px;
+ max-width: calc(100vw - 40px);
+ padding: 18px 18px 14px;
+ }
+ .dialog.danger {
+ border-top-color: var(--danger, #e5484d);
+ }
+ .head {
+ display: flex;
+ gap: 13px;
+ align-items: flex-start;
+ }
+ .badge {
+ flex-shrink: 0;
+ width: 38px;
+ height: 38px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ border-radius: 10px;
+ background: var(--accent-soft);
+ color: var(--accent);
+ }
+ .badge.danger {
+ background: color-mix(in srgb, var(--danger, #e5484d) 16%, transparent);
+ color: var(--danger, #e5484d);
+ }
+ .titles { min-width: 0; }
+ h3 {
+ font-size: var(--fs-md);
+ font-weight: 700;
+ margin-bottom: 3px;
+ }
+ .msg {
+ font-size: var(--fs-sm);
+ color: var(--text-2);
+ line-height: 1.4;
+ }
+ .detail {
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ margin: 12px 0 0;
+ padding: 8px 10px;
+ background: var(--bg-2);
+ border-radius: var(--r-sm);
+ line-height: 1.45;
+ }
+ .detail.danger {
+ color: color-mix(in srgb, var(--danger, #e5484d) 85%, var(--text-2));
+ background: color-mix(in srgb, var(--danger, #e5484d) 9%, transparent);
+ }
+ .actions {
+ display: flex;
+ justify-content: flex-end;
+ gap: 8px;
+ margin-top: 16px;
+ }
+ .btn-danger {
+ background: var(--danger, #e5484d);
+ color: #fff;
+ border-color: transparent;
+ }
+ .btn-danger:hover { filter: brightness(1.08); }
+</style>
diff --git a/frontend/src/components/Icon.svelte b/frontend/src/components/Icon.svelte
index d0822b6..469375b 100644
--- a/frontend/src/components/Icon.svelte
+++ b/frontend/src/components/Icon.svelte
@@ -12,6 +12,7 @@
plus: 'M12 5v14m-7-7h14',
folder: 'M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7Z',
folderOpen: 'M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v1M3 7v11a2 2 0 0 0 2 2h13a2 2 0 0 0 2-1.5l1.6-6A1.5 1.5 0 0 0 20.1 10H6.4a2 2 0 0 0-1.9 1.4L3 16',
+ folderMinus: 'M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7Zm6 6h6',
x: 'M6 6l12 12M18 6 6 18',
chevronRight: 'm9 6 6 6-6 6',
chevronLeft: 'm15 6-6 6 6 6',
diff --git a/frontend/src/lib/inspect.js b/frontend/src/lib/inspect.js
new file mode 100644
index 0000000..b5c9722
--- /dev/null
+++ b/frontend/src/lib/inspect.js
@@ -0,0 +1,137 @@
+/**
+ * Inspect-session helpers, shared by the Selection / Frame / Collage / Save tabs.
+ *
+ * The Inspect tool is a scratch workspace: captured frames, per-frame adjustments
+ * and a collage layout live here as plain data ("recipes") and only become case
+ * media on an explicit Save. These pure helpers turn slider values into the live
+ * CSS preview + the backend op pipeline, and handle the collage perspective math.
+ */
+
+// Order the adjust pipeline is applied in (matches the backend ORDER in bake()).
+export const ADJUST_ORDER = [
+ 'brightness', 'contrast', 'saturation', 'gamma', 'sharpness', 'rotate', 'grayscale', 'invert',
+];
+
+let _seq = 0;
+export const uid = (prefix = 'id') => `${prefix}_${Date.now().toString(36)}_${_seq++}`;
+
+export function adjustDefaults(filters) {
+ const out = {};
+ for (const f of filters) out[f.id] = f.params[0]?.default ?? 0;
+ return out;
+}
+
+// The video gear only exposes these css-filter ids; a frame captured from a
+// tuned video inherits them so it looks like it came from the modified clip.
+export const VIDEO_ADJUST_IDS = ['brightness', 'contrast', 'saturation', 'gamma', 'grayscale', 'invert'];
+
+/** Seed a new frame's adjust values from the current video-gear values. */
+export function videoSeed(filters, videoAdjust) {
+ const out = adjustDefaults(filters);
+ for (const id of VIDEO_ADJUST_IDS) {
+ if (videoAdjust && id in videoAdjust) out[id] = videoAdjust[id];
+ }
+ return out;
+}
+
+const paramName = (f) => f.params[0]?.name ?? 'amount';
+const defaultOf = (f) => f.params[0]?.default ?? 0;
+
+/** Build the live-preview CSS `filter` + `transform` strings from slider values. */
+export function previewStyle(filters, values) {
+ values = values ?? {};
+ const pick = (getter) =>
+ filters
+ .filter(getter)
+ .map((f) => getter(f).replaceAll('{v}', values[f.id] ?? defaultOf(f)))
+ .join(' ');
+ return {
+ filter: pick((f) => f.css),
+ transform: pick((f) => f.transform),
+ };
+}
+
+export function isNeutral(filters, values) {
+ values = values ?? {};
+ return filters.every((f) => (values[f.id] ?? defaultOf(f)) === defaultOf(f));
+}
+
+/** Turn slider values (+ optional fractional crop) into the backend op pipeline. */
+export function buildOps(filters, values, crop = null) {
+ values = values ?? {};
+ const ops = [];
+ if (crop) ops.push({ op: 'crop', params: crop });
+ for (const id of ADJUST_ORDER) {
+ const f = filters.find((x) => x.id === id);
+ if (!f || (values[id] ?? defaultOf(f)) === defaultOf(f)) continue;
+ ops.push({ op: id, params: { [paramName(f)]: values[id] } });
+ }
+ return ops;
+}
+
+// ---------------------------------------------------------------------------
+// Collage perspective: map an image's box to a 4-point quad via a CSS matrix3d.
+// Classic homography-from-4-corners (general 2D projection). The same quad is
+// sent to the backend, which composites the full-res warp with PIL — so the
+// on-screen preview and the saved image agree.
+// ---------------------------------------------------------------------------
+
+function adj(m) {
+ return [
+ m[4] * m[8] - m[5] * m[7], m[2] * m[7] - m[1] * m[8], m[1] * m[5] - m[2] * m[4],
+ m[5] * m[6] - m[3] * m[8], m[0] * m[8] - m[2] * m[6], m[2] * m[3] - m[0] * m[5],
+ m[3] * m[7] - m[4] * m[6], m[1] * m[6] - m[0] * m[7], m[0] * m[4] - m[1] * m[3],
+ ];
+}
+
+function mul(a, b) {
+ const c = new Array(9);
+ for (let i = 0; i < 3; i++)
+ for (let j = 0; j < 3; j++)
+ c[3 * i + j] = a[3 * i] * b[j] + a[3 * i + 1] * b[3 + j] + a[3 * i + 2] * b[6 + j];
+ return c;
+}
+
+function mulV(m, v) {
+ return [
+ m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
+ m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
+ m[6] * v[0] + m[7] * v[1] + m[8] * v[2],
+ ];
+}
+
+function basisToPoints(p) {
+ const m = [p[0][0], p[1][0], p[2][0], p[0][1], p[1][1], p[2][1], 1, 1, 1];
+ const v = mulV(adj(m), [p[3][0], p[3][1], 1]);
+ return mul(m, [v[0], 0, 0, 0, v[1], 0, 0, 0, v[2]]);
+}
+
+/**
+ * CSS `matrix3d(...)` mapping the box (0,0)-(w,h) onto `quad`
+ * (4 points: TL, TR, BR, BL, in the same pixel space as the element's parent).
+ */
+export function quadMatrix3d(w, h, quad) {
+ const src = [[0, 0], [w, 0], [w, h], [0, h]];
+ let H = mul(basisToPoints(quad), adj(basisToPoints(src)));
+ H = H.map((x) => x / H[8]);
+ const t = [
+ H[0], H[3], 0, H[6],
+ H[1], H[4], 0, H[7],
+ 0, 0, 1, 0,
+ H[2], H[5], 0, H[8],
+ ];
+ return `matrix3d(${t.join(',')})`;
+}
+
+/** A sensible starting quad: the image scaled to fit `maxW`, placed at (ox, oy). */
+export function initialQuad(natW, natH, maxW, ox, oy) {
+ const scale = Math.min(1, maxW / (natW || maxW));
+ const w = Math.round((natW || maxW) * scale);
+ const h = Math.round((natH || maxW) * scale);
+ return [
+ [ox, oy],
+ [ox + w, oy],
+ [ox + w, oy + h],
+ [ox, oy + h],
+ ];
+}
diff --git a/frontend/src/lib/inspectModules.js b/frontend/src/lib/inspectModules.js
deleted file mode 100644
index f73cb06..0000000
--- a/frontend/src/lib/inspectModules.js
+++ /dev/null
@@ -1,28 +0,0 @@
-/**
- * Inspector module registry — the frontend extension seam.
- *
- * Add a mini-tool by writing a Svelte component under tools/inspect/ and
- * appending one entry here:
- * { id, label, icon, kinds, component }
- * - kinds: which source media kinds the module applies to ('image' | 'video')
- *
- * Each module receives props:
- * { source, probeInfo, shared, mediaList, onProduced }
- * - source : the selected media item ({ path, filename, kind, ... })
- * - probeInfo : dimensions / duration / fps from /inspect/probe
- * - shared : reactive bridge to the viewer (filter, transform, crop,
- * cropMode, currentTime, seekTo)
- * - mediaList : all case media (for modules that pick several images)
- * - onProduced : call with the API result after filing a new derivative
- */
-import FramesModule from '../tools/inspect/FramesModule.svelte';
-import AdjustModule from '../tools/inspect/AdjustModule.svelte';
-import CollageModule from '../tools/inspect/CollageModule.svelte';
-import AnalyzeModule from '../tools/inspect/AnalyzeModule.svelte';
-
-export const INSPECT_MODULES = [
- { id: 'frames', label: 'Frames', icon: 'video', kinds: ['video'], component: FramesModule },
- { id: 'adjust', label: 'Adjust', icon: 'sliders', kinds: ['image'], component: AdjustModule },
- { id: 'collage', label: 'Collage', icon: 'layers', kinds: ['image', 'video'], component: CollageModule },
- { id: 'analyze', label: 'Analyze', icon: 'eye', kinds: ['image'], component: AnalyzeModule },
-];
diff --git a/frontend/src/lib/state.svelte.js b/frontend/src/lib/state.svelte.js
index dc26759..fd25e9b 100644
--- a/frontend/src/lib/state.svelte.js
+++ b/frontend/src/lib/state.svelte.js
@@ -11,6 +11,7 @@ export const caseState = $state({
current: null, // { id, name, scratch, entities, links, ... }
list: [],
loading: false,
+ rev: 0, // bumped on every reload so tools can re-fetch their own artifacts
});
export const uiState = $state({
@@ -23,6 +24,7 @@ export const uiState = $state({
openProof: null, // proof name to load in the Proof Composer
openDraft: null, // draft name to load in the Post Composer
inspectPath: null, // media path to open in the Inspect tool
+ openInspect: null, // inspect-session name to reopen in the Inspect tool
gotoCoords: null, // { lat, lon } to fly to in the Satellite tool
});
@@ -87,6 +89,7 @@ export async function initSession() {
export async function reloadCase() {
if (caseState.current) {
caseState.current = await api.get(`/api/cases/${caseState.current.id}`);
+ caseState.rev++;
}
}
diff --git a/frontend/src/tools/Inspector.svelte b/frontend/src/tools/Inspector.svelte
index 269cb90..4e2038f 100644
--- a/frontend/src/tools/Inspector.svelte
+++ b/frontend/src/tools/Inspector.svelte
@@ -1,46 +1,102 @@
<script>
import { api } from '../lib/api.js';
import { caseState, uiState, reloadCase, toast } from '../lib/state.svelte.js';
- import { INSPECT_MODULES } from '../lib/inspectModules.js';
+ import {
+ adjustDefaults, buildOps, previewStyle, isNeutral, uid, videoSeed, initialQuad, VIDEO_ADJUST_IDS,
+ } from '../lib/inspect.js';
import Icon from '../components/Icon.svelte';
+ import SelectionMenu from './inspect/SelectionMenu.svelte';
+ import FrameMenu from './inspect/FrameMenu.svelte';
+ import CollageCanvas from './inspect/CollageCanvas.svelte';
+ import CollageMenu from './inspect/CollageMenu.svelte';
+ import SaveGallery from './inspect/SaveGallery.svelte';
+ import SaveMenu from './inspect/SaveMenu.svelte';
+
+ // The Inspect tool is a *scratch workspace*. Opening a photo/video starts a
+ // session; captured frames, per-frame adjustments, video tuning and a collage
+ // layout all live here as plain data. Nothing becomes case media until the Save
+ // tab commits it — the recipes are re-derived full-res on the backend then.
+ const TAB_META = {
+ selection: { label: 'Selection', icon: 'video' },
+ frame: { label: 'Frame', icon: 'image' },
+ collage: { label: 'Collage', icon: 'layers' },
+ save: { label: 'Save', icon: 'save' },
+ };
let mediaList = $state([]);
let loadedFor = $state(null);
- let source = $state(null);
+ let filters = $state([]);
+ let analyses = $state([]);
let probeInfo = $state(null);
- let moduleId = $state(null);
- let produced = $state(null);
-
- // reactive bridge between the modules and the viewer
- const shared = $state({
- filter: '',
- transform: '',
- crop: null, // { x, y, w, h } fractional
- cropMode: false,
- currentTime: 0,
- seekTo: null,
+
+ let activeTab = $state('selection');
+ let collageSelectedId = $state(null);
+ let saving = $state(false);
+ const saveUi = $state({ selected: {}, folder: '' });
+ // the saved session this workspace came from (if any) — re-saving overwrites it
+ // in place instead of forking a new named session.
+ let openedSession = $state(null);
+ const sessionModal = $state({ open: false, mode: 'save', name: null, title: '', list: [], busy: false });
+
+ // the live session (reset on source / case change)
+ const session = $state({
+ source: null,
+ videoAdjust: {},
+ frames: [],
+ activeFrameId: null,
+ collage: { width: 1600, height: 800, background: '#12141c', transparent: false, nodes: [] },
+ saved: {},
});
+ // viewer bridge (video seek + crop overlay), mirrors the old shared object
+ const shared = $state({ currentTime: 0, seekTo: null, cropMode: false });
let videoEl = $state();
- let cropDraw = $state(null); // in-progress crop rectangle
+ let cropDraw = $state(null);
- const modules = $derived(
- source ? INSPECT_MODULES.filter((m) => m.kinds.includes(source.kind)) : []
+ const videoFilters = $derived(filters.filter((f) => VIDEO_ADJUST_IDS.includes(f.id)));
+ const tabs = $derived(
+ session.source?.kind === 'video' ? ['selection', 'frame', 'collage', 'save'] : ['frame', 'collage', 'save']
);
- const ActiveModule = $derived(modules.find((m) => m.id === moduleId)?.component ?? null);
+ const activeFrame = $derived(session.frames.find((f) => f.id === session.activeFrameId) ?? null);
+ const framePreview = $derived(activeFrame ? previewStyle(filters, activeFrame.adjust) : { filter: '', transform: '' });
+ const videoPreview = $derived(previewStyle(videoFilters, session.videoAdjust));
- // load case media; react to case switches
+ const savables = $derived.by(() => {
+ const out = [];
+ const cid = caseState.current?.id;
+ if (session.source?.kind === 'video' && !isNeutral(videoFilters, session.videoAdjust)) {
+ const t = session.source.thumbnail ? `/files/${cid}/${session.source.thumbnail}` : null;
+ out.push({ key: 'video', kind: 'video', label: 'Video 1', thumb: t, saved: !!session.saved.video });
+ }
+ let imgN = 0;
+ for (const fr of session.frames) {
+ imgN += 1;
+ out.push({
+ key: `frame:${fr.id}`, kind: 'frame', frame: fr, thumb: fr.url,
+ label: `Image ${imgN}`, filter: previewStyle(filters, fr.adjust).filter,
+ saved: !!session.saved[`frame:${fr.id}`],
+ });
+ }
+ if (session.collage.nodes.length) {
+ out.push({
+ key: 'collage', kind: 'collage', label: 'Collage 1',
+ thumb: null, collage: session.collage, saved: !!session.saved.collage,
+ });
+ }
+ return out;
+ });
+
+ // -- lifecycle ------------------------------------------------------------
$effect(() => {
const id = caseState.current?.id;
if (id !== loadedFor) {
loadedFor = id;
mediaList = [];
- source = null;
+ resetSession();
if (id) refresh(id);
}
});
- // deep-link from the Media Library ("Inspect")
$effect(() => {
if (uiState.tool === 'inspect' && uiState.inspectPath && mediaList.length) {
const target = mediaList.find((m) => m.path === uiState.inspectPath);
@@ -49,7 +105,15 @@
}
});
- // apply a requested video seek coming from a module
+ // reopen a saved session from the sidebar (like proofs/posts)
+ $effect(() => {
+ if (uiState.tool === 'inspect' && uiState.openInspect && mediaList.length) {
+ const name = uiState.openInspect;
+ uiState.openInspect = null;
+ openSession(name);
+ }
+ });
+
$effect(() => {
if (shared.seekTo != null && videoEl) {
videoEl.currentTime = shared.seekTo;
@@ -57,19 +121,39 @@
}
});
+ async function ensureOps() {
+ if (filters.length) return;
+ const ops = await api.get('/api/inspect/ops');
+ filters = ops.filters.filter((f) => f.id !== 'crop');
+ analyses = ops.analyses;
+ }
+
async function refresh(id = caseState.current?.id) {
if (!id) return;
mediaList = await api.get(`/api/cases/${id}/media`);
- if (source) {
- const still = mediaList.find((m) => m.path === source.path);
- if (!still) source = null;
- }
+ }
+
+ function resetSession() {
+ for (const fr of session.frames) if (fr.url?.startsWith('blob:')) URL.revokeObjectURL(fr.url);
+ session.source = null;
+ session.videoAdjust = {};
+ session.frames = [];
+ session.activeFrameId = null;
+ session.collage = { width: 1600, height: 800, background: '#12141c', transparent: false, nodes: [] };
+ session.saved = {};
+ saveUi.selected = {};
+ saveUi.folder = '';
+ openedSession = null;
+ collageSelectedId = null;
+ shared.currentTime = 0;
+ shared.cropMode = false;
+ cropDraw = null;
}
async function select(item) {
- resetViewer();
- source = item;
- produced = null;
+ await ensureOps();
+ resetSession();
+ session.source = item;
try {
probeInfo = await api.get(
`/api/cases/${caseState.current.id}/inspect/probe?path=${encodeURIComponent(item.path)}`
@@ -77,34 +161,99 @@
} catch {
probeInfo = { kind: item.kind };
}
- const applicable = INSPECT_MODULES.filter((m) => m.kinds.includes(item.kind));
- moduleId = applicable[0]?.id ?? null;
+ if (item.kind === 'video') {
+ session.videoAdjust = adjustDefaults(videoFilters);
+ activeTab = 'selection';
+ } else {
+ const frame = makeFrame(item.path, null, `/files/${caseState.current.id}/${item.path}`);
+ session.frames.push(frame);
+ session.activeFrameId = frame.id;
+ activeTab = 'frame';
+ }
}
- function resetViewer() {
- shared.filter = '';
- shared.transform = '';
- shared.crop = null;
- shared.cropMode = false;
- shared.currentTime = 0;
+ function makeFrame(path, time, url) {
+ return {
+ id: uid('fr'), path, time, url,
+ adjust: adjustDefaults(filters), crop: null,
+ w: probeInfo?.width, h: probeInfo?.height,
+ };
}
- function onProduced(res) {
- produced = res.item;
- refresh();
+ // Render a recipe (video frame / image + ops) to a blob URL, no filing.
+ async function renderUrl(path, time, ops = []) {
+ const res = await fetch(`/api/cases/${caseState.current.id}/inspect/render-preview`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ path, time: time ?? null, ops }),
+ });
+ if (!res.ok) {
+ let detail = 'render failed';
+ try {
+ detail = (await res.json()).detail;
+ } catch {
+ /* non-json */
+ }
+ throw new Error(detail);
+ }
+ return URL.createObjectURL(await res.blob());
}
- function inspectProduced() {
- const item = mediaList.find((m) => m.path === produced.path) ?? produced;
- select({ ...item, kind: 'image' });
+ function imageSize(url) {
+ return new Promise((resolve) => {
+ const im = new Image();
+ im.onload = () => resolve({ w: im.naturalWidth, h: im.naturalHeight });
+ im.onerror = () => resolve({ w: probeInfo?.width || 320, h: probeInfo?.height || 240 });
+ im.src = url;
+ });
}
- function sendToComposer(item) {
- if (!uiState.composeQueue.includes(item.path)) uiState.composeQueue.push(item.path);
- uiState.tool = 'proof';
+ // -- frame capture (Selection) -------------------------------------------
+ async function capture(time) {
+ try {
+ const url = await renderUrl(session.source.path, time, []);
+ const frame = makeFrame(session.source.path, time, url);
+ // frames captured from a tuned video inherit those gear adjustments
+ frame.adjust = videoSeed(filters, session.videoAdjust);
+ session.frames.push(frame);
+ session.activeFrameId = frame.id;
+ toast('Frame added to tray — not saved yet', 'ok');
+ } catch (e) {
+ toast(e.message, 'danger');
+ }
}
- // -- crop overlay ---------------------------------------------------------
+ // Collage pieces are snapshots frozen at add-time: the modified image is baked
+ // now and later frame edits never change it (deliberate — see SPEC).
+ async function addToCollage(frame) {
+ try {
+ const ops = buildOps(filters, frame.adjust, frame.crop);
+ const url = await renderUrl(frame.path, frame.time, ops);
+ const dim = await imageSize(url);
+ const count = session.collage.nodes.length;
+ const off = 30 + (count % 4) * 40;
+ const quad = initialQuad(dim.w, dim.h, session.collage.width * 0.5, off, off);
+ const node = {
+ id: uid('nd'), frameId: frame.id, url, w: dim.w, h: dim.h,
+ save: { path: frame.path, time: frame.time ?? null, ops }, quad,
+ };
+ session.collage.nodes.push(node);
+ collageSelectedId = node.id;
+ } catch (e) {
+ toast(e.message, 'danger');
+ }
+ }
+
+ function removeFrame(id) {
+ const fr = session.frames.find((f) => f.id === id);
+ if (fr?.url?.startsWith('blob:')) URL.revokeObjectURL(fr.url);
+ session.frames = session.frames.filter((f) => f.id !== id);
+ // collage pieces are independent snapshots — they stay.
+ delete session.saved[`frame:${id}`];
+ if (session.activeFrameId === id) session.activeFrameId = session.frames[0]?.id ?? null;
+ }
+
+ // -- crop overlay (Frame tab) --------------------------------------------
function frac(e, el) {
const r = el.getBoundingClientRect();
return {
@@ -112,47 +261,214 @@
y: Math.min(Math.max((e.clientY - r.top) / r.height, 0), 1),
};
}
-
function cropDown(e) {
- if (!shared.cropMode) return;
+ if (!shared.cropMode || !activeFrame) return;
e.preventDefault();
const p = frac(e, e.currentTarget);
cropDraw = { sx: p.x, sy: p.y, x: p.x, y: p.y, w: 0, h: 0 };
e.currentTarget.setPointerCapture(e.pointerId);
}
-
function cropMove(e) {
if (!cropDraw) return;
const p = frac(e, e.currentTarget);
cropDraw = {
- sx: cropDraw.sx,
- sy: cropDraw.sy,
- x: Math.min(cropDraw.sx, p.x),
- y: Math.min(cropDraw.sy, p.y),
- w: Math.abs(p.x - cropDraw.sx),
- h: Math.abs(p.y - cropDraw.sy),
+ sx: cropDraw.sx, sy: cropDraw.sy,
+ x: Math.min(cropDraw.sx, p.x), y: Math.min(cropDraw.sy, p.y),
+ w: Math.abs(p.x - cropDraw.sx), h: Math.abs(p.y - cropDraw.sy),
};
}
-
function cropUp() {
- if (cropDraw && cropDraw.w > 0.02 && cropDraw.h > 0.02) {
- shared.crop = { x: cropDraw.x, y: cropDraw.y, w: cropDraw.w, h: cropDraw.h };
+ if (cropDraw && cropDraw.w > 0.02 && cropDraw.h > 0.02 && activeFrame) {
+ activeFrame.crop = { x: cropDraw.x, y: cropDraw.y, w: cropDraw.w, h: cropDraw.h };
shared.cropMode = false;
}
cropDraw = null;
}
+ const cropBox = $derived(cropDraw ?? activeFrame?.crop ?? null);
+
+ // -- save (the only gate that files entities) ----------------------------
+ async function saveSelected() {
+ const cid = caseState.current.id;
+ const folder = saveUi.folder?.trim() || null;
+ const chosen = savables.filter((it) => saveUi.selected[it.key]);
+ if (!chosen.length) return;
+ saving = true;
+ try {
+ const frameItems = chosen
+ .filter((it) => it.kind === 'frame')
+ .map((it) => ({
+ path: it.frame.path,
+ time: it.frame.time ?? null,
+ ops: buildOps(filters, it.frame.adjust, it.frame.crop),
+ }));
+ if (frameItems.length) {
+ await api.post(`/api/cases/${cid}/inspect/save-frames`, { items: frameItems, folder });
+ for (const it of chosen) if (it.kind === 'frame') session.saved[it.key] = true;
+ }
+ if (chosen.some((it) => it.kind === 'video')) {
+ await api.post(`/api/cases/${cid}/inspect/enhance-video`, {
+ path: session.source.path, params: session.videoAdjust, folder,
+ });
+ session.saved.video = true;
+ }
+ if (chosen.some((it) => it.kind === 'collage')) {
+ // each node carries its frozen snapshot recipe (path/time/ops)
+ const nodes = session.collage.nodes.map((n) => ({ src: n.save, quad: n.quad }));
+ await api.post(`/api/cases/${cid}/inspect/compose`, {
+ width: Math.round(session.collage.width),
+ height: Math.round(session.collage.height),
+ background: session.collage.transparent ? null : session.collage.background,
+ nodes, folder,
+ });
+ session.saved.collage = true;
+ }
+ await reloadCase();
+ await refresh();
+ saveUi.selected = {};
+ toast(`Saved ${chosen.length} item${chosen.length === 1 ? '' : 's'} to the case`, 'ok');
+ } catch (e) {
+ toast(e.message, 'danger');
+ } finally {
+ saving = false;
+ }
+ }
- const cropBox = $derived(cropDraw ?? shared.crop);
+ // -- saveable sessions (persist the whole workspace, reopen later) --------
+ function sessionSpec() {
+ return {
+ source: { path: session.source.path, kind: session.source.kind },
+ videoAdjust: { ...session.videoAdjust },
+ activeFrameId: session.activeFrameId,
+ frames: session.frames.map((f) => ({
+ id: f.id, path: f.path, time: f.time, adjust: { ...f.adjust }, crop: f.crop, w: f.w, h: f.h,
+ })),
+ collage: {
+ width: session.collage.width, height: session.collage.height,
+ background: session.collage.background, transparent: session.collage.transparent,
+ nodes: session.collage.nodes.map((n) => ({
+ id: n.id, frameId: n.frameId, save: n.save, w: n.w, h: n.h, quad: n.quad,
+ })),
+ },
+ };
+ }
+
+ function openSaveDialog() {
+ sessionModal.mode = 'save';
+ sessionModal.name = openedSession?.name ?? null;
+ sessionModal.title = openedSession?.title || session.source?.label || session.source?.filename || 'Inspect session';
+ sessionModal.open = true;
+ }
+
+ async function openLoadDialog() {
+ sessionModal.mode = 'open';
+ sessionModal.busy = true;
+ sessionModal.open = true;
+ try {
+ sessionModal.list = await api.get(`/api/cases/${caseState.current.id}/inspect/sessions`);
+ } catch (e) {
+ toast(e.message, 'danger');
+ } finally {
+ sessionModal.busy = false;
+ }
+ }
+
+ async function confirmSaveSession() {
+ const title = sessionModal.title.trim();
+ if (!title) return;
+ sessionModal.busy = true;
+ try {
+ const res = await api.post(`/api/cases/${caseState.current.id}/inspect/sessions`, {
+ name: sessionModal.name, title, spec: sessionSpec(),
+ });
+ openedSession = { name: res.name, title };
+ await reloadCase();
+ sessionModal.open = false;
+ toast('Session saved — reopen it from the sidebar', 'ok');
+ } catch (e) {
+ toast(e.message, 'danger');
+ } finally {
+ sessionModal.busy = false;
+ }
+ }
+
+ 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;
+ 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 ?? []) {
+ try {
+ const url = await renderUrl(f.path, f.time, []);
+ session.frames.push({ ...f, url });
+ } catch {
+ /* skip a frame whose source is gone */
+ }
+ }
+ session.activeFrameId = spec.activeFrameId ?? session.frames[0]?.id ?? null;
+ const nodes = [];
+ for (const n of spec.collage?.nodes ?? []) {
+ try {
+ nodes.push({ ...n, url: await renderUrl(n.save.path, n.save.time, n.save.ops) });
+ } catch {
+ /* skip a node whose source is gone */
+ }
+ }
+ session.collage = {
+ width: spec.collage?.width ?? 1600,
+ height: spec.collage?.height ?? 800,
+ background: spec.collage?.background ?? '#12141c',
+ transparent: spec.collage?.transparent ?? false,
+ nodes,
+ };
+ openedSession = { name, title: spec.title || name };
+ activeTab = src.kind === 'video' ? 'selection' : 'frame';
+ sessionModal.open = false;
+ }
+
+ async function deleteSession(name) {
+ try {
+ await api.del(`/api/cases/${caseState.current.id}/inspect/sessions/${name}`);
+ sessionModal.list = sessionModal.list.filter((s) => s.name !== name);
+ if (openedSession?.name === name) openedSession = null;
+ await reloadCase();
+ } catch (e) {
+ toast(e.message, 'danger');
+ }
+ }
</script>
<div class="tool">
<div class="tool-header">
<h2>Inspect</h2>
- <span class="sub">open a photo or video — grab frames, adjust, collage &amp; analyse</span>
+ <span class="sub">a scratch workspace — capture, tune, collage; save only what you keep</span>
<div class="spacer"></div>
+ {#if caseState.current}
+ <button class="btn btn-sm" onclick={openLoadDialog} title="Reopen a saved session">
+ <Icon name="folderOpen" size={14} /> Open
+ </button>
+ <button class="btn btn-sm" disabled={!session.source} onclick={openSaveDialog} title="Save this workspace">
+ <Icon name="save" size={14} /> Save session
+ </button>
+ {/if}
<select
class="input source-select"
- value={source?.path ?? ''}
+ value={session.source?.path ?? ''}
onchange={(e) => {
const m = mediaList.find((x) => x.path === e.target.value);
if (m) select(m);
@@ -171,7 +487,7 @@
<p>Open a case and add media to start inspecting.</p>
<button class="btn btn-primary" onclick={() => (uiState.tool = 'media')}>Go to Media Library</button>
</div>
- {:else if !source}
+ {:else if !session.source}
<div class="empty">
<Icon name="inspect" size={40} />
<p>Choose a media above to open it.</p>
@@ -180,79 +496,126 @@
{/if}
</div>
{:else}
+ <div class="tabbar">
+ {#each tabs as t (t)}
+ <button class="tab" class:active={activeTab === t} onclick={() => (activeTab = t)}>
+ <Icon name={TAB_META[t].icon} size={15} /> {TAB_META[t].label}
+ </button>
+ {/each}
+ </div>
+
<div class="workspace">
- <div class="viewer">
- <div
- class="frame"
- class:cropping={shared.cropMode}
- onpointerdown={cropDown}
- onpointermove={cropMove}
- onpointerup={cropUp}
- >
- {#if source.kind === 'video'}
+ <div class="viewer" class:pad={activeTab !== 'collage' && activeTab !== 'save'}>
+ {#if activeTab === 'selection'}
+ <div class="frame">
<!-- svelte-ignore a11y_media_has_caption -->
<video
bind:this={videoEl}
- src={`/files/${caseState.current.id}/${source.path}`}
+ src={`/files/${caseState.current.id}/${session.source.path}`}
controls
ontimeupdate={() => (shared.currentTime = videoEl?.currentTime ?? 0)}
- style:filter={shared.filter}
- style:transform={shared.transform}
+ style:filter={videoPreview.filter}
+ style:transform={videoPreview.transform}
></video>
- {:else}
- <img
- src={`/files/${caseState.current.id}/${source.path}`}
- alt={source.filename}
- style:filter={shared.filter}
- style:transform={shared.transform}
- />
- {/if}
-
- {#if cropBox}
+ </div>
+ {:else if activeTab === 'frame'}
+ {#if activeFrame}
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
<div
- class="crop-box"
- style:left={`${cropBox.x * 100}%`}
- style:top={`${cropBox.y * 100}%`}
- style:width={`${cropBox.w * 100}%`}
- style:height={`${cropBox.h * 100}%`}
- ></div>
+ class="frame"
+ class:cropping={shared.cropMode}
+ onpointerdown={cropDown}
+ onpointermove={cropMove}
+ onpointerup={cropUp}
+ >
+ <img src={activeFrame.url} alt="frame" style:filter={framePreview.filter} style:transform={framePreview.transform} />
+ {#if cropBox}
+ <div
+ class="crop-box"
+ style:left={`${cropBox.x * 100}%`}
+ style:top={`${cropBox.y * 100}%`}
+ style:width={`${cropBox.w * 100}%`}
+ style:height={`${cropBox.h * 100}%`}
+ ></div>
+ {/if}
+ </div>
+ {:else}
+ <div class="hint-mid">
+ <Icon name="image" size={34} />
+ <p>No frame selected — capture frames in the Selection tab.</p>
+ </div>
{/if}
- </div>
+ {:else if activeTab === 'collage'}
+ <CollageCanvas {session} bind:selectedId={collageSelectedId} />
+ {:else if activeTab === 'save'}
+ <SaveGallery {savables} {saveUi} />
+ {/if}
</div>
<aside class="panel">
- <div class="module-tabs">
- {#each modules as m (m.id)}
- <button class="mtab" class:active={moduleId === m.id} onclick={() => (moduleId = m.id)}>
- <Icon name={m.icon} size={15} /> {m.label}
- </button>
- {/each}
+ {#if activeTab === 'selection'}
+ <SelectionMenu {probeInfo} {shared} {videoFilters} {session} {capture} />
+ {:else if activeTab === 'frame'}
+ <FrameMenu {session} {filters} {analyses} {activeFrame} {shared} {removeFrame} setActive={(id) => (session.activeFrameId = id)} />
+ {:else if activeTab === 'collage'}
+ <CollageMenu {session} {filters} bind:selectedId={collageSelectedId} {addToCollage} />
+ {:else if activeTab === 'save'}
+ <SaveMenu {savables} {saveUi} {saving} save={saveSelected} />
+ {/if}
+ </aside>
+ </div>
+ {/if}
+
+ {#if sessionModal.open}
+ <!-- svelte-ignore a11y_click_events_have_key_events -->
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
+ <div class="modal-back" onclick={() => (sessionModal.open = false)} role="presentation">
+ <!-- svelte-ignore a11y_click_events_have_key_events -->
+ <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
+ <div class="modal" onclick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" tabindex="-1">
+ <div class="modal-head">
+ <h3>{sessionModal.mode === 'save' ? 'Save session' : 'Open session'}</h3>
+ <button class="btn btn-ghost btn-xs" onclick={() => (sessionModal.open = false)} aria-label="Close">
+ <Icon name="x" size={15} />
+ </button>
</div>
- {#if produced}
- <div class="produced fade-up">
- <img src={`/files/${caseState.current.id}/${produced.thumbnail ?? produced.path}`} alt="result" />
- <div class="produced-body">
- <span class="produced-name">{produced.filename}</span>
- <div class="produced-actions">
- <button class="btn btn-xs" onclick={inspectProduced}><Icon name="inspect" size={12} /> Inspect</button>
- <button class="btn btn-xs" onclick={() => sendToComposer(produced)}>
- <Icon name="proof" size={12} /> Composer
- </button>
- </div>
- </div>
- <button class="btn btn-ghost btn-xs" onclick={() => (produced = null)} aria-label="Dismiss">
- <Icon name="x" size={13} />
+ {#if sessionModal.mode === 'save'}
+ <p class="modal-hint">Persist this whole workspace — frames, adjustments and the collage — to reopen later. Saving the session does not file any media.</p>
+ <input
+ class="input"
+ placeholder="Session name"
+ bind:value={sessionModal.title}
+ onkeydown={(e) => e.key === 'Enter' && confirmSaveSession()}
+ />
+ <div class="modal-actions">
+ <button class="btn btn-sm" onclick={() => (sessionModal.open = false)}>Cancel</button>
+ <button class="btn btn-primary btn-sm" disabled={sessionModal.busy || !sessionModal.title.trim()} onclick={confirmSaveSession}>
+ <Icon name="save" size={14} /> Save
</button>
</div>
- {/if}
-
- <div class="module-body">
- {#if ActiveModule}
- <ActiveModule {source} {probeInfo} {shared} {mediaList} {onProduced} />
+ {:else}
+ {#if sessionModal.busy}
+ <p class="modal-hint">Loading…</p>
+ {:else if sessionModal.list.length === 0}
+ <p class="modal-hint">No saved sessions yet.</p>
+ {:else}
+ <div class="session-list">
+ {#each sessionModal.list as s (s.name)}
+ <div class="session-row">
+ <button class="session-open" 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">
+ <Icon name="trash" size={14} />
+ </button>
+ </div>
+ {/each}
+ </div>
{/if}
- </div>
- </aside>
+ {/if}
+ </div>
</div>
{/if}
</div>
@@ -285,7 +648,8 @@
.source-select {
max-width: 280px;
}
- .empty {
+ .empty,
+ .hint-mid {
flex: 1;
display: flex;
flex-direction: column;
@@ -293,6 +657,36 @@
justify-content: center;
gap: 12px;
color: var(--text-3);
+ text-align: center;
+ }
+ .hint-mid p {
+ max-width: 260px;
+ font-size: var(--fs-sm);
+ }
+ .tabbar {
+ display: flex;
+ gap: 4px;
+ padding: 8px 12px;
+ border-bottom: 1px solid var(--border);
+ flex-shrink: 0;
+ }
+ .tab {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 7px 12px;
+ border-radius: var(--r-md);
+ font-size: var(--fs-sm);
+ font-weight: 600;
+ color: var(--text-3);
+ }
+ .tab:hover {
+ color: var(--text-1);
+ background: var(--bg-2);
+ }
+ .tab.active {
+ color: var(--accent);
+ background: var(--accent-soft);
}
.workspace {
flex: 1;
@@ -305,10 +699,12 @@
display: flex;
align-items: center;
justify-content: center;
- padding: 18px;
background: var(--bg-0);
overflow: auto;
}
+ .viewer.pad {
+ padding: 18px;
+ }
.frame {
position: relative;
display: inline-block;
@@ -322,7 +718,7 @@
.frame img,
.frame video {
max-width: 100%;
- max-height: calc(100vh - var(--topbar-h) - 120px);
+ max-height: calc(100vh - var(--topbar-h) - 160px);
display: block;
}
.crop-box {
@@ -339,69 +735,82 @@
display: flex;
flex-direction: column;
min-height: 0;
+ overflow: auto;
+ padding: 14px;
}
- .module-tabs {
+ .modal-back {
+ position: fixed;
+ inset: 0;
+ background: rgba(6, 9, 14, 0.6);
display: flex;
- gap: 4px;
- padding: 10px;
- border-bottom: 1px solid var(--border);
- flex-wrap: wrap;
+ align-items: center;
+ justify-content: center;
+ z-index: 50;
+ }
+ .modal {
+ width: 420px;
+ max-width: calc(100vw - 40px);
+ max-height: calc(100vh - 80px);
+ overflow: auto;
+ background: var(--bg-1);
+ border: 1px solid var(--border-strong);
+ border-radius: var(--r-lg, 12px);
+ box-shadow: var(--shadow-2);
+ padding: 16px;
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
}
- .mtab {
+ .modal-head {
display: flex;
align-items: center;
- gap: 5px;
- padding: 6px 9px;
- border-radius: var(--r-md);
- font-size: var(--fs-sm);
- font-weight: 600;
- color: var(--text-3);
+ justify-content: space-between;
}
- .mtab:hover {
- color: var(--text-1);
- background: var(--bg-2);
- }
- .mtab.active {
- color: var(--accent);
- background: var(--accent-soft);
+ .modal-head h3 {
+ font-size: var(--fs-md);
+ font-weight: 700;
}
- .module-body {
- padding: 14px;
- overflow: auto;
- flex: 1;
+ .modal-hint {
+ color: var(--text-3);
+ font-size: var(--fs-sm);
+ margin: 0;
}
- .produced {
+ .modal-actions {
display: flex;
- align-items: center;
+ justify-content: flex-end;
gap: 8px;
- margin: 10px;
- padding: 8px;
- border: 1px solid var(--border-strong);
- border-radius: var(--r-md);
- background: var(--bg-2);
}
- .produced img {
- width: 46px;
- height: 46px;
- object-fit: cover;
- border-radius: var(--r-sm);
+ .session-list {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
}
- .produced-body {
+ .session-row {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ }
+ .session-open {
flex: 1;
- min-width: 0;
display: flex;
flex-direction: column;
- gap: 5px;
+ gap: 2px;
+ text-align: left;
+ padding: 8px 10px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ background: var(--bg-2);
}
- .produced-name {
- font-size: var(--fs-xs);
- color: var(--text-2);
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
+ .session-open:hover {
+ border-color: var(--accent);
}
- .produced-actions {
- display: flex;
- gap: 5px;
+ .session-title {
+ font-size: var(--fs-sm);
+ font-weight: 600;
+ color: var(--text-1);
+ }
+ .session-meta {
+ font-size: var(--fs-xs);
+ color: var(--text-3);
}
</style>
diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelte
index 0439066..3ea13a3 100644
--- a/frontend/src/tools/Satellite.svelte
+++ b/frontend/src/tools/Satellite.svelte
@@ -67,19 +67,25 @@
$effect(() => {
const id = caseState.current?.id;
- if (id !== capturesFor) {
- capturesFor = id;
+ caseState.rev; // re-fetch when the case is reloaded elsewhere (e.g. sidebar delete)
+ if (!id) {
+ capturesFor = null;
captures = [];
- if (id) api.get(`/api/cases/${id}/satellite`).then((r) => (captures = r));
+ return;
}
+ capturesFor = id;
+ api.get(`/api/cases/${id}/satellite`).then((r) => (captures = r));
});
- // fly to coordinates handed off from the sidebar (place entity click)
+ // fly to coordinates handed off from the sidebar (place entity click) —
+ // match the capture's own zoom/bearing, like clicking its card
$effect(() => {
const target = uiState.gotoCoords;
if (mapReady && target && Number.isFinite(target.lat) && Number.isFinite(target.lon)) {
uiState.gotoCoords = null;
- map.setView([target.lat, target.lon], Math.max(map.getZoom(), 16));
+ const zoom = Number.isFinite(target.zoom) ? target.zoom : Math.max(map.getZoom(), 16);
+ map.setView([target.lat, target.lon], zoom);
+ setBearing(Number.isFinite(target.bearing) ? target.bearing : 0);
}
});
@@ -143,16 +149,20 @@
`/api/cases/${caseState.current.id}/satellite?path=${encodeURIComponent(item.path)}`
);
captures = captures.filter((c) => c.path !== item.path);
+ // the capture's place entity may have gone with it — refresh the sidebar
+ await reloadCase();
}
- // --- notes modal ---
+ // --- details modal (title + notes) ---
let notesItem = $state(null);
let notesText = $state('');
+ let notesTitle = $state('');
let notesSaving = $state(false);
function openNotes(item) {
notesItem = item;
notesText = item.notes ?? '';
+ notesTitle = item.title ?? coordsLabel(item);
}
async function saveNotes() {
@@ -161,11 +171,13 @@
try {
const updated = await api.patch(
`/api/cases/${caseState.current.id}/satellite`,
- { path: notesItem.path, notes: notesText }
+ { path: notesItem.path, notes: notesText, title: notesTitle }
);
const idx = captures.findIndex((c) => c.path === notesItem.path);
if (idx !== -1) captures[idx] = updated;
notesItem = null;
+ // the mirrored place entity was retitled too — refresh the sidebar
+ await reloadCase();
toast('Saved', 'ok', 1600);
} catch (e) {
toast(e.message, 'danger');
@@ -174,6 +186,10 @@
}
}
+ function coordsLabel(item) {
+ return `${item.lat.toFixed(6)}, ${item.lon.toFixed(6)}`;
+ }
+
function sendToComposer(item) {
if (!uiState.composeQueue.includes(item.path)) uiState.composeQueue.push(item.path);
uiState.tool = 'proof';
@@ -347,7 +363,8 @@
loading="lazy"
/>
<div class="cap-meta">
- <span class="mono coords">{item.lat.toFixed(6)}, {item.lon.toFixed(6)}</span>
+ <span class="title">{item.title ?? coordsLabel(item)}</span>
+ <span class="mono coords">{coordsLabel(item)}</span>
<span class="prov">z{item.zoom}{item.bearing ? ` · ${Math.round(item.bearing)}°` : ''} · {item.provider_label} · {item.fetched_at?.slice(0, 10)}</span>
</div>
</button>
@@ -396,7 +413,14 @@
<!-- satellite notes modal -->
{#if notesItem}
- <Modal title="Capture notes" onclose={() => (notesItem = null)} width="420px">
+ <Modal title="Capture details" onclose={() => (notesItem = null)} width="420px">
+ <label style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin-bottom:5px">Title</label>
+ <input
+ class="input"
+ placeholder={coordsLabel(notesItem)}
+ bind:value={notesTitle}
+ />
+ <hr style="border:none;border-top:1px solid var(--border);margin:12px 0" />
<div class="sat-info-rows">
<div class="sat-info-row">
<span class="sat-info-label">Coordinates</span>
@@ -692,9 +716,20 @@
display: flex;
flex-direction: column;
}
+ .title {
+ font-size: var(--fs-sm);
+ color: var(--text-1);
+ font-weight: 600;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
.coords {
font-size: var(--fs-xs);
- color: var(--text-1);
+ color: var(--text-3);
+ }
+ .cap-goto:hover .title {
+ color: var(--accent);
}
.prov {
font-size: var(--fs-xs);
diff --git a/frontend/src/tools/inspect/AdjustModule.svelte b/frontend/src/tools/inspect/AdjustModule.svelte
deleted file mode 100644
index 0b09f9f..0000000
--- a/frontend/src/tools/inspect/AdjustModule.svelte
+++ /dev/null
@@ -1,204 +0,0 @@
-<script>
- import { onMount } from 'svelte';
- import { api } from '../../lib/api.js';
- import { caseState, reloadCase, toast } from '../../lib/state.svelte.js';
- import Icon from '../../components/Icon.svelte';
-
- // Non-destructive image adjustments. Controls are generated from the backend
- // filter registry (/api/inspect/ops) — adding a server-side filter surfaces a
- // slider here automatically. Live preview uses each filter's CSS hint; the
- // real render happens on "Export" so it stays reproducible (spec §6).
- let { source, shared, onProduced } = $props();
-
- const ORDER = ['brightness', 'contrast', 'saturation', 'gamma', 'sharpness', 'rotate', 'grayscale', 'invert'];
-
- let filters = $state([]);
- let values = $state({}); // filterId -> single param value
- let baking = $state(false);
-
- onMount(async () => {
- const ops = await api.get('/api/inspect/ops');
- filters = ops.filters
- .filter((f) => f.id !== 'crop')
- .sort((a, b) => ORDER.indexOf(a.id) - ORDER.indexOf(b.id));
- resetValues();
- });
-
- function resetValues() {
- const next = {};
- for (const f of filters) next[f.id] = f.params[0]?.default ?? 0;
- values = next;
- clearCrop();
- }
-
- function paramName(f) {
- return f.params[0]?.name ?? 'amount';
- }
-
- function isDefault(f) {
- return values[f.id] === (f.params[0]?.default ?? 0);
- }
-
- // live preview: CSS filter + transform strings pushed to the viewer
- $effect(() => {
- shared.filter = filters
- .filter((f) => f.css)
- .map((f) => f.css.replaceAll('{v}', values[f.id]))
- .join(' ');
- shared.transform = filters
- .filter((f) => f.transform)
- .map((f) => f.transform.replaceAll('{v}', values[f.id]))
- .join(' ');
- });
-
- function clearCrop() {
- shared.crop = null;
- shared.cropMode = false;
- }
-
- function toggleCrop() {
- shared.cropMode = !shared.cropMode;
- }
-
- function reset() {
- resetValues();
- }
-
- async function bake() {
- const ops = [];
- if (shared.crop) ops.push({ op: 'crop', params: shared.crop });
- for (const id of ORDER) {
- const f = filters.find((x) => x.id === id);
- if (!f || isDefault(f)) continue;
- ops.push({ op: id, params: { [paramName(f)]: values[id] } });
- }
- if (!ops.length) {
- toast('Nothing to apply — adjust a slider or set a crop first', 'info');
- return;
- }
- baking = true;
- try {
- const res = await api.post(`/api/cases/${caseState.current.id}/inspect/bake`, {
- path: source.path,
- ops,
- });
- await reloadCase();
- onProduced(res);
- toast(res.duplicate ? 'Identical image already in the case' : 'Edited image filed', res.duplicate ? 'warn' : 'ok');
- } catch (e) {
- toast(e.message, 'danger');
- } finally {
- baking = false;
- }
- }
-</script>
-
-<div class="module">
- {#each filters as f (f.id)}
- <label class="row" class:toggle={f.params[0]?.type === 'toggle'}>
- <span class="lbl">
- {f.label}
- {#if !f.css && !f.transform}<span class="pill" title="No live preview — applied on export">export</span>{/if}
- </span>
- {#if f.params[0]?.type === 'toggle'}
- <input type="checkbox" checked={values[f.id] === 1} onchange={(e) => (values[f.id] = e.target.checked ? 1 : 0)} />
- {:else}
- <input
- type="range"
- min={f.params[0].min}
- max={f.params[0].max}
- step={f.params[0].step}
- bind:value={values[f.id]}
- />
- <span class="val mono">{Number(values[f.id]).toFixed(f.params[0].step < 1 ? 2 : 0)}{f.params[0].unit}</span>
- {/if}
- </label>
- {/each}
-
- <div class="crop-row">
- <button class="btn btn-sm" class:active={shared.cropMode} onclick={toggleCrop}>
- <Icon name="crop" size={14} /> {shared.cropMode ? 'Drag on image…' : 'Crop region'}
- </button>
- {#if shared.crop}
- <span class="crop-info mono">
- {Math.round(shared.crop.w * 100)}% × {Math.round(shared.crop.h * 100)}%
- </span>
- <button class="btn btn-ghost btn-xs" onclick={clearCrop} title="Clear crop"><Icon name="x" size={13} /></button>
- {/if}
- </div>
-
- <div class="actions">
- <button class="btn btn-ghost btn-sm" onclick={reset}><Icon name="reset" size={14} /> Reset</button>
- <button class="btn btn-primary" disabled={baking} onclick={bake}>
- <Icon name="save" size={15} /> Export as new image
- </button>
- </div>
-</div>
-
-<style>
- .module {
- display: flex;
- flex-direction: column;
- gap: 10px;
- }
- .row {
- display: grid;
- grid-template-columns: 90px 1fr 42px;
- align-items: center;
- gap: 8px;
- font-size: var(--fs-sm);
- }
- .row.toggle {
- grid-template-columns: 1fr auto;
- }
- .lbl {
- color: var(--text-2);
- display: flex;
- align-items: center;
- gap: 5px;
- }
- .pill {
- font-size: 9px;
- text-transform: uppercase;
- letter-spacing: 0.04em;
- padding: 1px 4px;
- border-radius: 4px;
- background: var(--bg-2);
- color: var(--text-3);
- }
- input[type='range'] {
- width: 100%;
- accent-color: var(--accent);
- }
- input[type='checkbox'] {
- accent-color: var(--accent);
- width: 15px;
- height: 15px;
- }
- .val {
- text-align: right;
- color: var(--text-3);
- font-size: var(--fs-xs);
- }
- .crop-row {
- display: flex;
- align-items: center;
- gap: 8px;
- border-top: 1px solid var(--border);
- padding-top: 12px;
- }
- .crop-info {
- font-size: var(--fs-xs);
- color: var(--text-3);
- }
- .btn.active {
- color: var(--accent);
- border-color: var(--accent);
- }
- .actions {
- display: flex;
- justify-content: space-between;
- gap: 8px;
- margin-top: 4px;
- }
-</style>
diff --git a/frontend/src/tools/inspect/AdjustSliders.svelte b/frontend/src/tools/inspect/AdjustSliders.svelte
new file mode 100644
index 0000000..d2eedc5
--- /dev/null
+++ b/frontend/src/tools/inspect/AdjustSliders.svelte
@@ -0,0 +1,82 @@
+<script>
+ // Slider bank generated from the backend filter registry (/api/inspect/ops).
+ // Writes live into `values` (a reactive object owned by the session), so the
+ // caller can build both the CSS live-preview and the backend op pipeline.
+ let { filters, values } = $props();
+</script>
+
+<div class="sliders">
+ {#each filters as f (f.id)}
+ <label class="row" class:toggle={f.params[0]?.type === 'toggle'}>
+ <span class="lbl">
+ {f.label}
+ {#if !f.css && !f.transform}<span class="pill" title="Applied on save">save</span>{/if}
+ </span>
+ {#if f.params[0]?.type === 'toggle'}
+ <input
+ type="checkbox"
+ checked={values[f.id] === 1}
+ onchange={(e) => (values[f.id] = e.target.checked ? 1 : 0)}
+ />
+ {:else}
+ <input
+ type="range"
+ min={f.params[0].min}
+ max={f.params[0].max}
+ step={f.params[0].step}
+ bind:value={values[f.id]}
+ />
+ <span class="val mono">
+ {Number(values[f.id]).toFixed(f.params[0].step < 1 ? 2 : 0)}{f.params[0].unit}
+ </span>
+ {/if}
+ </label>
+ {/each}
+</div>
+
+<style>
+ .sliders {
+ display: flex;
+ flex-direction: column;
+ gap: 9px;
+ }
+ .row {
+ display: grid;
+ grid-template-columns: 90px 1fr 42px;
+ align-items: center;
+ gap: 8px;
+ font-size: var(--fs-sm);
+ }
+ .row.toggle {
+ grid-template-columns: 1fr auto;
+ }
+ .lbl {
+ color: var(--text-2);
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ }
+ .pill {
+ font-size: 9px;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ padding: 1px 4px;
+ border-radius: 4px;
+ background: var(--bg-2);
+ color: var(--text-3);
+ }
+ input[type='range'] {
+ width: 100%;
+ accent-color: var(--accent);
+ }
+ input[type='checkbox'] {
+ accent-color: var(--accent);
+ width: 15px;
+ height: 15px;
+ }
+ .val {
+ text-align: right;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+</style>
diff --git a/frontend/src/tools/inspect/AnalyzeModule.svelte b/frontend/src/tools/inspect/AnalyzeModule.svelte
deleted file mode 100644
index ed44475..0000000
--- a/frontend/src/tools/inspect/AnalyzeModule.svelte
+++ /dev/null
@@ -1,180 +0,0 @@
-<script>
- import { onMount } from 'svelte';
- import { api } from '../../lib/api.js';
- import { caseState, toast } from '../../lib/state.svelte.js';
- import Icon from '../../components/Icon.svelte';
-
- // Read-only inspectors. Each analysis returns one of a few render kinds
- // (keyvalue / histogram / image / text) so new analyses need no new UI here.
- let { source } = $props();
-
- let analyses = $state([]);
- let active = $state(null);
- let result = $state(null);
- let running = $state(false);
- let canvasEl = $state();
-
- onMount(async () => {
- analyses = (await api.get('/api/inspect/ops')).analyses;
- });
-
- async function run(name) {
- active = name;
- running = true;
- result = null;
- try {
- result = await api.post(`/api/cases/${caseState.current.id}/inspect/analyze`, {
- path: source.path,
- name,
- });
- if (result.kind === 'histogram') requestAnimationFrame(drawHistogram);
- } catch (e) {
- toast(e.message, 'danger');
- } finally {
- running = false;
- }
- }
-
- function drawHistogram() {
- if (!canvasEl || result?.kind !== 'histogram') return;
- const ctx = canvasEl.getContext('2d');
- const W = (canvasEl.width = canvasEl.clientWidth);
- const H = (canvasEl.height = 120);
- ctx.clearRect(0, 0, W, H);
- const ch = result.channels;
- const peak = Math.max(1, ...ch.r, ...ch.g, ...ch.b);
- ctx.globalCompositeOperation = 'lighter';
- for (const [name, color] of [
- ['r', 'rgba(230,70,70,0.8)'],
- ['g', 'rgba(70,210,110,0.8)'],
- ['b', 'rgba(90,140,240,0.8)'],
- ]) {
- ctx.beginPath();
- ctx.moveTo(0, H);
- ch[name].forEach((v, i) => ctx.lineTo((i / 255) * W, H - (v / peak) * H));
- ctx.lineTo(W, H);
- ctx.fillStyle = color;
- ctx.fill();
- }
- ctx.globalCompositeOperation = 'source-over';
- }
-</script>
-
-<div class="module">
- <div class="tabs">
- {#each analyses as a (a.id)}
- <button class="btn btn-sm" class:active={active === a.id} onclick={() => run(a.id)}>
- {a.label}
- </button>
- {/each}
- </div>
-
- {#if running}
- <p class="status"><Icon name="clock" size={14} /> Analysing…</p>
- {:else if result}
- {#if result.kind === 'keyvalue'}
- <table class="kv">
- <tbody>
- {#each Object.entries(result.rows) as [k, v] (k)}
- <tr><th>{k}</th><td class="mono">{v}</td></tr>
- {/each}
- </tbody>
- </table>
- {:else if result.kind === 'histogram'}
- <canvas bind:this={canvasEl} class="hist"></canvas>
- <p class="legend"><span class="r">R</span> <span class="g">G</span> <span class="b">B</span> intensity 0→255</p>
- {:else if result.kind === 'image'}
- <img class="analysis-img" src={result.data_url} alt="analysis" />
- {#if result.note}<p class="note"><Icon name="alert" size={13} /> {result.note}</p>{/if}
- {:else if result.kind === 'text'}
- <pre class="text">{result.text}</pre>
- {/if}
- {:else}
- <p class="status dim">Pick an analysis above.</p>
- {/if}
-</div>
-
-<style>
- .module {
- display: flex;
- flex-direction: column;
- gap: 10px;
- }
- .tabs {
- display: flex;
- flex-wrap: wrap;
- gap: 6px;
- }
- .btn.active {
- color: var(--accent);
- border-color: var(--accent);
- }
- .status {
- display: flex;
- align-items: center;
- gap: 6px;
- color: var(--text-3);
- font-size: var(--fs-sm);
- }
- .status.dim {
- color: var(--text-3);
- }
- .kv {
- width: 100%;
- border-collapse: collapse;
- font-size: var(--fs-xs);
- }
- .kv th {
- text-align: left;
- color: var(--text-3);
- font-weight: 600;
- padding: 3px 8px 3px 0;
- vertical-align: top;
- white-space: nowrap;
- }
- .kv td {
- padding: 3px 0;
- color: var(--text-2);
- word-break: break-all;
- }
- .kv tr + tr {
- border-top: 1px solid var(--border);
- }
- .hist {
- width: 100%;
- height: 120px;
- background: var(--bg-0);
- border-radius: var(--r-sm);
- }
- .legend {
- font-size: var(--fs-xs);
- color: var(--text-3);
- margin: 0;
- }
- .legend .r {
- color: #e64646;
- }
- .legend .g {
- color: #46d26e;
- }
- .legend .b {
- color: #5a8cf0;
- }
- .analysis-img {
- width: 100%;
- border-radius: var(--r-sm);
- background: #000;
- }
- .note {
- display: flex;
- gap: 6px;
- font-size: var(--fs-xs);
- color: var(--warn, #d8a24a);
- margin: 0;
- }
- .text {
- font-size: var(--fs-xs);
- white-space: pre-wrap;
- color: var(--text-2);
- }
-</style>
diff --git a/frontend/src/tools/inspect/CollageCanvas.svelte b/frontend/src/tools/inspect/CollageCanvas.svelte
new file mode 100644
index 0000000..f6ff651
--- /dev/null
+++ b/frontend/src/tools/inspect/CollageCanvas.svelte
@@ -0,0 +1,184 @@
+<script>
+ import { quadMatrix3d } from '../../lib/inspect.js';
+ import Icon from '../../components/Icon.svelte';
+
+ // Interactive collage surface. Each node is a tray frame placed as a 4-point
+ // quad (canvas pixels). Drag the body to move all four corners together; drag a
+ // corner handle to warp — a hand-made panorama. The same quads are sent to the
+ // backend, which renders the full-res warp with PIL (see compose_perspective).
+ let { session, selectedId = $bindable() } = $props();
+
+ let wrapEl = $state();
+ let availW = $state(800);
+ let availH = $state(600);
+
+ const cw = $derived(session.collage.width);
+ const ch = $derived(session.collage.height);
+ const scale = $derived(Math.min(availW / cw, availH / ch, 1) || 1);
+
+ function boxOf(node) {
+ return { w: node.w || 320, h: node.h || 240, url: node.url };
+ }
+
+ // client px -> canvas px (the inner surface is scaled with transform-origin 0 0)
+ function toCanvas(e) {
+ const r = wrapEl.getBoundingClientRect();
+ return [(e.clientX - r.left) / scale, (e.clientY - r.top) / scale];
+ }
+
+ function startMove(e, node) {
+ e.preventDefault();
+ selectedId = node.id;
+ let [px, py] = toCanvas(e);
+ const move = (ev) => {
+ const [nx, ny] = toCanvas(ev);
+ const dx = nx - px;
+ const dy = ny - py;
+ node.quad = node.quad.map(([x, y]) => [x + dx, y + dy]);
+ px = nx;
+ py = ny;
+ };
+ const up = () => {
+ window.removeEventListener('pointermove', move);
+ window.removeEventListener('pointerup', up);
+ };
+ window.addEventListener('pointermove', move);
+ window.addEventListener('pointerup', up);
+ }
+
+ function startWarp(e, node, corner) {
+ e.preventDefault();
+ e.stopPropagation();
+ selectedId = node.id;
+ const move = (ev) => {
+ node.quad[corner] = toCanvas(ev);
+ node.quad = [...node.quad];
+ };
+ const up = () => {
+ window.removeEventListener('pointermove', move);
+ window.removeEventListener('pointerup', up);
+ };
+ window.addEventListener('pointermove', move);
+ window.addEventListener('pointerup', up);
+ }
+</script>
+
+<!-- svelte-ignore a11y_no_static_element_interactions -->
+<div
+ class="wrap"
+ bind:this={wrapEl}
+ bind:clientWidth={availW}
+ bind:clientHeight={availH}
+ onpointerdown={() => (selectedId = null)}
+>
+ <div
+ class="surface"
+ class:checker={session.collage.transparent}
+ style:width={`${cw}px`}
+ style:height={`${ch}px`}
+ style:transform={`scale(${scale})`}
+ style:background={session.collage.transparent ? null : session.collage.background}
+ >
+ {#each session.collage.nodes as node (node.id)}
+ {@const box = boxOf(node)}
+ <img
+ class="node"
+ class:selected={node.id === selectedId}
+ src={box.url}
+ alt="collage piece"
+ style:width={`${box.w}px`}
+ style:height={`${box.h}px`}
+ style:transform={quadMatrix3d(box.w, box.h, node.quad)}
+ draggable="false"
+ onpointerdown={(e) => (e.stopPropagation(), startMove(e, node))}
+ />
+ {#if node.id === selectedId}
+ {#each node.quad as pt, i (i)}
+ <button
+ class="handle"
+ style:left={`${pt[0]}px`}
+ style:top={`${pt[1]}px`}
+ style:width={`${16 / scale}px`}
+ style:height={`${16 / scale}px`}
+ onpointerdown={(e) => startWarp(e, node, i)}
+ aria-label={`Warp corner ${i + 1}`}
+ ></button>
+ {/each}
+ {/if}
+ {/each}
+ </div>
+
+ {#if session.collage.nodes.length === 0}
+ <div class="empty">
+ <Icon name="layers" size={34} />
+ <p>Add frames from the menu, then drag to move and pull the corners to warp.</p>
+ </div>
+ {/if}
+</div>
+
+<style>
+ .wrap {
+ position: relative;
+ flex: 1;
+ width: 100%;
+ height: 100%;
+ display: flex;
+ align-items: flex-start;
+ justify-content: flex-start;
+ overflow: hidden;
+ }
+ .surface {
+ position: relative;
+ transform-origin: 0 0;
+ box-shadow: var(--shadow-2);
+ flex-shrink: 0;
+ }
+ /* transparent canvas: a checkerboard shows what alpha will be exported */
+ .surface.checker {
+ background-color: #2a2f3a;
+ background-image:
+ linear-gradient(45deg, rgba(255, 255, 255, 0.07) 25%, transparent 25%, transparent 75%, rgba(255, 255, 255, 0.07) 75%),
+ linear-gradient(45deg, rgba(255, 255, 255, 0.07) 25%, transparent 25%, transparent 75%, rgba(255, 255, 255, 0.07) 75%);
+ background-size: 24px 24px;
+ background-position: 0 0, 12px 12px;
+ }
+ .node {
+ position: absolute;
+ top: 0;
+ left: 0;
+ transform-origin: 0 0;
+ cursor: move;
+ user-select: none;
+ outline: 1px solid transparent;
+ }
+ .node.selected {
+ outline: 1px dashed var(--accent);
+ }
+ .handle {
+ position: absolute;
+ transform: translate(-50%, -50%);
+ border-radius: 50%;
+ background: var(--accent);
+ border: 2px solid #10141c;
+ cursor: grab;
+ padding: 0;
+ touch-action: none;
+ }
+ .empty {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 10px;
+ color: var(--text-3);
+ text-align: center;
+ padding: 20px;
+ pointer-events: none;
+ }
+ .empty p {
+ max-width: 260px;
+ font-size: var(--fs-sm);
+ }
+</style>
diff --git a/frontend/src/tools/inspect/CollageMenu.svelte b/frontend/src/tools/inspect/CollageMenu.svelte
new file mode 100644
index 0000000..a80e3ea
--- /dev/null
+++ b/frontend/src/tools/inspect/CollageMenu.svelte
@@ -0,0 +1,194 @@
+<script>
+ import { previewStyle } from '../../lib/inspect.js';
+ import Icon from '../../components/Icon.svelte';
+
+ // Right-panel menu for the Collage tab: add tray frames to the canvas, set the
+ // canvas size/background, and act on the selected piece. The layout stays in
+ // session.collage until the Save tab commits it to a single flattened image.
+ // Each added piece is a frozen snapshot of the frame's current look (addToCollage).
+ let { session, filters, selectedId = $bindable(), addToCollage } = $props();
+
+ const onCanvas = (id) => session.collage.nodes.some((n) => n.frameId === id);
+ const selected = $derived(session.collage.nodes.find((n) => n.id === selectedId) ?? null);
+
+ function removeNode(id) {
+ session.collage.nodes = session.collage.nodes.filter((n) => n.id !== id);
+ if (selectedId === id) selectedId = null;
+ }
+
+ function bringFront(id) {
+ const i = session.collage.nodes.findIndex((n) => n.id === id);
+ if (i !== -1) session.collage.nodes.push(session.collage.nodes.splice(i, 1)[0]);
+ }
+
+ function resetWarp(node) {
+ const xs = node.quad.map((p) => p[0]);
+ const ys = node.quad.map((p) => p[1]);
+ const x0 = Math.min(...xs);
+ const y0 = Math.min(...ys);
+ const x1 = Math.max(...xs);
+ const y1 = Math.max(...ys);
+ node.quad = [[x0, y0], [x1, y0], [x1, y1], [x0, y1]];
+ }
+</script>
+
+<div class="module">
+ <p class="hint">Pieces are the frames you captured. Add them, drag to arrange, pull corners to warp into a panorama.</p>
+
+ <div class="section">
+ <div class="section-head"><span>Frames</span></div>
+ <div class="grid">
+ {#each session.frames as fr (fr.id)}
+ {@const look = previewStyle(filters, fr.adjust)}
+ <button class="tile" class:used={onCanvas(fr.id)} onclick={() => addToCollage(fr)} title={onCanvas(fr.id) ? 'Add again (fresh snapshot)' : 'Add to canvas'}>
+ <img src={fr.url} alt="frame" style:filter={look.filter} style:transform={look.transform} />
+ <span class="add"><Icon name="plus" size={12} /></span>
+ </button>
+ {/each}
+ </div>
+ {#if session.frames.length === 0}<p class="empty">No frames captured yet.</p>{/if}
+ </div>
+
+ <div class="section">
+ <div class="section-head"><span>Canvas</span></div>
+ <div class="controls">
+ <label>Width <input type="number" min="16" max="8192" step="20" bind:value={session.collage.width} /></label>
+ <label>Height <input type="number" min="16" max="8192" step="20" bind:value={session.collage.height} /></label>
+ <label class="bg">Fill <input type="color" bind:value={session.collage.background} disabled={session.collage.transparent} /></label>
+ </div>
+ <label class="check">
+ <input type="checkbox" bind:checked={session.collage.transparent} />
+ Transparent canvas <span class="sub">— export only the pieces (PNG alpha)</span>
+ </label>
+ </div>
+
+ {#if selected}
+ <div class="section">
+ <div class="section-head"><span>Selected piece</span></div>
+ <div class="actions">
+ <button class="btn btn-sm" onclick={() => bringFront(selected.id)}><Icon name="layers" size={13} /> Front</button>
+ <button class="btn btn-sm" onclick={() => resetWarp(selected)}><Icon name="reset" size={13} /> Unwarp</button>
+ <button class="btn btn-sm danger" onclick={() => removeNode(selected.id)}><Icon name="trash" size={13} /> Remove</button>
+ </div>
+ </div>
+ {/if}
+
+ <button class="btn btn-sm w-full" disabled title="Automatic stitching is coming soon">
+ <Icon name="hash" size={14} /> Auto panorama (coming soon)
+ </button>
+</div>
+
+<style>
+ .module {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ }
+ .hint,
+ .empty {
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ margin: 0;
+ }
+ .section {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ }
+ .section + .section {
+ border-top: 1px solid var(--border);
+ padding-top: 12px;
+ }
+ .section-head {
+ font-weight: 600;
+ font-size: var(--fs-sm);
+ }
+ .grid {
+ display: grid;
+ grid-template-columns: repeat(3, 1fr);
+ gap: 6px;
+ max-height: 200px;
+ overflow: auto;
+ }
+ .tile {
+ position: relative;
+ aspect-ratio: 1;
+ border-radius: var(--r-sm);
+ overflow: hidden;
+ border: 2px solid transparent;
+ padding: 0;
+ }
+ .tile.used {
+ border-color: var(--border-strong);
+ }
+ .tile img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: block;
+ }
+ .tile .add {
+ position: absolute;
+ bottom: 3px;
+ right: 3px;
+ background: var(--accent);
+ color: #10141c;
+ border-radius: 4px;
+ display: flex;
+ padding: 1px;
+ }
+ .controls {
+ display: flex;
+ gap: 8px;
+ }
+ .controls label {
+ display: flex;
+ flex-direction: column;
+ gap: 3px;
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ flex: 1;
+ }
+ .controls input[type='number'] {
+ width: 100%;
+ background: var(--bg-2);
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ padding: 4px 6px;
+ color: var(--text-1);
+ font-size: var(--fs-sm);
+ }
+ .controls .bg input {
+ height: 28px;
+ padding: 0;
+ background: none;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ }
+ .controls .bg input:disabled {
+ opacity: 0.4;
+ }
+ .check {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ cursor: pointer;
+ }
+ .check .sub {
+ color: var(--text-3);
+ }
+ .actions {
+ display: flex;
+ gap: 6px;
+ flex-wrap: wrap;
+ }
+ .danger {
+ color: var(--danger, #d86a6a);
+ }
+ .w-full {
+ width: 100%;
+ justify-content: center;
+ }
+</style>
diff --git a/frontend/src/tools/inspect/CollageModule.svelte b/frontend/src/tools/inspect/CollageModule.svelte
deleted file mode 100644
index 2467313..0000000
--- a/frontend/src/tools/inspect/CollageModule.svelte
+++ /dev/null
@@ -1,152 +0,0 @@
-<script>
- import { api } from '../../lib/api.js';
- import { caseState, reloadCase, toast } from '../../lib/state.svelte.js';
- import Icon from '../../components/Icon.svelte';
-
- // Assemble several case images (frames, crops, photos) into one contact-sheet.
- let { mediaList, onProduced } = $props();
-
- let picked = $state([]); // ordered list of paths
- let columns = $state(2);
- let cell = $state(400);
- let gap = $state(8);
- let building = $state(false);
-
- const images = $derived((mediaList ?? []).filter((m) => m.kind === 'image'));
-
- function toggle(path) {
- const i = picked.indexOf(path);
- if (i === -1) picked.push(path);
- else picked.splice(i, 1);
- }
-
- function orderOf(path) {
- const i = picked.indexOf(path);
- return i === -1 ? null : i + 1;
- }
-
- async function build() {
- if (picked.length < 1) return;
- building = true;
- try {
- const res = await api.post(`/api/cases/${caseState.current.id}/inspect/collage`, {
- paths: [...picked],
- columns,
- cell,
- gap,
- });
- await reloadCase();
- onProduced(res);
- picked = [];
- toast('Collage filed to the case', 'ok');
- } catch (e) {
- toast(e.message, 'danger');
- } finally {
- building = false;
- }
- }
-</script>
-
-<div class="module">
- <p class="hint">Pick images in the order you want them; they tile left-to-right.</p>
-
- <div class="grid">
- {#each images as m (m.path)}
- <button class="tile" class:sel={orderOf(m.path)} onclick={() => toggle(m.path)} title={m.filename}>
- <img src={`/files/${caseState.current.id}/${m.thumbnail ?? m.path}`} alt={m.filename} />
- {#if orderOf(m.path)}<span class="badge">{orderOf(m.path)}</span>{/if}
- </button>
- {/each}
- </div>
-
- {#if images.length === 0}
- <p class="empty">No images yet — capture frames or add media first.</p>
- {/if}
-
- <div class="controls">
- <label>Cols <input type="number" min="1" max="8" bind:value={columns} /></label>
- <label>Cell <input type="number" min="64" max="1024" step="20" bind:value={cell} /></label>
- <label>Gap <input type="number" min="0" max="64" bind:value={gap} /></label>
- </div>
-
- <button class="btn btn-primary w-full" disabled={building || picked.length < 1} onclick={build}>
- <Icon name="layers" size={15} /> Build collage ({picked.length})
- </button>
-</div>
-
-<style>
- .module {
- display: flex;
- flex-direction: column;
- gap: 10px;
- }
- .hint,
- .empty {
- color: var(--text-3);
- font-size: var(--fs-xs);
- margin: 0;
- }
- .grid {
- display: grid;
- grid-template-columns: repeat(3, 1fr);
- gap: 6px;
- max-height: 320px;
- overflow: auto;
- }
- .tile {
- position: relative;
- aspect-ratio: 1;
- border-radius: var(--r-sm);
- overflow: hidden;
- border: 2px solid transparent;
- }
- .tile img {
- width: 100%;
- height: 100%;
- object-fit: cover;
- display: block;
- }
- .tile.sel {
- border-color: var(--accent);
- }
- .badge {
- position: absolute;
- top: 3px;
- left: 3px;
- background: var(--accent);
- color: #10141c;
- font-size: 11px;
- font-weight: 700;
- border-radius: 50%;
- width: 18px;
- height: 18px;
- display: flex;
- align-items: center;
- justify-content: center;
- }
- .controls {
- display: flex;
- gap: 8px;
- }
- .controls label {
- display: flex;
- flex-direction: column;
- gap: 3px;
- font-size: var(--fs-xs);
- color: var(--text-3);
- flex: 1;
- }
- .controls input {
- width: 100%;
- background: var(--bg-2);
- border: 1px solid var(--border);
- border-radius: var(--r-sm);
- padding: 4px 6px;
- color: var(--text-1);
- font-size: var(--fs-sm);
- }
- .w-full {
- width: 100%;
- justify-content: center;
- }
-</style>
diff --git a/frontend/src/tools/inspect/CollagePreview.svelte b/frontend/src/tools/inspect/CollagePreview.svelte
new file mode 100644
index 0000000..97e8445
--- /dev/null
+++ b/frontend/src/tools/inspect/CollagePreview.svelte
@@ -0,0 +1,71 @@
+<script>
+ import { quadMatrix3d } from '../../lib/inspect.js';
+
+ // Read-only miniature of a collage layout — the same node quads/urls the Save
+ // tab will composite, scaled to fit its container. Used for the Save gallery
+ // thumbnail so a collage no longer shows an empty placeholder.
+ let { collage } = $props();
+
+ let availW = $state(150);
+ let availH = $state(112);
+
+ const cw = $derived(collage.width || 1);
+ const ch = $derived(collage.height || 1);
+ const scale = $derived(Math.min(availW / cw, availH / ch) || 0);
+ const boxOf = (n) => ({ w: n.w || 320, h: n.h || 240, url: n.url });
+</script>
+
+<div class="prev" bind:clientWidth={availW} bind:clientHeight={availH}>
+ <div
+ class="surface"
+ class:checker={collage.transparent}
+ style:width={`${cw}px`}
+ style:height={`${ch}px`}
+ style:transform={`scale(${scale})`}
+ style:background={collage.transparent ? null : collage.background}
+ >
+ {#each collage.nodes as node (node.id)}
+ {@const box = boxOf(node)}
+ <img
+ class="node"
+ src={box.url}
+ alt="collage piece"
+ style:width={`${box.w}px`}
+ style:height={`${box.h}px`}
+ style:transform={quadMatrix3d(box.w, box.h, node.quad)}
+ draggable="false"
+ />
+ {/each}
+ </div>
+</div>
+
+<style>
+ .prev {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ overflow: hidden;
+ }
+ .surface {
+ position: relative;
+ transform-origin: center;
+ flex-shrink: 0;
+ }
+ .surface.checker {
+ background-color: #2a2f3a;
+ background-image:
+ linear-gradient(45deg, rgba(255, 255, 255, 0.07) 25%, transparent 25%, transparent 75%, rgba(255, 255, 255, 0.07) 75%),
+ linear-gradient(45deg, rgba(255, 255, 255, 0.07) 25%, transparent 25%, transparent 75%, rgba(255, 255, 255, 0.07) 75%);
+ background-size: 16px 16px;
+ background-position: 0 0, 8px 8px;
+ }
+ .node {
+ position: absolute;
+ top: 0;
+ left: 0;
+ transform-origin: 0 0;
+ user-select: none;
+ }
+</style>
diff --git a/frontend/src/tools/inspect/FrameMenu.svelte b/frontend/src/tools/inspect/FrameMenu.svelte
new file mode 100644
index 0000000..be363ed
--- /dev/null
+++ b/frontend/src/tools/inspect/FrameMenu.svelte
@@ -0,0 +1,319 @@
+<script>
+ import { api } from '../../lib/api.js';
+ import { caseState, toast } from '../../lib/state.svelte.js';
+ import { adjustDefaults, buildOps, previewStyle } from '../../lib/inspect.js';
+ import Icon from '../../components/Icon.svelte';
+ import AdjustSliders from './AdjustSliders.svelte';
+
+ // Right-panel menu for the Frame tab. Works on the *active* tray frame:
+ // pick it, adjust it (live-previewed), crop it, or analyse it — all without
+ // filing anything. The recipe is committed later from the Save tab.
+ let { session, filters, analyses, activeFrame, shared, removeFrame, setActive } = $props();
+
+ let showAnalyze = $state(false);
+ let analyzing = $state(null);
+ let analysis = $state(null);
+ let canvasEl = $state();
+
+ function reset() {
+ if (!activeFrame) return;
+ activeFrame.adjust = adjustDefaults(filters);
+ activeFrame.crop = null;
+ shared.cropMode = false;
+ }
+
+ function toggleCrop() {
+ shared.cropMode = !shared.cropMode;
+ }
+
+ function clearCrop() {
+ if (activeFrame) activeFrame.crop = null;
+ shared.cropMode = false;
+ }
+
+ async function runAnalysis(name) {
+ if (!activeFrame) return;
+ analyzing = name;
+ analysis = null;
+ try {
+ analysis = await api.post(`/api/cases/${caseState.current.id}/inspect/analyze`, {
+ path: activeFrame.path,
+ name,
+ time: activeFrame.time ?? null,
+ ops: buildOps(filters, activeFrame.adjust, activeFrame.crop),
+ });
+ if (analysis.kind === 'histogram') requestAnimationFrame(drawHistogram);
+ } catch (e) {
+ toast(e.message, 'danger');
+ } finally {
+ analyzing = null;
+ }
+ }
+
+ function drawHistogram() {
+ if (!canvasEl || analysis?.kind !== 'histogram') return;
+ const ctx = canvasEl.getContext('2d');
+ const W = (canvasEl.width = canvasEl.clientWidth);
+ const H = (canvasEl.height = 120);
+ ctx.clearRect(0, 0, W, H);
+ const ch = analysis.channels;
+ const peak = Math.max(1, ...ch.r, ...ch.g, ...ch.b);
+ ctx.globalCompositeOperation = 'lighter';
+ for (const [name, color] of [
+ ['r', 'rgba(230,70,70,0.8)'],
+ ['g', 'rgba(70,210,110,0.8)'],
+ ['b', 'rgba(90,140,240,0.8)'],
+ ]) {
+ ctx.beginPath();
+ ctx.moveTo(0, H);
+ ch[name].forEach((v, i) => ctx.lineTo((i / 255) * W, H - (v / peak) * H));
+ ctx.lineTo(W, H);
+ ctx.fillStyle = color;
+ ctx.fill();
+ }
+ ctx.globalCompositeOperation = 'source-over';
+ }
+</script>
+
+<div class="module">
+ <div class="tray">
+ {#each session.frames as fr, i (fr.id)}
+ <div class="thumb" class:active={fr.id === session.activeFrameId}>
+ <button class="pick" onclick={() => setActive(fr.id)} title={fr.time != null ? `Image ${i + 1} · t=${fr.time.toFixed(2)}s` : `Image ${i + 1}`}>
+ <img src={fr.url} alt={`Image ${i + 1}`} style:filter={previewStyle(filters, fr.adjust).filter} />
+ <span class="num">{i + 1}</span>
+ {#if session.saved[`frame:${fr.id}`]}<span class="saved" title="Saved"><Icon name="check" size={11} /></span>{/if}
+ </button>
+ <button class="del" onclick={() => removeFrame(fr.id)} aria-label="Remove frame"><Icon name="x" size={12} /></button>
+ </div>
+ {/each}
+ {#if session.frames.length === 0}
+ <p class="empty">No frames yet — capture some in the Selection tab.</p>
+ {/if}
+ </div>
+
+ {#if activeFrame}
+ <div class="section">
+ <AdjustSliders {filters} values={activeFrame.adjust} />
+ <div class="crop-row">
+ <button class="btn btn-sm" class:active={shared.cropMode} onclick={toggleCrop}>
+ <Icon name="crop" size={14} /> {shared.cropMode ? 'Drag on image…' : 'Crop region'}
+ </button>
+ {#if activeFrame.crop}
+ <span class="crop-info mono">
+ {Math.round(activeFrame.crop.w * 100)}% × {Math.round(activeFrame.crop.h * 100)}%
+ </span>
+ <button class="btn btn-ghost btn-xs" onclick={clearCrop} aria-label="Clear crop"><Icon name="x" size={13} /></button>
+ {/if}
+ </div>
+ <button class="btn btn-ghost btn-sm reset" onclick={reset}><Icon name="reset" size={14} /> Reset frame</button>
+ </div>
+
+ <div class="section">
+ <button class="section-head as-btn" onclick={() => (showAnalyze = !showAnalyze)}>
+ <span><Icon name="eye" size={14} /> Analyze</span>
+ <Icon name={showAnalyze ? 'chevronDown' : 'chevronRight'} size={14} />
+ </button>
+ {#if showAnalyze}
+ <div class="atabs">
+ {#each analyses as a (a.id)}
+ <button class="btn btn-sm" class:active={analyzing === a.id} onclick={() => runAnalysis(a.id)}>{a.label}</button>
+ {/each}
+ </div>
+ {#if analyzing}
+ <p class="hint"><Icon name="clock" size={13} /> Analysing…</p>
+ {:else if analysis}
+ {#if analysis.kind === 'keyvalue'}
+ <table class="kv"><tbody>
+ {#each Object.entries(analysis.rows) as [k, v] (k)}<tr><th>{k}</th><td class="mono">{v}</td></tr>{/each}
+ </tbody></table>
+ {:else if analysis.kind === 'histogram'}
+ <canvas bind:this={canvasEl} class="hist"></canvas>
+ {:else if analysis.kind === 'image'}
+ <img class="ana-img" src={analysis.data_url} alt="analysis" />
+ {#if analysis.note}<p class="note"><Icon name="alert" size={13} /> {analysis.note}</p>{/if}
+ {:else if analysis.kind === 'text'}
+ <pre class="text">{analysis.text}</pre>
+ {/if}
+ {/if}
+ {/if}
+ </div>
+ {/if}
+</div>
+
+<style>
+ .module {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ }
+ .tray {
+ display: flex;
+ gap: 6px;
+ flex-wrap: wrap;
+ }
+ .thumb {
+ position: relative;
+ width: 60px;
+ height: 60px;
+ }
+ .thumb .pick {
+ width: 100%;
+ height: 100%;
+ border-radius: var(--r-sm);
+ overflow: hidden;
+ border: 2px solid transparent;
+ padding: 0;
+ }
+ .thumb.active .pick {
+ border-color: var(--accent);
+ }
+ .thumb img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: block;
+ }
+ .thumb .del {
+ position: absolute;
+ top: -6px;
+ right: -6px;
+ width: 18px;
+ height: 18px;
+ border-radius: 50%;
+ background: var(--bg-2);
+ border: 1px solid var(--border-strong);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: var(--text-2);
+ }
+ .num {
+ position: absolute;
+ top: 2px;
+ left: 2px;
+ min-width: 15px;
+ height: 15px;
+ padding: 0 3px;
+ border-radius: 4px;
+ background: rgba(6, 9, 14, 0.7);
+ color: #fff;
+ font-size: 10px;
+ font-weight: 700;
+ line-height: 15px;
+ text-align: center;
+ }
+ .saved {
+ position: absolute;
+ bottom: 2px;
+ left: 2px;
+ background: var(--accent);
+ color: #10141c;
+ border-radius: 4px;
+ display: flex;
+ padding: 1px;
+ }
+ .empty {
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ margin: 4px 0;
+ }
+ .section {
+ border-top: 1px solid var(--border);
+ padding-top: 12px;
+ display: flex;
+ flex-direction: column;
+ gap: 9px;
+ }
+ .crop-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ }
+ .crop-info {
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ }
+ .btn.active {
+ color: var(--accent);
+ border-color: var(--accent);
+ }
+ .reset {
+ align-self: flex-start;
+ }
+ .section-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ font-weight: 600;
+ font-size: var(--fs-sm);
+ }
+ .section-head span {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ }
+ .as-btn {
+ width: 100%;
+ background: none;
+ color: var(--text-1);
+ text-align: left;
+ }
+ .atabs {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ }
+ .hint {
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ margin: 0;
+ display: flex;
+ gap: 5px;
+ align-items: center;
+ }
+ .kv {
+ width: 100%;
+ border-collapse: collapse;
+ font-size: var(--fs-xs);
+ }
+ .kv th {
+ text-align: left;
+ color: var(--text-3);
+ font-weight: 600;
+ padding: 3px 8px 3px 0;
+ vertical-align: top;
+ white-space: nowrap;
+ }
+ .kv td {
+ padding: 3px 0;
+ color: var(--text-2);
+ word-break: break-all;
+ }
+ .kv tr + tr {
+ border-top: 1px solid var(--border);
+ }
+ .hist {
+ width: 100%;
+ height: 120px;
+ background: var(--bg-0);
+ border-radius: var(--r-sm);
+ }
+ .ana-img {
+ width: 100%;
+ border-radius: var(--r-sm);
+ background: #000;
+ }
+ .note {
+ display: flex;
+ gap: 6px;
+ font-size: var(--fs-xs);
+ color: var(--warn, #d8a24a);
+ margin: 0;
+ }
+ .text {
+ font-size: var(--fs-xs);
+ white-space: pre-wrap;
+ color: var(--text-2);
+ }
+</style>
diff --git a/frontend/src/tools/inspect/SaveGallery.svelte b/frontend/src/tools/inspect/SaveGallery.svelte
new file mode 100644
index 0000000..5d9a32b
--- /dev/null
+++ b/frontend/src/tools/inspect/SaveGallery.svelte
@@ -0,0 +1,146 @@
+<script>
+ import Icon from '../../components/Icon.svelte';
+ import CollagePreview from './CollagePreview.svelte';
+
+ // Viewer side of the Save tab: everything this session produced that can be
+ // filed — the enhanced video, each adjusted frame, the collage. Tick the ones
+ // to commit; the menu on the right does the actual save.
+ let { savables, saveUi } = $props();
+
+ function toggle(key) {
+ saveUi.selected[key] = !saveUi.selected[key];
+ }
+</script>
+
+<div class="gallery">
+ {#if savables.length === 0}
+ <div class="empty">
+ <Icon name="save" size={34} />
+ <p>Nothing to save yet — capture frames, build a collage, or adjust the video first.</p>
+ </div>
+ {:else}
+ {#each savables as it (it.key)}
+ <button class="card" class:sel={saveUi.selected[it.key]} class:saved={it.saved} onclick={() => toggle(it.key)}>
+ <div class="thumb">
+ {#if it.kind === 'collage' && it.collage?.nodes.length}
+ <CollagePreview collage={it.collage} />
+ {:else if it.thumb}
+ <img src={it.thumb} alt={it.label} style:filter={it.filter} />
+ {:else}
+ <Icon name={it.kind === 'collage' ? 'layers' : it.kind === 'video' ? 'video' : 'image'} size={30} />
+ {/if}
+ <span class="kind"><Icon name={it.kind === 'video' ? 'video' : it.kind === 'collage' ? 'layers' : 'image'} size={12} /></span>
+ <span class="tick"><Icon name="check" size={14} /></span>
+ </div>
+ <span class="label">{it.label}</span>
+ {#if it.saved}<span class="badge">saved</span>{/if}
+ </button>
+ {/each}
+ {/if}
+</div>
+
+<style>
+ .gallery {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
+ gap: 12px;
+ align-content: start;
+ width: 100%;
+ height: 100%;
+ overflow: auto;
+ padding: 4px;
+ }
+ .empty {
+ grid-column: 1 / -1;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 10px;
+ color: var(--text-3);
+ text-align: center;
+ min-height: 240px;
+ }
+ .empty p {
+ max-width: 280px;
+ font-size: var(--fs-sm);
+ }
+ .card {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ padding: 8px;
+ border: 2px solid var(--border);
+ border-radius: var(--r-md);
+ background: var(--bg-1);
+ text-align: left;
+ position: relative;
+ }
+ .card.sel {
+ border-color: var(--accent);
+ }
+ .thumb {
+ position: relative;
+ aspect-ratio: 4 / 3;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: var(--bg-0);
+ border-radius: var(--r-sm);
+ overflow: hidden;
+ color: var(--text-3);
+ }
+ .thumb img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ }
+ .kind {
+ position: absolute;
+ top: 4px;
+ left: 4px;
+ background: rgba(6, 9, 14, 0.6);
+ color: #fff;
+ border-radius: 4px;
+ display: flex;
+ padding: 2px;
+ }
+ .tick {
+ position: absolute;
+ top: 4px;
+ right: 4px;
+ width: 22px;
+ height: 22px;
+ border-radius: 50%;
+ background: var(--bg-2);
+ border: 1px solid var(--border-strong);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: transparent;
+ }
+ .card.sel .tick {
+ background: var(--accent);
+ border-color: var(--accent);
+ color: #10141c;
+ }
+ .label {
+ font-size: var(--fs-sm);
+ color: var(--text-2);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+ .badge {
+ position: absolute;
+ bottom: 8px;
+ right: 8px;
+ font-size: 9px;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ padding: 1px 5px;
+ border-radius: 4px;
+ background: var(--accent-soft);
+ color: var(--accent);
+ }
+</style>
diff --git a/frontend/src/tools/inspect/SaveMenu.svelte b/frontend/src/tools/inspect/SaveMenu.svelte
new file mode 100644
index 0000000..2ccfd21
--- /dev/null
+++ b/frontend/src/tools/inspect/SaveMenu.svelte
@@ -0,0 +1,85 @@
+<script>
+ import { caseState, uiState } from '../../lib/state.svelte.js';
+ import Icon from '../../components/Icon.svelte';
+
+ // Right-panel menu for the Save tab: choose a destination folder and commit the
+ // ticked items. This is the *only* place the Inspect session files case
+ // entities — nothing before it touched the case.
+ let { savables, saveUi, saving, save } = $props();
+
+ const folders = $derived(caseState.current?.folders ?? []);
+ const count = $derived(savables.filter((it) => saveUi.selected[it.key]).length);
+
+ function selectAll() {
+ for (const it of savables) saveUi.selected[it.key] = true;
+ }
+ function selectNone() {
+ saveUi.selected = {};
+ }
+</script>
+
+<div class="module">
+ <p class="hint">Tick items on the left, pick a folder, and save. Everything lands in the Media Library with provenance back to its source.</p>
+
+ <div class="pickers">
+ <button class="btn btn-sm" onclick={selectAll} disabled={!savables.length}>Select all</button>
+ <button class="btn btn-sm" onclick={selectNone} disabled={!count}>Clear</button>
+ </div>
+
+ <label class="folder">
+ <span><Icon name="folder" size={14} /> Folder (optional)</span>
+ <input list="inspect-folders" placeholder="Unfiled" bind:value={saveUi.folder} />
+ <datalist id="inspect-folders">
+ {#each folders as f (f)}<option value={f}></option>{/each}
+ </datalist>
+ </label>
+
+ <button class="btn btn-primary w-full" disabled={saving || !count} onclick={save}>
+ <Icon name="save" size={15} /> {saving ? 'Saving…' : `Save ${count || ''} to case`.trim()}
+ </button>
+
+ <button class="btn btn-ghost btn-sm w-full" onclick={() => (uiState.tool = 'media')}>
+ <Icon name="media" size={14} /> Open Media Library
+ </button>
+</div>
+
+<style>
+ .module {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ }
+ .hint {
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ margin: 0;
+ }
+ .pickers {
+ display: flex;
+ gap: 6px;
+ }
+ .folder {
+ display: flex;
+ flex-direction: column;
+ gap: 5px;
+ font-size: var(--fs-sm);
+ color: var(--text-2);
+ }
+ .folder span {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ }
+ .folder input {
+ background: var(--bg-2);
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ padding: 6px 8px;
+ color: var(--text-1);
+ font-size: var(--fs-sm);
+ }
+ .w-full {
+ width: 100%;
+ justify-content: center;
+ }
+</style>
diff --git a/frontend/src/tools/inspect/FramesModule.svelte b/frontend/src/tools/inspect/SelectionMenu.svelte
similarity index 67%
rename from frontend/src/tools/inspect/FramesModule.svelte
rename to frontend/src/tools/inspect/SelectionMenu.svelte
index 6c043ff..0fb476d 100644
--- a/frontend/src/tools/inspect/FramesModule.svelte
+++ b/frontend/src/tools/inspect/SelectionMenu.svelte
@@ -1,14 +1,19 @@
<script>
import { api } from '../../lib/api.js';
- import { caseState, uiState, reloadCase, toast } from '../../lib/state.svelte.js';
+ import { caseState, toast } from '../../lib/state.svelte.js';
+ import { isNeutral } from '../../lib/inspect.js';
import Icon from '../../components/Icon.svelte';
+ import AdjustSliders from './AdjustSliders.svelte';
- // Extracts frames from a video into the case (spec v2 gesture).
- let { source, probeInfo, shared, onProduced } = $props();
+ // Right-panel menu for the Selection tab: scrub the video, capture frames into
+ // the transient tray (nothing is filed here), and tune video-level adjustments
+ // via the gear — those feed the optional "enhanced video" saved in the Save tab.
+ let { probeInfo, shared, videoFilters, session, capture } = $props();
let suggestions = $state([]);
let scanning = $state(false);
let capturing = $state(false);
+ let showGear = $state(false);
const duration = $derived(probeInfo?.duration ?? 0);
@@ -23,21 +28,10 @@
shared.seekTo = t;
}
- async function capture(time = shared.currentTime ?? 0) {
+ async function grab(time = shared.currentTime ?? 0) {
capturing = true;
try {
- const res = await api.post(`/api/cases/${caseState.current.id}/inspect/frame`, {
- path: source.path,
- time,
- });
- await reloadCase();
- onProduced(res);
- toast(
- res.duplicate ? 'That frame is already in the case' : `Frame captured at ${fmt(time)}`,
- res.duplicate ? 'warn' : 'ok'
- );
- } catch (e) {
- toast(e.message, 'danger');
+ await capture(time);
} finally {
capturing = false;
}
@@ -48,11 +42,10 @@
suggestions = [];
try {
const { job_id } = await api.post(`/api/cases/${caseState.current.id}/inspect/suggest`, {
- path: source.path,
+ path: session.source.path,
bins: 12,
});
- const frames = await poll(job_id);
- suggestions = frames;
+ suggestions = await poll(job_id);
} catch (e) {
toast(e.message, 'danger');
} finally {
@@ -70,6 +63,7 @@
}
const maxScore = $derived(Math.max(1, ...suggestions.map((s) => s.score)));
+ const gearActive = $derived(!isNeutral(videoFilters, session.videoAdjust));
</script>
<div class="module">
@@ -85,9 +79,24 @@
<button class="btn btn-sm" onclick={() => step(1)} title="Forward 1s">+1s</button>
</div>
- <button class="btn btn-primary w-full" disabled={capturing} onclick={() => capture()}>
- <Icon name="image" size={15} /> Capture this frame
+ <button class="btn btn-primary w-full" disabled={capturing} onclick={() => grab()}>
+ <Icon name="image" size={15} /> Capture frame to tray
</button>
+ <p class="hint tray-note">
+ <Icon name="layers" size={12} /> {session.frames.length} frame{session.frames.length === 1 ? '' : 's'}
+ in tray — nothing is saved until the Save tab.
+ </p>
+
+ <div class="section">
+ <button class="section-head as-btn" onclick={() => (showGear = !showGear)}>
+ <span><Icon name="settings" size={14} /> Video adjustments {#if gearActive}<span class="dot"></span>{/if}</span>
+ <Icon name={showGear ? 'chevronDown' : 'chevronRight'} size={14} />
+ </button>
+ {#if showGear}
+ <p class="hint">Preview the whole clip brighter/clearer; save an enhanced copy in Save.</p>
+ <AdjustSliders filters={videoFilters} values={session.videoAdjust} />
+ {/if}
+ </div>
<div class="section">
<div class="section-head">
@@ -98,7 +107,6 @@
</button>
</div>
<p class="hint">Samples the clip and ranks frames by focus — sharper is higher.</p>
-
{#each suggestions as s (s.time)}
<div class="sugg" class:top={s.rank === 0}>
<span class="mono">{fmt(s.time)}</span>
@@ -106,7 +114,7 @@
<button class="btn btn-ghost btn-xs" onclick={() => (shared.seekTo = s.time)} title="Seek here">
<Icon name="eye" size={13} />
</button>
- <button class="btn btn-xs" disabled={capturing} onclick={() => capture(s.time)} title="Capture">
+ <button class="btn btn-xs" disabled={capturing} onclick={() => grab(s.time)} title="Capture">
<Icon name="image" size={13} />
</button>
</div>
@@ -143,12 +151,18 @@
width: 100%;
justify-content: center;
}
+ .tray-note {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ margin: -4px 0 0;
+ }
.section {
border-top: 1px solid var(--border);
padding-top: 12px;
display: flex;
flex-direction: column;
- gap: 6px;
+ gap: 8px;
}
.section-head {
display: flex;
@@ -157,10 +171,27 @@
font-weight: 600;
font-size: var(--fs-sm);
}
+ .section-head span {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ }
+ .as-btn {
+ width: 100%;
+ background: none;
+ color: var(--text-1);
+ text-align: left;
+ }
+ .dot {
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: var(--accent);
+ }
.hint {
color: var(--text-3);
font-size: var(--fs-xs);
- margin: 0 0 4px;
+ margin: 0;
}
.sugg {
display: flex;
diff --git a/src/ozimut/api/cases.py b/src/ozimut/api/cases.py
index 48025aa..25f36e2 100644
--- a/src/ozimut/api/cases.py
+++ b/src/ozimut/api/cases.py
@@ -7,6 +7,8 @@ from typing import Any
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field
+from ..engine import media as media_engine
+from ..engine import satellite as satellite_engine
from ..workspace import Case, CaseError
router = APIRouter(prefix="/api/cases", tags=["cases"])
@@ -19,6 +21,13 @@ def get_case(case_id: str) -> Case:
raise HTTPException(status_code=404, detail=str(exc)) from exc
+def _unlink_inside(case: Case, rel_path: str) -> None:
+ try:
+ case.resolve_inside(rel_path).unlink(missing_ok=True)
+ except CaseError:
+ pass
+
+
class CreateCase(BaseModel):
name: str = Field(min_length=1, max_length=120)
@@ -136,8 +145,35 @@ def update_entity(case_id: str, entity_id: str, body: EntityPatch) -> dict[str,
@router.delete("/{case_id}/entities/{entity_id}")
def remove_entity(case_id: str, entity_id: str) -> dict[str, str]:
+ """Delete an entity and the on-disk artifact it stands for, so removing a
+ row in the sidebar deletes it everywhere it appears (spec §3.5)."""
+ case = get_case(case_id)
+ entity = next((e for e in case.read()["entities"] if e["id"] == entity_id), None)
+ if entity is None:
+ raise HTTPException(status_code=404, detail=f"entity '{entity_id}' not found")
+
+ etype = entity.get("type")
+ attrs = entity.get("attrs", {})
+
+ # media has its own delete that drops file + thumbnail + sidecar + entity
+ if etype == "media" and attrs.get("path"):
+ try:
+ media_engine.delete_media(case, attrs["path"])
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ return {"status": "deleted"}
+
+ # other artifact-backed types: drop the file(s) before removing the row
+ if etype == "place" and attrs.get("path"):
+ satellite_engine.unlink_capture(case, attrs["path"])
+ elif etype == "proof" and attrs.get("spec"):
+ _unlink_inside(case, attrs["spec"])
+ _unlink_inside(case, attrs["spec"].removesuffix(".json") + ".png")
+ elif etype == "post" and attrs.get("draft"):
+ _unlink_inside(case, attrs["draft"])
+
try:
- get_case(case_id).remove_entity(entity_id)
+ case.remove_entity(entity_id)
except CaseError as exc:
raise HTTPException(status_code=404, detail=str(exc)) from exc
return {"status": "deleted"}
diff --git a/src/ozimut/api/inspect.py b/src/ozimut/api/inspect.py
index cc5569e..ccb407d 100644
--- a/src/ozimut/api/inspect.py
+++ b/src/ozimut/api/inspect.py
@@ -7,9 +7,12 @@ the Proof Composer picker with zero extra plumbing). Long scans run as jobs.
from __future__ import annotations
+import json
+import re
+from datetime import datetime, timezone
from typing import Any
-from fastapi import APIRouter, HTTPException
+from fastapi import APIRouter, HTTPException, Response
from pydantic import BaseModel, Field
from .. import jobs
@@ -56,10 +59,68 @@ class CollageIn(BaseModel):
label: str | None = None
+class PreviewIn(BaseModel):
+ path: str
+ time: float = Field(ge=0)
+
+
+class RenderPreviewIn(BaseModel):
+ path: str
+ time: float | None = Field(default=None, ge=0)
+ ops: list[Op] = []
+
+
+class FrameSpec(BaseModel):
+ path: str
+ time: float | None = Field(default=None, ge=0)
+ ops: list[Op] = []
+ label: str | None = None
+
+
+class SaveFramesIn(BaseModel):
+ items: list[FrameSpec] = Field(min_length=1)
+ folder: str | None = None
+
+
+class NodeSrc(BaseModel):
+ path: str
+ time: float | None = Field(default=None, ge=0)
+ ops: list[Op] = []
+
+
+class ComposeNode(BaseModel):
+ src: NodeSrc
+ quad: list[tuple[float, float]] = Field(min_length=4, max_length=4)
+
+
+class ComposeIn(BaseModel):
+ width: int = Field(ge=16, le=8192)
+ height: int = Field(ge=16, le=8192)
+ nodes: list[ComposeNode] = Field(min_length=1)
+ background: str | None = "#12141c" # None → transparent (RGBA) canvas
+ label: str | None = None
+ folder: str | None = None
+
+
+class EnhanceVideoIn(BaseModel):
+ path: str
+ params: dict[str, Any] = {}
+ label: str | None = None
+ folder: str | None = None
+
+
class AnalyzeIn(BaseModel):
path: str
name: str
params: dict[str, Any] = {}
+ time: float | None = Field(default=None, ge=0)
+ ops: list[Op] = []
+
+
+class SessionIn(BaseModel):
+ name: str | None = None # slug; None → derived from title
+ title: str = Field(min_length=1, max_length=200)
+ spec: dict[str, Any]
@router.get("/inspect/ops")
@@ -139,12 +200,189 @@ def collage(case_id: str, body: CollageIn) -> dict[str, Any]:
raise HTTPException(status_code=422, detail=str(exc)) from exc
[email protected]("/cases/{case_id}/inspect/frame/preview")
+def preview_frame(case_id: str, body: PreviewIn) -> Response:
+ """Decode one video frame and return the PNG — nothing is filed (tray preview)."""
+ case = get_case(case_id)
+ try:
+ png = inspect_engine.preview_frame_png(case, body.path, body.time)
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ except (RuntimeError, OSError) as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ return Response(content=png, media_type="image/png")
+
+
[email protected]("/cases/{case_id}/inspect/render-preview")
+def render_preview(case_id: str, body: RenderPreviewIn) -> Response:
+ """Render a recipe (frame/image + ops) to a PNG — nothing is filed.
+
+ Backs collage snapshots and rebuilding tray/collage previews when a saved
+ session is reopened.
+ """
+ case = get_case(case_id)
+ ops = [op.model_dump() for op in body.ops]
+ try:
+ png = inspect_engine.render_preview_png(case, body.path, time_s=body.time, ops=ops)
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ except (ValueError, RuntimeError, OSError) as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ return Response(content=png, media_type="image/png")
+
+
[email protected]("/cases/{case_id}/inspect/save-frames")
+def save_frames(case_id: str, body: SaveFramesIn) -> dict[str, Any]:
+ """Commit selected tray frames to the case (Save gate)."""
+ case = get_case(case_id)
+ results = []
+ try:
+ for item in body.items:
+ ops = [op.model_dump() for op in item.ops]
+ results.append(
+ inspect_engine.save_frame(
+ case, item.path, time_s=item.time, ops=ops,
+ label=item.label, folder=body.folder,
+ )
+ )
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ except (ValueError, RuntimeError, OSError) as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ return {"saved": results}
+
+
[email protected]("/cases/{case_id}/inspect/compose")
+def compose(case_id: str, body: ComposeIn) -> dict[str, Any]:
+ """Composite a perspective-warped collage from tray/case images (Save gate)."""
+ case = get_case(case_id)
+ nodes = [
+ {"src": {**n.src.model_dump(exclude={"ops"}),
+ "ops": [op.model_dump() for op in n.src.ops]},
+ "quad": [list(pt) for pt in n.quad]}
+ for n in body.nodes
+ ]
+ try:
+ return inspect_engine.compose_perspective(
+ case, width=body.width, height=body.height, nodes=nodes,
+ background=body.background, label=body.label, folder=body.folder,
+ )
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ except (ValueError, RuntimeError, OSError) as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+
+
[email protected]("/cases/{case_id}/inspect/enhance-video")
+def enhance_video(case_id: str, body: EnhanceVideoIn) -> dict[str, Any]:
+ """Re-encode a video with the gear's adjustments and file it as new media."""
+ case = get_case(case_id)
+ try:
+ return inspect_engine.enhance_video(
+ case, body.path, body.params, label=body.label, folder=body.folder
+ )
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ except (ValueError, RuntimeError, OSError) as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+
+
@router.post("/cases/{case_id}/inspect/analyze")
def analyze(case_id: str, body: AnalyzeIn) -> dict[str, Any]:
case = get_case(case_id)
+ ops = [op.model_dump() for op in body.ops]
try:
- return inspect_engine.run_analysis(case, body.path, body.name, body.params)
+ return inspect_engine.run_analysis(
+ case, body.path, body.name, body.params, time_s=body.time, ops=ops
+ )
except CaseError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
- except (ValueError, OSError) as exc:
+ except (ValueError, RuntimeError, OSError) as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
+
+
+# ---------------------------------------------------------------------------
+# Saveable workspace sessions (persist the whole Inspect scratch, reopen later).
+# Mirrors the proofs pattern: a JSON spec on disk + an upserted entity, so a
+# session reopens from the sidebar. Only recipes are stored (no pixels).
+# ---------------------------------------------------------------------------
+
+
+def _slug(text: str) -> str:
+ slug = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
+ return slug[:80] or "session"
+
+
+def _now() -> str:
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
[email protected]("/cases/{case_id}/inspect/sessions")
+def list_sessions(case_id: str) -> list[dict[str, Any]]:
+ case = get_case(case_id)
+ out = []
+ for spec_path in sorted(case.subdir("inspect").glob("*.json")):
+ try:
+ spec = json.loads(spec_path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ continue
+ if spec.get("ozimut_inspect") != 1:
+ continue
+ out.append({
+ "name": spec_path.stem,
+ "title": spec.get("title", spec_path.stem),
+ "updated_at": spec.get("updated_at"),
+ "frames": len(spec.get("frames", [])),
+ "collage": len(spec.get("collage", {}).get("nodes", [])),
+ "source": spec.get("source", {}).get("path"),
+ })
+ out.sort(key=lambda s: s.get("updated_at") or "", reverse=True)
+ return out
+
+
[email protected]("/cases/{case_id}/inspect/sessions/{name}")
+def load_session(case_id: str, name: str) -> dict[str, Any]:
+ case = get_case(case_id)
+ try:
+ spec_path = case.resolve_inside(f"inspect/{name}.json")
+ except CaseError as exc:
+ raise HTTPException(status_code=403, detail=str(exc)) from exc
+ if not spec_path.exists():
+ raise HTTPException(status_code=404, detail="session not found")
+ return json.loads(spec_path.read_text(encoding="utf-8"))
+
+
[email protected]("/cases/{case_id}/inspect/sessions")
+def save_session(case_id: str, body: SessionIn) -> dict[str, Any]:
+ case = get_case(case_id)
+ name = _slug(body.name or body.title)
+ spec = dict(body.spec)
+ spec["ozimut_inspect"] = 1
+ spec["title"] = body.title
+ spec.setdefault("created_at", _now())
+ spec["updated_at"] = _now()
+
+ spec_path = case.subdir("inspect") / f"{name}.json"
+ spec_path.write_text(json.dumps(spec, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+
+ rel = f"inspect/{name}.json"
+ existing = case.find_entity(attr="spec", value=rel)
+ if existing:
+ case.update_entity(existing["id"], {"label": body.title})
+ else:
+ case.add_entity("inspect-session", body.title, attrs={"spec": rel}, by="inspect")
+ return {"name": name, "spec_path": rel}
+
+
[email protected]("/cases/{case_id}/inspect/sessions/{name}")
+def delete_session(case_id: str, name: str) -> dict[str, str]:
+ case = get_case(case_id)
+ try:
+ spec_path = case.resolve_inside(f"inspect/{name}.json")
+ except CaseError as exc:
+ raise HTTPException(status_code=403, detail=str(exc)) from exc
+ spec_path.unlink(missing_ok=True)
+ entity = case.find_entity(attr="spec", value=f"inspect/{name}.json")
+ if entity:
+ case.remove_entity(entity["id"])
+ return {"status": "deleted"}
diff --git a/src/ozimut/api/satellite.py b/src/ozimut/api/satellite.py
index 688812c..cac8e96 100644
--- a/src/ozimut/api/satellite.py
+++ b/src/ozimut/api/satellite.py
@@ -9,7 +9,7 @@ from typing import Any
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field
-from ..engine import geo, tiles
+from ..engine import geo, satellite as satellite_engine, tiles
from .cases import get_case
router = APIRouter(prefix="/api", tags=["satellite"])
@@ -33,6 +33,7 @@ class ParseIn(BaseModel):
class SatelliteUpdateIn(BaseModel):
path: str
notes: str | None = None
+ title: str | None = None
@router.get("/satellite/providers")
@@ -93,52 +94,42 @@ def capture(case_id: str, body: CaptureIn) -> dict[str, Any]:
stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
name = f"sat_{stamp}_z{provenance['zoom']}_{provider.id}.png"
+ rel_path = f"satellite/{name}"
sat_dir = case.subdir("satellite")
image.save(sat_dir / name, "PNG")
+ label = satellite_engine.coords_label(body.lat, body.lon)
provenance["filename"] = name
+ provenance["title"] = label
provenance["plus_code"] = geo.plus_code(body.lat, body.lon)
provenance["dms"] = geo.to_dms(body.lat, body.lon)
(sat_dir / f"{name}.json").write_text(
json.dumps(provenance, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
)
- # suggest a place entity — analyst confirms or dismisses (spec §3.5)
- label = f"{body.lat:.6f}, {body.lon:.6f}"
- if not case.find_entity(attr="coords", value=label):
- case.add_entity(
- "place",
- label,
- attrs={"coords": label, "lat": body.lat, "lon": body.lon,
- "plus_code": provenance["plus_code"]},
- by="satellite",
- status="suggested",
- )
+ # one capture == one place entity, tied by its path (spec §3.5); capturing is
+ # a deliberate act, so it's filed straight away — retitle/refile/delete later
+ case.add_entity(
+ "place",
+ label,
+ attrs={"coords": label, "lat": body.lat, "lon": body.lon,
+ "plus_code": provenance["plus_code"], "path": rel_path,
+ "zoom": provenance["zoom"], "bearing": body.bearing},
+ by="satellite",
+ status="confirmed",
+ )
- return {"path": f"satellite/{name}", **provenance}
+ return {"path": rel_path, **provenance}
@router.get("/cases/{case_id}/satellite")
def list_captures(case_id: str) -> list[dict[str, Any]]:
- case = get_case(case_id)
- sat_dir = case.subdir("satellite")
- captures = []
- for sidecar in sorted(sat_dir.glob("*.png.json")):
- image_name = sidecar.name[: -len(".json")]
- if not (sat_dir / image_name).exists():
- continue
- data = json.loads(sidecar.read_text(encoding="utf-8"))
- data["path"] = f"satellite/{image_name}"
- captures.append(data)
- captures.sort(key=lambda d: d.get("fetched_at") or "", reverse=True)
- return captures
+ return satellite_engine.list_captures(get_case(case_id))
@router.delete("/cases/{case_id}/satellite")
def delete_capture(case_id: str, path: str) -> dict[str, str]:
- case = get_case(case_id)
- image = case.resolve_inside(path)
- image.unlink(missing_ok=True)
- image.with_name(image.name + ".json").unlink(missing_ok=True)
+ # also drops the mirrored place entity when its last capture is gone
+ satellite_engine.delete_capture(get_case(case_id), path)
return {"status": "deleted"}
@@ -160,6 +151,15 @@ def update_capture(case_id: str, body: SatelliteUpdateIn) -> dict[str, Any]:
data.pop("notes", None)
else:
data["notes"] = body.notes
+ if body.title is not None:
+ # empty title falls back to the coordinates; keep entity label in sync
+ title = body.title.strip() or satellite_engine.coords_label(
+ data["lat"], data["lon"]
+ )
+ data["title"] = title
+ entity = case.find_entity(attr="path", value=body.path)
+ if entity:
+ case.update_entity(entity["id"], {"label": title})
sidecar_path.write_text(
json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
)
diff --git a/src/ozimut/engine/inspect.py b/src/ozimut/engine/inspect.py
index 1b82754..b7dc139 100644
--- a/src/ozimut/engine/inspect.py
+++ b/src/ozimut/engine/inspect.py
@@ -250,12 +250,29 @@ def registries() -> dict[str, Any]:
}
-def run_analysis(case: Case, rel_path: str, name: str, params: dict[str, Any]) -> dict[str, Any]:
+def run_analysis(
+ case: Case,
+ rel_path: str,
+ name: str,
+ params: dict[str, Any],
+ *,
+ time_s: float | None = None,
+ ops: list[dict[str, Any]] | None = None,
+) -> dict[str, Any]:
+ """Run a read-only analysis on a filed image or a transient frame recipe.
+
+ ``time_s``/``ops`` let the Inspect session analyse a not-yet-saved frame
+ (extracted from ``rel_path`` at ``time_s``, optionally adjusted) without filing
+ anything. Plain image analysis (no ``time_s``/``ops``) keeps the original file
+ open so metadata analyses (EXIF) still see it.
+ """
analysis = ANALYSES.get(name)
if analysis is None:
raise ValueError(f"unknown analysis {name!r}")
- with Image.open(case.resolve_inside(rel_path)) as img:
- return analysis.run(img, params or {})
+ if time_s is None and not ops:
+ with Image.open(case.resolve_inside(rel_path)) as img:
+ return analysis.run(img, params or {})
+ return analysis.run(_source_image(case, rel_path, time_s, ops), params or {})
# ---------------------------------------------------------------------------
@@ -441,3 +458,243 @@ def collage(
if label and not result.get("duplicate"):
media_engine.update_media(case, result["item"]["path"], {"label": label})
return result
+
+
+# ---------------------------------------------------------------------------
+# Session workspace: recipes -> filed entities (Inspect Selection/Frame/Collage/Save)
+# ---------------------------------------------------------------------------
+#
+# The Inspect UI is a scratch workspace: frames, adjustments and a collage layout
+# live in the browser as *recipes* (``{path, time?, ops[]}``) and nothing enters the
+# case until an explicit Save. These functions turn a recipe back into pixels and
+# file the result — full-res and reproducible, so provenance stays honest (spec §6).
+
+
+def _source_image(
+ case: Case, rel_path: str, time_s: float | None = None, ops: list[dict[str, Any]] | None = None
+) -> Image.Image:
+ """Materialise a recipe into a PIL image (no filing).
+
+ ``time_s`` set → decode that frame from the video ``rel_path``; otherwise open
+ the image at ``rel_path``. ``ops`` (the adjust/crop pipeline) are applied last.
+ """
+ if time_s is not None:
+ img = extract_frame(case.resolve_inside(rel_path), time_s)
+ else:
+ img = Image.open(case.resolve_inside(rel_path))
+ img.load()
+ if ops:
+ img = apply_ops(img, ops)
+ return img
+
+
+def preview_frame_png(case: Case, video_rel: str, time_s: float) -> bytes:
+ """Decode one video frame and return PNG bytes — for the transient tray only."""
+ frame = extract_frame(case.resolve_inside(video_rel), time_s)
+ buf = io.BytesIO()
+ frame.save(buf, "PNG")
+ return buf.getvalue()
+
+
+def render_preview_png(
+ case: Case, rel_path: str, *, time_s: float | None = None, ops: list[dict[str, Any]] | None = None
+) -> bytes:
+ """Render a recipe (video frame or image + ops) to PNG bytes — no filing.
+
+ Backs collage snapshots and rebuilding previews when a saved session reopens.
+ """
+ buf = io.BytesIO()
+ _source_image(case, rel_path, time_s, ops).convert("RGB").save(buf, "PNG")
+ return buf.getvalue()
+
+
+def save_frame(
+ case: Case,
+ rel_path: str,
+ *,
+ time_s: float | None = None,
+ ops: list[dict[str, Any]] | None = None,
+ label: str | None = None,
+ folder: str | None = None,
+) -> dict[str, Any]:
+ """File one tray frame (a video frame or an adjusted image) as case media."""
+ image = _source_image(case, rel_path, time_s, ops)
+ stem = Path(rel_path).stem[:40]
+ if time_s is not None:
+ tag, op = f"_t{time_s:.2f}s", "frame"
+ else:
+ tag, op = "_edit", "adjust"
+ name = f"{stem}{tag}_{_stamp()}.png"
+ source = _derivation(
+ rel_path, _source_sha(case, rel_path), op=op,
+ **({"time": round(time_s, 3)} if time_s is not None else {}),
+ **({"ops": ops} if ops else {}),
+ )
+ result = media_engine.import_image(case, image, name, source, by="inspect")
+ if not result.get("duplicate"):
+ patch: dict[str, Any] = {}
+ if label:
+ patch["label"] = label
+ if folder:
+ patch["folder"] = folder
+ if patch:
+ media_engine.update_media(case, result["item"]["path"], patch)
+ return result
+
+
+def _solve_linear(matrix: list[list[float]], rhs: list[float]) -> list[float]:
+ """Gaussian elimination with partial pivoting (small square systems, no numpy)."""
+ n = len(rhs)
+ a = [row[:] + [rhs[i]] for i, row in enumerate(matrix)]
+ for col in range(n):
+ pivot = max(range(col, n), key=lambda r: abs(a[r][col]))
+ if abs(a[pivot][col]) < 1e-12:
+ raise ValueError("degenerate perspective quad")
+ a[col], a[pivot] = a[pivot], a[col]
+ pv = a[col][col]
+ a[col] = [v / pv for v in a[col]]
+ for r in range(n):
+ if r != col and a[r][col]:
+ factor = a[r][col]
+ a[r] = [v - factor * a[col][i] for i, v in enumerate(a[r])]
+ return [a[i][n] for i in range(n)]
+
+
+def _perspective_coeffs(dst_quad: list[list[float]], src_quad: list[list[float]]) -> list[float]:
+ """8 coeffs for ``Image.transform(PERSPECTIVE)`` mapping ``dst_quad``→``src_quad``.
+
+ PIL samples the *output* pixel and needs the matching *input* coordinate, so we
+ solve for the map from destination (canvas) corners to source-image corners.
+ """
+ matrix, rhs = [], []
+ for (x, y), (u, v) in zip(dst_quad, src_quad):
+ matrix.append([x, y, 1, 0, 0, 0, -u * x, -u * y])
+ matrix.append([0, 0, 0, x, y, 1, -v * x, -v * y])
+ rhs.extend((u, v))
+ return _solve_linear(matrix, rhs)
+
+
+def compose_perspective(
+ case: Case,
+ *,
+ width: int,
+ height: int,
+ nodes: list[dict[str, Any]],
+ background: str | None = "#12141c",
+ label: str | None = None,
+ folder: str | None = None,
+) -> dict[str, Any]:
+ """Composite tray/case images, each warped into a 4-point quad, onto a canvas.
+
+ ``nodes`` are painted in order (later = on top); each is
+ ``{"src": {path, time?, ops[]}, "quad": [[x,y]×4]}`` with the quad in canvas
+ pixels (top-left, top-right, bottom-right, bottom-left). A falsy ``background``
+ yields a transparent (RGBA) canvas so the saved PNG carries only the pieces.
+ """
+ if not nodes:
+ raise ValueError("collage needs at least one image")
+ width = max(16, min(int(width), 8192))
+ height = max(16, min(int(height), 8192))
+ canvas = (
+ Image.new("RGB", (width, height), background)
+ if background
+ else Image.new("RGBA", (width, height), (0, 0, 0, 0))
+ )
+
+ sources: list[str] = []
+ for node in nodes:
+ spec = node.get("src") or {}
+ rel = spec.get("path")
+ if not rel:
+ raise ValueError("collage node is missing a source path")
+ img = _source_image(case, rel, spec.get("time"), spec.get("ops")).convert("RGB")
+ w, h = img.size
+ src_corners = [[0, 0], [w, 0], [w, h], [0, h]]
+ quad = [[float(x), float(y)] for x, y in node["quad"]]
+ coeffs = _perspective_coeffs(quad, src_corners)
+ warped = img.transform((width, height), Image.PERSPECTIVE, coeffs, Image.BICUBIC)
+ mask = Image.new("L", (w, h), 255).transform(
+ (width, height), Image.PERSPECTIVE, coeffs, Image.BICUBIC
+ )
+ canvas.paste(warped, (0, 0), mask)
+ sources.append(rel)
+
+ source = _derivation("", None, op="collage", sources=sources, perspective=True)
+ name = f"collage_{_stamp()}.png"
+ result = media_engine.import_image(case, canvas, name, source, by="inspect")
+ if not result.get("duplicate"):
+ patch: dict[str, Any] = {}
+ if label:
+ patch["label"] = label
+ if folder:
+ patch["folder"] = folder
+ if patch:
+ media_engine.update_media(case, result["item"]["path"], patch)
+ return result
+
+
+# Map the frontend's css-filter values (multiplicative, 1.0 = neutral) to ffmpeg's
+# `eq` filter, whose brightness is additive. Only the css-previewable filters carry
+# over to video; grayscale/invert are handled as saturation/negate.
+def _eq_filterchain(params: dict[str, Any]) -> str | None:
+ def val(key, default):
+ try:
+ return float(params.get(key, default))
+ except (TypeError, ValueError):
+ return default
+
+ eq = {
+ "brightness": round(val("brightness", 1.0) - 1.0, 4),
+ "contrast": round(val("contrast", 1.0), 4),
+ "saturation": 0.0 if val("grayscale", 0) >= 1 else round(val("saturation", 1.0), 4),
+ "gamma": round(val("gamma", 1.0), 4),
+ }
+ neutral = {"brightness": 0.0, "contrast": 1.0, "saturation": 1.0, "gamma": 1.0}
+ parts = [f"eq={':'.join(f'{k}={v}' for k, v in eq.items())}"] if eq != neutral else []
+ if val("invert", 0) >= 1:
+ parts.append("negate")
+ return ",".join(parts) or None
+
+
+def enhance_video(
+ case: Case,
+ video_rel: str,
+ params: dict[str, Any],
+ *,
+ label: str | None = None,
+ folder: str | None = None,
+) -> dict[str, Any]:
+ """Re-encode a video with the gear's adjustments and file it as new media."""
+ if not media_engine.ffmpeg_available():
+ raise RuntimeError("ffmpeg is required to enhance video")
+ vf = _eq_filterchain(params)
+ if not vf:
+ raise ValueError("no adjustments to apply — tune the gear first")
+
+ src = case.resolve_inside(video_rel)
+ stem = Path(src.name).stem[:40]
+ tmp = case.subdir("media") / f".enhance_{_stamp()}.mp4"
+ try:
+ proc = subprocess.run(
+ ["ffmpeg", "-y", "-loglevel", "error", "-i", str(src),
+ "-vf", vf, "-c:a", "copy", str(tmp)],
+ capture_output=True, timeout=600,
+ )
+ if proc.returncode != 0 or not tmp.exists():
+ raise RuntimeError(
+ (proc.stderr or b"").decode("utf-8", "replace").strip() or "video enhance failed"
+ )
+ name = f"{stem}_enhanced_{_stamp()}.mp4"
+ source = _derivation(video_rel, _source_sha(case, video_rel), op="enhance-video", params=params)
+ result = media_engine.import_produced_file(case, tmp, name, source, by="inspect")
+ finally:
+ tmp.unlink(missing_ok=True)
+ if not result.get("duplicate"):
+ patch: dict[str, Any] = {}
+ if label:
+ patch["label"] = label
+ if folder:
+ patch["folder"] = folder
+ if patch:
+ media_engine.update_media(case, result["item"]["path"], patch)
+ return result
diff --git a/src/ozimut/engine/media.py b/src/ozimut/engine/media.py
index 7c15696..b8ccbe1 100644
--- a/src/ozimut/engine/media.py
+++ b/src/ozimut/engine/media.py
@@ -169,7 +169,24 @@ def import_image(
if not name.lower().endswith(".png"):
name = f"{Path(name).stem}.png"
dest = unique_path(media_dir, name)
- image.convert("RGB").save(dest, "PNG")
+ # Preserve an alpha channel (e.g. a transparent collage canvas); everything
+ # else is flattened to RGB. The thumbnail stage composites alpha over black.
+ image.save(dest, "PNG") if image.mode == "RGBA" else image.convert("RGB").save(dest, "PNG")
+ return _register(case, dest, source, by=by)
+
+
+def import_produced_file(
+ case: Case, src_path: Path, filename: str, source: dict[str, Any], *, by: str = "inspect"
+) -> dict[str, Any]:
+ """File a tool-produced file (e.g. an ffmpeg-enhanced video) into the case.
+
+ Unlike ``import_image`` (PNG only) this keeps the produced container/codec and,
+ unlike ``import_stream``, records a derivation ``source`` so the output stays
+ auditable back to its origin (spec §6). The source file is moved into ``media/``.
+ """
+ media_dir = case.subdir("media")
+ dest = unique_path(media_dir, safe_filename(filename))
+ shutil.move(str(src_path), str(dest))
return _register(case, dest, source, by=by)
diff --git a/src/ozimut/engine/satellite.py b/src/ozimut/engine/satellite.py
new file mode 100644
index 0000000..7c63d45
--- /dev/null
+++ b/src/ozimut/engine/satellite.py
@@ -0,0 +1,71 @@
+"""Satellite captures on disk and their one-to-one sync with ``place`` entities.
+
+A capture is an image plus a JSON sidecar under ``<case>/satellite/``:
+
+ satellite/sat_<stamp>_z<zoom>_<provider>.png
+ satellite/sat_<stamp>_z<zoom>_<provider>.png.json # provenance (lat/lon/…)
+
+Every capture is mirrored by exactly one ``place`` entity in ``case.json``
+(spec §3.5): one capture == one entity on the right. They are tied by the
+capture's relative ``path``, stored on the entity as ``attrs.path`` — not by
+coordinates, so two captures of the same point stay two independent entities.
+The entity ``label`` is the capture title (coordinates by default, editable).
+
+Deleting in one place must delete in the other, so all delete paths funnel here:
+
+* delete a capture → drop the one ``place`` entity that points at it;
+* delete a ``place`` → drop the one capture file it points at (handled by the
+ entities API via :func:`unlink_capture`).
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+from ..workspace import Case
+
+
+def coords_label(lat: float, lon: float) -> str:
+ """Default capture title / place label: the point's coordinates."""
+ return f"{lat:.6f}, {lon:.6f}"
+
+
+def _read_sidecar(case: Case, rel_path: str) -> dict[str, Any] | None:
+ image = case.resolve_inside(rel_path)
+ sidecar = image.with_name(image.name + ".json")
+ if not sidecar.exists():
+ return None
+ return json.loads(sidecar.read_text(encoding="utf-8"))
+
+
+def list_captures(case: Case) -> list[dict[str, Any]]:
+ sat_dir = case.subdir("satellite")
+ captures: list[dict[str, Any]] = []
+ for sidecar in sorted(sat_dir.glob("*.png.json")):
+ image_name = sidecar.name[: -len(".json")]
+ if not (sat_dir / image_name).exists():
+ continue
+ data = json.loads(sidecar.read_text(encoding="utf-8"))
+ data["path"] = f"satellite/{image_name}"
+ lat, lon = data.get("lat"), data.get("lon")
+ if not data.get("title") and lat is not None and lon is not None:
+ data["title"] = coords_label(lat, lon)
+ captures.append(data)
+ captures.sort(key=lambda d: d.get("fetched_at") or "", reverse=True)
+ return captures
+
+
+def unlink_capture(case: Case, rel_path: str) -> None:
+ """Remove a capture's image + sidecar from disk (leaves entities alone)."""
+ image = case.resolve_inside(rel_path)
+ image.unlink(missing_ok=True)
+ image.with_name(image.name + ".json").unlink(missing_ok=True)
+
+
+def delete_capture(case: Case, rel_path: str) -> None:
+ """Delete one capture and the single ``place`` entity mirroring it."""
+ unlink_capture(case, rel_path)
+ entity = case.find_entity(attr="path", value=rel_path)
+ if entity:
+ case.remove_entity(entity["id"])
diff --git a/src/ozimut/workspace.py b/src/ozimut/workspace.py
index 6d07e67..b7d0f1a 100644
--- a/src/ozimut/workspace.py
+++ b/src/ozimut/workspace.py
@@ -26,7 +26,7 @@ from typing import Any, Literal
from . import config
-CASE_SUBDIRS = ("media", "satellite", "proofs", "exports")
+CASE_SUBDIRS = ("media", "satellite", "proofs", "exports", "inspect")
EntityStatus = Literal["confirmed", "suggested"]
@@ -276,19 +276,37 @@ class Case:
raise CaseError(f"link '{link_id}' not found")
self._write_json(data)
- # -- folders (organisational buckets for entities) -----------------------
+ # -- folders (nested organisational buckets for entities) ----------------
+ #
+ # Folders form a tree encoded as ``/``-separated paths, e.g.
+ # ``Sources/Telegram``. An entity's ``attrs.folder`` holds the full path of
+ # the node it is filed under. The stored list always contains every
+ # ancestor of every leaf, so the tree is well-formed on its own.
+
+ @staticmethod
+ def _normalize_folder(name: str) -> str:
+ parts = [p.strip() for p in str(name).split("/")]
+ parts = [p for p in parts if p]
+ if not parts:
+ raise CaseError("folder name is required")
+ return "/".join(parts)
def list_folders(self) -> list[str]:
return self.read().get("folders", [])
def add_folder(self, name: str) -> list[str]:
- name = name.strip()
- if not name:
- raise CaseError("folder name is required")
+ path = self._normalize_folder(name)
data = self.read()
folders = data.setdefault("folders", [])
- if name not in folders:
- folders.append(name)
+ # materialise the leaf and every ancestor so the tree stays connected
+ segments = path.split("/")
+ changed = False
+ for i in range(1, len(segments) + 1):
+ ancestor = "/".join(segments[:i])
+ if ancestor not in folders:
+ folders.append(ancestor)
+ changed = True
+ if changed:
folders.sort(key=str.lower)
self._write_json(data)
return data["folders"]
@@ -296,11 +314,14 @@ class Case:
def remove_folder(self, name: str) -> list[str]:
data = self.read()
folders = data.setdefault("folders", [])
- if name in folders:
- folders.remove(name)
- # unassign any entity still pointing at the removed folder
+ # a folder and its whole subtree go together
+ prefix = name + "/"
+ doomed = {f for f in folders if f == name or f.startswith(prefix)}
+ data["folders"] = [f for f in folders if f not in doomed]
+ # unassign any entity filed under a removed node (or its descendants)
for entity in data.get("entities", []):
- if entity.get("attrs", {}).get("folder") == name:
+ folder = entity.get("attrs", {}).get("folder")
+ if folder is not None and (folder == name or folder.startswith(prefix)):
entity["attrs"].pop("folder", None)
self._write_json(data)
return data["folders"]
diff --git a/tests/test_cases_api.py b/tests/test_cases_api.py
index 02e348c..a6743c2 100644
--- a/tests/test_cases_api.py
+++ b/tests/test_cases_api.py
@@ -204,3 +204,64 @@ def test_delete_folder_unassigns_entities(client):
entity = next(e for e in data["entities"] if e["id"] == ent["id"])
assert "folder" not in entity["attrs"]
+
+def test_nested_folder_materialises_ancestors(client):
+ cid = client.post("/api/cases", json={"name": "Nested"}).json()["id"]
+
+ # creating a leaf path also creates every ancestor node
+ folders = client.post(
+ f"/api/cases/{cid}/folders", json={"name": "Sources/Telegram/Group A"}
+ ).json()
+ assert folders == ["Sources", "Sources/Telegram", "Sources/Telegram/Group A"]
+
+ # segments are trimmed and empty ones dropped
+ folders = client.post(
+ f"/api/cases/{cid}/folders", json={"name": " Sources / Signal "}
+ ).json()
+ assert "Sources/Signal" in folders
+
+
+def test_delete_folder_cascades_subtree(client):
+ cid = client.post("/api/cases", json={"name": "Cascade"}).json()["id"]
+ client.post(f"/api/cases/{cid}/folders", json={"name": "Sources/Telegram"})
+ deep = client.post(
+ f"/api/cases/{cid}/entities",
+ json={"type": "note", "label": "chat log",
+ "attrs": {"folder": "Sources/Telegram"}},
+ ).json()
+
+ # deleting the parent removes the whole subtree and unfiles its entities
+ remaining = client.delete(
+ f"/api/cases/{cid}/folders", params={"name": "Sources"}
+ ).json()
+ assert remaining == []
+ data = client.get(f"/api/cases/{cid}").json()
+ entity = next(e for e in data["entities"] if e["id"] == deep["id"])
+ assert "folder" not in entity["attrs"]
+
+
+def test_delete_media_entity_removes_file(client):
+ import io
+
+ cid = client.post("/api/cases", json={"name": "Sync"}).json()["id"]
+ png = (
+ b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
+ b"\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\nIDATx\x9cc\x00"
+ b"\x01\x00\x00\x05\x00\x01\r\n-\xb4\x00\x00\x00\x00IEND\xaeB`\x82"
+ )
+ item = client.post(
+ f"/api/cases/{cid}/media/upload",
+ files={"file": ("frame.png", io.BytesIO(png), "image/png")},
+ ).json()["item"]
+ entity = next(
+ e for e in client.get(f"/api/cases/{cid}").json()["entities"]
+ if e["type"] == "media"
+ )
+
+ # deleting the media entity from the sidebar deletes the underlying file too
+ client.delete(f"/api/cases/{cid}/entities/{entity['id']}")
+ assert client.get(f"/files/{cid}/{item['path']}").status_code == 404
+ assert not any(
+ e["type"] == "media" for e in client.get(f"/api/cases/{cid}").json()["entities"]
+ )
+
diff --git a/tests/test_inspect_api.py b/tests/test_inspect_api.py
index 31bf0bc..9051be3 100644
--- a/tests/test_inspect_api.py
+++ b/tests/test_inspect_api.py
@@ -159,6 +159,275 @@ def test_analyze_unknown_is_rejected(client):
assert res.status_code == 422
+# -- session workspace: recipes -> filed entities (Save gate) ----------------
+
+
+def test_save_frames_files_selected_images_into_folder(client):
+ cid = client.post("/api/cases", json={"name": "Save"}).json()["id"]
+ item = _upload(client, cid, "orig.png")
+ before = len(client.get(f"/api/cases/{cid}/media").json())
+
+ res = client.post(
+ f"/api/cases/{cid}/inspect/save-frames",
+ json={
+ "items": [
+ {"path": item["path"], "ops": [{"op": "brightness", "params": {"amount": 1.5}}],
+ "label": "Tuned"}
+ ],
+ "folder": "Frames",
+ },
+ ).json()
+ saved = res["saved"]
+ assert len(saved) == 1 and saved[0]["duplicate"] is False
+
+ listing = client.get(f"/api/cases/{cid}/media").json()
+ assert len(listing) == before + 1
+ new_path = saved[0]["item"]["path"]
+ entity = next(
+ e for e in client.get(f"/api/cases/{cid}").json()["entities"]
+ if e["attrs"].get("path") == new_path
+ )
+ assert entity["attrs"]["folder"] == "Frames"
+ assert entity["provenance"]["by"] == "inspect"
+
+
+def test_compose_perspective_files_one_collage(client):
+ cid = client.post("/api/cases", json={"name": "Compose"}).json()["id"]
+ a = _upload(client, cid, "a.png", _png_bytes(color=(10, 20, 30), size=(80, 60)))
+ b = _upload(client, cid, "b.png", _png_bytes(color=(200, 100, 50), size=(80, 60)))
+ before = len(client.get(f"/api/cases/{cid}/media").json())
+
+ res = client.post(
+ f"/api/cases/{cid}/inspect/compose",
+ json={
+ "width": 400, "height": 300,
+ "nodes": [
+ {"src": {"path": a["path"]},
+ "quad": [[0, 0], [200, 10], [190, 300], [0, 290]]},
+ {"src": {"path": b["path"]},
+ "quad": [[200, 10], [400, 0], [400, 300], [190, 300]]},
+ ],
+ },
+ ).json()
+ assert res["duplicate"] is False
+ assert len(client.get(f"/api/cases/{cid}/media").json()) == before + 1
+ probe = client.get(
+ f"/api/cases/{cid}/inspect/probe", params={"path": res["item"]["path"]}
+ ).json()
+ assert probe["width"] == 400 and probe["height"] == 300
+ listing = client.get(f"/api/cases/{cid}/media").json()
+ collage = next(m for m in listing if m["path"] == res["item"]["path"])
+ assert collage["source"]["op"] == "collage" and collage["source"]["perspective"] is True
+
+
+def test_compose_transparent_background_keeps_alpha(client):
+ cid = client.post("/api/cases", json={"name": "Alpha"}).json()["id"]
+ a = _upload(client, cid, "a.png", _png_bytes(color=(10, 20, 30), size=(80, 60)))
+
+ res = client.post(
+ f"/api/cases/{cid}/inspect/compose",
+ json={
+ "width": 400, "height": 300, "background": None,
+ "nodes": [
+ {"src": {"path": a["path"]},
+ "quad": [[20, 20], [120, 20], [120, 100], [20, 100]]},
+ ],
+ },
+ ).json()
+ assert res["duplicate"] is False
+
+ png = client.get(f"/files/{cid}/{res['item']['path']}").content
+ img = Image.open(io.BytesIO(png))
+ assert img.mode == "RGBA"
+ # a corner outside every quad stays fully transparent
+ assert img.getpixel((0, 0))[3] == 0
+ # a pixel inside the placed piece is opaque
+ assert img.getpixel((60, 60))[3] == 255
+
+
+def test_compose_requires_nodes(client):
+ cid = client.post("/api/cases", json={"name": "NoNodes"}).json()["id"]
+ res = client.post(
+ f"/api/cases/{cid}/inspect/compose", json={"width": 100, "height": 100, "nodes": []}
+ )
+ assert res.status_code == 422
+
+
+def test_analyze_accepts_transient_ops_without_filing(client):
+ cid = client.post("/api/cases", json={"name": "AnalyzeOps"}).json()["id"]
+ item = _upload(client, cid, "img.png", _png_bytes(color=(255, 0, 0), size=(20, 20)))
+ before = len(client.get(f"/api/cases/{cid}/media").json())
+
+ res = client.post(
+ f"/api/cases/{cid}/inspect/analyze",
+ json={"path": item["path"], "name": "histogram",
+ "ops": [{"op": "invert", "params": {"on": 1}}]},
+ ).json()
+ assert res["kind"] == "histogram"
+ # inverting pure red pushes the red channel to 0
+ assert res["channels"]["r"][0] == 400
+ # analysing a transient recipe files nothing
+ assert len(client.get(f"/api/cases/{cid}/media").json()) == before
+
+
[email protected](not media_engine.ffmpeg_available(), reason="ffmpeg not installed")
+def test_frame_preview_returns_png_without_filing(client, tmp_path):
+ import subprocess
+
+ video = tmp_path / "clip.mp4"
+ subprocess.run(
+ ["ffmpeg", "-y", "-loglevel", "error", "-f", "lavfi",
+ "-i", "testsrc=duration=2:size=160x120:rate=10", str(video)],
+ check=True,
+ )
+ cid = client.post("/api/cases", json={"name": "Preview"}).json()["id"]
+ with video.open("rb") as fh:
+ item = client.post(
+ f"/api/cases/{cid}/media/upload", files={"file": ("clip.mp4", fh, "video/mp4")}
+ ).json()["item"]
+ before = len(client.get(f"/api/cases/{cid}/media").json())
+
+ res = client.post(
+ f"/api/cases/{cid}/inspect/frame/preview", json={"path": item["path"], "time": 1.0}
+ )
+ assert res.status_code == 200
+ assert res.headers["content-type"] == "image/png"
+ assert Image.open(io.BytesIO(res.content)).size == (160, 120)
+ # a preview never files anything
+ assert len(client.get(f"/api/cases/{cid}/media").json()) == before
+
+
[email protected](not media_engine.ffmpeg_available(), reason="ffmpeg not installed")
+def test_enhance_video_files_new_video(client, tmp_path):
+ import subprocess
+
+ video = tmp_path / "clip.mp4"
+ subprocess.run(
+ ["ffmpeg", "-y", "-loglevel", "error", "-f", "lavfi",
+ "-i", "testsrc=duration=1:size=160x120:rate=10", str(video)],
+ check=True,
+ )
+ cid = client.post("/api/cases", json={"name": "Enhance"}).json()["id"]
+ with video.open("rb") as fh:
+ item = client.post(
+ f"/api/cases/{cid}/media/upload", files={"file": ("clip.mp4", fh, "video/mp4")}
+ ).json()["item"]
+
+ res = client.post(
+ f"/api/cases/{cid}/inspect/enhance-video",
+ json={"path": item["path"], "params": {"brightness": 1.3, "contrast": 1.2},
+ "folder": "Enhanced"},
+ ).json()
+ assert res["duplicate"] is False
+ new_path = res["item"]["path"]
+ assert new_path.endswith(".mp4")
+ probe = client.get(
+ f"/api/cases/{cid}/inspect/probe", params={"path": new_path}
+ ).json()
+ assert probe["kind"] == "video"
+ entity = next(
+ e for e in client.get(f"/api/cases/{cid}").json()["entities"]
+ if e["attrs"].get("path") == new_path
+ )
+ assert entity["attrs"]["folder"] == "Enhanced"
+
+
+def test_render_preview_applies_ops_without_filing(client):
+ cid = client.post("/api/cases", json={"name": "Render"}).json()["id"]
+ item = _upload(client, cid, "img.png", _png_bytes(color=(255, 0, 0), size=(30, 20)))
+ before = len(client.get(f"/api/cases/{cid}/media").json())
+
+ res = client.post(
+ f"/api/cases/{cid}/inspect/render-preview",
+ json={"path": item["path"], "ops": [{"op": "crop", "params": {"x": 0, "y": 0, "w": 0.5, "h": 1}}]},
+ )
+ assert res.status_code == 200
+ assert res.headers["content-type"] == "image/png"
+ assert Image.open(io.BytesIO(res.content)).size == (15, 20) # cropped to half width
+ assert len(client.get(f"/api/cases/{cid}/media").json()) == before # nothing filed
+
+
+def test_session_save_list_load_delete_roundtrip(client):
+ cid = client.post("/api/cases", json={"name": "Session"}).json()["id"]
+ item = _upload(client, cid, "clip.png")
+ spec = {
+ "source": {"path": item["path"], "kind": "image"},
+ "videoAdjust": {},
+ "frames": [{"id": "fr1", "path": item["path"], "time": None, "adjust": {"brightness": 1.4}, "crop": None}],
+ "collage": {"width": 800, "height": 400, "background": "#101010", "nodes": []},
+ }
+ saved = client.post(
+ f"/api/cases/{cid}/inspect/sessions", json={"title": "My session", "spec": spec}
+ ).json()
+ assert saved["name"] == "my-session"
+
+ listing = client.get(f"/api/cases/{cid}/inspect/sessions").json()
+ assert len(listing) == 1 and listing[0]["title"] == "My session" and listing[0]["frames"] == 1
+
+ # an inspect-session entity is upserted so it reopens from the sidebar
+ entities = client.get(f"/api/cases/{cid}").json()["entities"]
+ ent = next(e for e in entities if e["type"] == "inspect-session")
+ assert ent["attrs"]["spec"] == "inspect/my-session.json"
+
+ loaded = client.get(f"/api/cases/{cid}/inspect/sessions/my-session").json()
+ assert loaded["ozimut_inspect"] == 1
+ assert loaded["frames"][0]["adjust"]["brightness"] == 1.4
+
+ # re-saving under the same title updates in place (no duplicate entity)
+ client.post(f"/api/cases/{cid}/inspect/sessions", json={"title": "My session", "spec": spec})
+ entities = client.get(f"/api/cases/{cid}").json()["entities"]
+ assert sum(1 for e in entities if e["type"] == "inspect-session") == 1
+
+ client.delete(f"/api/cases/{cid}/inspect/sessions/my-session")
+ assert client.get(f"/api/cases/{cid}/inspect/sessions").json() == []
+ entities = client.get(f"/api/cases/{cid}").json()["entities"]
+ assert not any(e["type"] == "inspect-session" for e in entities)
+
+
+def test_session_resave_by_name_overwrites_after_rename(client):
+ # Reopening a session then saving it re-uses its slug (name), so a title
+ # change updates the same session in place instead of forking a new one.
+ cid = client.post("/api/cases", json={"name": "Rename"}).json()["id"]
+ item = _upload(client, cid, "clip.png")
+ spec = {"source": {"path": item["path"], "kind": "image"}, "frames": [], "collage": {"nodes": []}}
+
+ first = client.post(
+ f"/api/cases/{cid}/inspect/sessions", json={"title": "Original", "spec": spec}
+ ).json()
+ assert first["name"] == "original"
+
+ client.post(
+ f"/api/cases/{cid}/inspect/sessions",
+ json={"name": first["name"], "title": "Renamed", "spec": spec},
+ )
+ listing = client.get(f"/api/cases/{cid}/inspect/sessions").json()
+ assert len(listing) == 1
+ assert listing[0]["name"] == "original" and listing[0]["title"] == "Renamed"
+ entities = client.get(f"/api/cases/{cid}").json()["entities"]
+ assert sum(1 for e in entities if e["type"] == "inspect-session") == 1
+
+
[email protected](not media_engine.ffmpeg_available(), reason="ffmpeg not installed")
+def test_enhance_video_rejects_neutral_params(client, tmp_path):
+ import subprocess
+
+ video = tmp_path / "clip.mp4"
+ subprocess.run(
+ ["ffmpeg", "-y", "-loglevel", "error", "-f", "lavfi",
+ "-i", "testsrc=duration=1:size=160x120:rate=10", str(video)],
+ check=True,
+ )
+ cid = client.post("/api/cases", json={"name": "Neutral"}).json()["id"]
+ with video.open("rb") as fh:
+ item = client.post(
+ f"/api/cases/{cid}/media/upload", files={"file": ("clip.mp4", fh, "video/mp4")}
+ ).json()["item"]
+ res = client.post(
+ f"/api/cases/{cid}/inspect/enhance-video", json={"path": item["path"], "params": {}}
+ )
+ assert res.status_code == 422
+
+
@pytest.mark.skipif(not media_engine.ffmpeg_available(), reason="ffmpeg not installed")
def test_frame_capture_from_video(client, tmp_path):
import subprocess
diff --git a/tests/test_satellite_api.py b/tests/test_satellite_api.py
index 13709e3..76426b2 100644
--- a/tests/test_satellite_api.py
+++ b/tests/test_satellite_api.py
@@ -34,3 +34,91 @@ def test_capture_defaults_to_north(client, monkeypatch):
json={"lat": 48.8584, "lon": 2.2945, "zoom": 16, "width": 512, "height": 512},
).json()
assert result["bearing"] == 0.0
+
+
+def _capture(client, cid, lat, lon, zoom=16):
+ return client.post(
+ f"/api/cases/{cid}/satellite/capture",
+ json={"lat": lat, "lon": lon, "zoom": zoom, "width": 512, "height": 512},
+ ).json()
+
+
+def _places(client, cid):
+ return [e for e in client.get(f"/api/cases/{cid}").json()["entities"]
+ if e["type"] == "place"]
+
+
+def test_capture_creates_place_entity(client, monkeypatch):
+ monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)
+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]
+ cap = _capture(client, cid, 48.8584, 2.2945)
+ places = _places(client, cid)
+ assert len(places) == 1
+ # the entity is tied to this exact capture by path, titled with its coords
+ assert places[0]["attrs"]["coords"] == "48.858400, 2.294500"
+ assert places[0]["attrs"]["path"] == cap["path"]
+ assert places[0]["label"] == "48.858400, 2.294500"
+ # zoom/bearing travel with the place so the sidebar can restore the view
+ assert places[0]["attrs"]["zoom"] == 16
+ assert places[0]["attrs"]["bearing"] == 0.0
+ # capturing files the place straight away — no confirm step
+ assert places[0]["provenance"]["status"] == "confirmed"
+
+
+def test_each_capture_is_its_own_entity(client, monkeypatch):
+ monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)
+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]
+ # two captures at the same coordinates are two independent entities (1:1)
+ _capture(client, cid, 48.8584, 2.2945, zoom=16)
+ _capture(client, cid, 48.8584, 2.2945, zoom=17)
+ assert len(_places(client, cid)) == 2
+
+
+def test_delete_capture_removes_only_its_place(client, monkeypatch):
+ monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)
+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]
+ first = _capture(client, cid, 48.8584, 2.2945, zoom=16)
+ second = _capture(client, cid, 48.8584, 2.2945, zoom=17)
+
+ client.delete(f"/api/cases/{cid}/satellite", params={"path": first["path"]})
+ # only the deleted capture's place is gone; the sibling stays intact
+ places = _places(client, cid)
+ assert len(places) == 1
+ assert places[0]["attrs"]["path"] == second["path"]
+ remaining = client.get(f"/api/cases/{cid}/satellite").json()
+ assert [c["path"] for c in remaining] == [second["path"]]
+
+
+def test_delete_place_entity_removes_only_its_capture(client, monkeypatch):
+ monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)
+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]
+ first = _capture(client, cid, 48.8584, 2.2945, zoom=16)
+ second = _capture(client, cid, 48.8584, 2.2945, zoom=17)
+ place = next(p for p in _places(client, cid) if p["attrs"]["path"] == first["path"])
+
+ # deleting the place from the sidebar wipes just its one capture
+ client.delete(f"/api/cases/{cid}/entities/{place['id']}")
+ assert len(_places(client, cid)) == 1
+ remaining = client.get(f"/api/cases/{cid}/satellite").json()
+ assert [c["path"] for c in remaining] == [second["path"]]
+
+
+def test_edit_title_renames_place_entity(client, monkeypatch):
+ monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)
+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]
+ cap = _capture(client, cid, 48.8584, 2.2945)
+
+ updated = client.patch(
+ f"/api/cases/{cid}/satellite",
+ json={"path": cap["path"], "title": "Eiffel Tower"},
+ ).json()
+ assert updated["title"] == "Eiffel Tower"
+ assert _places(client, cid)[0]["label"] == "Eiffel Tower"
+
+ # listing reflects the stored title
+ listed = client.get(f"/api/cases/{cid}/satellite").json()
+ assert listed[0]["title"] == "Eiffel Tower"
+
+ # clearing the title falls back to the coordinates on both sides
+ client.patch(f"/api/cases/{cid}/satellite", json={"path": cap["path"], "title": " "})
+ assert _places(client, cid)[0]["label"] == "48.858400, 2.294500"