Split each burst across the autopilot's destinations
ci / rust (push) Successful in 3m53s
ci / typescript (push) Successful in 9m23s

One different frame per destination, rotation when a sequence is short, and an optional copy or camera original.
This commit was merged in pull request #316.
This commit is contained in:
spark committed 2026-11-29 16:07:13 +00:00
commit d165996046
7 files changed
+405 -30

No files matched your search

+54 -13
View File
@@ -29,7 +29,7 @@ import {
import { curate, matchMinutes } from "./curate.js";
import { type LearntStyle, learntStyle } from "./learning.js";
import { detailForCrop, lookValues } from "./look.js";
import { exportTargets, galleryReceivers, MELHORES_GAP_MS, picksNeeded, type GalleryExport } from "./targets.js";
import { assignBurstExports, exportSlots, exportTargets, galleryReceivers, MELHORES_GAP_MS, picksNeeded, type BurstExportSlot, type GalleryExport } from "./targets.js";
const STALE_RUNNING_MS = 10 * 60_000;
/** A burst is decided once no new frame of it has arrived for this long. */
@@ -282,7 +282,18 @@ export class AutopilotService {
const score = rec?.score == null ? null : rec.score * (look.get(p.id) ?? 1);
return { ...p, rec, camera: p.cameraSerial ?? p.cameraModel ?? p.uploaderId ?? "?", score };
});
for (const burst of groupBursts(frames, settings.burstGapSec * 1000)) {
const orderedBursts = groupBursts(frames, settings.burstGapSec * 1000);
const sentByTarget = new Map<string, number>();
if (settings.deliverExports.length > 0) {
const sentRows = await db.deliveryItem.groupBy({
by: ["targetId"],
where: { eventId, status: { in: ["QUEUED", "RUNNING", "WAITING", "DONE"] } },
_count: true,
});
for (const row of sentRows) sentByTarget.set(row.targetId, row._count);
}
for (let burstIndex = 0; burstIndex < orderedBursts.length; burstIndex++) {
const burst = orderedBursts[burstIndex]!;
if (burst.every((f) => f.rec?.decided)) continue;
// Still arriving: wait until the burst has settled.
if (Math.max(...burst.map((f) => f.createdAt.getTime())) > now.getTime() - BURST_SETTLE_MS) continue;
@@ -301,7 +312,8 @@ export class AutopilotService {
// between frames) is still that sequence. A frame that looks different may add another, up to four.
let take = asked;
if (!reportage) {
take = Math.min(asked, Math.max(0, settings.picksPerBurst));
const cap = settings.deliverExports.length > 0 ? settings.deliverExports.length : settings.picksPerBurst;
take = Math.min(asked, Math.max(0, cap));
}
const start = Math.min(...burst.map((f) => (f.capturedAt ?? f.createdAt).getTime()));
const sameCamera = frames
@@ -323,13 +335,16 @@ export class AutopilotService {
});
if (already.length > 0) {
const next = bestOf(pool, 1)[0];
const room = next
? sequenceSendRoom(settings.picksPerBurst, already.map((frame) => frame.look), {
subject: next.rec?.subject ?? null,
people: next.rec?.people ?? null,
reason: next.rec?.reason ?? null,
})
: 0;
let sequenceCap = settings.picksPerBurst;
if (settings.deliverExports.length > 0) sequenceCap = settings.deliverExports.length;
let room = 0;
if (next) {
room = sequenceSendRoom(sequenceCap, already.map((frame) => frame.look), {
subject: next.rec?.subject ?? null,
people: next.rec?.people ?? null,
reason: next.rec?.reason ?? null,
});
}
take = Math.min(take, room);
}
const chosen = bestOf(pool, take)
@@ -408,11 +423,37 @@ export class AutopilotService {
await db.photo.update({ where: { id: f.id }, data: { autopilot: { ...(f.rec ?? {}), decided: true, picked: pickedIds.has(f.id) } as object } });
}
// "Only the best" delivers per window of the match instead (below), not every burst's picks.
// N exports → rank i of this burst to export i (same file never to two).
const targets = exportTargets(settings);
if (settings.selection === "bursts" && targets.length && best.length && this.deps.deliveries && event.createdById) {
// One different frame per destination still under its total. A copy (Direto → Arquivo) shares the frame.
const slots: BurstExportSlot[] = exportSlots(settings).map((slot) => ({
...slot,
sent: sentByTarget.get(slot.targetId) ?? 0,
}));
if (settings.selection === "bursts" && settings.deliverExports.length > 0 && slots.length && best.length && this.deps.deliveries && event.createdById) {
const when = new Map(photos.map((p) => [p.id, p.capturedAt]));
const sendable = best.filter((f) => f.rec?.hold !== "ball" && takenHere([f.id], when, event).length);
const plan = assignBurstExports(slots, burstIndex, sendable.length);
for (const assignment of plan) {
const frame = sendable[assignment.rank];
if (!frame) continue;
const targets = [assignment.targetId, ...assignment.alsoTargetIds];
for (const targetId of targets) {
await this.deps.deliveries
.enqueue({
organizationId: event.organizationId,
targetId,
photoIds: [frame.id],
again: false,
originals: assignment.originals,
requestedById: event.createdById,
})
.catch((err: unknown) => log.warn({ err, targetId }, "autopilot: delivery not queued"));
}
sentByTarget.set(assignment.targetId, (sentByTarget.get(assignment.targetId) ?? 0) + 1);
}
} else if (settings.selection === "bursts" && slots.length && best.length && this.deps.deliveries && event.createdById) {
const when = new Map(photos.map((p) => [p.id, p.capturedAt]));
const sendable = best.filter((f) => f.rec?.hold !== "ball" && takenHere([f.id], when, event).length);
const targets = exportTargets(settings);
for (let i = 0; i < targets.length && i < sendable.length; i++) {
const id = sendable[i]!.id;
await this.deps.deliveries
+88
View File
@@ -22,8 +22,96 @@ export function exportTargets(settings: Pick<AutopilotSettings, "deliverTargetId
return out;
}
export interface BurstExportSlot {
targetId: string;
alsoTargetIds: string[];
/** Null: this destination stays in every burst. */
count: number | null;
originals: boolean;
/** Photos already queued or delivered to `targetId` in this event. */
sent: number;
}
export interface BurstAssignment {
targetId: string;
alsoTargetIds: string[];
originals: boolean;
/** Index into the burst's ranked frames. 0 is the best available. */
rank: number;
}
/** The configured exports, or one slot per legacy destination when that list is empty. */
export function exportSlots(
settings: Pick<AutopilotSettings, "deliverExports" | "deliverTargetIds" | "deliverTargetId" | "restTargetId">,
): Omit<BurstExportSlot, "sent">[] {
const configured = settings.deliverExports ?? [];
if (configured.length) {
const seen = new Set<string>();
const slots: Omit<BurstExportSlot, "sent">[] = [];
for (const row of configured) {
if (!row.targetId || seen.has(row.targetId)) continue;
seen.add(row.targetId);
const also: string[] = [];
for (const id of row.alsoTargetIds) {
if (!id || id === row.targetId || seen.has(id)) continue;
seen.add(id);
also.push(id);
}
slots.push({
targetId: row.targetId,
alsoTargetIds: also,
count: row.count,
originals: row.originals,
});
}
return slots;
}
return exportTargets(settings).map((targetId) => ({
targetId,
alsoTargetIds: [],
count: null,
originals: false,
}));
}
/**
* One different frame per destination that is still under its total. A short burst starts at the next
* destination, so the frames that do exist rotate and every total can still be met. A destination that
* already has its `count` is skipped. `alsoTargetIds` ride with that frame and do not take another one.
*/
export function assignBurstExports(slots: readonly BurstExportSlot[], burstIndex: number, frameCount: number): BurstAssignment[] {
if (frameCount <= 0 || slots.length === 0) return [];
const open: { slot: BurstExportSlot; order: number }[] = [];
for (let order = 0; order < slots.length; order++) {
const slot = slots[order]!;
if (slot.count !== null && slot.sent >= slot.count) continue;
open.push({ slot, order });
}
if (open.length === 0) return [];
const start = burstIndex % slots.length;
open.sort((left, right) => {
const leftTurn = (left.order - start + slots.length) % slots.length;
const rightTurn = (right.order - start + slots.length) % slots.length;
return leftTurn - rightTurn;
});
const take = Math.min(open.length, frameCount);
const assigned: BurstAssignment[] = [];
for (let rank = 0; rank < take; rank++) {
const slot = open[rank]!.slot;
assigned.push({
targetId: slot.targetId,
alsoTargetIds: slot.alsoTargetIds,
originals: slot.originals,
rank,
});
}
return assigned;
}
/** How many frames of a burst to keep: one per configured export, else `picksPerBurst`. */
export function picksNeeded(settings: AutopilotSettings): number {
const configured = settings.deliverExports?.length ?? 0;
if (configured > 0) return Math.min(10, configured);
const n = exportTargets(settings).length;
if (n > 0) return Math.min(5, Math.max(1, n));
return settings.picksPerBurst;
+57 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { AutopilotSettings } from "@photoreport/contracts";
import { exportTargets, galleryReceivers, picksNeeded } from "../src/autopilot/targets.js";
import { assignBurstExports, exportSlots, exportTargets, galleryReceivers, picksNeeded, type BurstExportSlot } from "../src/autopilot/targets.js";
const a = "11111111-1111-4111-8111-111111111111";
const b = "22222222-2222-4222-8222-222222222222";
@@ -17,6 +17,62 @@ describe("exportTargets", () => {
});
});
function slot(targetId: string, extra: Partial<BurstExportSlot> = {}): BurstExportSlot {
return {
targetId,
alsoTargetIds: [],
count: null,
originals: false,
sent: 0,
...extra,
};
}
describe("exportSlots", () => {
it("keeps a copy on the same frame and out of the pick list", () => {
const settings = AutopilotSettings.parse({
enabled: true,
deliverExports: [
{ targetId: a, alsoTargetIds: [b], count: 50, originals: false },
{ targetId: c, alsoTargetIds: [], count: null, originals: true },
],
});
expect(exportSlots(settings)).toEqual([
{ targetId: a, alsoTargetIds: [b], count: 50, originals: false },
{ targetId: c, alsoTargetIds: [], count: null, originals: true },
]);
});
});
describe("assignBurstExports", () => {
const three = [slot(a), slot(b), slot(c)];
it("gives one different frame to each destination when the burst has enough", () => {
expect(assignBurstExports(three, 0, 3).map((row) => row.targetId)).toEqual([a, b, c]);
});
it("rotates the only frame so a short burst does not always feed the first destination", () => {
expect(assignBurstExports(three, 0, 1).map((row) => row.targetId)).toEqual([a]);
expect(assignBurstExports(three, 1, 1).map((row) => row.targetId)).toEqual([b]);
expect(assignBurstExports(three, 2, 1).map((row) => row.targetId)).toEqual([c]);
expect(assignBurstExports(three, 3, 1).map((row) => row.targetId)).toEqual([a]);
});
it("stops a destination that already has its total and keeps filling the others", () => {
const slots = [slot(a, { count: 20, sent: 20 }), slot(b, { count: 80, sent: 20 }), slot(c)];
expect(assignBurstExports(slots, 0, 2).map((row) => row.targetId)).toEqual([b, c]);
});
it("sends the same frame's copy alongside, without taking a second frame", () => {
const slots = [slot(a, { alsoTargetIds: [b] }), slot(c)];
const plan = assignBurstExports(slots, 0, 2);
expect(plan).toEqual([
{ targetId: a, alsoTargetIds: [b], originals: false, rank: 0 },
{ targetId: c, alsoTargetIds: [], originals: false, rank: 1 },
]);
});
});
describe("picksNeeded", () => {
it("matches the number of exports when set", () => {
const s = AutopilotSettings.parse({ enabled: true, deliverTargetIds: [a, b, c] });
+8
View File
@@ -578,6 +578,14 @@ export const t = {
noPicks: "Não escolher",
minLongEdge: "Resolução mínima do recorte",
deliver: "Enviar as escolhidas para",
exportAdd: "Acrescentar envio",
exportRemove: "Tirar",
exportAlso: "A mesma foto também para",
exportCount: "Total neste jogo",
exportOriginals: "Originais, sem edição",
exportHelp:
"Há tantos escolhidos por sequência quantos os envios: uma foto diferente para cada um. Se a sequência não chegar para todos, a que houver vai rodando, para no fim cada destino chegar ao total que pediste. Vazio nesse total: uma por sequência, até ao fim. «Também para» manda a mesma foto aos dois (Cofina Direto e Cofina Arquivo) e não conta como outra escolha. Originais sai o ficheiro da câmara, sem o recorte nem o tom.",
exportPlayers: "Um destino com «Esperar pelas caras» sai com os jogadores no ficheiro. Se os nomes chegarem depois, o ficheiro volta a ser enviado.",
noDelivery: "Não enviar",
selection: "O que enviar",
selectionBursts: "As escolhidas de cada sequência",
+170 -15
View File
@@ -4,6 +4,153 @@ import { useEffect, useState } from "react";
import { t } from "../i18n.js";
import { ZerozeroGamePicker } from "./ZerozeroGame.js";
type ExportRow = AutopilotSettings["deliverExports"][number];
/** As many burst exports as the photographer lists. One frame each; a copy shares that frame. */
function BurstExports(props: {
settings: AutopilotSettings;
targets: DeliveryTarget[];
canEdit: boolean;
onChange: (next: AutopilotSettings) => void;
}) {
const L = t.autopilot;
const rows = props.settings.deliverExports;
const used = new Set<string>();
for (const row of rows) {
used.add(row.targetId);
for (const id of row.alsoTargetIds) used.add(id);
}
const commit = (nextRows: ExportRow[]) => {
const primaries: string[] = [];
for (const row of nextRows) primaries.push(row.targetId);
props.onChange({
...props.settings,
deliverExports: nextRows,
deliverTargetIds: primaries,
deliverTargetId: primaries[0] ?? null,
});
};
const update = (index: number, row: ExportRow) => {
const next = rows.map((item) => ({ ...item, alsoTargetIds: [...item.alsoTargetIds] }));
next[index] = row;
commit(next);
};
const add = () => {
let free = "";
for (const target of props.targets) {
if (!used.has(target.id)) {
free = target.id;
break;
}
}
if (!free) return;
commit([...rows, { targetId: free, alsoTargetIds: [], count: null, originals: false }]);
};
const remove = (index: number) => {
commit(rows.filter((_, i) => i !== index));
};
return (
<div className="space-y-2">
<p className="text-faint">{L.exportHelp}</p>
{rows.map((row, index) => {
const also = row.alsoTargetIds[0] ?? "";
return (
<div key={`${row.targetId}-${index}`} className="space-y-1 border border-line p-1.5">
<label className="flex items-center justify-between gap-2">
<span>{index + 1}</span>
<span className="flex items-center gap-1">
<select
className="h-6 max-w-[160px] border border-black bg-cell px-1"
disabled={!props.canEdit}
value={row.targetId}
onChange={(e) => {
const value = e.target.value;
if (!value) return;
const alsoIds = row.alsoTargetIds.filter((id) => id !== value);
update(index, { ...row, targetId: value, alsoTargetIds: alsoIds });
}}
>
{props.targets.map((target) => {
if (used.has(target.id) && target.id !== row.targetId && target.id !== also) return null;
return (
<option key={target.id} value={target.id}>
{target.name}
</option>
);
})}
</select>
<button type="button" className="text-faint hover:text-ink" disabled={!props.canEdit} onClick={() => remove(index)}>
{L.exportRemove}
</button>
</span>
</label>
<label className="flex items-center justify-between gap-2">
<span className="text-faint">{L.exportAlso}</span>
<select
className="h-6 max-w-[160px] border border-black bg-cell px-1"
disabled={!props.canEdit}
value={also}
onChange={(e) => {
const value = e.target.value;
if (!value) update(index, { ...row, alsoTargetIds: [] });
else update(index, { ...row, alsoTargetIds: [value] });
}}
>
<option value="">{L.noDelivery}</option>
{props.targets.map((target) => {
if (target.id === row.targetId) return null;
if (used.has(target.id) && target.id !== also) return null;
return (
<option key={target.id} value={target.id}>
{target.name}
</option>
);
})}
</select>
</label>
<label className="flex items-center justify-between gap-2">
<span className="text-faint">{L.exportCount}</span>
<input
type="number"
min={1}
max={2000}
disabled={!props.canEdit}
value={row.count ?? ""}
placeholder="—"
onChange={(e) => {
const raw = e.target.value.trim();
let count: number | null = null;
if (raw) count = Math.max(1, Math.min(2000, Number(raw) || 1));
update(index, { ...row, count });
}}
className="h-6 w-20 border border-black bg-[#161617] px-1 text-ink"
/>
</label>
<label className="flex items-center gap-2">
<input
type="checkbox"
disabled={!props.canEdit}
checked={row.originals}
onChange={(e) => update(index, { ...row, originals: e.target.checked })}
/>
<span>{L.exportOriginals}</span>
</label>
</div>
);
})}
<button type="button" className="pr-quiet" disabled={!props.canEdit || used.size >= props.targets.length} onClick={add}>
{L.exportAdd}
</button>
<p className="text-faint">{L.exportPlayers}</p>
</div>
);
}
/**
* Autopilot for the open event (docs/photo-editing-rules.md): photos arriving by FTP or the desktop app's ingest
* are edited (tone, level, crop) and the best frames of each burst picked, and optionally delivered.
@@ -30,9 +177,12 @@ export function AutopilotButton(props: {
}, [props.autopilotAsk, props.event.id, props.onAsked]);
const save = async (next: AutopilotSettings) => {
// Keep deliverTargetIds in sync with the two legacy slots (N exports = ordered list).
const ids = [next.deliverTargetId, next.restTargetId].filter((x): x is string => !!x);
const synced = { ...next, deliverTargetIds: ids.length ? ids : next.deliverTargetIds ?? [] };
// Burst groups already name every destination. The two legacy slots must not wipe that list.
let synced = next;
if (next.selection !== "bursts" || next.deliverExports.length === 0) {
const ids = [next.deliverTargetId, next.restTargetId].filter((x): x is string => !!x);
if (ids.length > 0) synced = { ...next, deliverTargetIds: ids };
}
setS(synced);
setState("saving");
try {
@@ -59,7 +209,7 @@ export function AutopilotButton(props: {
{L.button}
</button>
{open && (
<div className="absolute right-0 top-7 z-30 w-[360px] space-y-3 border border-black bg-panel p-3 text-[12px] shadow-xl" role="dialog" aria-label={L.button}>
<div className="absolute right-0 top-7 z-30 w-[420px] space-y-3 border border-black bg-panel p-3 text-[12px] shadow-xl" role="dialog" aria-label={L.button}>
<label className="flex items-center justify-between gap-2">
<span className="font-semibold uppercase tracking-wide text-ink">{L.button}</span>
<input type="checkbox" disabled={!props.canEdit} checked={s.enabled} onChange={(e) => void save({ ...s, enabled: e.target.checked })} aria-label={L.enable} />
@@ -110,17 +260,22 @@ export function AutopilotButton(props: {
))}
</select>
</label>
<label className="flex items-center justify-between gap-2">
<span>{L.deliver}</span>
<select className="h-6 max-w-[180px] border border-black bg-cell px-1" disabled={!s.enabled || !props.canEdit} value={s.deliverTargetId ?? ""} onChange={(e) => void save({ ...s, deliverTargetId: e.target.value || null })}>
<option value="">{L.noDelivery}</option>
{props.targets.map((x) => (
<option key={x.id} value={x.id}>
{x.name}
</option>
))}
</select>
</label>
{s.selection === "bursts" && (
<BurstExports settings={s} targets={props.targets} canEdit={props.canEdit && s.enabled} onChange={(next) => void save(next)} />
)}
{s.selection !== "bursts" && (
<label className="flex items-center justify-between gap-2">
<span>{L.deliver}</span>
<select className="h-6 max-w-[180px] border border-black bg-cell px-1" disabled={!s.enabled || !props.canEdit} value={s.deliverTargetId ?? ""} onChange={(e) => void save({ ...s, deliverTargetId: e.target.value || null })}>
<option value="">{L.noDelivery}</option>
{props.targets.map((x) => (
<option key={x.id} value={x.id}>
{x.name}
</option>
))}
</select>
</label>
)}
<label className="flex items-center justify-between gap-2">
<span>{L.selection}</span>
<select className="h-6 max-w-[180px] border border-black bg-cell px-1" disabled={!s.enabled || !props.canEdit} value={s.selection} onChange={(e) => void save({ ...s, selection: e.target.value as AutopilotSettings["selection"] })}>
+12 -1
View File
@@ -14,6 +14,17 @@ import { kv } from "./kv.js";
import { localPhotos } from "./local.js";
import { localId, offlineQueue } from "./queue.js";
/** One pick per export group, otherwise the event's own number. Matches the server. */
function picksFor(settings: AutopilotSettings): number {
if (settings.deliverExports.length > 0) {
return Math.min(10, settings.deliverExports.length);
}
if (settings.deliverTargetIds.length > 0) {
return Math.min(5, settings.deliverTargetIds.length);
}
return settings.picksPerBurst;
}
/** Same settle window as the server: a burst is decided once no new frame has arrived for this long. */
const BURST_SETTLE_MS = 15_000;
const PENDING_KEY = (orgId: string, eventId: string) => `autopilot:pending:${orgId}:${eventId}`;
@@ -98,7 +109,7 @@ export async function planLocalAutopilot(args: {
const pending = await loadPending(args.orgId, args.event.id);
const next = [...pending.filter((f) => f.sha256 !== frame.sha256), frame];
await savePending(args.orgId, args.event.id, next);
scheduleSettle(args.orgId, args.event.id, settings.picksPerBurst, settings.burstGapSec * 1000);
scheduleSettle(args.orgId, args.event.id, picksFor(settings), settings.burstGapSec * 1000);
}
const timers = new Map<string, ReturnType<typeof setTimeout>>();
+16
View File
@@ -61,6 +61,22 @@ export const AutopilotSettings = z.object({
* legacy pair below. Empty: use `deliverTargetId` / `restTargetId` when set.
*/
deliverTargetIds: z.array(z.string().uuid()).max(10).default([]),
/**
* One frame of each burst per row. `alsoTargetIds` receive that same frame (Cofina Direto and Arquivo) and
* are not a separate pick. `count` is how many photos that destination takes over the match (null: no cap).
* `originals`: the camera file, without the develop render. Empty: `deliverTargetIds`, one destination each.
*/
deliverExports: z
.array(
z.object({
targetId: z.string().uuid(),
alsoTargetIds: z.array(z.string().uuid()).max(4).default([]),
count: z.number().int().min(1).max(2000).nullable().default(null),
originals: z.boolean().default(false),
}),
)
.max(10)
.default([]),
/** Legacy first export (null: don't). Kept for older clients; folded into `deliverTargetIds` when that is empty. */
deliverTargetId: z.string().uuid().nullable().default(null),
/**