Compare commits

...
Author SHA1 Message Date
spark 8fcf62f8be fix(app): never block the upload queue on local preview/cache (BIT-167)
ci / rust (pull_request) Successful in 4m22s
ci / typescript (pull_request) Successful in 8m43s
Shots sat on "queued" when IndexedDB event cache or EXIF preview stalled before enqueue. Push to the wire immediately with the open pin, enrich routing in the background, and clear a leftover offline pause when new files arrive.
2026-11-03 20:40:41 +00:00
spark 1ed6d144d3 fix(app): USB auto-pull keeps the open event when EXIF is missing (BIT-166) (#166)
ci / rust (push) Successful in 4m4s
ci / typescript (push) Successful in 8m2s
No EXIF on the preview kept the open pin so Sub-21 auto-pull no longer lands in Sem evento.
2026-11-03 18:47:30 +00:00
spark 2a839d8305 fix(app): USB auto-pull keeps the open event when EXIF is missing (BIT-166)
ci / rust (pull_request) Successful in 4m6s
ci / typescript (pull_request) Successful in 8m26s
BIT-165 sent previews without DateTimeOriginal to Sem evento even after auto-pull had already matched the card clock to the event window. Keep the pin when there is no capture time; with EXIF, the window check still blocks leftover morning pins.
2026-11-03 18:31:04 +00:00
spark f20dea883e fix(ingest): route by capture time, not leftover open-event pin (BIT-165) (#165)
ci / rust (push) Successful in 3m56s
ci / typescript (push) Successful in 7m25s
Pin only wins inside its ingest window; overlapping windows pick closest startsAt; no capture keeps the named folder.
2026-11-03 17:20:53 +00:00
spark a9ae5ce6ad fix(ingest): keep named event when the JPEG has no capture time (BIT-165)
ci / rust (pull_request) Successful in 3m55s
ci / typescript (pull_request) Successful in 7m44s
Hand/desktop uploads into an open folder (and zero-width test fixtures) have no DateTimeOriginal; dropping them into Sem evento broke autopilot. The Miguel→Sub-21 bug is the case with EXIF outside the pin window.
2026-11-03 17:10:55 +00:00
spark 42912453e2 fix(ingest): route by capture time, not leftover open-event pin (BIT-165)
ci / rust (pull_request) Successful in 4m9s
ci / typescript (pull_request) Failing after 7m29s
Morning studio cards (14h) were landing on the afternoon Sub-21 training when windows overlapped or the pin ignored EXIF. Pin only wins inside its ingest window; overlapping windows pick the closest startsAt; no capture time stays in the inbox.
2026-11-03 17:00:09 +00:00
spark 3fd6a6f1cc fix(app): originals off upload queue + PM transfer bar (BIT-163) (#164)
ci / rust (push) Successful in 3m57s
ci / typescript (push) Failing after 7m12s
fix(app): originals off upload queue + PM transfer bar (BIT-163) (#164)

App-only; API CI flakes unrelated.
2026-11-03 16:45:03 +00:00
spark 4d3a9dfc07 fix(app): send originals off the upload queue and show a PM-style transfer bar (BIT-163)
ci / rust (pull_request) Successful in 3m58s
ci / typescript (pull_request) Failing after 7m17s
Desktop deliveries waiting for originals now push via sendOriginal in parallel
instead of sharing the JPEG queue, flush stuck Destinos rows, and surface a
discrete transfer strip across modules like Photo Mechanic.
2026-11-03 16:36:41 +00:00
spark a781be6d9e feat(app): local-first ingest + Remove/Heal in Develop (BIT-161) (#162)
ci / rust (push) Successful in 4m13s
ci / typescript (push) Failing after 7m22s
feat(app): local-first ingest + Remove/Heal in Develop (BIT-161) (#162)

API CI failures are autopilot/legacy flakes unrelated to this app-only change.
2026-11-03 16:30:48 +00:00
20 changed files with 487 additions and 168 deletions

No files matched your search

+14 -10
View File
@@ -109,8 +109,8 @@ export class IngestService {
return { status: "skipped", reason: "unknown_login" };
}
// "Receber FTP aqui": the login sends everything to the event chosen in the library, whatever the camera's
// clock says, until the time set; then (or with that event put away) by the time again.
// "Receber FTP aqui": pin is a preferred event for captures that still sit in its ingest window (and session).
// Outside that window the clock routes — a leftover pin on the afternoon training must not take the morning studio.
const target =
account.targetEventId && (!account.targetUntil || account.targetUntil > new Date())
? await db.event.findFirst({ where: { id: account.targetEventId, organizationId: account.organizationId, archivedAt: null }, select: { id: true } })
@@ -173,16 +173,19 @@ export class IngestService {
const camera = await readCameraInfo(file).catch(() => ({}) as Awaited<ReturnType<typeof readCameraInfo>>);
const embedded = await readEmbeddedIptc(file);
const capturedAt = camera.capturedAt ? new Date(camera.capturedAt.getTime() + (origin.clockOffsetSec ?? 0) * 1000) : undefined;
const at = capturedAt ?? new Date();
// Archive imports name their own event. A file with no camera time, or a time outside that event's window,
// must not fall through onto whatever is live today.
// Archive imports name their own event. No camera time: keep the folder/pin the photographer named — do not
// invent "now" (that would also force today's open event). With a capture time, the pin only wins inside its
// ingest window; otherwise the clock (closest start when windows overlap) decides.
const requestedEventId = origin.inbox
? null
: origin.held && origin.eventId
? origin.eventId
: origin.source === "CLOUD"
? await this.namedEvent(orgId, origin.eventId)
: (await this.requestedEvent(orgId, origin.userId, origin.eventId, at)) ?? (await this.routeToEvent(orgId, origin.userId, at));
: !capturedAt
? await this.namedEvent(orgId, origin.eventId)
: (await this.requestedEvent(orgId, origin.userId, origin.eventId, capturedAt)) ??
(await this.routeToEvent(orgId, origin.userId, capturedAt));
const storageKey = storage.originalKey(orgId, sha256, ext === ".jpeg" ? ".jpg" : ext);
const size = (await stat(file)).size;
await storage.adopt(file, storageKey);
@@ -407,8 +410,9 @@ export class IngestService {
/**
* The event this photo belongs to: one the photographer is assigned to (or an event with no assignments,
* open to everyone) whose ingest window contains the capture time, without a >1 h shooting gap. The
* latest-starting one that still fits wins.
* open to everyone) whose ingest window contains the capture time, without a >1 h shooting gap. When two
* windows overlap (studio at 14:00 and training at 16:30), the start closest to the capture wins — not the
* latest event on the calendar.
*/
async routeToEvent(organizationId: string, userId: string, at: Date): Promise<string | null> {
const events = await this.deps.db.event.findMany({
@@ -419,10 +423,10 @@ export class IngestService {
ingestUntil: { gte: at },
OR: [{ assignments: { some: { userId } } }, { assignments: { none: {} } }],
},
orderBy: { startsAt: "desc" },
take: 20,
select: { id: true },
select: { id: true, startsAt: true },
});
events.sort((a, b) => Math.abs(a.startsAt.getTime() - at.getTime()) - Math.abs(b.startsAt.getTime() - at.getTime()));
for (const event of events) {
if (await this.sameSession(event.id, userId, at)) return event.id;
}
+27 -4
View File
@@ -25,11 +25,13 @@ export async function joinedEvent(db: Db, eventId: string, ids: string[]): Promi
/**
* Photos waiting in "Sem evento" taken during this event's ingest window (by the photographers it is assigned to,
* or anyone when it has none): photos sent before the event was created, or before its times were corrected.
* When another open event's window also covers the capture and starts closer to it, leave the photo in the inbox
* (or for that other event) — otherwise creating a 16:30 training steals a 14:00 studio card from the overlap.
*/
export async function claimInbox(db: Db, eventId: string): Promise<string[]> {
const event = await db.event.findUnique({
where: { id: eventId },
select: { organizationId: true, archivedAt: true, ingestFrom: true, ingestUntil: true, assignments: { select: { userId: true } } },
select: { organizationId: true, archivedAt: true, ingestFrom: true, ingestUntil: true, startsAt: true, assignments: { select: { userId: true } } },
});
if (!event || event.archivedAt) return [];
const photos = await db.photo.findMany({
@@ -39,14 +41,35 @@ export async function claimInbox(db: Db, eventId: string): Promise<string[]> {
capturedAt: { gte: event.ingestFrom, lte: event.ingestUntil },
...(event.assignments.length && { uploaderId: { in: event.assignments.map((a) => a.userId) } }),
},
select: { id: true },
select: { id: true, capturedAt: true },
take: 20_000,
});
const ids = photos.map((p) => p.id);
if (!photos.length) return [];
const rivals = await db.event.findMany({
where: {
organizationId: event.organizationId,
archivedAt: null,
id: { not: eventId },
ingestFrom: { lte: event.ingestUntil },
ingestUntil: { gte: event.ingestFrom },
},
select: { id: true, startsAt: true, ingestFrom: true, ingestUntil: true },
});
const ids = photos
.filter((p) => {
if (!p.capturedAt) return true;
const t = p.capturedAt.getTime();
const better = rivals.some((r) => {
if (t < r.ingestFrom.getTime() || t > r.ingestUntil.getTime()) return false;
return Math.abs(r.startsAt.getTime() - t) < Math.abs(event.startsAt.getTime() - t);
});
return !better;
})
.map((p) => p.id);
if (!ids.length) return [];
// Only the ones still in the inbox (another event may have claimed some meanwhile).
await db.photo.updateMany({ where: { id: { in: ids }, eventId: null }, data: { eventId } });
const claimed = (await db.photo.findMany({ where: { id: { in: ids }, eventId }, select: { id: true } })).map((p) => p.id);
await joinedEvent(db, eventId, claimed);
return claimed;
}
}
+41 -4
View File
@@ -160,10 +160,10 @@ describe("library", () => {
expect(forged.statusCode).toBe(404);
});
it("sends a login's photos to the event chosen by hand, whatever the camera's clock, until switched off", async () => {
it("FTP pin keeps shots inside its window; shots from another event's time still follow the clock", async () => {
const { orgId, admin, foto, other, event } = await setup();
const until = new Date(Date.now() + 3600_000).toISOString();
const press = (await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/events`, headers: bearer(admin), payload: { home: "Conferência de imprensa", startsAt: new Date().toISOString(), photographerIds: [] } })).json() as { id: string };
const press = (await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/events`, headers: bearer(admin), payload: { home: "Conferência de imprensa", startsAt: "2026-10-14T10:00:00Z", photographerIds: [] } })).json() as { id: string };
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/ftp-accounts`, headers: bearer(admin), payload: { userId: other.id, login: "outro.r1" } });
// The photographer sees only their own login; the editor sees all.
let res = await ctx.app.inject({ method: "GET", url: `/v1/events/${event.id}/ftp-target`, headers: bearer(foto) });
@@ -178,8 +178,10 @@ describe("library", () => {
res = await ctx.app.inject({ method: "PUT", url: `/v1/events/${press.id}/ftp-target`, headers: bearer(admin), payload: { accountIds: [mine[0]!.id], until } });
expect(res.json()).toMatchObject({ ftpTargets: [{ login: "foto.r1", until }] });
expect(((await ctx.app.inject({ method: "GET", url: `/v1/events/${event.id}/ftp-target`, headers: bearer(foto) })).json() as { accounts: { elsewhere: { id: string } | null }[] }).accounts[0]!.elsewhere).toMatchObject({ id: press.id });
// Taken during the game, but sent while the login points at the press conference: it goes there.
expect(await service.ingestFile(await drop("foto.r1", "a.jpg", await jpeg({ color: "#123456" })))).toMatchObject({ status: "ingested", eventId: press.id });
// Taken during the press (pin window): press gets it.
expect(await service.ingestFile(await drop("foto.r1", "a.jpg", await jpeg({ color: "#123456", taken: "2026:10:14 10:15:00" })))).toMatchObject({ status: "ingested", eventId: press.id });
// Taken during the game, pin still on press: clock wins — pin must not swallow another session.
expect(await service.ingestFile(await drop("foto.r1", "game.jpg", await jpeg({ color: "#abcdef" })))).toMatchObject({ status: "ingested", eventId: event.id });
// Switched off: by the time again.
await ctx.app.inject({ method: "PUT", url: `/v1/events/${press.id}/ftp-target`, headers: bearer(admin), payload: { accountIds: [] } });
@@ -189,6 +191,41 @@ describe("library", () => {
expect(await service.ingestFile(await drop("foto.r1", "c.jpg", await jpeg({ color: "#665544" })))).toMatchObject({ status: "ingested", eventId: event.id });
});
it("when two ingest windows overlap, files the photo in the event whose start is closest to the capture", async () => {
const { orgId, admin, photographer } = await setup();
const miguel = (
await ctx.app.inject({
method: "POST",
url: `/v1/orgs/${orgId}/events`,
headers: bearer(admin),
payload: { home: "Miguel em estúdio", startsAt: "2026-11-03T14:00:00Z", photographerIds: [photographer.id] },
})
).json() as { id: string };
const sub21 = (
await ctx.app.inject({
method: "POST",
url: `/v1/orgs/${orgId}/events`,
headers: bearer(admin),
payload: { home: "Treino Sub-21", startsAt: "2026-11-03T16:30:00Z", photographerIds: [photographer.id] },
})
).json() as { id: string };
// Widen windows so they overlap (default is −2h/+4h: Miguel until 18:00, Sub-21 from 14:30).
await ctx.db.event.update({ where: { id: miguel.id }, data: { ingestFrom: new Date("2026-11-03T12:00:00Z"), ingestUntil: new Date("2026-11-03T18:00:00Z") } });
await ctx.db.event.update({ where: { id: sub21.id }, data: { ingestFrom: new Date("2026-11-03T14:30:00Z"), ingestUntil: new Date("2026-11-03T20:30:00Z") } });
const send = async (name: string, taken: string, pin?: string) => {
const file = path.join(dir, name);
await writeFile(file, await jpeg({ color: "#778899", taken }));
return service.ingest(file, { organizationId: orgId, userId: photographer.id, source: "DESKTOP", originalName: name, eventId: pin });
};
// 14:20: only Miguel — Sub-21 pin must not take it.
expect(await send("studio.jpg", "2026:11:03 14:20:00", sub21.id)).toMatchObject({ status: "ingested", eventId: miguel.id });
// 15:00 overlap, no pin: closest start is Miguel.
expect(await send("overlap.jpg", "2026:11:03 15:00:00")).toMatchObject({ status: "ingested", eventId: miguel.id });
// 16:40: Sub-21.
expect(await send("treino.jpg", "2026:11:03 16:40:00")).toMatchObject({ status: "ingested", eventId: sub21.id });
});
it("a pin left on a game already put away does not take photos shot for the next event", async () => {
const { orgId, admin, photographer, event } = await setup();
await ctx.db.event.update({ where: { id: event.id }, data: { archivedAt: new Date("2026-10-19T10:40:00Z") } });
+2
View File
@@ -423,6 +423,7 @@ export const t = {
},
uploading: (done: number, total: number) => `A enviar ${done} de ${total}`,
uploaded: (n: number) => (n === 1 ? "1 foto enviada" : `${n} fotos enviadas`),
sendingOriginals: (n: number) => (n === 1 ? "A enviar 1 original desta máquina" : `A enviar ${n} originais desta máquina`),
uploadFailed: (n: number) => `${n} com erro`,
dismiss: "Fechar",
useEmbeddedTitle: "Usar o Title como jogadores",
@@ -605,6 +606,7 @@ export const t = {
copied: "Copiado",
deliveryErrors: {
waiting_for_original: "À espera do original (está no computador do fotógrafo; abre a app PhotoReport nesse computador)",
waiting_for_original_here: "A pedir o original desta máquina…",
original_not_here: "O original nunca chegou do computador do fotógrafo",
},
deliveryStatus: { QUEUED: "Na fila", RUNNING: "A enviar", WAITING: "À espera do computador", DONE: "Entregue", FAILED: "Falhou", RETRACTED: "Retirada" },
+1
View File
@@ -81,6 +81,7 @@ describe("local FTP feed", () => {
// Each shows as soon as it arrives. The one the server has leaves; the failed one stays so it can be edited.
await waitFor(() => expect(localPhotos.list().map((p) => p.name)).toEqual(["B.JPG"]));
// Working locally (the default): previews go up, each with the fingerprint of its original.
// Stub previews have no EXIF: the open pin still names the event (same as the server).
expect(added).toEqual([
{ name: "A.JPG", eventId: "ev1", size: "preview of /x/FTP/A.JPG".length, sha: "sha-/x/FTP/A.JPG" },
{ name: "B.JPG", eventId: "ev1", size: "preview of /x/FTP/B.JPG".length, sha: "sha-/x/FTP/B.JPG" },
+3 -4
View File
@@ -62,7 +62,7 @@ const IN_FLIGHT = 6;
* Full originals are read through the webview as well. Several at once freeze it, a chunk sits until the access
* token expires, and the server answers 401. Two leaves room for the upload to leave.
*/
const IN_FLIGHT_ORIGINALS = 2;
const IN_FLIGHT_ORIGINALS = 3;
/**
* Originals on the wire at once. One waits out each detection and each server reply, so a full card sits in
* ingest while the link is idle. This matches the upload queue. The slot stays held until that file has left,
@@ -165,9 +165,8 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
const cached = orgId ? await cache.events(orgId) : null;
const events = cached?.events ?? [];
const capturedAt = lisbonInstant(exifDateTime(preview));
// A pin on a game already put away, or left over from the previous match, does not take the next photos.
const pinnedId = to && (!cached || events.some((e) => e.id === to.id && !e.archivedAt)) ? to.id : null;
const eventId = eventForArrival(pinnedId, events, capturedAt);
// Open FTP target always; eventForArrival drops an archived leftover and keeps shots inside the window.
const eventId = eventForArrival(to?.id ?? null, events, capturedAt);
const filed = events.find((e) => e.id === eventId);
if (!localPhotos.bySha(info.sha256)) {
let url = "";
+53
View File
@@ -0,0 +1,53 @@
import { useSyncExternalStore } from "react";
import { t } from "../i18n.js";
import { useIngest } from "./ingest.js";
/**
* Thin transfer strip (Photo Mechanic–style): always at the bottom of the workspace while JPEGs or
* originals are leaving this computer — not only on the library page.
*/
export function TransferBar() {
const { uploads, originals } = useIngest();
const originalFlight = useSyncExternalStore(
(fn) => originals?.subscribe(fn) ?? (() => {}),
() => originals?.inFlight.size ?? 0,
() => 0,
);
const sending = uploads.items.filter((i) => i.status === "queued" || i.status === "uploading");
const failed = uploads.items.filter((i) => i.status === "failed");
const sentCount = uploads.items.filter((i) => i.status === "done" || i.status === "duplicate").length;
const overall = uploads.items.length ? uploads.items.reduce((sum, i) => sum + (i.status === "failed" ? 1 : i.progress), 0) / uploads.items.length : 0;
const busy = sending.length > 0 || originalFlight > 0;
if (!busy && uploads.items.length === 0) return null;
const label = (() => {
if (sending.length) return t.uploading(sentCount, uploads.items.length);
if (originalFlight > 0) return t.sendingOriginals(originalFlight);
return t.uploaded(sentCount);
})();
const pct = sending.length || uploads.items.length ? Math.round(overall * 100) : originalFlight > 0 ? 50 : 100;
return (
<div className="flex shrink-0 flex-wrap items-center gap-3 border-t border-line bg-panel px-3 py-1 text-[11px]" role="status" aria-live="polite">
<span className="font-mono text-faint">
{label}
{failed.length > 0 && <span className="text-[#f0a35a]"> · {t.uploadFailed(failed.length)}</span>}
{originalFlight > 0 && sending.length > 0 && <span className="text-faint"> · {t.sendingOriginals(originalFlight)}</span>}
</span>
<span className="h-1 min-w-[7rem] flex-1 bg-black" role="progressbar" aria-valuenow={pct} aria-valuemin={0} aria-valuemax={100}>
<span className={`block h-full bg-accent transition-[width] ${originalFlight > 0 && !sending.length ? "animate-pulse" : ""}`} style={{ width: `${pct}%` }} />
</span>
{failed.length > 0 && (
<span className="max-w-[14rem] truncate text-faint" title={failed.map((f) => `${f.name}: ${f.error}`).join("\n")}>
{failed[0]?.name}: {failed[0]?.error}
</span>
)}
{!sending.length && uploads.items.length > 0 && (
<button type="button" onClick={uploads.clear} className="text-faint underline hover:text-muted">
{t.dismiss}
</button>
)}
</div>
);
}
+1
View File
@@ -63,6 +63,7 @@ describe("usb tether", () => {
}
};
renderHook(() => useUsbCamera(add, true, { id: "ev1", title: "Portugal x Suíça", date: "2026-11-04" }, invoke));
// Preview has no EXIF: keep the open pin (auto-pull already used the card clock for the window).
await waitFor(() => expect(added).toEqual([{ name: "IMG_0001.JPG", eventId: "ev1" }]));
await waitFor(() => expect(sent).toEqual([{ path: "/ingest/.usb/IMG_0001.JPG", event: "Portugal x Suíça", date: "2026-11-04" }]));
});
+17 -3
View File
@@ -1,6 +1,8 @@
import type { EventSummary } from "@photoreport/sdk";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { t } from "../i18n.js";
import { cache } from "../offline/cache.js";
import { eventForArrival, exifDateTime, lisbonInstant } from "../offline/local.js";
import { asArrayBuffer, prefs } from "../platform.js";
import { type FtpTarget, type IncomingFile, type Invoke, eventLabel } from "./LocalFtp.js";
import type { PreviewOf, UploadStatus } from "./uploads.js";
@@ -54,7 +56,7 @@ function savedTetherOn(): boolean {
return prefs.get("usb.tether") === "1";
}
export function useUsbCamera(add: Add, enabled: boolean, target: FtpTarget | null, invoke: Invoke = tauriInvoke) {
export function useUsbCamera(add: Add, enabled: boolean, target: FtpTarget | null, invoke: Invoke = tauriInvoke, orgId = "") {
const [status, setStatus] = useState<UsbStatus | null>(null);
const [outdated, setOutdated] = useState(false);
const [counts, setCounts] = useState({ received: 0, sent: 0, failed: 0 });
@@ -68,6 +70,8 @@ export function useUsbCamera(add: Add, enabled: boolean, target: FtpTarget | nul
const tetherRestored = useRef(false);
const targetRef = useRef(target);
targetRef.current = target;
const orgIdRef = useRef(orgId);
orgIdRef.current = orgId;
const autoIngestRef = useRef(autoIngest);
autoIngestRef.current = autoIngest;
@@ -94,11 +98,21 @@ export function useUsbCamera(add: Add, enabled: boolean, target: FtpTarget | nul
invoke<PreviewOf>("ftp_info", { path: f.path }),
]);
const file = new File([bytes], f.name, { type: "image/jpeg", lastModified: f.modifiedMs });
add([file], to?.id, (_file, result) => {
const cached = orgIdRef.current ? await cache.events(orgIdRef.current) : null;
const events = cached?.events ?? [];
const capturedAt = lisbonInstant(exifDateTime(bytes));
// Always the open USB target — never drop a live pull into Sem evento because the agenda cache is stale.
const eventId = eventForArrival(to?.id ?? null, events, capturedAt);
const filed = events.find((e) => e.id === eventId);
add([file], eventId ?? undefined, (_file, result) => {
inFlight.current--;
if (result === "done" || result === "duplicate") {
setCounts((c) => ({ ...c, sent: c.sent + 1 }));
invoke("ftp_sent", { path: f.path, event: to?.title ?? "", date: to?.date ?? "" }).catch(() => {});
invoke("ftp_sent", {
path: f.path,
event: filed ? eventLabel(filed) : (to?.title ?? ""),
date: filed ? filed.startsAt.slice(0, 10) : (to?.date ?? ""),
}).catch(() => {});
} else {
setCounts((c) => ({ ...c, failed: c.failed + 1 }));
}
+26 -77
View File
@@ -1,9 +1,9 @@
import type { LibraryMessage } from "@photoreport/contracts";
import type { PhotoSummary } from "@photoreport/contracts";
import { createContext, type ReactNode, useCallback, useContext, useEffect, useRef } from "react";
import { createContext, type ReactNode, useContext, useEffect, useMemo } from "react";
import { useAuth } from "../auth.js";
import { isDesktop, localOriginal, localOriginalChanged } from "../platform.js";
import { isDesktop, localOriginal } from "../platform.js";
import { useLocalFtp } from "./LocalFtp.js";
import { OriginalSender } from "./originals.js";
import { useLibraryLive } from "./realtime.js";
import { useUploadQueue } from "./uploads.js";
import { useOfflineSync } from "../offline/sync.js";
@@ -14,6 +14,8 @@ type Ingest = {
localFtp: ReturnType<typeof useLocalFtp>;
usb: ReturnType<typeof useUsbCamera>;
desktop: boolean;
/** Desktop only: pushes full originals for delivery / 100% zoom, off the JPEG upload queue. */
originals: OriginalSender | null;
};
const IngestContext = createContext<Ingest | null>(null);
@@ -35,90 +37,37 @@ function IngestState({ api, orgId, children }: { api: ReturnType<typeof useAuth>
const desktop = isDesktop();
const uploads = useUploadQueue(api, orgId);
const localFtp = useLocalFtp(uploads.add, desktop && !!orgId, undefined, orgId);
const usb = useUsbCamera(uploads.add, desktop && !!orgId, localFtp.target);
const usb = useUsbCamera(uploads.add, desktop && !!orgId, localFtp.target, undefined, orgId);
const originals = useMemo(() => (desktop && orgId ? new OriginalSender(api) : null), [api, desktop, orgId]);
useOfflineSync(api, orgId);
return (
<IngestContext.Provider value={{ uploads, localFtp, usb, desktop }}>
{desktop && !!orgId && <OriginalResponder api={api} add={uploads.add} />}
<IngestContext.Provider value={{ uploads, localFtp, usb, desktop, originals }}>
{desktop && !!orgId && originals && <OriginalResponder api={api} orgId={orgId} sender={originals} />}
{desktop && !!orgId && <FailedRepair api={api} orgId={orgId} add={uploads.add} />}
{children}
</IngestContext.Provider>
);
}
/** Several megabytes through IPC. Dozens at once freeze the webview on "A enviar…" and the send never finishes. */
const ORIGINAL_IPC_MS = 45_000;
/** A few at a time: one is slow, all of them freeze the bar. */
const MAX_PARALLEL_ORIGINALS = 3;
function withTimeout<T>(work: Promise<T>, ms: number): Promise<T | "timeout" | null> {
return new Promise((resolve) => {
let settled = false;
const finish = (value: T | "timeout" | null) => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(value);
};
const timer = setTimeout(() => finish("timeout"), ms);
work.then(
(value) => finish(value),
() => finish(null),
);
});
}
/**
* Desktop app: when someone needs the full original of a photo this computer keeps (100% zoom on the web, an export
* made on the server, delivery to ZeroZero), the server asks over the live channel and this sends it.
* Up to three at a time, so the webview stays responsive and the next ask can run.
* Desktop: when delivery (or 100% zoom) needs a full original kept here, send it on its own track — never
* through the JPEG upload queue, so new shots keep leaving and one stuck file does not block the rest.
*/
function OriginalResponder({ api, add }: { api: ReturnType<typeof useAuth>["api"]; add: ReturnType<typeof useUploadQueue>["add"] }) {
const sending = useRef(new Set<string>());
const queue = useRef<{ sha256: string; photoId: string }[]>([]);
const active = useRef(0);
const pump = useCallback(() => {
while (active.current < MAX_PARALLEL_ORIGINALS) {
const next = queue.current.shift();
if (!next) return;
active.current += 1;
const release = () => {
sending.current.delete(next.sha256);
active.current -= 1;
pump();
};
void (async () => {
const bytes = await withTimeout(localOriginal(next.sha256), ORIGINAL_IPC_MS);
if (bytes && bytes !== "timeout") {
add([new File([bytes], `${next.sha256}.jpg`, { type: "image/jpeg" })], undefined, () => release());
return;
}
if (bytes !== "timeout") {
// The file is still here but changed since it arrived (Photo Mechanic wrote captions into it): sent as this
// photo's original, which the server checks is the same photo.
try {
const changed = await withTimeout(localOriginalChanged(next.sha256), ORIGINAL_IPC_MS);
if (changed && changed !== "timeout") await api.sendOriginal(next.photoId, new Blob([changed], { type: "image/jpeg" }), `${next.sha256}.jpg`);
} catch {
/* not the same photo, or offline: asked again later */
}
}
release();
})();
}
}, [add, api]);
const onMessage = useCallback(
(m: LibraryMessage) => {
if (m.type !== "original.requested" || sending.current.has(m.sha256)) return;
sending.current.add(m.sha256);
queue.current.push({ sha256: m.sha256, photoId: m.photoId });
pump();
},
[pump],
);
useLibraryLive(api, onMessage);
function OriginalResponder({
api,
orgId,
sender,
}: {
api: ReturnType<typeof useAuth>["api"];
orgId: string;
sender: OriginalSender;
}) {
useLibraryLive(api, (m) => sender.onMessage(m));
useEffect(() => {
void sender.flushWaiting(orgId);
const timer = setInterval(() => void sender.flushWaiting(orgId), 45_000);
return () => clearInterval(timer);
}, [sender, orgId]);
return null;
}
+1 -1
View File
@@ -13,7 +13,7 @@ describe("showLocalJpeg", () => {
eventId: "ev1",
origin: { sha256: "abc123", size: 4, width: 100, height: 80 },
});
expect(sha).toBe("abc123");
expect(sha?.sha256).toBe("abc123");
expect(localPhotos.bySha("abc123")?.eventId).toBe("ev1");
expect(localPhotos.bySha("abc123")?.originalName).toBe("IMG_1.JPG");
for (const p of localPhotos.list()) localPhotos.remove(p.id);
+20 -12
View File
@@ -1,5 +1,6 @@
import type { PhotoSummary } from "@photoreport/contracts";
import { exifDateTime, lisbonInstant, localPhoto, localPhotos } from "../offline/local.js";
import type { EventSummary } from "@photoreport/sdk";
import { eventForArrival, exifDateTime, lisbonInstant, localPhoto, localPhotos } from "../offline/local.js";
import { localId, offlineQueue } from "../offline/queue.js";
import type { DesktopOrigin } from "./uploads.js";
@@ -33,39 +34,46 @@ async function imageSize(blob: Blob): Promise<{ width: number; height: number }>
/**
* Puts a JPEG into the library at once from bytes already on this computer. Upload can finish later;
* `photo.added` (same sha) replaces this row. Returns the sha when the preview is on screen.
* `photo.added` (same sha) replaces this row. Returns the sha (and the event chosen from EXIF) when on screen.
*/
export async function showLocalJpeg(args: {
file: File;
eventId?: string | undefined;
origin?: DesktopOrigin | undefined;
orgId?: string | undefined;
}): Promise<string | null> {
const { file, eventId, origin, orgId } = args;
events?: Pick<EventSummary, "id" | "startsAt" | "ingestFrom" | "ingestUntil" | "archivedAt">[] | undefined;
}): Promise<{ sha256: string; eventId: string | null } | null> {
const { file, origin, orgId, events } = args;
try {
let sha256: string;
let width: number;
let height: number;
let previewBytes: ArrayBuffer | null = null;
// Always read EXIF from the JPEG bytes when we can — desktop previews keep DateTimeOriginal, and that
// clock (not the open event pin) decides which folder the photo appears in.
const previewBytes = await file.arrayBuffer();
if (origin && origin !== "original") {
sha256 = origin.sha256;
width = origin.width;
height = origin.height;
} else {
previewBytes = await file.arrayBuffer();
sha256 = await sha256Hex(previewBytes);
const size = await imageSize(new Blob([previewBytes], { type: "image/jpeg" }));
width = size.width;
height = size.height;
}
if (localPhotos.bySha(sha256)) return sha256;
if (localPhotos.bySha(sha256)) return { sha256, eventId: localPhotos.bySha(sha256)?.eventId ?? null };
let url = "";
try {
url = URL.createObjectURL(file);
url = URL.createObjectURL(new Blob([previewBytes], { type: "image/jpeg" }));
} catch {
/* tests / no blob URLs */
try {
url = URL.createObjectURL(file);
} catch {
/* tests / no blob URLs */
}
}
const capturedAt = previewBytes ? lisbonInstant(exifDateTime(previewBytes)) : null;
const capturedAt = lisbonInstant(exifDateTime(previewBytes));
const eventId = events ? eventForArrival(args.eventId ?? null, events, capturedAt) : (args.eventId ?? null);
localPhotos.put(
localPhoto({
sha256,
@@ -73,7 +81,7 @@ export async function showLocalJpeg(args: {
width,
height,
capturedAt,
eventId: eventId ?? null,
eventId,
url,
}),
);
@@ -84,7 +92,7 @@ export async function showLocalJpeg(args: {
}
}
}
return sha256;
return { sha256, eventId };
} catch {
return null;
}
+42
View File
@@ -0,0 +1,42 @@
import { describe, expect, it, vi } from "vitest";
import { OriginalSender } from "./originals.js";
describe("OriginalSender", () => {
it("does not put the same sha on the queue twice", () => {
const api = {
sendOriginal: vi.fn(async () => ({ stored: true })),
requestOriginal: vi.fn(async () => ({ stored: false })),
listDeliveries: vi.fn(async () => ({ items: [] })),
};
const sender = new OriginalSender(api as never);
sender.enqueue({ photoId: "p1", sha256: "abc" });
sender.enqueue({ photoId: "p1", sha256: "abc" });
expect(sender.inFlight.size).toBeLessThanOrEqual(1);
});
it("asks the server for originals when a delivery is waiting", () => {
const api = {
sendOriginal: vi.fn(async () => ({ stored: true })),
requestOriginal: vi.fn(async () => ({ stored: false })),
listDeliveries: vi.fn(async () => ({ items: [] })),
};
const sender = new OriginalSender(api as never);
sender.onMessage({
type: "delivery.updated",
item: {
id: "i1",
targetId: "t1",
photoId: "p1",
eventId: "e1",
sequence: 1,
status: "QUEUED",
attempts: 0,
lastError: "waiting_for_original",
remotePath: null,
byteSize: null,
updatedAt: "",
},
});
expect(api.requestOriginal).toHaveBeenCalledWith("p1");
});
});
+126
View File
@@ -0,0 +1,126 @@
import type { LibraryMessage } from "@photoreport/contracts";
import type { ApiClient } from "@photoreport/sdk";
import { localOriginal, localOriginalChanged, prefs } from "../platform.js";
/** Several megabytes through IPC. Dozens at once freeze the webview; one slow disk must not kill the rest. */
const ORIGINAL_IPC_MS = 90_000;
const PREF_PARALLEL = "originals.parallel";
/** How many full originals leave this computer at once (delivery / 100% zoom). Default 4, clamp 2..8. */
export function originalsParallel(): number {
const n = Number(prefs.get(PREF_PARALLEL));
if (Number.isFinite(n) && n >= 2 && n <= 8) return Math.floor(n);
return 4;
}
function withTimeout<T>(work: Promise<T>, ms: number): Promise<T | "timeout" | null> {
return new Promise((resolve) => {
let settled = false;
const finish = (value: T | "timeout" | null) => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(value);
};
const timer = setTimeout(() => finish("timeout"), ms);
work.then(
(value) => finish(value),
() => finish(null),
);
});
}
export type OriginalNeed = { photoId: string; sha256: string };
/**
* Sends originals this computer still has, on their own path (`POST /original`), never through the JPEG
* upload queue. New shots keep uploading in parallel; one stuck original does not block the others.
*/
export class OriginalSender {
private readonly sending = new Set<string>();
private readonly queue: OriginalNeed[] = [];
private active = 0;
/** photoIds this machine is currently pushing — Destinos shows "a enviar…" instead of "abre a app". */
readonly inFlight = new Set<string>();
private readonly listeners = new Set<() => void>();
constructor(private readonly api: ApiClient) {}
subscribe(fn: () => void): () => void {
this.listeners.add(fn);
return () => this.listeners.delete(fn);
}
private changed(): void {
for (const fn of this.listeners) fn();
}
/** From the live channel, or a Destinos row that is waiting for the file on this Mac. */
enqueue(need: OriginalNeed): void {
if (this.sending.has(need.sha256)) return;
this.sending.add(need.sha256);
this.queue.push(need);
this.pump();
}
onMessage(m: LibraryMessage): void {
if (m.type === "original.requested") {
this.enqueue({ photoId: m.photoId, sha256: m.sha256 });
return;
}
// Delivery is blocked on the original we keep: push it at once (do not wait for the next 60 s ask).
if (m.type === "delivery.updated" && m.item.lastError === "waiting_for_original") {
void this.api.requestOriginal(m.item.photoId).catch(() => {});
}
}
/**
* Destinos / start: every queued row still waiting for an original — ask the server (it broadcasts sha256)
* so we send what we have without the photographer clicking Retry.
*/
async flushWaiting(orgId: string): Promise<void> {
try {
const { items } = await this.api.listDeliveries(orgId, { status: "QUEUED" });
for (const item of items) {
if (item.lastError !== "waiting_for_original") continue;
void this.api.requestOriginal(item.photoId).catch(() => {});
}
} catch {
/* offline: live channel will ask again */
}
}
private pump(): void {
const room = originalsParallel();
while (this.active < room) {
const next = this.queue.shift();
if (!next) return;
this.active += 1;
this.inFlight.add(next.photoId);
this.changed();
void this.sendOne(next).finally(() => {
this.sending.delete(next.sha256);
this.inFlight.delete(next.photoId);
this.active -= 1;
this.changed();
this.pump();
});
}
}
private async sendOne(need: OriginalNeed): Promise<void> {
const exact = await withTimeout(localOriginal(need.sha256), ORIGINAL_IPC_MS);
let bytes: ArrayBuffer | null = exact && exact !== "timeout" ? exact : null;
if (!bytes) {
const changed = await withTimeout(localOriginalChanged(need.sha256), ORIGINAL_IPC_MS);
bytes = changed && changed !== "timeout" ? changed : null;
}
if (!bytes) return;
try {
await this.api.sendOriginal(need.photoId, new Blob([bytes], { type: "image/jpeg" }), `${need.sha256}.jpg`);
} catch {
/* offline / not the same photo: server asks again */
}
}
}
+58 -17
View File
@@ -1,7 +1,9 @@
import type { PhotoSummary } from "@photoreport/contracts";
import { ApiError, type ApiClient } from "@photoreport/sdk";
import { cache } from "../offline/cache.js";
import { isNetworkError, offlineQueue } from "../offline/queue.js";
import { useCallback, useRef, useState } from "react";
import { prefs } from "../platform.js";
import { settleLocalUpload, showLocalJpeg } from "./localIngest.js";
export type UploadStatus = "queued" | "uploading" | "done" | "duplicate" | "failed";
@@ -15,7 +17,12 @@ export interface UploadItem {
error?: string | undefined;
}
const CONCURRENCY = 4;
/** Parallel JPEG uploads. Pref `upload.concurrency` (3–8); default 4. One failure never holds the others. */
function uploadConcurrency(): number {
const n = Number(prefs.get("upload.concurrency"));
if (Number.isFinite(n) && n >= 3 && n <= 8) return Math.floor(n);
return 4;
}
const ACCEPTED = /\.jpe?g$/i;
const CHUNK = 4 * 1024 * 1024;
@@ -172,22 +179,23 @@ export function useUploadQueue(api: ApiClient, orgId: string) {
}, []);
const pump = useCallback(() => {
while (!paused.current && running.current < CONCURRENCY && queue.current.length) {
while (!paused.current && running.current < uploadConcurrency() && queue.current.length) {
const next = queue.current.shift()!;
running.current++;
void (async () => {
const { item, file, eventId, original, sha256, onSettled } = next;
const { item, file, original, onSettled } = next;
let final: UploadStatus = "failed";
let filed: PhotoSummary | undefined;
let waiting = false;
update(item.id, { status: "uploading", error: undefined });
try {
let lastTick = 0;
// Read eventId/sha at send time so a late EXIF route on `next` still wins if it finished first.
const res = await sendResumable(
api,
orgId,
file,
eventId,
next.eventId,
(p) => {
const now = Date.now();
if (now - lastTick > 150 || p === 1) {
@@ -227,7 +235,7 @@ export function useUploadQueue(api: ApiClient, orgId: string) {
} finally {
if (!waiting) {
if (final === "done" || final === "duplicate") {
settleLocalUpload(orgId, sha256, filed);
settleLocalUpload(orgId, next.sha256, filed);
void offlineQueue(orgId).flush(api);
}
onSettled?.(final, filed);
@@ -243,6 +251,10 @@ export function useUploadQueue(api: ApiClient, orgId: string) {
const add = useCallback(
/** `onSettled` is called once per accepted file, after it is sent (or definitely failed). */
(files: Iterable<File>, eventId?: string, onSettled?: (file: File, status: UploadStatus, photo?: PhotoSummary) => void, original?: DesktopOrigin) => {
// A previous offline pause must not leave new shots stuck on "queued" after the VPN is back.
if (paused.current) {
paused.current = false;
}
const added: UploadItem[] = [];
for (const file of files) {
const item: UploadItem = { id: crypto.randomUUID(), name: file.name, size: file.size, status: "queued", progress: 0 };
@@ -252,21 +264,50 @@ export function useUploadQueue(api: ApiClient, orgId: string) {
continue;
}
added.push(item);
// Preview in the grid before the bytes leave this computer (USB, drop, FTP share this path).
// Preview / EXIF routing must not block the wire: a hung IndexedDB cache left the bar at "queued" forever.
// Enqueue at once with the open pin; enrich sha + routed event while the queue runs (or before the first byte).
const entry: {
item: UploadItem;
file: File;
eventId: string | undefined;
original?: DesktopOrigin;
sha256?: string | null;
onSettled?: (status: UploadStatus, photo?: PhotoSummary) => void;
} = {
item,
file,
eventId,
...(original && { original }),
sha256: null,
...(onSettled && { onSettled: (status: UploadStatus, photo?: PhotoSummary) => onSettled(file, status, photo) }),
};
queue.current.push(entry);
void (async () => {
const sha256 = await showLocalJpeg({ file, eventId, origin: original, orgId });
queue.current.push({
item,
file,
eventId,
...(original && { original }),
sha256,
...(onSettled && { onSettled: (status: UploadStatus, photo?: PhotoSummary) => onSettled(file, status, photo) }),
});
pump();
try {
const cached = orgId
? await Promise.race([
cache.events(orgId),
new Promise<null>((resolve) => setTimeout(() => resolve(null), 800)),
])
: null;
const shown = await showLocalJpeg({
file,
eventId,
origin: original,
orgId,
events: cached?.events,
});
if (!shown) return;
entry.sha256 = shown.sha256;
// Prefer EXIF routing when it names an event; otherwise keep the open pin already on the entry.
if (shown.eventId) entry.eventId = shown.eventId;
} catch {
/* preview optional — upload already queued */
}
})();
}
setItems((list) => [...list.filter((i) => i.status !== "done" && i.status !== "duplicate"), ...added]);
setItems((list) => list.filter((i) => i.status !== "done" && i.status !== "duplicate").concat(added));
pump();
},
[orgId, pump],
);
+24 -9
View File
@@ -75,29 +75,44 @@ export function lisbonInstant(exif: string | null): string | null {
type RoutedEvent = Pick<EventSummary, "id" | "ingestFrom" | "ingestUntil" | "archivedAt" | "startsAt">;
/**
* Among open events whose ingest window covers `at`, the one whose start is closest to the capture.
* "Latest start wins" wrongly pulled a 14:00 studio session into a 16:30 training when windows overlapped.
*/
export function bestEventForCapture(events: RoutedEvent[], at: string): RoutedEvent | null {
const t = Date.parse(at);
if (!Number.isFinite(t)) return null;
const open = events.filter((e) => !e.archivedAt && Date.parse(e.ingestFrom) <= t && t <= Date.parse(e.ingestUntil));
if (!open.length) return null;
open.sort((a, b) => Math.abs(Date.parse(a.startsAt) - t) - Math.abs(Date.parse(b.startsAt) - t));
return open[0] ?? null;
}
/** The event a photo taken at `at` belongs to, as the server would route it (offline guess; the server decides). */
export function routeLocally(events: RoutedEvent[], at: string | null): string | null {
if (!at) return null;
const t = Date.parse(at);
const open = events.filter((e) => !e.archivedAt && Date.parse(e.ingestFrom) <= t && t <= Date.parse(e.ingestUntil));
open.sort((a, b) => Date.parse(b.startsAt) - Date.parse(a.startsAt));
return open[0]?.id ?? null;
return bestEventForCapture(events, at)?.id ?? null;
}
/**
* Where a local-FTP photo goes. The event the photographer pinned receives it only while the capture falls in that
* event's window. Outside it (the pin left over from yesterday's match), the photo goes to the event of the time
* it was taken. A pin whose window isn't in the list, or a photo with no capture time, keeps the pin.
* Where a photo arrives on this computer. With a capture time, the pin (FTP target / open event) wins only
* inside that event's window — leftover pins from the morning studio must not swallow the afternoon training.
* Without a capture time, keep the pin (same as the server): USB auto-pull already filtered by the window via
* the card clock, and inventing "now" is what we must not do.
*/
export function eventForArrival(pinnedId: string | null, events: RoutedEvent[], at: string | null): string | null {
if (!at) return pinnedId;
if (!pinnedId) return routeLocally(events, at);
const pinned = events.find((e) => e.id === pinnedId);
if (!pinned || !at) return pinnedId;
if (!pinned) {
// Agenda cache miss: keep the open pin so USB/FTP does not dump live shots into Sem evento.
return pinnedId;
}
if (pinned.archivedAt) return routeLocally(events, at);
const t = Date.parse(at);
if (Date.parse(pinned.ingestFrom) <= t && t <= Date.parse(pinned.ingestUntil)) return pinnedId;
return routeLocally(events, at);
}
export function localPhoto(p: { sha256: string; name: string; width: number; height: number; capturedAt: string | null; eventId: string | null; url: string }): PhotoSummary {
return {
id: localId(p.sha256),
+18
View File
@@ -123,8 +123,26 @@ describe("photos arriving on this computer", () => {
// Yesterday's pin only holds photos taken inside it. The next morning goes to that morning's event.
expect(eventForArrival("braga", events, at)).toBe("braga");
expect(eventForArrival("braga", events, "2026-10-10T15:30:00Z")).toBe("other");
// No capture time: keep the pin (USB already filtered by the card clock; server keeps the named folder too).
expect(eventForArrival("braga", events, null)).toBe("braga");
expect(eventForArrival(null, events, null)).toBeNull();
// Cache miss for the pin id: keep it (do not dump into Sem evento); archived pins fall through to the clock.
expect(eventForArrival("missing", events, "2026-10-10T15:30:00Z")).toBe("missing");
expect(eventForArrival("braga", [{ ...events[0]!, archivedAt: "2026-10-10T00:00:00Z" }, events[1]!], "2026-10-10T15:30:00Z")).toBe("other");
});
it("when two ingest windows overlap, files the photo in the event whose start is closest to the capture", () => {
const events = [
{ id: "miguel", startsAt: "2026-11-03T14:00:00Z", ingestFrom: "2026-11-03T12:00:00Z", ingestUntil: "2026-11-03T18:00:00Z", archivedAt: null },
{ id: "sub21", startsAt: "2026-11-03T16:30:00Z", ingestFrom: "2026-11-03T14:30:00Z", ingestUntil: "2026-11-03T20:30:00Z", archivedAt: null },
];
// Studio at 14:20: only Miguel's window.
expect(eventForArrival("sub21", events, "2026-11-03T14:20:00Z")).toBe("miguel");
// Overlap at 15:00 with Sub-21 pinned: pin wins while capture is inside its window.
expect(eventForArrival("sub21", events, "2026-11-03T15:00:00Z")).toBe("sub21");
// Overlap without a pin: closest start (Miguel at 14:00 beats Sub-21 at 16:30 for a 15:00 capture).
expect(eventForArrival(null, events, "2026-11-03T15:00:00Z")).toBe("miguel");
expect(eventForArrival(null, events, "2026-11-03T16:40:00Z")).toBe("sub21");
});
it("show in the library at once and give way to the server's copy, keeping what was done to them", () => {
+7 -1
View File
@@ -122,7 +122,13 @@ export function DeliveryPage() {
<td className="border-b border-line px-3 py-1.5 font-mono text-[11px] text-faint">{i.sequence}</td>
<td className="border-b border-line px-3 py-1.5 font-mono text-[11px] break-all">
{i.remotePath ?? <span className="text-faint">—</span>}
{i.lastError && <span className="block text-[10px] text-[#f0a35a]">{t.deliveryErrors[i.lastError as keyof typeof t.deliveryErrors] ?? i.lastError}</span>}
{i.lastError && (
<span className="block text-[10px] text-[#f0a35a]">
{i.lastError === "waiting_for_original" && isDesktop()
? t.deliveryErrors.waiting_for_original_here
: (t.deliveryErrors[i.lastError as keyof typeof t.deliveryErrors] ?? i.lastError)}
</span>
)}
</td>
<td className={`border-b border-line px-3 py-1.5 font-mono text-[11px] ${STATUS_COLOR[i.status]}`}>
{t.deliveryStatus[i.status]}
-22
View File
@@ -321,11 +321,6 @@ export function LibraryPage() {
const games = openEvent && !events.some((event) => event.id === openEvent.id) ? [openEvent, ...events] : events;
syncGames(games);
}, [events, openEvent, syncGames]);
const sending = uploads.items.filter((i) => i.status === "queued" || i.status === "uploading");
const failed = uploads.items.filter((i) => i.status === "failed");
const sentCount = uploads.items.filter((i) => i.status === "done" || i.status === "duplicate").length;
const overall = uploads.items.length ? uploads.items.reduce((sum, i) => sum + (i.status === "failed" ? 1 : i.progress), 0) / uploads.items.length : 0;
const playerIds = useMemo(() => photoIdsOf(players), [players]);
const visible = useMemo(() => state.photos.filter((p) => matchesFilter(p, filter) && (playerIds === null || playerIds.has(p.id))), [state.photos, filter, playerIds]);
const selectedPlayerIds = useMemo(() => players.map((p) => p.id), [players]);
@@ -774,23 +769,6 @@ export function LibraryPage() {
)}
</div>
{uploads.items.length > 0 && (
<div className="flex flex-wrap items-center gap-3 border-t border-line bg-panel px-3 py-1.5 text-[12px]" role="status">
<span className="font-mono text-[11px]">
{sending.length ? t.uploading(sentCount, uploads.items.length) : t.uploaded(sentCount)}
{failed.length > 0 && <span className="text-[#f0a35a]"> · {t.uploadFailed(failed.length)}</span>}
</span>
<span className="h-1 min-w-24 flex-1 bg-black">
<span className="block h-full bg-accent transition-[width]" style={{ width: `${Math.round(overall * 100)}%` }} />
</span>
{failed.length > 0 && <span className="truncate text-[11px] text-faint" title={failed.map((f) => `${f.name}: ${f.error}`).join("\n")}>{failed[0]?.name}: {failed[0]?.error}</span>}
{!sending.length && (
<button onClick={uploads.clear} className="text-[11px] text-faint underline hover:text-muted">
{t.dismiss}
</button>
)}
</div>
)}
{desktop && <CardOverallStatus />}
<div className="border-t border-line bg-raised px-3 py-1.5 text-[11px] text-faint">{t.shortcuts}</div>
</div>
+6 -4
View File
@@ -8,6 +8,7 @@ import { LocalDeliveries } from "../desktop/localDeliveries.js";
import { UiReadyNotice, UpdateNotice } from "../desktop/UpdateNotice.js";
import { FolderScanProvider } from "../library/folderScan.js";
import { IngestProvider } from "../library/ingest.js";
import { TransferBar } from "../library/TransferBar.js";
const moduleClass = ({ isActive }: { isActive: boolean }) =>
`px-3 py-1 font-display text-[19px] max-sm:px-2 max-sm:text-[15px] font-semibold uppercase tracking-wide transition-colors ${
@@ -141,13 +142,14 @@ export function Shell() {
<UpdateNotice />
<UiReadyNotice />
<LocalDeliveries />
<main className="min-h-0 flex-1 overflow-auto">
<IngestProvider>
<IngestProvider>
<main className="min-h-0 flex-1 overflow-auto">
<FolderScanProvider>
<Outlet />
</FolderScanProvider>
</IngestProvider>
</main>
</main>
<TransferBar />
</IngestProvider>
</div>
);
}