The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.
JavaScript
/**
* @vitest-environment happy-dom
*
* The startup check reads the extension's marker off <html>, so this file needs
* a document like extBridge's own tests do.
*/
import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
import { caseState, uiState, closeCase, setSidebarWidth } from './state.svelte.js';
import { MIN_W, MAX_W } from './sidebar.js';
// The prefs tests below exercise import-time module state, so the transport is
// stubbed and the module re-imported fresh per test. The static import above
// still works: these tests never call the API.
vi.mock('./api.js', () => ({
api: { get: vi.fn(), post: vi.fn(), put: vi.fn(), patch: vi.fn(), del: vi.fn() },
}));
// The two bridge probes wait 700 ms of real time for an answer, and the startup
// check does not await them. Left real, their timers outlive the test that
// started them and can fire after happy-dom is torn down. Here nothing answers,
// at once; extBridge.test.js covers the probes themselves.
vi.mock('./extBridge.js', async (importOriginal) => ({
...(await importOriginal()),
pingExtensions: vi.fn(async () => []),
extensionState: vi.fn(async () => []),
}));
async function freshState() {
vi.resetModules();
return import('./state.svelte.js');
}
function deferred() {
let resolve;
let reject;
const promise = new Promise((yes, no) => {
resolve = yes;
reject = no;
});
return { promise, resolve, reject };
}
describe('closeCase', () => {
beforeEach(() => {
caseState.current = { id: 'case-a', name: 'Case A' };
uiState.composeQueue = ['media/a.jpg'];
uiState.postProof = { title: 'x' };
uiState.openProof = 'proof-a';
uiState.openDraft = 'draft-a';
uiState.inspectPath = 'media/a.jpg';
uiState.reverseTarget = { path: 'media/a.jpg', kind: 'image', label: 'a.jpg' };
uiState.focusMedia = 'media/a.jpg';
uiState.openInspect = 'session-a';
uiState.openCollage = 'collage-a';
uiState.openAnalyzer = 'runs-123456789abc';
uiState.drawInGraph = { label: 'A question' };
uiState.openBoardEntity = 'entity-a';
uiState.openGraphEntity = 'entity-a';
uiState.timelineFocus = { itemId: 'event-a' };
uiState.timelineRange = { from: '2026-01-01', to: '2026-02-01' };
uiState.mapTimelineRange = { from: '2026-01-01', to: '2026-02-01' };
uiState.gotoCoords = { lat: 1, lon: 2 };
uiState.lookAt = { tool: 'detect', lat: 1, lon: 2, zoom: 12 };
});
it('drops the open case', () => {
closeCase();
expect(caseState.current).toBeNull();
});
it('clears every cross-tool handoff, so nothing meant for the closed case leaks into whatever opens next', () => {
closeCase();
expect(uiState.composeQueue).toEqual([]);
expect(uiState.postProof).toBeNull();
expect(uiState.openProof).toBeNull();
expect(uiState.openDraft).toBeNull();
expect(uiState.inspectPath).toBeNull();
expect(uiState.reverseTarget).toBeNull();
expect(uiState.focusMedia).toBeNull();
expect(uiState.openInspect).toBeNull();
expect(uiState.openCollage).toBeNull();
expect(uiState.openAnalyzer).toBeNull();
expect(uiState.drawInGraph).toBeNull();
expect(uiState.openBoardEntity).toBeNull();
expect(uiState.openGraphEntity).toBeNull();
expect(uiState.timelineFocus).toBeNull();
expect(uiState.timelineRange).toBeNull();
expect(uiState.mapTimelineRange).toBeNull();
expect(uiState.gotoCoords).toBeNull();
expect(uiState.lookAt).toBeNull();
expect(uiState.openNotebook).toBeNull();
expect(uiState.focusCapture).toBeNull();
expect(uiState.skyAt).toBeNull();
expect(uiState.refViewers).toEqual([]);
});
it('leaves the camera the map tabs share, which is not case state', () => {
uiState.mapView = { lat: 1, lon: 2, zoom: 12, bearing: 0, by: 'satellite' };
closeCase();
expect(uiState.mapView).toEqual({ lat: 1, lon: 2, zoom: 12, bearing: 0, by: 'satellite' });
});
});
describe('setSidebarWidth', () => {
afterEach(() => vi.restoreAllMocks());
it('takes a dragged width as-is when it fits', () => {
vi.spyOn(window, 'innerWidth', 'get').mockReturnValue(1600);
setSidebarWidth(440);
expect(uiState.sidebarW).toBe(440);
});
it('clamps against the live window, not just the fixed bounds', () => {
vi.spyOn(window, 'innerWidth', 'get').mockReturnValue(900);
setSidebarWidth(MAX_W); // legal on a wide screen, half the canvas here
expect(uiState.sidebarW).toBe(450);
setSidebarWidth(10);
expect(uiState.sidebarW).toBe(MIN_W);
});
});
describe('prefsReady — tools must not race the settings fetch', () => {
let api;
beforeEach(async () => {
({ api } = await import('./api.js'));
api.get.mockReset();
});
it('does not resolve before the preferences land', async () => {
let release;
api.get.mockReturnValue(new Promise((r) => (release = r)));
const { prefsReady, loadPrefs, prefs } = await freshState();
let ready = false;
prefsReady.then(() => (ready = true));
loadPrefs();
await Promise.resolve();
expect(ready).toBe(false); // a tool awaiting this is still parked
release({ home_view: { lat: -33.8568, lon: 151.2153, zoom: 17 } });
await prefsReady;
// the home view is readable the moment prefsReady resolves — that ordering
// is what keeps the Satellite map off its built-in default
expect(prefs.homeView).toEqual({ lat: -33.8568, lon: 151.2153, zoom: 17 });
});
it('resolves even when the settings read fails, leaving the defaults', async () => {
api.get.mockRejectedValue(new Error('offline'));
const { prefsReady, loadPrefs, prefs } = await freshState();
await loadPrefs().catch(() => {});
await expect(prefsReady).resolves.toBeUndefined(); // never hangs a tool
expect(prefs.homeView).toEqual({ lat: 43, lon: 25, zoom: 3 });
});
});
describe('applyPrefs', () => {
it('adopts a settings payload and ignores absent fields', async () => {
const { applyPrefs, prefs } = await freshState();
applyPrefs({ coord_format: 'mgrs', units: 'imperial' });
expect(prefs.coordFormat).toBe('mgrs');
expect(prefs.units).toBe('imperial');
expect(prefs.postMention).toBe('@GeoConfirmed'); // untouched by a partial payload
expect(prefs.postTarget).toBe('x'); // untouched by a partial payload
expect(prefs.signatureHandle).toBe(''); // untouched by a partial payload
applyPrefs({ post_mention: '' }); // an empty mention is a real choice, not absence
expect(prefs.postMention).toBe('');
applyPrefs({ post_target: 'bluesky' });
expect(prefs.postTarget).toBe('bluesky');
expect(prefs.postTemplate).toBe(''); // no default template until one is chosen
applyPrefs({ post_template: 'tpl_1' });
expect(prefs.postTemplate).toBe('tpl_1');
applyPrefs({ post_template: '' }); // clearing it is a real choice too
expect(prefs.postTemplate).toBe('');
applyPrefs({ signature_handle: '@example' });
expect(prefs.signatureHandle).toBe('@example');
});
it('shares one camera across the map tabs until Settings says otherwise', async () => {
const { applyPrefs, prefs } = await freshState();
expect(prefs.mapSync).toBe(true);
applyPrefs({ units: 'metric' });
expect(prefs.mapSync).toBe(true);
applyPrefs({ map_sync: false });
expect(prefs.mapSync).toBe(false);
});
it('keeps the version the full payload names, and keeps it through a partial one', async () => {
// the welcome names it, and PUT /api/settings/prefs answers without it
const { applyPrefs, appInfo } = await freshState();
expect(appInfo.version).toBe('');
applyPrefs({ version: '0.3.3', units: 'metric' });
expect(appInfo.version).toBe('0.3.3');
applyPrefs({ units: 'imperial' });
expect(appInfo.version).toBe('0.3.3');
});
});
describe('startup update check', () => {
it('checks the app and the downloaders by default, and neither when the Settings switch is off', async () => {
const { api } = await import('./api.js');
api.get.mockReset().mockResolvedValue({
current: 'v0.1.0', latest: null, update_available: false, scrapers: [],
});
const { applyPrefs, checkForUpdatesOnStart } = await freshState();
await checkForUpdatesOnStart();
expect(api.get).toHaveBeenCalledWith('/api/settings/update?check=true');
expect(api.get).toHaveBeenCalledWith('/api/settings/scrapers?check=true');
api.get.mockClear();
applyPrefs({ update_check_on_start: false });
await checkForUpdatesOnStart();
// The switch governs the network, which is what `?check=true` marks. The
// local reads that stay behind — what the app's own extension folder holds —
// reach the loopback server and nothing else, so they are not what it gates.
expect(api.get.mock.calls.flat().filter((path) => String(path).includes('check=true')))
.toEqual([]);
});
it('records what the downloaders check found', async () => {
const { api } = await import('./api.js');
const entries = [{ dist: 'yt-dlp', version: '2026.1.1', latest: '2026.7.1', outdated: true }];
api.get.mockReset().mockImplementation((path) =>
path.startsWith('/api/settings/scrapers')
? Promise.resolve({ scrapers: entries })
: Promise.resolve({ update_available: false }),
);
const { checkForUpdatesOnStart, updatesState } = await freshState();
await checkForUpdatesOnStart();
expect(updatesState.scrapers).toEqual(entries);
});
it('compares the installed extension without asking the network', async () => {
const { api } = await import('./api.js');
api.get.mockReset().mockRejectedValue(new Error('must not be called'));
document.documentElement.dataset.azimutCaptureExtension = '0.2.1';
const { applyPrefs, checkForUpdatesOnStart, updatesState } = await freshState();
applyPrefs({ update_check_on_start: false, extension_version: '0.2.5' });
await checkForUpdatesOnStart();
// The marker on <html> is a synchronous local read, so the version half of
// the answer holds even with every request failing.
expect(api.get.mock.calls.flat().filter((path) => String(path).includes('check=true')))
.toEqual([]);
expect(updatesState.extensionInstalled).toBe('0.2.1');
expect(updatesState.extensionBundled).toBe('0.2.5');
delete document.documentElement.dataset.azimutCaptureExtension;
});
it('reads the extension folder locally, and never on the network switch', async () => {
// The digest comparison the badge needs is a disk read on the loopback
// server plus two postMessage probes: no third party, nothing to gate.
const { api } = await import('./api.js');
api.get.mockReset().mockResolvedValue({
path: '/w/.azimut/extension',
staged: false,
bundled: { version: '0.3.0', payload: 'new' },
folder: { install_id: 'mine', version: '0.3.0', payload: 'old' },
});
const { applyPrefs, checkExtension, updatesState } = await freshState();
applyPrefs({ update_check_on_start: false });
await checkExtension();
expect(api.get).toHaveBeenCalledWith('/api/settings/extension');
// Nothing answered the probes here, so the verdict is "nothing loaded" —
// and it is a verdict, not a failure.
expect(updatesState.extension.status).toBe('absent');
});
it('leaves the version fallback in charge when the folder cannot be read', async () => {
const { api } = await import('./api.js');
api.get.mockReset().mockRejectedValue(new Error('offline'));
const { checkExtension, updatesState } = await freshState();
await expect(checkExtension()).resolves.toBeFalsy();
expect(updatesState.extension).toBe(null);
});
it('leaves no bridge timer running once a test is over', async () => {
const { api } = await import('./api.js');
api.get.mockReset().mockRejectedValue(new Error('offline'));
const { checkForUpdatesOnStart } = await freshState();
const { pingExtensions, extensionState } = await import('./extBridge.js');
vi.useFakeTimers();
try {
await checkForUpdatesOnStart();
expect(pingExtensions).toHaveBeenCalled();
expect(extensionState).toHaveBeenCalled();
expect(vi.getTimerCount()).toBe(0);
} finally {
vi.useRealTimers();
}
});
it('does not surface an offline failure', async () => {
const { api } = await import('./api.js');
api.get.mockReset().mockRejectedValue(new Error('offline'));
const { checkForUpdatesOnStart, updatesState } = await freshState();
await expect(checkForUpdatesOnStart()).resolves.toBeUndefined();
expect(updatesState.app).toBeNull();
expect(updatesState.scrapers).toBeNull();
});
});
describe('templates store', () => {
let api;
beforeEach(async () => {
({ api } = await import('./api.js'));
api.get.mockReset();
api.post.mockReset();
api.del.mockReset();
});
it('loadTemplates mirrors both families, tolerating a bad payload', async () => {
const { loadTemplates, templatesState } = await freshState();
({ api } = await import('./api.js'));
api.get.mockResolvedValue({ proof: [{ id: 'a', name: 'Dark' }], post: [{ id: 'b', name: 'Terse' }] });
await loadTemplates();
expect(templatesState.proof.map((t) => t.id)).toEqual(['a']);
expect(templatesState.post.map((t) => t.id)).toEqual(['b']);
api.get.mockRejectedValue(new Error('offline'));
await loadTemplates(); // never throws; leaves the last good store
expect(templatesState.proof.map((t) => t.id)).toEqual(['a']);
});
it('saveTemplate posts to the kind endpoint then refreshes the store', async () => {
const { saveTemplate, templatesState } = await freshState();
({ api } = await import('./api.js'));
api.post.mockResolvedValue({ id: 'x', name: 'Dark', data: {} });
api.get.mockResolvedValue({ proof: [{ id: 'x', name: 'Dark' }], post: [] });
const rec = await saveTemplate('proof', { name: 'Dark', data: { bg: '#000' } });
expect(api.post).toHaveBeenCalledWith('/api/templates/proof', { name: 'Dark', data: { bg: '#000' } });
expect(rec.id).toBe('x');
expect(templatesState.proof).toHaveLength(1);
});
it('deleteTemplate hits the id endpoint then refreshes', async () => {
const { deleteTemplate, templatesState } = await freshState();
({ api } = await import('./api.js'));
api.del.mockResolvedValue({ deleted: true });
api.get.mockResolvedValue({ proof: [], post: [] });
await deleteTemplate('post', 'b');
expect(api.del).toHaveBeenCalledWith('/api/templates/post/b');
expect(templatesState.post).toEqual([]);
});
});
describe('case request ownership', () => {
let api;
let state;
beforeEach(async () => {
state = await freshState();
({ api } = await import('./api.js'));
api.get.mockReset();
state.caseState.current = null;
state.caseState.loading = false;
state.caseState.rev = 0;
});
it('keeps the latest case when an older open finishes last', async () => {
const first = deferred();
const second = deferred();
api.get.mockImplementation((path) =>
path.endsWith('/case-a') ? first.promise : second.promise
);
const openingA = state.openCase('case-a');
const openingB = state.openCase('case-b');
second.resolve({ id: 'case-b', name: 'Case B' });
await openingB;
first.resolve({ id: 'case-a', name: 'Case A' });
await openingA;
expect(state.caseState.current).toEqual({ id: 'case-b', name: 'Case B' });
expect(state.caseState.loading).toBe(false);
});
it('drops every handoff meant for the case being left behind', async () => {
// Switching cases and closing one share this list. Written out twice they
// drifted, and an `openProof` queued in case A was spent against case B.
state.caseState.current = { id: 'case-a', name: 'Case A' };
api.get.mockResolvedValue({ id: 'case-b', name: 'Case B' });
const queued = {
composeQueue: ['media/a.jpg'],
postProof: { title: 'x' },
openProof: 'proof-a',
openDraft: 'draft-a',
openNotebook: { noteId: 'note-a' },
inspectPath: 'media/a.jpg',
reverseTarget: { path: 'media/a.jpg', kind: 'image', label: 'a.jpg' },
focusMedia: 'media/a.jpg',
focusCapture: 'media/crop.png',
openInspect: 'session-a',
openCollage: 'collage-a',
drawInGraph: { label: 'A question' },
openBoardEntity: 'entity-a',
openGraphEntity: 'entity-a',
timelineFocus: { itemId: 'event-a' },
timelineRange: { from: '2026-01-01', to: '2026-02-01' },
mapTimelineRange: { from: '2026-01-01', to: '2026-02-01' },
gotoCoords: { lat: 1, lon: 2 },
lookAt: { tool: 'compare', lat: 1, lon: 2, zoom: 12 },
skyAt: { lat: 1, lon: 2, date: '2026-01-01', time: '12:00' },
refViewers: [{ id: 'v1' }],
};
Object.assign(state.uiState, queued);
await state.openCase('case-b');
for (const key of Object.keys(queued)) {
const left = state.uiState[key];
expect(Array.isArray(left) ? left : left ?? null, `uiState.${key}`).toEqual(
Array.isArray(queued[key]) ? [] : null
);
}
});
it('waits for case-owned work and cancels the switch when it cannot be saved', async () => {
const guard = vi.fn().mockResolvedValue(false);
const unregister = state.registerCaseChangeGuard(guard);
state.caseState.current = { id: 'case-a', name: 'Case A' };
await state.openCase('case-b');
expect(guard).toHaveBeenCalledWith({ fromId: 'case-a', toId: 'case-b' });
expect(api.get).not.toHaveBeenCalled();
expect(state.caseState.current.id).toBe('case-a');
expect(state.caseState.loading).toBe(false);
unregister();
});
// Promoting moves the scratch folder on the server. A guard asked afterwards,
// answered "Keep editing", left the app on a session id that no longer existed.
it('asks before promoting a session, and moves nothing when it is kept', async () => {
const guard = vi.fn().mockResolvedValue(false);
const unregister = state.registerCaseChangeGuard(guard);
state.caseState.current = { id: 'scratch_a', name: 'Scratch session', scratch: true };
api.post.mockReset();
expect(await state.promoteCase('Harbour')).toBeNull();
expect(guard).toHaveBeenCalledWith({ fromId: 'scratch_a', toId: null, reason: 'promote' });
expect(api.post).not.toHaveBeenCalled();
expect(state.caseState.current.id).toBe('scratch_a');
unregister();
});
it('promotes once the guards agree, without asking them twice', async () => {
const order = [];
const guard = vi.fn(async () => { order.push('guard'); return true; });
const unregister = state.registerCaseChangeGuard(guard);
state.caseState.current = { id: 'scratch_a', name: 'Scratch session', scratch: true };
api.post.mockReset();
api.post.mockImplementation(async (path) => {
order.push(path);
return { id: 'harbour' };
});
api.get.mockImplementation(async (path) =>
path === '/api/cases/harbour' ? { id: 'harbour', name: 'Harbour' } : []
);
expect(await state.promoteCase('Harbour')).toEqual({ id: 'harbour' });
expect(order).toEqual(['guard', '/api/cases/scratch_a/promote']);
expect(guard).toHaveBeenCalledTimes(1);
expect(state.caseState.current.id).toBe('harbour');
unregister();
});
// The example files a photo in whatever is current once this answers, so an answer
// for a case that lost must not read as the case being open.
it('does not answer with a case another choice has overtaken', async () => {
const opening = deferred();
state.caseState.current = null;
api.post.mockResolvedValue({ id: 'made', name: 'Made' });
api.get.mockImplementation((path) => {
if (path === '/api/cases/made') return opening.promise;
if (path === '/api/cases/later') return Promise.resolve({ id: 'later', name: 'Later' });
return Promise.resolve([]);
});
const creating = state.createCase('Made');
await vi.waitFor(() => expect(api.get).toHaveBeenCalledWith('/api/cases/made'));
await state.openCase('later');
opening.resolve({ id: 'made', name: 'Made' });
expect(await creating).toBeNull();
expect(state.caseState.current.id).toBe('later');
});
it('says when startup has reopened its case, even one it could not', async () => {
const opening = deferred();
api.get.mockImplementation((path) => (path === '/api/cases/case-a' ? opening.promise : Promise.resolve([])));
let settled = false;
const starting = state.initSession('case-a');
state.sessionStarted().then(() => (settled = true));
await vi.waitFor(() => expect(api.get).toHaveBeenCalledWith('/api/cases/case-a'));
expect(settled).toBe(false);
opening.reject(new Error('case not found'));
await expect(starting).rejects.toThrow('case not found');
await vi.waitFor(() => expect(settled).toBe(true));
});
it('creates no case when the analyst keeps the open one', async () => {
const unregister = state.registerCaseChangeGuard(async () => false);
state.caseState.current = { id: 'case-a', name: 'Case A' };
api.post.mockReset();
expect(await state.createCase('Harbour')).toBeNull();
expect(await state.adoptFolder('Harbour')).toBeNull();
expect(api.post).not.toHaveBeenCalled();
expect(state.caseState.current.id).toBe('case-a');
unregister();
});
it('does not let a late refresh reopen the case it started in', async () => {
const refresh = deferred();
api.get.mockReturnValue(refresh.promise);
state.caseState.current = { id: 'case-a', name: 'Case A' };
const reloading = state.reloadCase();
state.caseState.current = { id: 'case-b', name: 'Case B' };
refresh.resolve({ id: 'case-a', name: 'Case A refreshed' });
await reloading;
expect(state.caseState.current).toEqual({ id: 'case-b', name: 'Case B' });
expect(state.caseState.rev).toBe(0);
});
it('keeps the latest refresh when two writes finish out of order', async () => {
const first = deferred();
const second = deferred();
api.get
.mockReturnValueOnce(first.promise)
.mockReturnValueOnce(second.promise);
state.caseState.current = { id: 'case-a', name: 'Before' };
const older = state.reloadCase();
const newer = state.reloadCase();
second.resolve({ id: 'case-a', name: 'Newest' });
await newer;
first.resolve({ id: 'case-a', name: 'Older' });
await older;
expect(state.caseState.current).toEqual({ id: 'case-a', name: 'Newest' });
expect(state.caseState.rev).toBe(1);
});
it('opens an explicitly named detached-map case instead of the shared last case', async () => {
localStorage.setItem('azimut:lastCase', 'case-b');
api.get.mockImplementation(async (path) => {
if (path === '/api/cases/case-a') return { id: 'case-a', name: 'Case A' };
if (path === '/api/cases') return [];
if (path === '/api/workspace/folders') return [];
return {};
});
await state.initSession('case-a');
expect(state.caseState.current?.id).toBe('case-a');
expect(api.get).not.toHaveBeenCalledWith('/api/cases/case-b');
});
it('does not replace a missing explicit case with the shared last case', async () => {
localStorage.setItem('azimut:lastCase', 'case-b');
api.get.mockImplementation(async (path) => {
if (path === '/api/cases/missing') throw new Error('case not found');
if (path === '/api/cases') return [];
if (path === '/api/workspace/folders') return [];
return {};
});
await expect(state.initSession('missing')).rejects.toThrow('case not found');
expect(state.caseState.current).toBeNull();
expect(api.get).not.toHaveBeenCalledWith('/api/cases/case-b');
});
});