import { copyFile, mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import sharp from "sharp"; import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; import { AutopilotService } from "../src/autopilot/service.js"; import { bestOf, groupBursts, reportagePickCount } from "../src/autopilot/bursts.js"; import { type Candidate, actionScore, curate } from "../src/autopilot/curate.js"; import { correctionOf, fold, learntStyle, recordCorrection, styleOf } from "../src/autopilot/learning.js"; import type { Detections } from "../src/composition/compose.js"; import type { SubjectDetector } from "../src/composition/detect.js"; import type { RenderEngine, RenderJob, Settings } from "../src/develop/engine.js"; import { DevelopService } from "../src/develop/service.js"; import type { DeliveryService } from "../src/delivery/service.js"; import { IngestService } from "../src/ingest/service.js"; import { MemoryBroadcaster } from "../src/realtime.js"; import { LocalStorage, UrlSigner } from "../src/storage/storage.js"; import { bearer, createTestApp, login, resetDb, seedUser, type TestContext } from "./helpers.js"; const quiet = { info() {}, warn() {}, error() {} }; class FakeEngine implements RenderEngine { async replay(base: Settings | null, commands: unknown[]) { return { settings: { ...(base ?? {}), n: commands.length }, skipped: [], unedited: false }; } async render(job: RenderJob) { await copyFile(job.input, job.output); return { width: 600, height: 400 }; } async auto() { return { values: { "wb.temp": 5200, "wb.tint": 4, "light.exposure": 0.4, "light.contrast": 20 }, angle: 1.5 }; } async close() {} } /** A player in the middle; `focus` per photo (keyed by the sha in the preview's file name). */ class FakeDetector { readonly focus = new Map(); async detect(file: string): Promise { const sha = path.basename(file).split(".")[0]!; const focus = this.focus.get(sha) ?? 100; return { width: 600, height: 400, people: [{ x0: 0.42, y0: 0.2, x1: 0.58, y1: 0.85, score: 0.9, sharpness: 1, focus }], balls: [] }; } } describe("bursts", () => { const f = (id: string, ms: number | null, camera = "R1", score: number | null = 1) => ({ id, capturedAt: ms === null ? null : new Date(1_800_000_000_000 + ms), camera, score }); it("groups frames of one camera closer than the gap, never across cameras", () => { const bursts = groupBursts([f("a", 0), f("b", 200), f("c", 400), f("d", 5000), f("e", 300, "Z9"), f("x", null)], 1500); expect(bursts.map((b) => b.map((x) => x.id))).toEqual([["x"], ["a", "b", "c"], ["e"], ["d"]]); }); it("keeps the best frames, the earlier one on a near tie, in capture order", () => { const burst = [f("a", 0, "R1", 5), f("b", 100, "R1", 9), f("c", 200, "R1", 9.1), f("d", 300, "R1", 2)]; expect(bestOf(burst, 1).map((x) => x.id)).toEqual(["b"]); expect(bestOf(burst, 2).map((x) => x.id)).toEqual(["b", "c"]); expect(bestOf(burst, 0)).toEqual([]); }); it("keeps up to three frames of a sharp reportage sequence, and the event's number otherwise", () => { expect(reportagePickCount(4, 2)).toBe(3); expect(reportagePickCount(3, 1)).toBe(3); expect(reportagePickCount(2, 2)).toBe(2); expect(reportagePickCount(6, 5)).toBe(3); expect(reportagePickCount(8, 0)).toBe(0); }); }); describe("only the best", () => { const start = 1_800_000_000_000; const min = 60_000; let k = 0; const c = (at: number, score: number, extra: Partial = {}): Candidate => ({ id: `c${k++}`, at: start + at, burst: k, score, reason: "person", people: 1, subjectHeight: 0.5, rating: 0, rejected: false, ...extra }); it("prefers the ball, duels and big sharp subjects; never a rejected frame or an empty pitch", () => { const base = c(0, 2); expect(actionScore({ ...base, reason: "ball", people: 2 })).toBeGreaterThan(actionScore({ ...base, reason: "group", people: 2 })); expect(actionScore({ ...base, reason: "group", people: 2 })).toBeGreaterThan(actionScore(base)); expect(actionScore({ ...base, subjectHeight: 0.1 })).toBeLessThan(actionScore(base)); expect(actionScore({ ...base, rating: 4 })).toBeGreaterThan(actionScore({ ...base, reason: "ball" })); expect(actionScore({ ...base, rejected: true })).toBe(0); expect(actionScore({ ...base, reason: null })).toBe(0); }); it("spreads a gallery of the asked size over the match, carrying half-time forward, without twins", () => { // 90 minutes of play with a 15 minute break; a frame every 30 s, better ones now and then. const frames: Candidate[] = []; for (let t = -20 * min; t < 105 * min; t += 30_000) { if (t >= 45 * min && t < 60 * min) continue; frames.push(c(t, 1 + ((t / 30_000) % 7) / 3, t % (4 * min) === 0 ? { reason: "ball", people: 2 } : {})); } // A twin of a great frame, two seconds later in another burst. const great = c(20 * min, 9, { reason: "ball", people: 2 }); const twin = c(20 * min + 2_000, 8.9, { reason: "ball", people: 2 }); const rejected = c(30 * min, 20, { reason: "ball", rejected: true }); frames.push(great, twin, rejected); const opts = { count: 30, start, durationMs: 105 * min, now: start + 200 * min }; const all = curate(frames, [], opts).flatMap((d) => d.chosen); expect(all.length).toBeGreaterThanOrEqual(28); expect(all.length).toBeLessThanOrEqual(33); expect(all).toContain(great.id); expect(all).not.toContain(twin.id); expect(all).not.toContain(rejected.id); const at = new Map(frames.map((f) => [f.id, f.at - start])); // Nothing from the warm-up; both halves well represented. expect(all.every((id) => at.get(id)! >= -5 * min)).toBe(true); expect(all.filter((id) => at.get(id)! < 45 * min).length).toBeGreaterThanOrEqual(11); expect(all.filter((id) => at.get(id)! >= 60 * min).length).toBeGreaterThanOrEqual(11); // Live, window by window, it comes to the same gallery size. const decided: { id: string; chosen: boolean }[] = []; for (let now = start - 20 * min; now <= start + 200 * min; now += min) { const seen = frames.filter((f) => f.at <= now); for (const d of curate(seen, decided, { ...opts, now })) for (const id of d.ids) decided.push({ id, chosen: d.chosen.includes(id) }); } const live = decided.filter((d) => d.chosen).length; expect(Math.abs(live - all.length)).toBeLessThanOrEqual(2); }); }); describe("learning from corrections", () => { const set = (values: Record) => ({ command: "develop.set" as const, params: { values } }); const crop = (x0: number, x1: number) => ({ command: "crop.set" as const, params: { rect: { x0, y0: 0, x1, y1: 1 }, angle: 0, aspect: null } }); it("folds edits and measures what the person changed", () => { const auto = fold([set({ "light.exposure": 0.2, "wb.temp": 5200 }), crop(0.1, 0.9)]); const final = fold([set({ "light.exposure": 0.2, "wb.temp": 5200 }), crop(0.1, 0.9), set({ "light.exposure": 0.55, "wb.temp": 5500, "light.shadows": 12 }), crop(0.2, 0.8)]); expect(correctionOf(auto, final)).toEqual({ deltas: { "light.exposure": 0.35, "light.shadows": 12, "wb.temp": 300 }, cropScale: 0.75 }); // A reset is "less of everything the autopilot did" for tone; white balance says nothing then. expect(correctionOf(auto, fold([set({ "light.exposure": 0.2, "wb.temp": 5200 }), { command: "develop.reset" }]))).toEqual({ deltas: { "light.exposure": -0.2 }, cropScale: null }); // Creative extremes are not corrections. expect(correctionOf(fold([set({ "light.contrast": 10 })]), fold([set({ "light.contrast": 90 })]))).toBeNull(); }); it("keeps only what most corrections agree on", () => { const rows = [0.3, 0.25, 0.35, 0.3, -0.1].map((e, i) => ({ deltas: { "light.exposure": e, "light.contrast": i % 2 ? 8 : -8 }, cropScale: 0.7 })); const style = styleOf(rows, null); expect(style.offsets).toEqual({ "light.exposure": 0.3 }); expect(style.cropFactor).toBeCloseTo(Math.sqrt(0.7), 2); expect(styleOf(rows.slice(0, 4), null).offsets).toEqual({}); }); }); describe("autopilot", () => { let ctx: TestContext; let dir: string; let ingest: IngestService; let develop: DevelopService; let autopilot: AutopilotService; let detector: FakeDetector; const broadcaster = new MemoryBroadcaster(); beforeAll(async () => { dir = await mkdtemp(path.join(tmpdir(), "pr-autopilot-")); const ingestRoot = path.join(dir, "ingest"); ctx = await createTestApp({ STORAGE_ROOT: path.join(dir, "storage"), INGEST_ROOT: ingestRoot }, broadcaster); const storage = new LocalStorage(ctx.config.STORAGE_ROOT); const signer = new UrlSigner(ctx.config.JWT_SECRET, ctx.config.FILE_URL_TTL_SEC); const engine = new FakeEngine(); detector = new FakeDetector(); ingest = new IngestService({ db: ctx.db, storage, signer, broadcaster, ingestRoot, log: quiet }); develop = new DevelopService({ db: ctx.db, storage, signer, broadcaster, log: quiet, engine }); autopilot = new AutopilotService({ db: ctx.db, storage, broadcaster, log: quiet, develop, engine, detector: () => Promise.resolve(detector as unknown as SubjectDetector) }); }); afterAll(async () => { await ctx.app.close(); await ctx.db.$disconnect(); await rm(dir, { recursive: true, force: true }); }); beforeEach(async () => { await resetDb(ctx.db); broadcaster.sent.length = 0; }); let n = 0; async function shot(orgId: string, userId: string, eventId: string, at: number, focus: number, source: "FTP" | "UPLOAD" | "CLOUD" = "FTP") { n++; const data = await sharp({ create: { width: 600, height: 400, channels: 3, background: { r: (n * 31) % 256, g: 90, b: 120 } } }).jpeg().toBuffer(); const { createHash } = await import("node:crypto"); detector.focus.set(createHash("sha256").update(data).digest("hex"), focus); const file = path.join(dir, `IMG_${n}.JPG`); await writeFile(file, data); const out = await ingest.ingest(file, { organizationId: orgId, userId, source, originalName: `IMG_${n}.JPG`, eventId }); await ctx.db.photo.update({ where: { id: out.photoId }, data: { capturedAt: new Date(1_800_000_000_000 + at), cameraSerial: "R1-001" } }); return out.photoId; } async function setup(autopilotOn = true) { const { org, user } = await seedUser(ctx.db, "editor@fpa.pt", { org: "fpa", role: "EDITOR" }); const event = await ctx.db.event.create({ data: { organizationId: org!.id, home: "ABC", away: "CDE", startsAt: new Date("2026-10-11T14:00:00Z"), ingestFrom: new Date("2026-10-11T12:00:00Z"), ingestUntil: new Date("2026-10-11T18:00:00Z"), iptcTemplate: {}, // The original settings (half tone, white balance as shot, no look, whole bodies); the agency defaults have a test of their own. ...(autopilotOn && { autopilot: { enabled: true, picksPerBurst: 2, toneStrength: 0.5, whiteBalance: false, look: "none", framing: "full" } }), }, }); return { orgId: org!.id, userId: user.id, eventId: event.id }; } async function runQueue() { for (let ids = await autopilot.claim(10); ids.length; ids = await autopilot.claim(10)) for (const id of ids) await autopilot.process(id); } it("edits what arrives by FTP or by hand: measured tone, level, a crop around the subject; archive re-imports stay as sent", async () => { const { orgId, userId, eventId } = await setup(); const ftp = await shot(orgId, userId, eventId, 0, 300); const hand = await shot(orgId, userId, eventId, 60_000, 300, "CLOUD"); await runQueue(); const edits = await ctx.db.photoEdit.findMany({ where: { photoId: ftp }, orderBy: { seq: "asc" } }); expect(edits.map((e) => (e.command as { command: string }).command)).toEqual(["develop.set", "crop.set"]); expect(edits.every((e) => e.clientId === "autopilot")).toBe(true); // White balance stays as shot (off by default); tone at half strength. expect((edits[0]!.command as { params: { values: Record } }).params.values).toEqual({ "light.exposure": 0.2, "light.contrast": 10 }); const crop = (edits[1]!.command as { params: { rect: { x0: number; x1: number }; angle: number } }).params; expect(crop.angle).toBe(1.5); expect(crop.rect.x0).toBeLessThan(0.42); expect(crop.rect.x1).toBeGreaterThan(0.58); expect(await ctx.db.photoEdit.count({ where: { photoId: hand } })).toBe(0); expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: hand } })).autopilotStatus).toBe("NONE"); }); it("picks the sharpest frames of each burst once it has settled, never overriding a human flag", async () => { const { orgId, userId, eventId } = await setup(); const a = await shot(orgId, userId, eventId, 0, 100); const b = await shot(orgId, userId, eventId, 100, 900); const c = await shot(orgId, userId, eventId, 200, 500); const d = await shot(orgId, userId, eventId, 300, 50); const lone = await shot(orgId, userId, eventId, 10_000, 200); await ctx.db.photo.update({ where: { id: lone }, data: { flag: "REJECT" } }); await runQueue(); // Too soon: the burst may still be arriving. expect(await autopilot.decideBursts(new Date())).toBe(0); expect(await autopilot.decideBursts(new Date(Date.now() + 20_000))).toBe(2); const flags = Object.fromEntries((await ctx.db.photo.findMany({ where: { eventId } })).map((p) => [p.id, p.flag])); expect(flags).toEqual({ [a]: "NONE", [b]: "PICK", [c]: "PICK", [d]: "NONE", [lone]: "REJECT" }); // The second pick gets a tighter variant of its crop. expect(await ctx.db.photoEdit.count({ where: { photoId: c, opId: `autopilot-${c}-variant` } })).toBe(1); // Decided once: running again changes nothing. expect(await autopilot.decideBursts(new Date(Date.now() + 40_000))).toBe(0); }); it("only the best: chooses each window's game moments once the window has closed", async () => { const { eventId, orgId, userId } = await setup(); const start = new Date(1_800_000_000_000); // A gallery of 23 over 115 minutes: one photo per 5-minute window, unused ones carried forward. await ctx.db.event.update({ where: { id: eventId }, data: { startsAt: start, sport: "futebol", autopilot: { enabled: true, picksPerBurst: 2, selection: "best", bestCount: 23 } } }); const w0a = await shot(orgId, userId, eventId, 60_000, 900); const w0b = await shot(orgId, userId, eventId, 120_000, 300); const w2a = await shot(orgId, userId, eventId, 11 * 60_000, 800); const w2b = await shot(orgId, userId, eventId, 12 * 60_000, 700); const w2c = await shot(orgId, userId, eventId, 13 * 60_000, 100); await runQueue(); // Window 0 has closed (and settled), window 2 not yet. await autopilot.decideBursts(new Date(start.getTime() + 7 * 60_000)); const chosen = async () => Object.fromEntries((await ctx.db.photo.findMany({ where: { eventId } })).map((p) => [p.id, (p.autopilot as { curated?: boolean; chosen?: boolean }).curated ? !!(p.autopilot as { chosen?: boolean }).chosen : null])); expect(await chosen()).toEqual({ [w0a]: true, [w0b]: false, [w2a]: null, [w2b]: null, [w2c]: null }); // Window 2 also takes the share window 1 (no photos) did not use. await autopilot.decideBursts(new Date(start.getTime() + 17 * 60_000)); expect(await chosen()).toEqual({ [w0a]: true, [w0b]: false, [w2a]: true, [w2b]: true, [w2c]: false }); // The burst picks are still flagged for the photographer. expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: w2c } })).flag).toBe("PICK"); }); it("two clients: the gallery takes each moment's second pick, every other pick goes to the second client, never both", async () => { const { eventId, orgId, userId } = await setup(); const start = new Date(1_800_000_000_000); const record = "11111111-1111-4111-8111-111111111111"; const fap = "22222222-2222-4222-8222-222222222222"; await ctx.db.event.update({ where: { id: eventId }, data: { startsAt: start, ingestFrom: new Date(start.getTime() - 2 * 60 * 60 * 1000), ingestUntil: new Date(start.getTime() + 4 * 60 * 60 * 1000), sport: "andebol", createdById: userId, autopilot: { enabled: true, picksPerBurst: 2, selection: "best", bestCount: 16, deliverTargetId: record, restTargetId: fap }, }, }); const sent: { targetId: string; photoIds: string[] }[] = []; const deliveries = { enqueue: async (r: { targetId: string; photoIds: string[] }) => void sent.push({ targetId: r.targetId, photoIds: [...r.photoIds] }) }; const service = new AutopilotService({ db: ctx.db, storage: new LocalStorage(ctx.config.STORAGE_ROOT), broadcaster, log: quiet, develop, engine: new FakeEngine(), detector: () => Promise.resolve(detector as unknown as SubjectDetector), deliveries: deliveries as unknown as DeliveryService }); // Window 0 (one photo for the gallery): a strong burst and a weaker one. const a1 = await shot(orgId, userId, eventId, 60_000, 900); const a2 = await shot(orgId, userId, eventId, 60_100, 600); const b1 = await shot(orgId, userId, eventId, 120_000, 300); const b2 = await shot(orgId, userId, eventId, 120_100, 200); // Taken before this event's window, still filed here: not this client's folder. const later = await shot(orgId, userId, eventId, -3 * 60 * 60 * 1000, 950); for (let ids = await service.claim(10); ids.length; ids = await service.claim(10)) for (const id of ids) await service.process(id); await service.decideBursts(new Date(start.getTime() + 7 * 60_000)); const to = (target: string) => sent.filter((x) => x.targetId === target).flatMap((x) => x.photoIds); // The newspaper gets the strong moment as its second frame; the federation gets every other pick. expect(to(record)).toEqual([a2]); expect(to(fap).sort()).toEqual([a1, b1, b2].sort()); expect(to(record).filter((id) => to(fap).includes(id))).toEqual([]); expect([...to(record), ...to(fap)]).not.toContain(later); // Decided once: nothing is sent again. await service.decideBursts(new Date(start.getTime() + 8 * 60_000)); expect(to(record)).toEqual([a2]); expect(to(fap)).toHaveLength(3); }); it("never edits over a person's edit (made on the desktop app before the photo was uploaded)", async () => { const { orgId, userId, eventId } = await setup(); const photoId = await shot(orgId, userId, eventId, 0, 300); await develop.append(photoId, userId, { clientId: "offline-queue", ops: [{ opId: "mine-1", command: { command: "develop.set", params: { values: { "light.exposure": -0.5 } } } }] }); await runQueue(); const edits = await ctx.db.photoEdit.findMany({ where: { photoId } }); expect(edits.map((e) => e.clientId)).toEqual(["offline-queue"]); expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: photoId } })).autopilotStatus).toBe("DONE"); }); it("edits the agencies' way by default: neutral whites, fuller tone, the finishing look", async () => { const { orgId, userId, eventId } = await setup(); await ctx.db.event.update({ where: { id: eventId }, data: { autopilot: { enabled: true } } }); const id = await shot(orgId, userId, eventId, 0, 300); await ctx.db.photo.update({ where: { id }, data: { iso: 6400 } }); await runQueue(); const edits = await ctx.db.photoEdit.findMany({ where: { photoId: id }, orderBy: { seq: "asc" } }); const values = (edits[0]!.command as { params: { values: Record } }).params.values; // Sharpen starts at 40 and is scaled when the crop does not keep the whole frame (detailForCrop). expect(values).toMatchObject({ "wb.temp": 5200, "wb.tint": 4, "light.exposure": 0.3, "light.contrast": 15, "color.vibrance": 18, "detail.sharpenAmount": 38.5, "detail.nrLuminance": 22 }); expect(Object.keys(values).some((k) => k.startsWith("vignette."))).toBe(false); }); it("leaves events without autopilot alone", async () => { const { orgId, userId, eventId } = await setup(false); await shot(orgId, userId, eventId, 0, 100); expect(await autopilot.claim(10)).toEqual([]); }); it("learns from a photographer's corrections and edits the next photos that way", async () => { const { orgId, userId, eventId } = await setup(); await ctx.db.event.update({ where: { id: eventId }, data: { venue: "Pavilhão Flávio Sá Leite" } }); const photos: string[] = []; for (let i = 0; i < 6; i++) photos.push(await shot(orgId, userId, eventId, i * 10_000, 300)); await runQueue(); // The photographer lifts the exposure (0.2 -> 0.5) and crops tighter on five of them. for (const id of photos.slice(0, 5)) { const auto = fold((await ctx.db.photoEdit.findMany({ where: { photoId: id }, orderBy: { seq: "asc" } })).map((e) => e.command as never)); const r = auto.crop!; const shrink = (a: number, b: number) => [a + (b - a) * 0.08, b - (b - a) * 0.08] as const; const [x0, x1] = shrink(r.x0, r.x1); const [y0, y1] = shrink(r.y0, r.y1); await develop.append(id, userId, { clientId: "web-1", ops: [{ opId: `h-${id}-1`, command: { command: "develop.set", params: { values: { "light.exposure": 0.5 } } } }, { opId: `h-${id}-2`, command: { command: "crop.set", params: { rect: { x0, y0, x1, y1 }, angle: 1.5, aspect: [600, 400] } } }] }); expect(await recordCorrection(ctx.db, id)).toBe(true); } // Untouched photos and the autopilot's own edits teach nothing. expect(await recordCorrection(ctx.db, photos[5]!)).toBe(false); const style = await learntStyle(ctx.db, orgId, userId, "pavilhão flávio sá leite "); expect(style).toMatchObject({ samples: 5, venue: "pavilhão flávio sá leite", offsets: { "light.exposure": 0.3 } }); expect(style!.cropFactor).toBeCloseTo(0.84, 1); const next = await shot(orgId, userId, eventId, 100_000, 300); await runQueue(); const edits = await ctx.db.photoEdit.findMany({ where: { photoId: next }, orderBy: { seq: "asc" } }); expect((edits[0]!.command as { params: { values: Record } }).params.values).toEqual({ "light.exposure": 0.5, "light.contrast": 10 }); const before = fold((await ctx.db.photoEdit.findMany({ where: { photoId: photos[5]! }, orderBy: { seq: "asc" } })).map((e) => e.command as never)).crop!; const after = fold(edits.map((e) => e.command as never)).crop!; expect(after.x1 - after.x0).toBeLessThan(before.x1 - before.x0); expect(((await ctx.db.photo.findUniqueOrThrow({ where: { id: next } })).autopilot as { style: { samples: number } }).style.samples).toBe(5); // The photographer sees it in the app, and can make it forget. const token = (await login(ctx.app, "editor@fpa.pt")).body.accessToken; const seen = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/autopilot/style?venue=${encodeURIComponent("Pavilhão Flávio Sá Leite")}`, headers: bearer(token) }); expect(seen.json()).toMatchObject({ photographerId: userId, style: { samples: 5, offsets: { "light.exposure": 0.3 } } }); const gone = await ctx.app.inject({ method: "DELETE", url: `/v1/orgs/${orgId}/autopilot/style`, headers: bearer(token) }); expect(gone.json()).toEqual({ forgotten: 5 }); expect(await learntStyle(ctx.db, orgId, userId)).toBeNull(); }); it("tells the learner when a person (not the autopilot) edits", async () => { const { orgId, userId, eventId } = await setup(); const id = await shot(orgId, userId, eventId, 0, 300); const seen: string[] = []; const storage = new LocalStorage(ctx.config.STORAGE_ROOT); const d = new DevelopService({ db: ctx.db, storage, signer: new UrlSigner(ctx.config.JWT_SECRET, 60), broadcaster, log: quiet, onHumanEdit: (p) => seen.push(p) }); await d.append(id, userId, { clientId: "autopilot", ops: [{ opId: "a1", command: { command: "develop.set", params: { values: { "light.exposure": 0.1 } } } }] }); await d.append(id, userId, { clientId: "web-1", ops: [{ opId: "h1", command: { command: "develop.set", params: { values: { "light.exposure": 0.3 } } } }] }); await d.append(id, userId, { clientId: "web-1", ops: [{ opId: "h1", command: { command: "develop.set", params: { values: { "light.exposure": 0.3 } } } }] }); // retry: nothing new expect(seen).toEqual([id]); }); });