Files
photoanalyzer/frontend/js/api.js
domverse 457dd5bd90 US02-06: Deliver Workflow, Safety, Library, Analysis, and Stats Views
Ports the safety review and the Photo Analyzer Library/Analyze/Stats
experiences onto the shared API + service layer, and adds the Workflow
home, enforcing the pipeline gates and the one-mutating-job policy.

Backend
- migration 0005 + models: safety_reviews (append-only, latest row is the
  current decision) and analysis_results (donor photos schema re-keyed to
  asset_id).
- SafetyService: persist scores/decisions, review queue with filters, and
  the EXIF safety checkpoint (mutually-exclusive sfw/nsfw keyword written,
  read back, current_sha256 refreshed) that upload eligibility depends on.
- AnalysisService: the privacy gate — the vision provider is called ONLY for
  canonical, confirmed-SFW assets; nsfw/undecided are recorded skipped without
  a request. Provider is an injected adapter (real OpenAI-compatible Gemini
  call extracted from photo_analyzer.analyze_image; a fake in tests).
- LibraryService: Library search + Stats read model ported from webapp/query.py
  (LIKE search in place of FTS5; facets, top tags, years, albums, people).
- WorkflowService + GET /api/v1/workflow: per-stage readiness derived from the
  source tables — counts, blockers, last-run, action, and an active_job that
  drives read-only-during-jobs. Safety scoring and analysis run as durable jobs
  under the library_write lock via new domain handlers, so a second mutating
  job is refused.
- routes: workflow, safety (queue/counts/decisions/jobs), analysis
  (counts/results/jobs), library (assets/facets/stats).

Frontend
- five views (frontend/js/views.js) on the US02-05 shell: Workflow stepper
  (status text+icon, not colour alone; actions disabled with a reason while a
  job runs), Safety review (filter tabs, decide, persists across reload),
  Library (search + cards), Analyze (counts + live job log via the SSE
  adapter), Stats. Shared DOM helpers extracted to dom.js; Workflow is the home
  route.

Tests
- integration: provider-call privacy (nsfw never reaches the provider),
  sfw→nsfw flip drops analysis eligibility, decision persistence, one-mutating-
  job rejection, workflow counts, and the exiftool safety-keyword write/verify.
- e2e: Workflow cards, actions disabled+explained during a job, safety
  decide-persists-across-reload, Library search, Stats, Analyze counts.
- traceability map updated for US02-05 and US02-06.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-06 16:52:01 +02:00

83 lines
3.5 KiB
JavaScript

// Single API client: one place for fetch, JSON, the error envelope, and request
// cancellation. Every method accepts an optional { signal } from cancellable().
export const BASE = "/api/v1";
async function request(path, { signal, ...options } = {}) {
let response;
try {
response = await fetch(BASE + path, {
headers: { "Content-Type": "application/json" },
signal,
...options,
});
} catch (error) {
// A caller-cancelled fetch is not a failure; tag it so views can ignore it.
if (error.name === "AbortError") {
error.code = "cancelled";
}
throw error;
}
let body = null;
try {
body = await response.json();
} catch (_) {
body = null;
}
if (!response.ok) {
const envelope = body && body.error ? body.error : {};
const error = new Error(envelope.message || response.statusText);
error.status = response.status;
error.code = envelope.code || "error";
throw error;
}
return body;
}
// Cancellation: hand callers a signal to pass into any request and a cancel() to
// abort the in-flight fetch. Aborted requests reject with code "cancelled".
export function cancellable() {
const controller = new AbortController();
return { signal: controller.signal, cancel: () => controller.abort() };
}
export const api = {
listAssets: (params = {}, opts = {}) =>
request("/inventory/assets?" + new URLSearchParams(params).toString(), opts),
listClusters: (params = {}, opts = {}) =>
request("/duplicates/clusters?" + new URLSearchParams(params).toString(), opts),
getCluster: (id, opts = {}) =>
request(`/duplicates/clusters/${encodeURIComponent(id)}`, opts),
decide: (id, payload, opts = {}) =>
request(`/duplicates/clusters/${encodeURIComponent(id)}/decision`, {
method: "POST",
body: JSON.stringify(payload),
...opts,
}),
thumbnailUrl: (assetId, size = 512) =>
`${BASE}/assets/${encodeURIComponent(assetId)}/thumbnail?size=${size}`,
// ── Jobs ────────────────────────────────────────────────────────────────
startJob: (payload, opts = {}) =>
request("/jobs", { method: "POST", body: JSON.stringify(payload), ...opts }),
getJob: (id, opts = {}) => request(`/jobs/${encodeURIComponent(id)}`, opts),
cancelJob: (id, opts = {}) =>
request(`/jobs/${encodeURIComponent(id)}/cancel`, { method: "POST", ...opts }),
jobEvents: (id, after = 0, opts = {}) =>
request(`/jobs/${encodeURIComponent(id)}/events?after=${after}`, opts),
jobEventsStreamUrl: (id, after = 0) =>
`${BASE}/jobs/${encodeURIComponent(id)}/events/stream?after=${after}`,
// ── Workflow / safety / analysis / library ──────────────────────────────
workflow: (opts = {}) => request("/workflow", opts),
safetyQueue: (params = {}, opts = {}) =>
request("/safety/queue?" + new URLSearchParams(params).toString(), opts),
safetyDecide: (payload, opts = {}) =>
request("/safety/decisions", { method: "POST", body: JSON.stringify(payload), ...opts }),
safetyScoreJob: (opts = {}) => request("/safety/jobs", { method: "POST", ...opts }),
analysisCounts: (opts = {}) => request("/analysis/counts", opts),
analysisJob: (opts = {}) => request("/analysis/jobs", { method: "POST", ...opts }),
libraryAssets: (params = {}, opts = {}) =>
request("/library/assets?" + new URLSearchParams(params).toString(), opts),
libraryStats: (opts = {}) => request("/library/stats", opts),
};