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

Send each kind of export to a folder the analyst picked

OsintMeThat06479e6b75dd
diff --git a/frontend/e2e/app.fixture.js b/frontend/e2e/app.fixture.js
index c694f5f..5e5109b 100644
--- a/frontend/e2e/app.fixture.js
+++ b/frontend/e2e/app.fixture.js
@@ -22,8 +22,12 @@ const media = [{
kind: 'image',
width: 640,
height: 360,
+ size: 256,
+ sha256: '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef',
source: { type: 'upload' },
thumbnail: null,
+ thumb_state: 'ready',
+ enrich_state: 'ready',
folder: '',
notes: '',
}];
@@ -48,6 +52,17 @@ const settings = {
post_mention: '@GeoConfirmed',
post_target: 'x',
signature_handle: '',
+ signature: false,
+ export_dirs: { notes: '', media: '', proofs: '' },
+ api_keys: {},
+ providers_enabled: {},
+ free_tiers: {},
+ eco_max_zooms: {},
+ provider_status: {},
+ ingest_token: '',
+ version: '0.2.7',
+ workspace_root: '/tmp/azimut-browser-fixture',
+ extension_version: '0.2.7',
update_check_on_start: false,
update_dismissed_version: '',
usage: {},
@@ -115,6 +130,16 @@ export async function installAppFixture(page, options = {}) {
const savedIndexDelays = options.savedIndexDelays ?? {};
const proofIndexDelays = options.proofIndexDelays ?? {};
const fixtureDrafts = options.drafts ?? {};
+ const fixtureSettings = {
+ ...settings,
+ export_dirs: { ...settings.export_dirs, ...(options.exportDirs ?? {}) },
+ };
+ const settingsWrites = [];
+ const folderWrites = [];
+ const exportWrites = [];
+ const fixtureFolderRoots = options.folderRoots ?? [];
+ const fixtureFolderViews = { ...(options.folderViews ?? {}) };
+ const fixtureLookupEntities = options.lookupEntities ?? {};
const trashGroups = [...(options.trashGroups ?? [])];
const trashWrites = [];
const bundleCalls = [];
@@ -157,7 +182,46 @@ export async function installAppFixture(page, options = {}) {
if (path === '/api/settings/signature.png') {
return route.fulfill({ status: 404, body: '' });
}
- if (path === '/api/settings') return json(route, settings);
+ if (path === '/api/settings') return json(route, fixtureSettings);
+ if (path === '/api/settings/prefs' && request.method() === 'PUT') {
+ const payload = request.postDataJSON();
+ const previousExportDirs = fixtureSettings.export_dirs;
+ settingsWrites.push(payload);
+ Object.assign(fixtureSettings, payload);
+ if (payload.export_dirs) {
+ fixtureSettings.export_dirs = { ...previousExportDirs, ...payload.export_dirs };
+ }
+ return json(route, fixtureSettings);
+ }
+ if (path === '/api/folders/roots') return json(route, { roots: fixtureFolderRoots });
+ if (path === '/api/folders') {
+ const wanted = url.searchParams.get('path');
+ const view = fixtureFolderViews[wanted];
+ return view ? json(route, view) : json(route, { detail: 'Folder not found' }, 404);
+ }
+ if (path === '/api/folders/create' && request.method() === 'POST') {
+ const payload = request.postDataJSON();
+ const separator = payload.parent.endsWith('/') ? '' : '/';
+ const made = `${payload.parent}${separator}${payload.name}`;
+ folderWrites.push({ ...payload, path: made });
+ fixtureFolderViews[made] = {
+ path: made,
+ name: payload.name,
+ parent: payload.parent,
+ crumbs: [{ name: payload.name, path: made }],
+ folders: [],
+ truncated: false,
+ writable: true,
+ };
+ return json(route, { name: payload.name, path: made });
+ }
+ if (path === '/api/settings/scrapers') return json(route, { scrapers: [] });
+ if (path === '/api/settings/ffmpeg') {
+ return json(route, { available: true, version: 'fixture', source: 'bundled', path: '/tmp/ffmpeg' });
+ }
+ if (path === '/api/settings/diagnostics') {
+ return json(route, { kind: 'bug', title: 'Issue', report: 'Fixture report', url: 'https://example.invalid/issue' });
+ }
// Asked on mount, before any tool: the app has to know the workspace is
// there and whether a folder in it is still waiting to become a case.
if (path === '/api/settings/workspace') return json(route, workspaceStatus);
@@ -238,6 +302,19 @@ export async function installAppFixture(page, options = {}) {
});
return json(route, request.method() === 'DELETE' ? { status: 'deleted' } : { id: 'link-new' });
}
+ if (path === `/api/cases/${CASE_ID}/media/page`) {
+ return json(route, {
+ items: media,
+ next_cursor: null,
+ total: media.length,
+ facets: {
+ category_counts: { image: media.length, upload: media.length },
+ folder_counts: {},
+ gps_count: 0,
+ thumbnail_pending: 0,
+ },
+ });
+ }
if (path === `/api/cases/${CASE_ID}/media`) return json(route, media);
// One media file with everything its sidecar holds. The browse index leaves
// enrichment's metadata dumps out, so the Details panel reads a file at a time.
@@ -246,6 +323,14 @@ export async function installAppFixture(page, options = {}) {
const found = media.find((item) => item.path === wanted);
return found ? json(route, found) : route.fulfill({ status: 404, body: '{}' });
}
+ if (path === `/api/cases/${CASE_ID}/media/export` && request.method() === 'POST') {
+ const payload = request.postDataJSON();
+ exportWrites.push(payload);
+ return json(route, {
+ file: 'panel.svg',
+ folder: fixtureSettings.export_dirs.media || "the case's exports folder",
+ });
+ }
// Two different reads: the capture shelf (pickers list it beside media) and
// the geo index the Map panel groups. Both are needed — a picker whose
// shelf 404s shows no panels at all.
@@ -265,7 +350,7 @@ export async function installAppFixture(page, options = {}) {
}
if (path === `/api/cases/${CASE_ID}/notes`) return json(route, { text: '' });
if (path === `/api/cases/${CASE_ID}/entities/lookup`) {
- return json(route, { entity: null });
+ return json(route, { entity: fixtureLookupEntities[url.searchParams.get('value')] ?? null });
}
if (path === '/api/satellite/providers') return json(route, providers);
if (path === '/api/satellite/imagery-date') {
@@ -301,6 +386,9 @@ export async function installAppFixture(page, options = {}) {
linkWrites,
trashWrites,
bundleCalls,
+ settingsWrites,
+ folderWrites,
+ exportWrites,
expectNoUnexpectedRequests: () => expect(unexpected).toEqual([]),
};
}
diff --git a/frontend/e2e/settings.spec.js b/frontend/e2e/settings.spec.js
new file mode 100644
index 0000000..b031965
--- /dev/null
+++ b/frontend/e2e/settings.spec.js
@@ -0,0 +1,105 @@
+import { test, expect } from '@playwright/test';
+import { installAppFixture } from './app.fixture.js';
+
+test('keeps app settings in focused sections', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+
+ await page.goto('/#settings');
+ await expect(page.getByTitle('Settings')).toHaveClass(/gear-active/);
+
+ const rail = page.getByRole('navigation', { name: 'Settings sections' });
+ await expect(rail.getByRole('button')).toHaveText([
+ 'General',
+ 'Publishing',
+ 'Imagery',
+ 'Templates',
+ 'Capture extension',
+ 'Storage',
+ 'System',
+ ]);
+
+ await expect(page.getByRole('heading', { name: 'Coordinates' })).toBeVisible();
+ await rail.getByRole('button', { name: 'Publishing' }).click();
+ await expect(page.getByRole('heading', { name: 'Geo Report' })).toBeVisible();
+ await expect(page.getByRole('heading', { name: 'Signature' })).toBeVisible();
+
+ await rail.getByRole('button', { name: 'Storage' }).click();
+ await expect(page.getByRole('heading', { name: 'Export folders' })).toBeVisible();
+ await expect(page.getByText('Note PDFs')).toBeVisible();
+ await expect(page.getByText('Media copies')).toBeVisible();
+ await expect(page.getByText('Proof PNGs')).toBeVisible();
+ await expect(page.getByRole('link', { name: 'Export backup' }))
+ .toHaveAttribute('href', '/api/settings/export');
+ await expect(page.getByRole('button', { name: 'Import backup' })).toBeVisible();
+ await expect(page.getByText('keep this backup private')).toBeVisible();
+
+ await rail.getByRole('button', { name: 'System' }).click();
+ await expect(page.getByRole('heading', { name: 'Updates' })).toBeVisible();
+ await expect(page.getByRole('heading', { name: 'Report an issue' })).toBeVisible();
+
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('chooses a real export folder and uses it from Media Library', async ({ page }) => {
+ const root = '/fixture/Documents';
+ const entity = {
+ id: 'media-1',
+ type: 'media',
+ label: 'Panel',
+ attrs: { path: 'media/panel.svg' },
+ provenance: { by: 'user', at: '2026-08-02T00:00:00Z', status: 'confirmed' },
+ };
+ const fixture = await installAppFixture(page, {
+ folderRoots: [{ label: 'Documents', path: root }],
+ folderViews: {
+ [root]: {
+ path: root,
+ name: 'Documents',
+ parent: '/fixture',
+ crumbs: [{ name: 'Documents', path: root }],
+ folders: [],
+ truncated: false,
+ writable: true,
+ },
+ },
+ lookupEntities: { 'media/panel.svg': entity },
+ chains: {
+ 'media-1': {
+ entity,
+ sources: [],
+ lost: [],
+ dependents: [],
+ relations: [],
+ empty: true,
+ },
+ },
+ });
+
+ await page.goto('/#settings');
+ await page.getByRole('navigation', { name: 'Settings sections' })
+ .getByRole('button', { name: 'Storage' }).click();
+ const mediaRow = page.locator('.row').filter({ hasText: 'Media copies' });
+ await mediaRow.getByRole('button', { name: 'Change…' }).click();
+ const picker = page.getByRole('dialog', { name: 'Export destination' });
+ await picker.getByRole('button', { name: 'New folder' }).click();
+ await picker.getByRole('textbox', { name: 'New folder name' }).fill('Field reports');
+ await picker.getByRole('button', { name: 'Create' }).click();
+ await picker.getByRole('button', { name: 'Use this folder' }).click();
+
+ expect(fixture.folderWrites).toEqual([
+ { parent: root, name: 'Field reports', path: `${root}/Field reports` },
+ ]);
+ expect(fixture.settingsWrites.at(-1)).toEqual({
+ export_dirs: { media: `${root}/Field reports` },
+ });
+
+ await page.goto('/#media');
+ await page.reload();
+ await page.getByTitle('Info / Edit notes').click();
+ await page.getByRole('dialog', { name: 'Details' })
+ .getByRole('button', { name: 'Export', exact: true }).click();
+
+ expect(fixture.exportWrites).toEqual([{ path: 'media/panel.svg' }]);
+ await expect(page.getByText('panel.svg copied to Field reports')).toBeVisible();
+ fixture.expectNoUnexpectedRequests();
+});
diff --git a/frontend/src/components/EntityDetails.svelte b/frontend/src/components/EntityDetails.svelte
index de8115e..edfa1fd 100644
--- a/frontend/src/components/EntityDetails.svelte
+++ b/frontend/src/components/EntityDetails.svelte
@@ -25,7 +25,7 @@
import RelationList from './RelationList.svelte';
import RelationPicker from './RelationPicker.svelte';
- let { entityId, onclose, ondeleted } = $props();
+ let { entityId, onclose, ondeleted, previewActions } = $props();
// Chain rows walk the details to another entity in place; that override sticks
// until the host selects a different entity, when it clears back to the prop.
@@ -291,6 +291,12 @@
</div>
{/if}
+ {#if previewActions}
+ <div class="info-preview-actions">
+ {@render previewActions()}
+ </div>
+ {/if}
+
{#if EDITABLE.has(entity.type)}
<label class="modal-label" for="ed-title">Title</label>
<input id="ed-title" class="input" bind:value={infoTitle} placeholder={entity.attrs?.coords ?? 'Title'} />
@@ -567,6 +573,13 @@
object-fit: contain;
display: block;
}
+ .info-preview-actions {
+ display: flex;
+ justify-content: flex-end;
+ align-items: center;
+ gap: 6px;
+ margin: -6px 0 14px;
+ }
.info-rows {
display: flex;
flex-direction: column;
diff --git a/frontend/src/components/EntityDetails.test.js b/frontend/src/components/EntityDetails.test.js
index fda5ca1..00a495e 100644
--- a/frontend/src/components/EntityDetails.test.js
+++ b/frontend/src/components/EntityDetails.test.js
@@ -58,6 +58,13 @@ describe('import enrichment details', () => {
});
describe('reading the file behind an entity', () => {
+ it('can place host actions directly below the media preview', () => {
+ expect(source).toContain('let { entityId, onclose, ondeleted, previewActions } = $props();');
+ expect(source).toContain('{@render previewActions()}');
+ expect(source).toContain('.info-preview-actions {');
+ expect(source).toContain('justify-content: flex-end;');
+ });
+
it('reads one media file, not the whole case, to show its metadata', () => {
// the EXIF and video dumps this panel renders are hundreds of rows each and
// are deliberately absent from the browse index, so the list would neither
diff --git a/frontend/src/components/ExportFolderPicker.svelte b/frontend/src/components/ExportFolderPicker.svelte
new file mode 100644
index 0000000..356acd6
--- /dev/null
+++ b/frontend/src/components/ExportFolderPicker.svelte
@@ -0,0 +1,265 @@
+<script>
+ /**
+ * The destination picker every export shares: browse the filesystem, or go
+ * back to the case's own exports folder.
+ *
+ * A browser has no folder dialog that hands back a real path, so the walking
+ * happens server-side (`/api/folders`, engine/exportdir.py) and only folder
+ * names ever come back. Choosing saves the folder for that kind of export, so
+ * the next export goes there without asking.
+ */
+ import {
+ CASE_FOLDER_LABEL,
+ createFolder,
+ folderRoots,
+ listFolder,
+ saveDestination,
+ } from '../lib/exportDest.js';
+ import Icon from './Icon.svelte';
+ import Modal from './Modal.svelte';
+
+ let {
+ kind,
+ current = '',
+ confirmLabel = 'Use this folder',
+ onclose,
+ onchosen,
+ } = $props();
+
+ let roots = $state([]);
+ let view = $state(null); // { path, crumbs, folders, writable, truncated }
+ let error = $state('');
+ let busy = $state(false);
+ let naming = $state(false);
+ let newName = $state('');
+
+ $effect(() => {
+ start();
+ });
+
+ async function start() {
+ try {
+ roots = (await folderRoots()).roots;
+ } catch (e) {
+ error = e.message || 'Could not read your folders';
+ return;
+ }
+ // Open where the exports already go, so "change it slightly" is one click.
+ const opening = current || roots[0]?.path;
+ if (opening) await open(opening);
+ }
+
+ async function open(path) {
+ error = '';
+ naming = false;
+ try {
+ view = await listFolder(path);
+ } catch (e) {
+ error = e.message || 'Could not open that folder';
+ }
+ }
+
+ async function make() {
+ if (!newName.trim()) return;
+ busy = true;
+ error = '';
+ try {
+ const made = await createFolder(view.path, newName);
+ newName = '';
+ naming = false;
+ await open(made.path);
+ } catch (e) {
+ error = e.message || 'Could not create that folder';
+ } finally {
+ busy = false;
+ }
+ }
+
+ async function choose(path) {
+ busy = true;
+ error = '';
+ try {
+ const saved = await saveDestination(kind, path);
+ onchosen?.(saved[kind]);
+ onclose?.();
+ } catch (e) {
+ error = e.message || 'Could not save that folder';
+ } finally {
+ busy = false;
+ }
+ }
+</script>
+
+<Modal title="Export destination" {onclose} width="560px">
+ <div class="picker">
+ <div class="roots">
+ {#each roots as root (root.path)}
+ <button
+ class="btn btn-sm"
+ class:active={view?.path === root.path}
+ onclick={() => open(root.path)}
+ title={root.path}
+ >
+ {root.label}
+ </button>
+ {/each}
+ </div>
+
+ {#if view}
+ <div class="crumbs">
+ {#each view.crumbs as crumb (crumb.path)}
+ <button class="crumb" onclick={() => open(crumb.path)} title={crumb.path}>
+ {crumb.name}
+ </button>
+ {/each}
+ </div>
+
+ <div class="folders">
+ {#each view.folders as folder (folder.path)}
+ <button class="row" onclick={() => open(folder.path)} ondblclick={() => open(folder.path)}>
+ <Icon name="folder" size={14} />
+ <span>{folder.name}</span>
+ </button>
+ {:else}
+ <p class="empty">No folders here.</p>
+ {/each}
+ </div>
+
+ {#if view.truncated}
+ <p class="note">Only the first folders are listed. Open one to go deeper.</p>
+ {/if}
+ {/if}
+
+ {#if error}<p class="problem">{error}</p>{/if}
+
+ {#if naming}
+ <div class="new-folder">
+ <input
+ class="input"
+ bind:value={newName}
+ placeholder="Folder name"
+ aria-label="New folder name"
+ onkeydown={(e) => e.key === 'Enter' && make()}
+ />
+ <button class="btn btn-sm" onclick={make} disabled={busy || !newName.trim()}>Create</button>
+ <button class="btn btn-ghost btn-sm" onclick={() => (naming = false)}>Cancel</button>
+ </div>
+ {/if}
+
+ <footer>
+ <button
+ class="btn btn-sm"
+ onclick={() => (naming = true)}
+ disabled={busy || !view?.writable || naming}
+ >
+ New folder
+ </button>
+ <span class="spacer"></span>
+ <button class="btn btn-sm" onclick={() => choose('')} disabled={busy || !current}>
+ Use {CASE_FOLDER_LABEL}
+ </button>
+ <button
+ class="btn btn-sm btn-primary"
+ onclick={() => choose(view.path)}
+ disabled={busy || !view?.writable}
+ >
+ {confirmLabel}
+ </button>
+ </footer>
+
+ {#if view && !view.writable}
+ <p class="note">Azimut can't write in that folder. Pick another one.</p>
+ {/if}
+ </div>
+</Modal>
+
+<style>
+ .picker {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ }
+ .roots {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ }
+ .roots .active {
+ border-color: var(--accent);
+ color: var(--accent);
+ }
+ .crumbs {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 2px;
+ font-size: 12px;
+ }
+ .crumb {
+ background: none;
+ border: 0;
+ padding: 2px 4px;
+ color: var(--muted);
+ cursor: pointer;
+ border-radius: 4px;
+ }
+ .crumb:hover {
+ color: var(--text);
+ background: var(--surface-2);
+ }
+ .crumb + .crumb::before {
+ content: '/';
+ margin-right: 6px;
+ color: var(--muted);
+ }
+ .folders {
+ height: 240px;
+ overflow-y: auto;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ padding: 4px;
+ }
+ .row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ padding: 6px 8px;
+ background: none;
+ border: 0;
+ border-radius: 4px;
+ color: var(--text);
+ font-size: 13px;
+ text-align: left;
+ cursor: pointer;
+ }
+ .row:hover {
+ background: var(--surface-2);
+ }
+ .empty,
+ .note {
+ color: var(--muted);
+ font-size: 12px;
+ margin: 8px 4px;
+ }
+ .problem {
+ color: var(--danger);
+ font-size: 12px;
+ margin: 0 4px;
+ }
+ .new-folder {
+ display: flex;
+ gap: 6px;
+ }
+ .new-folder .input {
+ flex: 1;
+ }
+ footer {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ }
+ .spacer {
+ flex: 1;
+ }
+</style>
diff --git a/frontend/src/components/ExportFolderPicker.test.js b/frontend/src/components/ExportFolderPicker.test.js
new file mode 100644
index 0000000..6db51cb
--- /dev/null
+++ b/frontend/src/components/ExportFolderPicker.test.js
@@ -0,0 +1,21 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+const source = readFileSync(new URL('./ExportFolderPicker.svelte', import.meta.url), 'utf8');
+
+describe('Export folder picker', () => {
+ it('browses folders, creates one, and can return to the case default', () => {
+ expect(source).toContain('roots = (await folderRoots()).roots');
+ expect(source).toContain('view = await listFolder(path)');
+ expect(source).toContain('const made = await createFolder(view.path, newName)');
+ expect(source).toContain("onclick={() => choose('')}");
+ expect(source).toContain('onclick={() => choose(view.path)}');
+ expect(source).toContain("confirmLabel = 'Use this folder'");
+ expect(source).toContain('{confirmLabel}');
+ });
+
+ it('does not select a folder the backend says is unwritable', () => {
+ expect(source).toContain('disabled={busy || !view?.writable}');
+ expect(source).toContain("Azimut can't write in that folder. Pick another one.");
+ });
+});
diff --git a/frontend/src/components/ProofPreview.svelte b/frontend/src/components/ProofPreview.svelte
index 2b57820..f266b79 100644
--- a/frontend/src/components/ProofPreview.svelte
+++ b/frontend/src/components/ProofPreview.svelte
@@ -142,7 +142,7 @@
}));
g.add(new Konva.Text({
width: box.w, height: box.h, padding: box.h * 0.12, align: 'center', verticalAlign: 'middle',
- text: 'Add a logo in\nSettings → Preferences', fontSize: box.h * 0.16, fill: '#111',
+ text: 'Add a logo in\nSettings → Publishing', fontSize: box.h * 0.16, fill: '#111',
fontFamily: 'system-ui, sans-serif',
}));
}
diff --git a/frontend/src/components/ProofTemplateEditor.svelte b/frontend/src/components/ProofTemplateEditor.svelte
index 4e164c2..421a625 100644
--- a/frontend/src/components/ProofTemplateEditor.svelte
+++ b/frontend/src/components/ProofTemplateEditor.svelte
@@ -233,9 +233,9 @@
</label>
</div>
{#if logoMissing}
- <p class="warn"><Icon name="alert" /> No logo saved yet. Add one in Settings → Preferences.</p>
+ <p class="warn"><Icon name="alert" /> No logo saved yet. Add one in Settings → Publishing.</p>
{:else}
- <p class="hint">The logo comes from Settings → Preferences; drag it in the preview.</p>
+ <p class="hint">The logo comes from Settings → Publishing; drag it in the preview.</p>
{/if}
{/if}
</fieldset>
@@ -262,7 +262,7 @@
oninput={(e) => setSigText('color', e.target.value)} />
</label>
</div>
- <p class="hint">The account handle comes from Settings → Preferences; drag it into place in the preview.</p>
+ <p class="hint">The account handle comes from Settings → Publishing; drag it into place in the preview.</p>
{/if}
</fieldset>
diff --git a/frontend/src/components/UpdateModal.svelte b/frontend/src/components/UpdateModal.svelte
index 772a1e5..9e4e000 100644
--- a/frontend/src/components/UpdateModal.svelte
+++ b/frontend/src/components/UpdateModal.svelte
@@ -40,7 +40,7 @@
</div>
<p class="note">
- You can always update later from Settings → Updates.
+ You can always update later from Settings → System.
</p>
</Modal>
diff --git a/frontend/src/components/WorkspaceFolder.svelte b/frontend/src/components/WorkspaceFolder.svelte
index c581ef5..c16b768 100644
--- a/frontend/src/components/WorkspaceFolder.svelte
+++ b/frontend/src/components/WorkspaceFolder.svelte
@@ -215,7 +215,7 @@
</section>
<style>
- /* This block sits inside Settings' About tab and inside the stopped-workspace
+ /* This block sits inside Settings' Storage section and inside the stopped-workspace
panel. Neither parent's scoped styles reach in here, so the group heading,
the fact list and the notes are restated with the shared tokens — same
shape as every other Settings group. */
diff --git a/frontend/src/lib/coords.js b/frontend/src/lib/coords.js
index e234e71..795830e 100644
--- a/frontend/src/lib/coords.js
+++ b/frontend/src/lib/coords.js
@@ -1,6 +1,6 @@
// Latitude/longitude presentation. The app stores decimal degrees everywhere
// (case.json, proof specs, exports) — this module only decides how a pair is
-// *shown*, per the user's Settings → Preferences choice. Nothing here ever
+// *shown*, per the user's Settings → General choice. Nothing here ever
// changes what lands on disk, so a case reads the same for every reader.
//
// Kept pure and Leaflet-free so it can be unit-tested.
diff --git a/frontend/src/lib/exportDest.js b/frontend/src/lib/exportDest.js
new file mode 100644
index 0000000..93e0bc7
--- /dev/null
+++ b/frontend/src/lib/exportDest.js
@@ -0,0 +1,53 @@
+/**
+ * Export destinations: where the notes PDFs, the media copies and the proof
+ * PNGs land, and the folder browser that lets the analyst say so.
+ *
+ * The destination is remembered per kind, app-wide, in settings — a case folder
+ * is not the right home for it, since the whole point is that the analyst files
+ * finished work in the same place case after case. An empty destination means
+ * the case's own `exports/` folder, which is the default and always exists.
+ *
+ * The browser cannot hand back a real filesystem path, so the picker walks the
+ * backend's folder listing (`/api/folders`) instead of a file input.
+ */
+
+import { api } from './api.js';
+
+/** The exports that remember a folder. Mirrors `KINDS` in engine/exportdir.py. */
+export const KINDS = ['notes', 'media', 'proofs'];
+
+/** What to call the default in the UI, once per kind so the wording can't drift. */
+export const CASE_FOLDER_LABEL = "the case's exports folder";
+
+export const folderRoots = () => api.get('/api/folders/roots');
+export const listFolder = (path) => api.get(`/api/folders?path=${encodeURIComponent(path)}`);
+export const createFolder = (parent, name) => api.post('/api/folders/create', { parent, name });
+
+/** The saved destination per kind, as `{notes, media, proofs}` of paths. */
+export async function readDestinations() {
+ const settings = await api.get('/api/settings');
+ return normalise(settings.export_dirs);
+}
+
+/** Save one kind's destination. An empty path goes back to the case folder. */
+export async function saveDestination(kind, path) {
+ const prefs = await api.put('/api/settings/prefs', { export_dirs: { [kind]: path ?? '' } });
+ return normalise(prefs.export_dirs);
+}
+
+function normalise(dirs) {
+ const out = {};
+ for (const kind of KINDS) out[kind] = (dirs ?? {})[kind] ?? '';
+ return out;
+}
+
+/**
+ * How a destination reads in a button or a toast: the folder's own name, or the
+ * default's label. The full path is for the tooltip, not the sentence.
+ */
+export function destinationLabel(path) {
+ const text = String(path ?? '').trim();
+ if (!text) return CASE_FOLDER_LABEL;
+ const parts = text.split(/[\\/]/).filter(Boolean);
+ return parts[parts.length - 1] || text;
+}
diff --git a/frontend/src/lib/exportDest.test.js b/frontend/src/lib/exportDest.test.js
new file mode 100644
index 0000000..c31ce0e
--- /dev/null
+++ b/frontend/src/lib/exportDest.test.js
@@ -0,0 +1,69 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { api } from './api.js';
+import {
+ CASE_FOLDER_LABEL,
+ createFolder,
+ destinationLabel,
+ folderRoots,
+ listFolder,
+ readDestinations,
+ saveDestination,
+} from './exportDest.js';
+
+vi.mock('./api.js', () => ({
+ api: {
+ get: vi.fn(),
+ post: vi.fn(),
+ put: vi.fn(),
+ },
+}));
+
+beforeEach(() => vi.clearAllMocks());
+
+describe('export destinations', () => {
+ it('reads every kind and fills missing destinations with the case default', async () => {
+ api.get.mockResolvedValue({ export_dirs: { notes: '/reports' } });
+
+ await expect(readDestinations()).resolves.toEqual({
+ notes: '/reports',
+ media: '',
+ proofs: '',
+ });
+ expect(api.get).toHaveBeenCalledWith('/api/settings');
+ });
+
+ it('saves one kind without sending the others back', async () => {
+ api.put.mockResolvedValue({ export_dirs: { notes: '', media: '/evidence', proofs: '' } });
+
+ await expect(saveDestination('media', '/evidence')).resolves.toEqual({
+ notes: '',
+ media: '/evidence',
+ proofs: '',
+ });
+ expect(api.put).toHaveBeenCalledWith('/api/settings/prefs', {
+ export_dirs: { media: '/evidence' },
+ });
+ });
+
+ it('uses the shared folder browser endpoints', async () => {
+ api.get.mockResolvedValue({ roots: [] });
+ api.post.mockResolvedValue({ name: 'Report', path: '/work/Report' });
+
+ await folderRoots();
+ await listFolder('/work/Case one');
+ await createFolder('/work', 'Report');
+
+ expect(api.get).toHaveBeenNthCalledWith(1, '/api/folders/roots');
+ expect(api.get).toHaveBeenNthCalledWith(2, '/api/folders?path=%2Fwork%2FCase%20one');
+ expect(api.post).toHaveBeenCalledWith('/api/folders/create', {
+ parent: '/work',
+ name: 'Report',
+ });
+ });
+
+ it('shows only the final folder name and names the default consistently', () => {
+ expect(destinationLabel('')).toBe(CASE_FOLDER_LABEL);
+ expect(destinationLabel('/work/Report')).toBe('Report');
+ expect(destinationLabel('C:\\Work\\Evidence')).toBe('Evidence');
+ });
+});
diff --git a/frontend/src/lib/measure.js b/frontend/src/lib/measure.js
index 0f7201e..17bf7e1 100644
--- a/frontend/src/lib/measure.js
+++ b/frontend/src/lib/measure.js
@@ -72,7 +72,7 @@ export function angleAt(a, vertex, b) {
}
// Measurements are computed and stored in metres; `units` only picks how they
-// read (Settings → Preferences). International feet/miles/acres.
+// read (Settings → General). International feet/miles/acres.
const FT_PER_M = 3.28084;
const FT_PER_MI = 5280;
const SQFT_PER_ACRE = 43560;
diff --git a/frontend/src/lib/state.svelte.js b/frontend/src/lib/state.svelte.js
index e68c21a..9aa81d7 100644
--- a/frontend/src/lib/state.svelte.js
+++ b/frontend/src/lib/state.svelte.js
@@ -13,7 +13,7 @@ import { shouldShowUpdate } from './appUpdate.js';
import { loadRelationTypes } from './relations.svelte.js';
/**
- * App-wide display preferences (Settings → Preferences), mirrored from
+ * App-wide display preferences (Settings → General), mirrored from
* settings.json. Presentation only — every tool keeps filing decimal degrees
* and metres, so changing these never rewrites what's on disk.
*/
diff --git a/frontend/src/tools/MediaLibrary.svelte b/frontend/src/tools/MediaLibrary.svelte
index 3605eae..0fd44e6 100644
--- a/frontend/src/tools/MediaLibrary.svelte
+++ b/frontend/src/tools/MediaLibrary.svelte
@@ -21,6 +21,8 @@
import Modal from '../components/Modal.svelte';
import ConfirmDialog from '../components/ConfirmDialog.svelte';
import EntityDetails from '../components/EntityDetails.svelte';
+ import ExportFolderPicker from '../components/ExportFolderPicker.svelte';
+ import { destinationLabel, readDestinations } from '../lib/exportDest.js';
const KIND_ICONS = { image: 'image', satellite: 'satellite', video: 'video', audio: 'audio', file: 'file' };
@@ -239,6 +241,11 @@
// --- details modal (shared EntityDetails, keyed by the file's entity id) ---
let infoEntityId = $state(null);
+ let infoItem = $state(null); // the media row behind the details modal, for Export
+ // Where a media copy lands, app-wide and remembered. Empty = the case folder.
+ let exportDir = $state('');
+ let exportPicker = $state(false);
+ let exportBusy = $state(false);
// --- lightbox (←/→ flips through the filtered images) ---
let lightboxItem = $state(null);
@@ -593,8 +600,50 @@
// file's case entity — full provenance, derivation chain, title/notes/folder.
async function openInfo(item) {
const ent = await lookupEntity(caseState.current?.id, 'path', item.path);
- if (ent) infoEntityId = ent.id;
- else toast('This file has no case entity yet', 'warn');
+ if (ent) {
+ infoEntityId = ent.id;
+ infoItem = item;
+ readDestinations()
+ .then((dirs) => (exportDir = dirs.media))
+ .catch(() => {});
+ } else toast('This file has no case entity yet', 'warn');
+ }
+
+ /**
+ * Copy this file out to the media export folder.
+ *
+ * A copy: the case keeps the original with its hash and its provenance, and
+ * the analyst gets the file where they actually work with it.
+ */
+ async function exportMedia() {
+ const item = infoItem;
+ if (!item || exportBusy) return;
+ exportBusy = true;
+ try {
+ const result = await api.post(`/api/cases/${caseState.current.id}/media/export`, {
+ path: item.path,
+ });
+ toast(`${result.file} copied to ${destinationLabel(result.folder)}`, 'ok', 5200, {
+ label: 'Show',
+ onClick: () =>
+ api
+ .post(`/api/cases/${caseState.current.id}/media/export/reveal`)
+ .catch((error) => toast(error.message, 'warn')),
+ });
+ } catch (error) {
+ toast(`Export failed: ${error.message}`, 'danger');
+ } finally {
+ exportBusy = false;
+ }
+ }
+
+ async function openMediaExportPicker() {
+ try {
+ exportDir = (await readDestinations()).media;
+ } catch {
+ // The picker still has its case-folder default if Settings cannot load.
+ }
+ exportPicker = true;
}
</script>
@@ -1119,10 +1168,34 @@
entityId={infoEntityId}
onclose={() => (infoEntityId = null)}
ondeleted={() => (infoEntityId = null)}
- />
+ >
+ {#snippet previewActions()}
+ <button class="btn btn-sm" onclick={exportMedia} disabled={exportBusy}>
+ <Icon name="download" size={14} />
+ {exportBusy ? 'Exporting…' : 'Export'}
+ </button>
+ <button
+ class="btn btn-ghost btn-sm"
+ onclick={openMediaExportPicker}
+ title="Change export folder"
+ aria-label="Change export folder"
+ >
+ <Icon name="folder" size={14} />
+ </button>
+ {/snippet}
+ </EntityDetails>
</Modal>
{/if}
+{#if exportPicker}
+ <ExportFolderPicker
+ kind="media"
+ current={exportDir}
+ onclose={() => (exportPicker = false)}
+ onchosen={(path) => (exportDir = path)}
+ />
+{/if}
+
<!-- lightbox -->
<svelte:window onkeydown={onLightboxKey} />
{#if lightboxItem}
@@ -1504,13 +1577,13 @@
So the actions cell is a fixed width, and it is computed rather than typed:
one ghost icon button is a 14px glyph plus 8px of padding and a 1px border
- on each side, and the widest row holds six of them — GPS pin, info, open,
- inspect, proof, delete. A literal here goes stale the next time a tool earns
+ on each side, and the widest row holds six of them — GPS pin, info,
+ open, inspect, proof, delete. A literal here goes stale the next time a tool earns
a row action, and the symptom is the delete button quietly clipped off the
end of the row. */
--media-action: 32px;
--media-action-gap: 2px;
- /* the six buttons plus slack. Sized to the exact sum, the cell fits only
+ /* the seven buttons plus slack. Sized to the exact sum, the cell fits only
until a sub-pixel of rounding says otherwise, and then Delete — which
`margin-left: auto` holds at the right edge — is the one that goes. The
slack is also where that auto margin lives, so the row still reads as
diff --git a/frontend/src/tools/MediaLibrary.test.js b/frontend/src/tools/MediaLibrary.test.js
index 9fedc14..d6a2eb7 100644
--- a/frontend/src/tools/MediaLibrary.test.js
+++ b/frontend/src/tools/MediaLibrary.test.js
@@ -321,6 +321,19 @@ describe('row and card actions fit', () => {
expect(source).toContain('gap: var(--media-action-gap);');
});
+ it('keeps export only in Details, directly below the preview', () => {
+ expect(source).not.toContain('title="Export file"');
+ expect(source).not.toContain('onclick={() => exportMedia(item)}');
+ expect(source).not.toContain('Export folder');
+ expect(source).toContain('async function exportMedia()');
+ expect(source).toContain('{#snippet previewActions()}');
+ expect(source).toContain("{exportBusy ? 'Exporting…' : 'Export'}");
+ expect(source).toContain('aria-label="Change export folder"');
+ expect(source).toContain('<Icon name="folder" size={14} />');
+ expect(source).not.toContain('>Change folder</button>');
+ expect(source).toContain('exportDir = (await readDestinations()).media;');
+ });
+
it('keeps every card action reachable in the 150px small view', () => {
// the card clips its overflow, so a row that does not fit loses its last
// button — Delete
diff --git a/frontend/src/tools/ProofComposer.svelte b/frontend/src/tools/ProofComposer.svelte
index e9b5044..55c6d46 100644
--- a/frontend/src/tools/ProofComposer.svelte
+++ b/frontend/src/tools/ProofComposer.svelte
@@ -13,6 +13,8 @@
import SearchInput from '../components/SearchInput.svelte';
import FolderBrowser from '../components/FolderBrowser.svelte';
import ConfirmDialog from '../components/ConfirmDialog.svelte';
+ import ExportFolderPicker from '../components/ExportFolderPicker.svelte';
+ import { destinationLabel, readDestinations } from '../lib/exportDest.js';
import ProofToolbar from './proof/ProofToolbar.svelte';
import ProofCanvas from './proof/ProofCanvas.svelte';
import ProofLayersPanel from './proof/ProofLayersPanel.svelte';
@@ -108,7 +110,7 @@
const name = savedName;
if (!id || !name) return;
let live = true;
- lookupEntity(id, 'spec', `proofs/${name}.json`).then((bound) => {
+ lookupEntity(id, 'spec', `proofs/.meta/${name}.json`).then((bound) => {
if (live && !bound && savedName === name) {
savedName = null;
dirty = true;
@@ -2111,6 +2113,10 @@
function onKeydown(e) {
if (uiState.tool !== 'proof') return;
+ if (e.key === 'Escape' && exportMenuOpen) {
+ exportMenuOpen = false;
+ return;
+ }
if (['INPUT', 'TEXTAREA', 'SELECT'].includes(e.target.tagName)) return;
if (pathDraft && (e.key === 'Enter' || e.key === 'Escape')) {
finishPath(e.key === 'Enter');
@@ -2216,8 +2222,86 @@
}
}
+ // Copy the saved PNG out to the proofs export folder — the same picture, in
+ // the place finished work is filed. Unsaved pixels are saved first, so what
+ // lands there is never a proof ago.
+ let exporting = $state(false);
+ let exportDir = $state('');
+ let exportPicker = $state(false);
+ let exportAfterPick = $state(false);
+ let exportMenuOpen = $state(false);
+ async function exportProof() {
+ if (!proofHasContent || exporting || saving) return;
+ exporting = true;
+ try {
+ if (dirty || !savedName) await save();
+ // A failed save leaves the proof dirty; a title collision opens the
+ // overwrite prompt without binding a name. In either case there is no
+ // confirmed PNG to copy yet.
+ if (dirty || !savedName) return;
+ const cid = caseState.current.id;
+ const result = await api.post(`/api/cases/${cid}/proofs/${savedName}/export`);
+ exportDir = result.folder;
+ toast(`${result.file} written to ${destinationLabel(result.folder)}`, 'ok', 5200, {
+ label: 'Show',
+ onClick: () =>
+ api
+ .post(`/api/cases/${cid}/proofs/export/reveal`)
+ .catch((error) => toast(error.message, 'warn')),
+ });
+ } catch (e) {
+ toast(`Export failed: ${e.message}`, 'danger', 6000);
+ } finally {
+ exporting = false;
+ }
+ }
+
+ async function toggleExportMenu() {
+ exportMenuOpen = !exportMenuOpen;
+ if (!exportMenuOpen) return;
+ try {
+ exportDir = (await readDestinations()).proofs;
+ } catch {
+ // The remembered label can stay on its default when Settings is unavailable.
+ }
+ }
+
+ async function openExportPicker() {
+ exportMenuOpen = false;
+ exportAfterPick = true;
+ try {
+ exportDir = (await readDestinations()).proofs;
+ } catch {
+ // The picker still has its case-folder default if Settings cannot load.
+ }
+ exportPicker = true;
+ }
+
+ async function useExportFolder(path) {
+ exportDir = path;
+ if (!exportAfterPick) return;
+ exportAfterPick = false;
+ await exportProof();
+ }
+
+ async function exportProofPng() {
+ exportMenuOpen = false;
+ await exportProof();
+ }
+
+ async function revealProofExports() {
+ exportMenuOpen = false;
+ const cid = caseState.current?.id;
+ if (!cid) return;
+ try {
+ await api.post(`/api/cases/${cid}/proofs/export/reveal`);
+ } catch (error) {
+ toast(error.message, 'warn');
+ }
+ }
+
// Every proof already saved in this case, read off the filed entities: the
- // slugs (filename without `proofs/…​.json`) to catch a filename collision, and
+ // slugs (filename without `proofs/.meta/…​.json`) to catch a filename collision, and
// the names so a fresh proof can take one that reads apart from them.
const savedProofNames = () => savedSlugs(proofEntities, 'proof');
const savedProofTitles = () => savedTitles(proofEntities, 'proof');
@@ -2471,14 +2555,45 @@
</button>
{/if}
<button class="btn btn-sm" onclick={openNewProofDialog}><Icon name="plus" size={14} /> New proof</button>
- <button
- class="btn btn-sm"
- onclick={copyPng}
- disabled={!proofHasContent || copying}
- title="Copy the composed PNG to the clipboard"
- >
- <Icon name="copy" size={14} /> {copying ? 'Copying…' : 'Copy PNG'}
- </button>
+ <div class="export-split">
+ <button
+ class="btn btn-sm export-main"
+ onclick={copyPng}
+ disabled={!proofHasContent || copying}
+ title="Copy the proof PNG"
+ >
+ <Icon name="copy" size={14} /> {copying ? 'Copying…' : 'Copy'}
+ </button>
+ <button
+ class="btn btn-sm export-toggle"
+ onclick={toggleExportMenu}
+ aria-label="More export options"
+ aria-haspopup="menu"
+ aria-expanded={exportMenuOpen}
+ >
+ <Icon name="chevronDown" size={13} />
+ </button>
+ {#if exportMenuOpen}
+ <button class="export-backdrop" onclick={() => (exportMenuOpen = false)} aria-label="Close export menu"></button>
+ <div class="export-menu card" role="menu">
+ <button class="export-option" role="menuitem" onclick={exportProofPng} disabled={!proofHasContent || exporting || saving}>
+ <Icon name="download" size={14} />
+ <span>{exporting ? 'Exporting…' : 'Export PNG'}</span>
+ </button>
+ <button class="export-option" role="menuitem" onclick={openExportPicker} disabled={!proofHasContent || exporting || saving}>
+ <Icon name="folder" size={14} />
+ <span>Export to another folder…</span>
+ </button>
+ <button class="export-option" role="menuitem" onclick={revealProofExports} disabled={!caseState.current}>
+ <Icon name="folderOpen" size={14} />
+ <span>Show export folder</span>
+ </button>
+ <div class="export-destination" title={exportDir || "The case's exports folder"}>
+ Destination: {destinationLabel(exportDir)}
+ </div>
+ </div>
+ {/if}
+ </div>
<button class="btn btn-ok btn-sm" onclick={() => save()} disabled={!proofHasContent || saving}>
<Icon name="save" size={14} /> {saving ? 'Saving…' : 'Save proof'}
</button>
@@ -2752,7 +2867,7 @@
<span>Signature</span>
</label>
{#if !sigImg}
- <div class="adv-hint">Add a logo in Settings → Preferences to sign your proofs.</div>
+ <div class="adv-hint">Add a logo in Settings → Publishing to sign your proofs.</div>
{:else if proof.signature}
<div class="sig-anchors">
{#each SIG_ANCHORS as a (a.id)}
@@ -2812,7 +2927,7 @@
<span>Add account handle</span>
</label>
{#if !prefs.signatureHandle?.trim()}
- <div class="adv-hint">Add your account handle in Settings → Preferences to use it on proofs.</div>
+ <div class="adv-hint">Add your account handle in Settings → Publishing to use it on proofs.</div>
{:else if proof.signatureText}
<div class="adv-hint">Drag the account handle on the canvas to place it.</div>
{/if}
@@ -2855,6 +2970,19 @@
/>
{/if}
+{#if exportPicker}
+ <ExportFolderPicker
+ kind="proofs"
+ current={exportDir}
+ confirmLabel="Export here"
+ onclose={() => {
+ exportPicker = false;
+ exportAfterPick = false;
+ }}
+ onchosen={useExportFolder}
+ />
+{/if}
+
{#if discardConfirm}
<ConfirmDialog
title="Discard this proof?"
@@ -3035,6 +3163,62 @@
font-weight: 700;
}
.spacer { flex: 1; }
+ .export-split {
+ position: relative;
+ display: flex;
+ align-items: stretch;
+ }
+ .export-main {
+ border-radius: var(--r-sm) 0 0 var(--r-sm);
+ }
+ .export-toggle {
+ min-width: 27px;
+ margin-left: -1px;
+ padding-inline: 5px;
+ border-radius: 0 var(--r-sm) var(--r-sm) 0;
+ }
+ .export-backdrop {
+ position: fixed;
+ inset: 0;
+ z-index: 90;
+ cursor: default;
+ }
+ .export-menu {
+ position: absolute;
+ top: calc(100% + 6px);
+ right: 0;
+ z-index: 100;
+ min-width: 230px;
+ padding: 5px;
+ box-shadow: var(--shadow-2);
+ }
+ .export-option {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ padding: 7px 9px;
+ border-radius: var(--r-sm);
+ color: var(--text-1);
+ font-size: var(--fs-sm);
+ text-align: left;
+ }
+ .export-option:hover:not(:disabled) {
+ background: var(--bg-2);
+ }
+ .export-option:disabled {
+ color: var(--text-3);
+ }
+ .export-destination {
+ margin-top: 4px;
+ padding: 6px 9px 3px;
+ border-top: 1px solid var(--border);
+ overflow: hidden;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
.tpl-none {
margin: 0 0 6px;
font-size: var(--fs-xs);
diff --git a/frontend/src/tools/ProofComposer.test.js b/frontend/src/tools/ProofComposer.test.js
index bdcc1db..7892ab8 100644
--- a/frontend/src/tools/ProofComposer.test.js
+++ b/frontend/src/tools/ProofComposer.test.js
@@ -42,12 +42,49 @@ describe('Proof Composer header', () => {
expect(source).toContain('align-items: baseline;');
expect(source).toContain('font-weight: 700;');
});
+
+ it('exports the current proof and exposes its remembered destination', () => {
+ const header = source.slice(source.indexOf('<div class="tool-header">'), source.indexOf('</div>\n\n <div class="body">'));
+
+ expect(header).toContain("exporting ? 'Exporting…' : 'Export PNG'");
+ expect(header).toContain('onclick={exportProofPng}');
+ expect(header).toContain('onclick={toggleExportMenu}');
+ expect(source).toContain('exportDir = (await readDestinations()).proofs;');
+ expect(source).toContain('kind="proofs"');
+ expect(source).toContain('confirmLabel="Export here"');
+ expect(source).toContain('onchosen={useExportFolder}');
+ expect(source).toContain('api.post(`/api/cases/${cid}/proofs/${savedName}/export`)');
+ expect(source).toContain('/proofs/export/reveal`');
+ expect(source).toContain('if (dirty || !savedName) await save();');
+ expect(source).toContain('if (dirty || !savedName) return;');
+ });
+
+ it('uses Copy as the main action and keeps export choices in the compact menu', () => {
+ const split = source.slice(source.indexOf('<div class="export-split">'), source.indexOf('</div>\n <button class="btn btn-ok'));
+ const menu = source.slice(source.indexOf('<div class="export-menu card"'), source.indexOf('<div class="export-destination"'));
+
+ expect(split).toContain('onclick={copyPng}');
+ expect(split).toContain("copying ? 'Copying…' : 'Copy'");
+ expect(menu.indexOf("onclick={exportProofPng}")).toBeLessThan(menu.indexOf('onclick={openExportPicker}'));
+ expect(menu.indexOf('onclick={openExportPicker}')).toBeLessThan(menu.indexOf('onclick={revealProofExports}'));
+ expect(menu).toContain('<span>{exporting ? \'Exporting…\' : \'Export PNG\'}</span>');
+ expect(menu).toContain('<span>Export to another folder…</span>');
+ expect(menu).toContain('<span>Show export folder</span>');
+ expect(source).toContain('await exportProof();');
+ expect(source).toContain('.export-main {');
+ expect(source).toContain('.export-toggle {');
+ });
});
describe('Proof Composer naming', () => {
it('adopts the canonical filename stem returned by the backend', () => {
expect(source).toContain('proof.title = result.title;');
});
+
+ it('checks the current hidden spec path before claiming a saved proof was deleted', () => {
+ expect(source).toContain("lookupEntity(id, 'spec', `proofs/.meta/${name}.json`)");
+ expect(source).not.toContain("lookupEntity(id, 'spec', `proofs/${name}.json`)");
+ });
});
describe('Proof Composer pickers', () => {
diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelte
index ac0effa..a5a387a 100644
--- a/frontend/src/tools/Satellite.svelte
+++ b/frontend/src/tools/Satellite.svelte
@@ -2727,7 +2727,7 @@
}
// the HUD readout and everything copied out of it follow the user's
- // coordinate format (Settings → Preferences); captures keep decimal degrees
+ // coordinate format (Settings → General); captures keep decimal degrees
const readout = $derived(fmtCoords(displayCoords.lat, displayCoords.lon));
async function copyCoords() {
@@ -3461,7 +3461,10 @@
<div class="links-note mono">{readout}</div>
<!-- the way back: the capture extension files what you find over
there straight into the case, coordinates parsed from the URL -->
- <button type="button" class="links-advert" onclick={() => (uiState.tool = 'settings')}>
+ <button type="button" class="links-advert" onclick={() => {
+ uiState.settingsTab = 'extension';
+ uiState.tool = 'settings';
+ }}>
<Icon name="crop" size={12} />
<span>
{extensionVersion()
@@ -3674,6 +3677,7 @@
class="btn btn-primary"
onclick={() => {
extGateOpen = false;
+ uiState.settingsTab = 'extension';
uiState.tool = 'settings';
}}
>
diff --git a/frontend/src/tools/Satellite.test.js b/frontend/src/tools/Satellite.test.js
index 5d395f5..3c851e9 100644
--- a/frontend/src/tools/Satellite.test.js
+++ b/frontend/src/tools/Satellite.test.js
@@ -129,6 +129,12 @@ describe('Satellite saved work', () => {
});
});
+describe('Capture extension settings handoff', () => {
+ it('opens the extension section from both Satellite entry points', () => {
+ expect(source.match(/uiState\.settingsTab = 'extension'/g)).toHaveLength(2);
+ });
+});
+
describe('filing saved work from its details dialog', () => {
it('offers the same folder picker the rest of the app uses, in both dialogs', () => {
expect(source).toContain("import FolderSelect from '../components/FolderSelect.svelte'");
diff --git a/frontend/src/tools/Settings.svelte b/frontend/src/tools/Settings.svelte
index e56306c..22231f9 100644
--- a/frontend/src/tools/Settings.svelte
+++ b/frontend/src/tools/Settings.svelte
@@ -21,27 +21,31 @@
FREE_TIER,
} from '../lib/usage.js';
import { probeKey, googleMapsLoadedKey } from '../lib/gmaps.js';
- import { revealWorkspaceFolder } from '../lib/reveal.js';
import { extensionVersion, extensionOutdated } from '../lib/extBridge.js';
+ import { CASE_FOLDER_LABEL, saveDestination } from '../lib/exportDest.js';
import Icon from '../components/Icon.svelte';
+ import ExportFolderPicker from '../components/ExportFolderPicker.svelte';
import ProofTemplateEditor from '../components/ProofTemplateEditor.svelte';
import PostTemplateEditor from '../components/PostTemplateEditor.svelte';
import ConfirmDialog from '../components/ConfirmDialog.svelte';
import WorkspaceFolder from '../components/WorkspaceFolder.svelte';
- // Imagery keys and their usage meters share one card per provider.
+ // Keep workflow choices above app maintenance in the settings rail.
const TABS = [
- { id: 'preferences', label: 'Preferences', icon: 'sliders' },
+ { id: 'general', label: 'General', icon: 'sliders' },
+ { id: 'publishing', label: 'Publishing', icon: 'edit' },
{ id: 'imagery', label: 'Imagery', icon: 'key' },
{ id: 'templates', label: 'Templates', icon: 'layers' },
{ id: 'extension', label: 'Capture extension', icon: 'crop' },
- { id: 'about', label: 'About', icon: 'compass' },
+ { id: 'storage', label: 'Storage', icon: 'folder' },
+ { id: 'system', label: 'System', icon: 'compass' },
];
- let tab = $state('preferences');
+ let tab = $state('general');
const REPO_URL = 'https://github.com/OsintMeThat/azimut';
const SITE_URL = 'https://osintmethat.com';
+ // Imagery keys and their usage meters share one card per provider.
// The keyed imagery providers the app knows how to light up (IMAGERY_PROVIDERS.md).
// Keys are app-wide and stored in settings.json, outside cases and exports.
//
@@ -216,6 +220,24 @@
// back. A file written before those sections existed is a bare settings blob,
// so it gets wrapped into the current shape.
let settingsFile = $state(null);
+ let exportDirs = $state({ notes: '', media: '', proofs: '' });
+ let exportPickerKind = $state(null);
+
+ const EXPORT_KINDS = [
+ { id: 'notes', label: 'Note PDFs' },
+ { id: 'media', label: 'Media copies' },
+ { id: 'proofs', label: 'Proof PNGs' },
+ ];
+
+ async function resetExportDestination(kind) {
+ try {
+ const saved = await saveDestination(kind, '');
+ exportDirs = saved;
+ toast(`${EXPORT_KINDS.find((entry) => entry.id === kind)?.label} use ${CASE_FOLDER_LABEL}`, 'ok');
+ } catch (e) {
+ toast(`Could not reset the export folder: ${e.message}`, 'danger');
+ }
+ }
async function importSettings(event) {
const file = event.currentTarget.files?.[0];
@@ -299,7 +321,7 @@
try {
report = await api.get(`/api/settings/diagnostics?${params}`);
} catch {
- report = null; // the About tab falls back to a plain link to the tracker
+ report = null; // System falls back to a plain link to the tracker
}
}
@@ -376,6 +398,11 @@
workspace_root: s.workspace_root ?? '',
extension_version: s.extension_version ?? '',
};
+ exportDirs = {
+ notes: s.export_dirs?.notes ?? '',
+ media: s.export_dirs?.media ?? '',
+ proofs: s.export_dirs?.proofs ?? '',
+ };
ingestToken = s.ingest_token ?? '';
home = { lat: String(s.home_view.lat), lon: String(s.home_view.lon), zoom: String(s.home_view.zoom) };
mention = s.post_mention ?? '';
@@ -383,11 +410,11 @@
updateOnStart = s.update_check_on_start ?? true;
applyPrefs(s); // the rest of the app reads these live
await loadScrapers().catch(() => {}); // local disk read; never blocks Settings
- // shells out to `ffmpeg -version`; non-blocking, About tab only reads it
+ // shells out to `ffmpeg -version`; non-blocking, System only reads it
api.get('/api/settings/ffmpeg').then((r) => (ffmpeg = r)).catch(() => {});
}
- // Preferences save on change; the server returns canonical values.
+ // General settings save on change; the server returns canonical values.
async function savePrefs(patch) {
try {
const saved = await api.put('/api/settings/prefs', patch);
@@ -492,17 +519,6 @@
}
}
- // The path is printed right there, but copying it into a file manager by hand
- // is exactly what the first analyst to ask ended up doing.
- async function revealWorkspace() {
- try {
- await revealWorkspaceFolder();
- toast('Opened the workspace folder', 'ok', 2500);
- } catch (e) {
- toast(e.message || 'Could not open the folder', 'danger', 7000);
- }
- }
-
// a live sample so the format choice is legible before it's applied elsewhere
const coordSample = $derived(
formatCoords(Number(home.lat) || 48.8584, Number(home.lon) || 2.2945, prefs.coordFormat)
@@ -513,15 +529,16 @@
loadTemplates();
});
- // Build the report the first time About is opened: it reads the log buffer and
+ // Build the report the first time System is opened: it reads the log buffer and
// shells nothing out, but there's no reason to do it for the other tabs.
$effect(() => {
- if (tab === 'about' && !report) loadReport();
+ if (tab === 'system' && !report) loadReport();
});
$effect(() => {
if (uiState.tool !== 'settings') return;
- const target = uiState.settingsTab;
+ const aliases = { preferences: 'general', about: 'system' };
+ const target = aliases[uiState.settingsTab] ?? uiState.settingsTab;
if (!target) return;
if (TABS.some((t) => t.id === target)) tab = target;
uiState.settingsTab = null;
@@ -647,6 +664,7 @@
<button
class="rail-tab"
class:active={tab === t.id}
+ class:rail-break={t.id === 'storage'}
onclick={() => (tab = t.id)}
aria-current={tab === t.id ? 'page' : undefined}
>
@@ -657,7 +675,7 @@
</nav>
<div class="pane">
- {#if tab === 'preferences'}
+ {#if tab === 'general'}
<section class="group">
<h3>Coordinates</h3>
<div class="row">
@@ -723,7 +741,9 @@
</label>
</div>
</section>
+ {/if}
+ {#if tab === 'publishing'}
<section class="group">
<h3>Geo Report</h3>
<div class="row">
@@ -1129,19 +1149,62 @@
</section>
{/if}
- {#if tab === 'about'}
+ {#if tab === 'storage'}
+ <WorkspaceFolder onchange={(status) => (about.workspace_root = status.root)} />
+
+ <section class="group">
+ <h3>Export folders</h3>
+ <p class="note">Choose a folder for each export type.</p>
+ {#each EXPORT_KINDS as kind (kind.id)}
+ <div class="row">
+ <div class="row-label">
+ <span>{kind.label}</span>
+ <span class="row-hint mono export-path" title={exportDirs[kind.id] || CASE_FOLDER_LABEL}>
+ {exportDirs[kind.id] || CASE_FOLDER_LABEL}
+ </span>
+ </div>
+ <div class="scraper-actions">
+ <button class="btn btn-sm" onclick={() => (exportPickerKind = kind.id)}>Change…</button>
+ <button
+ class="btn btn-ghost btn-sm"
+ onclick={() => resetExportDestination(kind.id)}
+ disabled={!exportDirs[kind.id]}
+ >Reset</button>
+ </div>
+ </div>
+ {/each}
+ </section>
+
+ <section class="group">
+ <h3>Settings backup</h3>
+ <p class="note">
+ Carries settings, keys, templates and your signature; export folders and
+ download logins stay here, so keep this backup private.
+ </p>
+ <div class="links">
+ <a class="btn btn-sm" href="/api/settings/export" download>
+ <Icon name="save" size={13} /> Export backup
+ </a>
+ <button class="btn btn-sm" onclick={() => settingsFile?.click()}>
+ <Icon name="file" size={13} /> Import backup
+ </button>
+ <input
+ type="file"
+ accept="application/json,.json"
+ bind:this={settingsFile}
+ onchange={importSettings}
+ hidden
+ />
+ </div>
+ </section>
+ {/if}
+
+ {#if tab === 'system'}
<section class="group">
<h3>Azimut</h3>
<dl class="facts">
<dt>Version</dt>
<dd class="mono">{about.version || '—'}</dd>
- <dt>Workspace</dt>
- <dd class="mono workspace-fact">
- <span>{about.workspace_root || '—'}</span>
- <button class="btn btn-ghost btn-sm" onclick={revealWorkspace} title="Open this folder">
- <Icon name="folderOpen" size={13} /> Open
- </button>
- </dd>
<dt>ffmpeg</dt>
<dd class="mono" title={ffmpeg.path || ''}>
{#if ffmpeg.available}
@@ -1168,8 +1231,6 @@
</div>
</section>
- <WorkspaceFolder onchange={(status) => (about.workspace_root = status.root)} />
-
<section class="group">
<h3>Updates</h3>
<div class="row">
@@ -1277,29 +1338,6 @@
</p>
</section>
- <section class="group">
- <h3>Backup</h3>
- <p class="note">
- One file with your settings, keys, templates and signature, for another
- machine; keep it private. Your download login session stays on this machine.
- </p>
- <div class="links">
- <a class="btn btn-sm" href="/api/settings/export" download>
- <Icon name="save" size={13} /> Export backup
- </a>
- <button class="btn btn-sm" onclick={() => settingsFile?.click()}>
- <Icon name="file" size={13} /> Import backup
- </button>
- <input
- type="file"
- accept="application/json,.json"
- bind:this={settingsFile}
- onchange={importSettings}
- hidden
- />
- </div>
- </section>
-
<section class="group">
<h3>Downloaders</h3>
<p class="note">
@@ -1415,6 +1453,15 @@
</div>
</div>
+{#if exportPickerKind}
+ <ExportFolderPicker
+ kind={exportPickerKind}
+ current={exportDirs[exportPickerKind]}
+ onchosen={(path) => (exportDirs = { ...exportDirs, [exportPickerKind]: path })}
+ onclose={() => (exportPickerKind = null)}
+ />
+{/if}
+
{#if editing}
<div class="tpl-modal-overlay" role="presentation"
onclick={(e) => e.target === e.currentTarget && cancelEdit()}>
@@ -1475,7 +1522,7 @@
font-size: var(--fs-sm);
}
- /* Preferences use a section rail and one scrolling pane. */
+ /* Settings use a section rail and one scrolling pane. */
.split {
flex: 1;
display: flex;
@@ -1514,6 +1561,13 @@
color: var(--accent);
font-weight: 600;
}
+ .rail-tab.rail-break {
+ margin-top: 8px;
+ padding-top: 10px;
+ border-top: 1px solid var(--border);
+ border-top-left-radius: 0;
+ border-top-right-radius: 0;
+ }
.pane {
flex: 1;
@@ -1559,6 +1613,13 @@
font-size: var(--fs-xs);
line-height: 1.4;
}
+ .export-path {
+ display: block;
+ max-width: min(380px, 48vw);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
/* Recipe for a provider whose "key" is a configuration you build yourself */
.key-steps {
margin: 4px 0 8px;
diff --git a/frontend/src/tools/Settings.test.js b/frontend/src/tools/Settings.test.js
index 353bdba..4937c54 100644
--- a/frontend/src/tools/Settings.test.js
+++ b/frontend/src/tools/Settings.test.js
@@ -16,7 +16,7 @@ describe('Report an issue', () => {
expect(source).toContain("api.get(`/api/settings/diagnostics?${params}`)");
expect(source).toContain('clearTimeout(reportTimer)');
expect(source).toContain('setTimeout(loadReport, 400)');
- expect(source).toContain("if (tab === 'about' && !report) loadReport()");
+ expect(source).toContain("if (tab === 'system' && !report) loadReport()");
});
it('files through a real anchor, so no popup blocker sees a deferred open', () => {
@@ -47,22 +47,45 @@ describe('Backup', () => {
});
it('says what the file holds, and what it leaves behind', () => {
- expect(source).toContain('settings, keys, templates and signature');
- expect(source).toContain('login session stays on this machine');
+ expect(source).toContain('settings, keys, templates and your signature');
+ expect(source).toContain('export folders and');
+ expect(source).toContain('download logins stay here');
+ expect(source).toContain('keep this backup private');
expect(source).toContain('Export backup');
expect(source).toContain('Import backup');
});
+
+ it('keeps the download and import controls wired after moving to Storage', () => {
+ expect(source).toContain("{#if tab === 'storage'}");
+ expect(source).toContain('href="/api/settings/export" download');
+ expect(source).toContain('onchange={importSettings}');
+ });
});
describe('Workspace folder', () => {
- it('puts an Open button beside the path About already prints', () => {
- expect(source).toContain("import { revealWorkspaceFolder } from '../lib/reveal.js'");
- expect(source).toContain('<dt>Workspace</dt>');
- expect(source).toContain('onclick={revealWorkspace}');
+ it('keeps workspace management in Storage', () => {
+ expect(source).toContain("{#if tab === 'storage'}");
+ expect(source).toContain('<WorkspaceFolder onchange={(status) => (about.workspace_root = status.root)} />');
+ });
+});
+
+describe('Settings sections', () => {
+ it('separates workflow preferences from app maintenance', () => {
+ for (const id of ['general', 'publishing', 'imagery', 'templates', 'extension', 'storage', 'system']) {
+ expect(source).toContain(`id: '${id}'`);
+ }
+ expect(source).toContain("let tab = $state('general')");
+ });
+
+ it('keeps old direct links useful while callers migrate', () => {
+ expect(source).toContain("const aliases = { preferences: 'general', about: 'system' }");
});
- it('reports the outcome, since the window opens outside the browser', () => {
- expect(source).toContain("toast('Opened the workspace folder'");
- expect(source).toContain("toast(e.message || 'Could not open the folder'");
+ it('manages all three export folders from Storage', () => {
+ expect(source).toContain("{ id: 'notes', label: 'Note PDFs' }");
+ expect(source).toContain("{ id: 'media', label: 'Media copies' }");
+ expect(source).toContain("{ id: 'proofs', label: 'Proof PNGs' }");
+ expect(source).toContain('<ExportFolderPicker');
+ expect(source).toContain("await saveDestination(kind, '')");
});
});
diff --git a/src/azimut/api/folders.py b/src/azimut/api/folders.py
new file mode 100644
index 0000000..dab9b53
--- /dev/null
+++ b/src/azimut/api/folders.py
@@ -0,0 +1,52 @@
+"""REST API for the folder picker behind every export destination.
+
+A browser cannot hand back a real path and the repo rules forbid a GUI toolkit,
+so the picker is served from here: the analyst starts at one of `roots()` and
+walks down. Only directory names travel — see `engine/exportdir.py` for why the
+listing stops there.
+
+Nothing in this router writes an export. It answers "which folders are there",
+and `POST /create` makes one; the exports themselves are written by the routes
+that own the artifact (notes, media, proofs).
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from fastapi import APIRouter, HTTPException
+from pydantic import BaseModel, Field
+
+from ..engine import exportdir
+
+router = APIRouter(prefix="/api/folders", tags=["folders"])
+
+
+class NewFolderIn(BaseModel):
+ parent: str
+ name: str = Field(min_length=1, max_length=exportdir.MAX_NEW_NAME)
+
+
+def folder_roots() -> dict[str, Any]:
+ """Where the picker offers to start: the analyst's own folders, then the
+ workspace, then the drives on Windows."""
+ return {"roots": exportdir.roots()}
+
+
+def folder_listing(path: str) -> dict[str, Any]:
+ """The subfolders of one folder, plus the crumbs back out to the root."""
+ try:
+ return exportdir.listing(path)
+ except exportdir.ExportDirError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+
+
+def create_folder(body: NewFolderIn) -> dict[str, str]:
+ """Make one subfolder, so an export can go somewhere that isn't there yet."""
+ try:
+ return exportdir.create_folder(body.parent, body.name)
+ except exportdir.ExportDirError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
diff --git a/src/azimut/api/media.py b/src/azimut/api/media.py
index 951e0db..fe7065d 100644
--- a/src/azimut/api/media.py
+++ b/src/azimut/api/media.py
@@ -1,4 +1,5 @@
-"""REST API for the Media Library: upload, URL download (async job), list, delete."""
+"""REST API for the Media Library: upload, URL download (async job), list, delete,
+and copying one file back out to a folder of the analyst's own."""
from __future__ import annotations
@@ -9,7 +10,9 @@ from pydantic import BaseModel, Field, HttpUrl
from .. import config, jobs
from ..engine import enrich as enrich_engine
+from ..engine import exportdir
from ..engine import media as media_engine
+from ..engine import reveal as reveal_engine
from ..engine import thumbnails as thumbnail_engine
from ..workspace import Case, CaseError
from .cases import delete_by_path, get_case
@@ -30,6 +33,13 @@ class DeleteIn(BaseModel):
path: str
+class ExportIn(BaseModel):
+ """One media file to copy out. Where it goes is the folder saved for media
+ (engine/exportdir.py), never something the request names."""
+
+ path: str
+
+
class UpdateIn(BaseModel):
path: str
notes: str | None = None
@@ -274,6 +284,41 @@ def job_status(job_id: str) -> dict[str, Any]:
return job
[email protected]("/cases/{case_id}/media/export")
+def export_media_item(case_id: str, body: ExportIn) -> dict[str, str]:
+ """Copy one media file out of the case, into the media export folder.
+
+ A copy, never a move: the case keeps the original, hashes and all. The name
+ it lands under is the one on disk, and an existing file is never overwritten.
+ """
+ case = get_case(case_id)
+ try:
+ item = media_engine.read_item(case, body.path)
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ if item is None:
+ raise HTTPException(status_code=404, detail="media not found")
+ source = case.resolve_inside(item["path"])
+ try:
+ folder = exportdir.destination("media", case.path)
+ written = exportdir.copy_out(source, folder, source.name)
+ except exportdir.ExportDirError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ return {"file": written.name, "folder": str(folder), "path": str(written)}
+
+
[email protected]("/cases/{case_id}/media/export/reveal")
+def reveal_media_exports(case_id: str) -> dict[str, str]:
+ """Open the media export folder, resolved here rather than sent by the browser."""
+ case = get_case(case_id)
+ try:
+ folder = exportdir.destination("media", case.path)
+ reveal_engine.reveal(folder, workspace_only=False)
+ except (exportdir.ExportDirError, reveal_engine.RevealError) as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ return {"path": str(folder)}
+
+
@router.delete("/cases/{case_id}/media")
def delete_media(case_id: str, path: str) -> dict[str, Any]:
case = get_case(case_id)
diff --git a/src/azimut/api/proofs.py b/src/azimut/api/proofs.py
index 0fce0d0..43b261d 100644
--- a/src/azimut/api/proofs.py
+++ b/src/azimut/api/proofs.py
@@ -26,8 +26,10 @@ from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field
from ..engine import artifacts as artifact_engine
+from ..engine import exportdir
from ..engine import links as link_engine
from ..engine import media as media_engine
+from ..engine import reveal as reveal_engine
from ..engine import satellite as satellite_engine
from ..engine import thumbnails as thumbnail_engine
from ..workspace import Case, CaseError, ensure_dir
@@ -242,6 +244,40 @@ def load_proof(case_id: str, name: str) -> dict[str, Any]:
return json.loads(spec_path.read_text(encoding="utf-8"))
[email protected]("/cases/{case_id}/proofs/{name}/export")
+def export_proof_png(case_id: str, name: str) -> dict[str, str]:
+ """Copy a saved proof's PNG into the proofs export folder.
+
+ The proof itself does not move: this is the publishable picture, handed to
+ wherever the analyst files finished work.
+ """
+ case = get_case(case_id)
+ try:
+ png = case.resolve_inside(layout.proof_export_rel(name))
+ except CaseError as exc:
+ raise HTTPException(status_code=403, detail=str(exc)) from exc
+ if not png.exists():
+ raise HTTPException(status_code=404, detail="this proof has no export yet")
+ try:
+ folder = exportdir.destination("proofs", case.path)
+ written = exportdir.copy_out(png, folder, png.name)
+ except exportdir.ExportDirError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ return {"file": written.name, "folder": str(folder), "path": str(written)}
+
+
[email protected]("/cases/{case_id}/proofs/export/reveal")
+def reveal_proof_exports(case_id: str) -> dict[str, str]:
+ """Open the proofs export folder, resolved here rather than sent by the browser."""
+ case = get_case(case_id)
+ try:
+ folder = exportdir.destination("proofs", case.path)
+ reveal_engine.reveal(folder, workspace_only=False)
+ except (exportdir.ExportDirError, reveal_engine.RevealError) as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ return {"path": str(folder)}
+
+
@router.post("/cases/{case_id}/proofs")
def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:
case = get_case(case_id)
diff --git a/src/azimut/api/settings.py b/src/azimut/api/settings.py
index 7240a10..4ad1753 100644
--- a/src/azimut/api/settings.py
+++ b/src/azimut/api/settings.py
@@ -20,6 +20,7 @@ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_valida
from .. import __version__, config
from ..engine import (
diagnostics,
+ exportdir,
ffmpeg,
google_tiles,
reveal,
@@ -104,6 +105,8 @@ class PrefsIn(BaseModel):
update_dismissed_version: str | None = None
# login source for gated media downloads (engine/media.py); None leaves it
download_cookies: DownloadCookiesIn | None = None
+ # where each kind of export lands (engine/exportdir.py); "" = the case folder
+ export_dirs: dict[str, str] | None = None
def _prefs(settings: dict[str, Any]) -> dict[str, Any]:
@@ -125,6 +128,7 @@ def _prefs(settings: dict[str, Any]) -> dict[str, Any]:
"update_check_on_start": bool(settings.get("update_check_on_start", True)),
"update_dismissed_version": settings.get("update_dismissed_version", ""),
"download_cookies": settings.get("download_cookies", {"source": "none"}),
+ "export_dirs": exportdir.saved_dirs(settings),
}
@@ -154,7 +158,7 @@ def get_settings() -> dict[str, Any]:
# the shipped defaults, so Settings can show what it's departing from
"free_tier_default": config.FREE_TIER,
"block_share": config.BLOCK_SHARE,
- # About tab: what this build is, and where it keeps its files
+ # System: what this build is, and where it keeps its files
"version": __version__,
"workspace_root": str(config.workspace_root()),
# the capture-extension version this build ships — Settings compares it
@@ -169,7 +173,7 @@ def get_settings() -> dict[str, Any]:
@router.get("/settings/ffmpeg")
def ffmpeg_info() -> dict[str, Any]:
- """About tab: ffmpeg version + where it resolves from. Separate from the
+ """System: ffmpeg version + where it resolves from. Separate from the
hot /settings poll because it shells out to ``ffmpeg -version``."""
return ffmpeg.info()
@@ -187,6 +191,12 @@ def put_prefs(body: PrefsIn) -> dict[str, Any]:
browser = body.download_cookies.browser
if browser not in config.COOKIE_BROWSERS:
raise HTTPException(status_code=422, detail=f"unknown browser '{browser}'")
+ for kind, folder in (body.export_dirs or {}).items():
+ if kind in exportdir.KINDS and folder.strip():
+ try:
+ exportdir.resolve(folder)
+ except exportdir.ExportDirError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
settings = config.update_settings(lambda s: _apply_prefs(s, body))
# a login session on disk is a liability once it isn't the chosen source
if body.download_cookies is not None:
@@ -247,6 +257,14 @@ def _apply_prefs(settings: dict[str, Any], body: PrefsIn) -> None:
settings["update_check_on_start"] = bool(body.update_check_on_start)
if body.update_dismissed_version is not None:
settings["update_dismissed_version"] = body.update_dismissed_version.strip()[:64]
+ if body.export_dirs is not None:
+ merged = dict(settings.get("export_dirs", {}))
+ for kind, folder in body.export_dirs.items():
+ if kind not in exportdir.KINDS:
+ continue
+ # "" is how the analyst goes back to the case's own exports folder
+ merged[kind] = str(exportdir.resolve(folder)) if folder.strip() else ""
+ settings["export_dirs"] = merged
if body.download_cookies is not None:
dc = body.download_cookies
settings["download_cookies"] = (
@@ -418,18 +436,19 @@ def export_settings() -> Response:
"""Download everything app-wide that isn't a case, so another machine can be
set up identically (POST /settings/import).
- Three files in one: settings.json verbatim (so a key added to
- ``DEFAULT_SETTINGS`` travels without anyone remembering to list it here),
- templates.json, and the signature logo base64-encoded. It carries the user's
- own API keys by design — it's a local download of secrets that already live
- in their workspace.
+ Three files in one: portable settings, templates.json, and the signature
+ logo base64-encoded. It carries the user's own API keys by design — it's a
+ local download of secrets that already live in their workspace.
- Deliberately absent: ``cookies.txt`` (a live login session, tied to one
- machine's browser), the cases themselves (portable folders already), and a
- signature that isn't a valid PNG within the size gate.
+ Deliberately absent: export destinations (absolute paths chosen on this
+ machine), ``cookies.txt`` (a live login session), the cases themselves
+ (portable folders already), and a signature that isn't a valid PNG within
+ the size gate.
"""
+ portable_settings = config.load_settings()
+ portable_settings.pop("export_dirs", None)
bundle = {
- "settings": config.load_settings(),
+ "settings": portable_settings,
"templates": config.load_templates(),
"signature_png": _signature_b64(),
}
diff --git a/src/azimut/config.py b/src/azimut/config.py
index 3345dec..02ce5d3 100644
--- a/src/azimut/config.py
+++ b/src/azimut/config.py
@@ -88,7 +88,7 @@ DEFAULT_SETTINGS: dict[str, Any] = {
# Maps JS widget is not configurable here — swapping it out and back
# re-bills a map load, so eco is pinned off for it in engine/tiles.py.
"eco_max_zooms": {},
- # Display preferences, app-wide (Settings → Preferences):
+ # Display preferences, app-wide (Settings → General):
# - coord_format: how every tool renders a latitude/longitude — "dd"
# (decimal degrees), "dms" (degrees/minutes/seconds), "mgrs" (grid ref).
# - units: "metric" (m/km/ha) or "imperial" (ft/mi/acre) for measurements.
@@ -129,6 +129,11 @@ DEFAULT_SETTINGS: dict[str, Any] = {
# - {"source": "file", "file": "cookies.txt"} — an export kept in settings,
# the fallback where reading the browser can't work (Chromium on Windows).
"download_cookies": {"source": "none"},
+ # Where each kind of export lands (engine/exportdir.py), as an absolute path
+ # the analyst browsed to: {"notes": "", "media": "", "proofs": ""}. An empty
+ # entry means the case's own `exports/` folder, which is the default and the
+ # one destination that always exists.
+ "export_dirs": {},
}
# Accepted values for the display preferences above — mirror of
diff --git a/src/azimut/engine/coords.py b/src/azimut/engine/coords.py
index 7d577ac..46909c5 100644
--- a/src/azimut/engine/coords.py
+++ b/src/azimut/engine/coords.py
@@ -3,7 +3,7 @@
The app stores decimal degrees in its SQLite graph, sidecars and proof specs.
This module only decides how a pair is *written out* in a human-facing label,
-following the user's ``coord_format`` preference (Settings → Preferences).
+following the user's ``coord_format`` preference (Settings → General).
Both implementations must agree: a title minted here has to read exactly like
the same point rendered in the browser, so they are tested against the same
diff --git a/src/azimut/engine/diagnostics.py b/src/azimut/engine/diagnostics.py
index ee18e7e..70b71a2 100644
--- a/src/azimut/engine/diagnostics.py
+++ b/src/azimut/engine/diagnostics.py
@@ -3,7 +3,7 @@
A local app has no crash reporter behind it, so the useful facts about a broken
run only exist on the user's own machine. This module collects them into one
short Markdown block and turns it into a pre-filled GitHub issue URL, which the
-About tab shows in full before the user decides to open it. Nothing is sent from
+System shows in full before the user decides to open it. Nothing is sent from
here: the report is text and a link, and the browser does the sending on a
click.
@@ -403,7 +403,7 @@ def issue_url(body: str, *, subject: str = "", label: str = "") -> str:
def payload(summary: str = "", *, kind: str = DEFAULT_KIND) -> dict[str, str]:
- """What the About tab renders: the full report, and the link to file it."""
+ """What Settings → System renders: the full report, and the link to file it."""
if kind not in KINDS:
kind = DEFAULT_KIND
body = report(summary, kind=kind)
diff --git a/src/azimut/engine/exportdir.py b/src/azimut/engine/exportdir.py
new file mode 100644
index 0000000..1d0baa0
--- /dev/null
+++ b/src/azimut/engine/exportdir.py
@@ -0,0 +1,311 @@
+"""Where an export lands, and the folder browser that lets the analyst say so.
+
+Every export used to write into the case's own `exports/` folder. That is still
+the default, but a finished PDF or a media file is usually wanted somewhere the
+case is not — a shared drive, a report folder, the desktop. So each kind of
+export (notes, media, proofs) remembers one destination app-wide, and the analyst
+changes it by browsing the filesystem from here.
+
+Two rules shape this module:
+
+* **The browser never sends a path Azimut has not shown it.** A destination is
+ reached by walking `roots()` and `listing()`, both of which only ever return
+ directory names. Nothing here reads a file, and nothing lists one.
+* **An export may leave the workspace, but never lands in the machinery.** That
+ is the point of choosing a folder. What it must not do is drop files in the
+ hidden directories the app keeps its own state in, so those are refused.
+
+The saved destinations live in settings under `export_dirs`, one entry per kind.
+An empty entry means the case's own `exports/` folder, which is what a fresh
+install exports to.
+"""
+
+from __future__ import annotations
+
+import os
+import shutil
+import string
+import sys
+import tempfile
+from pathlib import Path
+from typing import Any, BinaryIO, Iterator
+
+from .. import config, layout
+
+#: The exports that remember a destination of their own. Notes and proofs are
+#: documents the analyst files somewhere; media is the original coming back out.
+KINDS = ("notes", "media", "proofs")
+
+#: The case subdir an export falls back to when its kind has no folder saved.
+CASE_EXPORTS = "exports"
+
+#: Bound on one listing. A folder holding more subfolders than this is a
+#: machine's, not an analyst's, and the picker is not a file manager.
+MAX_ENTRIES = 500
+
+#: A directory full of files should not make a folder-only picker walk millions
+#: of entries just to discover that none can be shown. The useful result stays
+#: capped at ``MAX_ENTRIES`` and the underlying scan has its own hard stop.
+MAX_SCANNED_ENTRIES = 5_000
+
+#: Longest folder name "New folder" will make.
+MAX_NEW_NAME = 60
+
+
+class ExportDirError(Exception):
+ """A folder that can't be browsed or written to, said in a way fit for a user."""
+
+
+# -- the saved destinations --------------------------------------------------
+
+
+def saved_dirs(settings: dict[str, Any] | None = None) -> dict[str, str]:
+ """The remembered destination per kind, empty string meaning the case folder."""
+ stored = (settings or config.load_settings()).get("export_dirs") or {}
+ return {kind: str(stored.get(kind) or "") for kind in KINDS}
+
+
+def destination(kind: str, case_path: Path) -> Path:
+ """The folder ``kind`` exports to for this case, created if it isn't there.
+
+ The saved destination, and without one the case's own `exports/`. A saved
+ folder that has since gone away (an unplugged drive, a folder deleted from
+ under us) falls back to the case rather than failing the export: the analyst
+ gets their file, in the place that always exists.
+
+ The browser never names a destination. It picks one, which is saved, and
+ every export after that reads it from here — so a request cannot write to a
+ folder the analyst has not chosen.
+ """
+ if kind not in KINDS:
+ raise ExportDirError(f"unknown export kind '{kind}'")
+ saved = saved_dirs().get(kind, "")
+ if saved:
+ try:
+ return resolve(saved)
+ except ExportDirError:
+ pass
+ fallback = layout.subdir(case_path, CASE_EXPORTS)
+ fallback.mkdir(parents=True, exist_ok=True)
+ return fallback
+
+
+def resolve(raw: str) -> Path:
+ """Validate a folder the analyst chose, and hand back the real path.
+
+ Raises :class:`ExportDirError` for a folder that isn't there, isn't a folder,
+ isn't writable, or is one of Azimut's own hidden directories.
+ """
+ text = str(raw or "").strip()
+ if not text:
+ raise ExportDirError("no folder given")
+ try:
+ target = Path(text).expanduser().resolve()
+ except OSError as exc: # a path the OS refuses to even normalise
+ raise ExportDirError("that is not a usable folder") from exc
+ if not target.exists():
+ raise ExportDirError("that folder does not exist")
+ if not target.is_dir():
+ raise ExportDirError("that is a file, not a folder")
+ if _is_machinery(target):
+ raise ExportDirError("that folder belongs to Azimut — pick another one")
+ if not _writable(target):
+ raise ExportDirError("that folder is not writable")
+ return target
+
+
+def _is_machinery(target: Path) -> bool:
+ """Whether ``target`` is inside state Azimut manages rather than user files.
+
+ The workspace itself is fair game (the default destination is inside a case),
+ but the hidden directories under it — the app's own `.azimut/`, a case's
+ `.data/`, a case's `.trash/`, a media folder's `.meta/` — are not somewhere a
+ finished document belongs.
+ """
+ try:
+ root = config.workspace_root().expanduser().resolve()
+ except OSError:
+ return False
+ try:
+ relative = target.relative_to(root)
+ except ValueError:
+ return False # outside the workspace entirely: the analyst's own folders
+ return any(part.startswith(".") for part in relative.parts)
+
+
+def _writable(directory: Path) -> bool:
+ """Whether a file can actually be created here, asked by trying."""
+ try:
+ with tempfile.NamedTemporaryFile(prefix=".azimut-write-", dir=directory):
+ pass
+ except OSError:
+ return False
+ return True
+
+
+# -- browsing ----------------------------------------------------------------
+
+
+def roots() -> list[dict[str, str]]:
+ """The places the picker offers to start from.
+
+ The analyst's own folders first, because that is where an export goes, then
+ the workspace. On Windows the drive letters come last, so a second disk is
+ reachable without typing a path.
+ """
+ home = Path.home()
+ found: list[dict[str, str]] = []
+
+ def offer(label: str, path: Path) -> None:
+ try:
+ resolved = path.expanduser().resolve()
+ except OSError:
+ return
+ if not resolved.is_dir():
+ return
+ if any(entry["path"] == str(resolved) for entry in found):
+ return
+ found.append({"label": label, "path": str(resolved)})
+
+ offer("Home", home)
+ offer("Desktop", home / "Desktop")
+ offer("Documents", home / "Documents")
+ offer("Downloads", home / "Downloads")
+ offer("Workspace", config.workspace_root())
+ if sys.platform == "win32":
+ for letter in string.ascii_uppercase:
+ offer(f"{letter}:", Path(f"{letter}:/"))
+ return found
+
+
+def listing(raw: str) -> dict[str, Any]:
+ """The subfolders of one folder, with the crumbs that lead back out.
+
+ Only directories are returned: the picker chooses a destination, so the files
+ already in it are none of its business — and not listing them keeps this from
+ becoming a way to read the disk from a browser tab.
+ """
+ text = str(raw or "").strip()
+ if not text:
+ raise ExportDirError("no folder given")
+ try:
+ target = Path(text).expanduser().resolve()
+ except OSError as exc:
+ raise ExportDirError("that is not a usable folder") from exc
+ if not target.is_dir():
+ raise ExportDirError("that folder does not exist")
+
+ folders: list[dict[str, str]] = []
+ truncated = False
+ try:
+ with os.scandir(target) as entries:
+ for scanned, entry in enumerate(entries, start=1):
+ if scanned > MAX_SCANNED_ENTRIES:
+ truncated = True
+ break
+ if entry.name.startswith("."):
+ continue
+ try:
+ is_dir = entry.is_dir()
+ except OSError:
+ continue
+ if not is_dir:
+ continue
+ if len(folders) >= MAX_ENTRIES:
+ truncated = True
+ break
+ folders.append({"name": entry.name, "path": str(target / entry.name)})
+ except OSError as exc:
+ raise ExportDirError("that folder can't be read") from exc
+
+ folders.sort(key=lambda entry: entry["name"].casefold())
+
+ return {
+ "path": str(target),
+ "name": target.name or str(target),
+ "parent": str(target.parent) if target.parent != target else "",
+ "crumbs": _crumbs(target),
+ "folders": folders,
+ "truncated": truncated,
+ "writable": _writable(target) and not _is_machinery(target),
+ }
+
+
+def _crumbs(target: Path) -> list[dict[str, str]]:
+ """Every folder on the way to ``target``, outermost first."""
+ parts = list(reversed([target, *target.parents]))
+ return [{"name": part.name or str(part), "path": str(part)} for part in parts]
+
+
+def create_folder(parent_raw: str, name: str) -> dict[str, str]:
+ """Make one subfolder inside a browsed folder, so an export can go somewhere new."""
+ parent = resolve(parent_raw)
+ clean = layout.slugify(name, "", limit=MAX_NEW_NAME)
+ if not clean:
+ raise ExportDirError("that folder name can't be used")
+ target = parent / clean
+ if target.exists():
+ raise ExportDirError("a folder by that name is already there")
+ try:
+ target.mkdir()
+ except OSError as exc:
+ raise ExportDirError("that folder could not be created") from exc
+ return {"name": target.name, "path": str(target)}
+
+
+# -- writing an export out ---------------------------------------------------
+
+
+def _candidate_paths(folder: Path, filename: str) -> Iterator[Path]:
+ candidate = folder / filename
+ yield candidate
+ for index in range(2, 1000):
+ yield folder / f"{candidate.stem} ({index}){candidate.suffix}"
+
+
+def _reserve_path(folder: Path, filename: str) -> tuple[Path, BinaryIO]:
+ """Atomically reserve a new file without overwriting an existing one."""
+ for candidate in _candidate_paths(folder, filename):
+ try:
+ return candidate, candidate.open("xb")
+ except FileExistsError:
+ continue
+ except OSError as exc:
+ raise ExportDirError(f"could not write to that folder: {exc}") from exc
+ raise ExportDirError("too many files by that name are already there")
+
+
+def _discard_failed(target: Path) -> None:
+ try:
+ target.unlink(missing_ok=True)
+ except OSError:
+ pass
+
+
+def copy_out(source: Path, folder: Path, filename: str) -> Path:
+ """Copy one file into ``folder`` under an atomically reserved name."""
+ if not source.is_file():
+ raise ExportDirError("that file is no longer on disk")
+ target, handle = _reserve_path(folder, filename)
+ try:
+ with handle, source.open("rb") as source_handle:
+ shutil.copyfileobj(source_handle, handle)
+ shutil.copystat(source, target)
+ except OSError as exc:
+ handle.close()
+ _discard_failed(target)
+ raise ExportDirError(f"could not write to that folder: {exc}") from exc
+ return target
+
+
+def write_out(data: bytes, folder: Path, filename: str) -> Path:
+ """Write generated bytes under an atomically reserved external name."""
+ target, handle = _reserve_path(folder, filename)
+ try:
+ with handle:
+ handle.write(data)
+ except OSError as exc:
+ handle.close()
+ _discard_failed(target)
+ raise ExportDirError(f"could not write to that folder: {exc}") from exc
+ return target
diff --git a/src/azimut/engine/reveal.py b/src/azimut/engine/reveal.py
index 8b91c21..597e5ef 100644
--- a/src/azimut/engine/reveal.py
+++ b/src/azimut/engine/reveal.py
@@ -41,15 +41,20 @@ def _within_workspace(target: Path) -> bool:
return True
-def reveal(path: Path) -> None:
+def reveal(path: Path, *, workspace_only: bool = True) -> None:
"""Open ``path`` in Explorer, Finder or the Linux desktop's file manager.
Raises :class:`RevealError` for a folder outside the workspace, a folder that
isn't there, or a Linux box with no ``xdg-open`` — a headless server being the
one place this genuinely cannot work.
+
+ ``workspace_only=False`` is for the one folder that is legitimately elsewhere:
+ an export destination the analyst browsed to and Azimut saved. The caller
+ resolves it from settings, never from the request, so opening it still shows
+ a folder the app chose.
"""
target = Path(path).expanduser().resolve()
- if not _within_workspace(target):
+ if workspace_only and not _within_workspace(target):
raise RevealError("that folder is outside the workspace")
if not target.is_dir():
raise RevealError("that folder no longer exists")
diff --git a/src/azimut/engine/satellite.py b/src/azimut/engine/satellite.py
index 766ca33..e04bc4e 100644
--- a/src/azimut/engine/satellite.py
+++ b/src/azimut/engine/satellite.py
@@ -42,7 +42,7 @@ _ENTITY_PAGE = 500
def coords_label(lat: float, lon: float, fmt: str | None = None) -> str:
"""Default capture title / place label: the point's coordinates, written in
- the user's coordinate format (Settings → Preferences).
+ the user's coordinate format (Settings → General).
Only *new* labels are minted here — a title already stored keeps whatever it
was named, so switching format never rewrites the case's existing titles.
diff --git a/tests/test_export_destinations.py b/tests/test_export_destinations.py
new file mode 100644
index 0000000..491d352
--- /dev/null
+++ b/tests/test_export_destinations.py
@@ -0,0 +1,255 @@
+"""Shared export destinations, folder browsing, and media/proof copies."""
+
+import base64
+import io
+from concurrent.futures import ThreadPoolExecutor
+from threading import Barrier
+
+import pytest
+from PIL import Image
+
+from azimut import layout
+from azimut.engine import exportdir
+from azimut.workspace import Case
+
+
+def _png_bytes() -> bytes:
+ data = io.BytesIO()
+ Image.new("RGB", (24, 16), (80, 90, 100)).save(data, "PNG")
+ return data.getvalue()
+
+
+def _case(client, name: str = "Exports") -> str:
+ return client.post("/api/cases", json={"name": name}).json()["id"]
+
+
+def _upload(client, case_id: str, name: str = "frame.png") -> dict:
+ response = client.post(
+ f"/api/cases/{case_id}/media/upload",
+ files={"file": (name, io.BytesIO(_png_bytes()), "image/png")},
+ )
+ assert response.status_code == 200
+ return response.json()["item"]
+
+
+def _save_proof(client, case_id: str, title: str = "Rooftop") -> dict:
+ return client.post(
+ f"/api/cases/{case_id}/proofs",
+ json={
+ "title": title,
+ "spec": {"panels": [], "shapes": []},
+ "png_base64": base64.b64encode(_png_bytes()).decode("ascii"),
+ },
+ ).json()
+
+
+def test_export_destinations_are_remembered_independently(client, tmp_path):
+ notes = tmp_path / "notes"
+ media = tmp_path / "media"
+ notes.mkdir()
+ media.mkdir()
+
+ response = client.put(
+ "/api/settings/prefs",
+ json={"export_dirs": {"notes": str(notes), "media": str(media)}},
+ )
+
+ assert response.status_code == 200
+ assert response.json()["export_dirs"] == {
+ "notes": str(notes),
+ "media": str(media),
+ "proofs": "",
+ }
+ assert client.get("/api/settings").json()["export_dirs"]["notes"] == str(notes)
+
+ reset = client.put("/api/settings/prefs", json={"export_dirs": {"notes": ""}})
+ assert reset.json()["export_dirs"]["notes"] == ""
+ assert reset.json()["export_dirs"]["media"] == str(media)
+
+
+def test_an_export_destination_must_be_an_existing_writable_folder(client, tmp_path):
+ missing = tmp_path / "missing"
+ file_path = tmp_path / "file.txt"
+ file_path.write_text("not a folder", encoding="utf-8")
+
+ assert client.put(
+ "/api/settings/prefs", json={"export_dirs": {"media": str(missing)}}
+ ).status_code == 422
+ assert client.put(
+ "/api/settings/prefs", json={"export_dirs": {"media": str(file_path)}}
+ ).status_code == 422
+
+
+def test_folder_browser_lists_only_visible_folders_and_can_create_one(client, tmp_path):
+ (tmp_path / "Visible").mkdir()
+ (tmp_path / ".hidden").mkdir()
+ (tmp_path / "file.txt").write_text("private contents", encoding="utf-8")
+
+ listed = client.get("/api/folders", params={"path": str(tmp_path)})
+
+ assert listed.status_code == 200
+ assert [entry["name"] for entry in listed.json()["folders"]] == ["Visible"]
+ assert "file.txt" not in listed.text
+ assert "private contents" not in listed.text
+
+ created = client.post(
+ "/api/folders/create", json={"parent": str(tmp_path), "name": "Final report"}
+ )
+ assert created.status_code == 200
+ assert created.json()["name"] == "Final report"
+ assert (tmp_path / "Final report").is_dir()
+
+
+def test_writability_probe_never_touches_a_preexisting_file(client, tmp_path):
+ sentinel = tmp_path / ".azimut-write-test"
+ sentinel.write_bytes(b"belongs to the analyst")
+
+ listed = client.get("/api/folders", params={"path": str(tmp_path)})
+ saved = client.put(
+ "/api/settings/prefs", json={"export_dirs": {"notes": str(tmp_path)}}
+ )
+
+ assert listed.status_code == saved.status_code == 200
+ assert sentinel.read_bytes() == b"belongs to the analyst"
+ assert [path for path in tmp_path.glob(".azimut-write-*") if path != sentinel] == []
+
+
+def test_folder_listing_stops_scanning_a_file_heavy_directory(tmp_path, monkeypatch):
+ class Entry:
+ def __init__(self, index):
+ self.name = f"file-{index}"
+
+ def is_dir(self):
+ return False
+
+ class Entries:
+ consumed = 0
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return False
+
+ def __iter__(self):
+ for index in range(exportdir.MAX_SCANNED_ENTRIES + 20):
+ self.consumed += 1
+ yield Entry(index)
+
+ entries = Entries()
+ monkeypatch.setattr(exportdir.os, "scandir", lambda _path: entries)
+
+ listed = exportdir.listing(str(tmp_path))
+
+ assert listed["folders"] == []
+ assert listed["truncated"] is True
+ assert entries.consumed == exportdir.MAX_SCANNED_ENTRIES + 1
+
+
+def test_media_export_defaults_to_the_case_then_uses_the_saved_folder(client, tmp_path):
+ case_id = _case(client, "Media export")
+ item = _upload(client, case_id)
+
+ first = client.post(f"/api/cases/{case_id}/media/export", json={"path": item["path"]})
+ default = layout.subdir(Case.open(case_id).path, "exports")
+ assert first.status_code == 200
+ assert first.json()["folder"] == str(default)
+ assert (default / "frame.png").read_bytes() == _png_bytes()
+
+ chosen = tmp_path / "evidence"
+ chosen.mkdir()
+ client.put("/api/settings/prefs", json={"export_dirs": {"media": str(chosen)}})
+ client.post(f"/api/cases/{case_id}/media/export", json={"path": item["path"]})
+ again = client.post(f"/api/cases/{case_id}/media/export", json={"path": item["path"]})
+
+ assert (chosen / "frame.png").is_file()
+ assert again.json()["file"] == "frame (2).png"
+ assert (chosen / "frame (2).png").is_file()
+
+
+def test_concurrent_exports_reserve_distinct_names(tmp_path):
+ destination = tmp_path / "exports"
+ destination.mkdir()
+ sources = []
+ for index in range(8):
+ source = tmp_path / f"source-{index}.txt"
+ source.write_text(f"content {index}", encoding="utf-8")
+ sources.append(source)
+ barrier = Barrier(len(sources))
+
+ def copy(index):
+ barrier.wait()
+ return exportdir.copy_out(sources[index], destination, "report.txt")
+
+ with ThreadPoolExecutor(max_workers=len(sources)) as pool:
+ written = list(pool.map(copy, range(len(sources))))
+
+ assert len({path.name for path in written}) == len(sources)
+ assert {path.read_text(encoding="utf-8") for path in written} == {
+ f"content {index}" for index in range(len(sources))
+ }
+
+
+def test_a_failed_external_copy_removes_its_reserved_file(tmp_path, monkeypatch):
+ source = tmp_path / "source.txt"
+ source.write_text("content", encoding="utf-8")
+ destination = tmp_path / "exports"
+ destination.mkdir()
+
+ def fail(_source, target):
+ target.write(b"partial")
+ raise OSError("disk full")
+
+ monkeypatch.setattr(exportdir.shutil, "copyfileobj", fail)
+
+ with pytest.raises(exportdir.ExportDirError, match="disk full"):
+ exportdir.copy_out(source, destination, "report.txt")
+ assert list(destination.iterdir()) == []
+
+
+def test_media_export_refuses_a_case_file_that_is_not_registered_media(client):
+ case_id = _case(client, "Media boundary")
+ case = Case.open(case_id)
+ case.write_notes("not media")
+
+ response = client.post(
+ f"/api/cases/{case_id}/media/export", json={"path": "notes.md"}
+ )
+
+ assert response.status_code == 404
+ assert list(layout.subdir(case.path, "exports").iterdir()) == []
+
+
+def test_proof_export_uses_its_own_saved_folder_and_never_overwrites(client, tmp_path):
+ case_id = _case(client, "Proof export")
+ saved = _save_proof(client, case_id)
+ chosen = tmp_path / "proofs"
+ chosen.mkdir()
+ client.put("/api/settings/prefs", json={"export_dirs": {"proofs": str(chosen)}})
+
+ first = client.post(f"/api/cases/{case_id}/proofs/{saved['name']}/export")
+ second = client.post(f"/api/cases/{case_id}/proofs/{saved['name']}/export")
+
+ assert first.status_code == 200
+ assert first.json()["file"] == "Rooftop.png"
+ assert second.json()["file"] == "Rooftop (2).png"
+ assert (chosen / "Rooftop.png").read_bytes() == _png_bytes()
+
+
+def test_reveal_routes_resolve_saved_folders_without_accepting_a_path(client, tmp_path, monkeypatch):
+ case_id = _case(client, "Reveal exports")
+ chosen = tmp_path / "chosen"
+ chosen.mkdir()
+ client.put(
+ "/api/settings/prefs",
+ json={"export_dirs": {"media": str(chosen), "proofs": str(chosen)}},
+ )
+ opened = []
+
+ from azimut.engine import reveal
+
+ monkeypatch.setattr(reveal, "reveal", lambda path, **_: opened.append(path))
+
+ assert client.post(f"/api/cases/{case_id}/media/export/reveal").status_code == 200
+ assert client.post(f"/api/cases/{case_id}/proofs/export/reveal").status_code == 200
+ assert opened == [chosen.resolve(), chosen.resolve()]
diff --git a/tests/test_satellite_api.py b/tests/test_satellite_api.py
index fdc6b4f..7f60a85 100644
--- a/tests/test_satellite_api.py
+++ b/tests/test_satellite_api.py
@@ -367,7 +367,7 @@ def test_edit_title_renames_capture_entity(client, monkeypatch):
def test_capture_title_follows_the_coordinate_format(client, monkeypatch):
- """A default title is minted in the user's format (Settings → Preferences),
+ """A default title is minted in the user's format (Settings → General),
while the machine-readable fields stay in decimal degrees."""
monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)
client.put("/api/settings/prefs", json={"coord_format": "mgrs"})
diff --git a/tests/test_settings_backup.py b/tests/test_settings_backup.py
index 6c0ffb8..f764053 100644
--- a/tests/test_settings_backup.py
+++ b/tests/test_settings_backup.py
@@ -1,9 +1,9 @@
"""Settings backup (export/import) and the lazy pairing-token mint.
-The backup is one JSON file carrying everything app-wide that isn't a case:
-settings.json, templates.json and the signature logo. Two invariants are worth
-more than the individual cases below — every setting that can be exported can be
-imported back (the drift gate), and ``cookies.txt`` never travels.
+The backup is one JSON file carrying everything portable that isn't a case:
+settings, templates and the signature logo. Two invariants are worth more than
+the individual cases below — every exported setting can be imported back (the
+drift gate), and machine-bound paths never travel.
"""
import base64
@@ -22,29 +22,28 @@ def bundle_of(client) -> dict:
# -- the drift gate ---------------------------------------------------------
-# Keys that settings.json holds but a backup deliberately does not restore.
-# Empty on purpose: an entry here is a decision, and it needs a reason next to
-# it. Anything else showing up in the gate below is an oversight, not a policy.
-NOT_RESTORED: dict[str, str] = {}
+# Keys that settings.json holds but a backup deliberately does not export.
+# Each entry is a deliberate portability decision. Anything else showing up in
+# the gate below is an oversight, not a policy.
+NOT_EXPORTED: dict[str, str] = {
+ "export_dirs": "absolute export paths belong to the machine that selected them",
+}
def test_every_exported_setting_can_be_imported_back():
- """The export dumps settings.json verbatim, so it can never fall behind; the
- import is an allowlist, so it can. This is the gate that says when it did.
+ """Export and import deliberately meet at one typed portability boundary.
A new key in DEFAULT_SETTINGS fails here until it is either typed into
- ImportedSettings or listed in NOT_RESTORED with a reason. Without it, a
- forgotten key is exported and then silently dropped on the way back — which
- is exactly how `download_cookies` went missing.
+ ImportedSettings or listed in NOT_EXPORTED with a reason.
"""
- exported = set(config.DEFAULT_SETTINGS)
+ exported = set(config.DEFAULT_SETTINGS) - set(NOT_EXPORTED)
importable = {
field.alias or name for name, field in ImportedSettings.model_fields.items()
}
- unhandled = exported - importable - set(NOT_RESTORED)
+ unhandled = exported - importable
assert not unhandled, (
f"settings key(s) {sorted(unhandled)} are exported but not importable: type them "
- "in ImportedSettings, or list them in NOT_RESTORED with the reason"
+ "in ImportedSettings, or list them in NOT_EXPORTED with the reason"
)
# And nothing claims to import a setting the app doesn't have.
assert not importable - exported
@@ -150,6 +149,19 @@ def test_export_leaves_the_workspace_location_behind(client, tmp_path):
assert "somewhere" not in str(blob)
+def test_export_leaves_absolute_export_destinations_behind(client, tmp_path):
+ chosen = tmp_path / "reports"
+ chosen.mkdir()
+ client.put(
+ "/api/settings/prefs", json={"export_dirs": {"notes": str(chosen)}}
+ )
+
+ blob = bundle_of(client)
+
+ assert "export_dirs" not in blob["settings"]
+ assert str(chosen) not in str(blob)
+
+
def test_the_browser_login_choice_travels_but_a_missing_file_does_not(client):
client.put(
"/api/settings/prefs",