From 7363753082f2b10b168b6616060afe24bb7c3b96 Mon Sep 17 00:00:00 2001 From: spark Date: Mon, 19 Oct 2026 17:03:47 +0100 Subject: [PATCH] Show and edit photos from this computer when the network is slow. A failed upload was dropping the local preview, and Revelar waited on the server before opening. The preview now stays on screen, and the next photo does not wait for the upload. --- apps/app/src/develop/session.test.ts | 25 ++++++++- apps/app/src/develop/session.ts | 71 ++++++++++++++++++-------- apps/app/src/library/LocalFtp.test.tsx | 5 +- apps/app/src/library/LocalFtp.tsx | 65 +++++++++++++++++++---- apps/app/src/pages/DevelopPage.tsx | 4 ++ apps/app/src/pages/LibraryPage.tsx | 36 ++++++++++--- 6 files changed, 166 insertions(+), 40 deletions(-) diff --git a/apps/app/src/develop/session.test.ts b/apps/app/src/develop/session.test.ts index 56a682e..b811dc8 100644 --- a/apps/app/src/develop/session.test.ts +++ b/apps/app/src/develop/session.test.ts @@ -1,6 +1,6 @@ import type { DevelopState, EditCommand, EditLogEntry, PostEdits } from "@photoreport/contracts"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { DevelopSession, type OutboxStore, type PendingOp, type SettingsEngine } from "./session.js"; +import { DevelopSession, type OutboxStore, type PendingOp, type SettingsEngine, type StateStore } from "./session.js"; /** Settings as a flat map of control values; enough to check ordering, undo and sync. */ const engine: SettingsEngine = { @@ -132,4 +132,27 @@ describe("DevelopSession", () => { expect(web.value("light.whites")).toBe(5); expect(web.seq).toBe(3); }); + + it("opens on the last state when the server does not answer", async () => { + server.developState = () => new Promise(() => {}); + const states: StateStore = { + get: async () => ({ settings: JSON.stringify({ "light.exposure": 0.4 }), seq: 2 }), + set: () => {}, + }; + const s = new DevelopSession("p", { + engine, + api: server, + clientId: "web", + states, + isOffline: (err) => err instanceof Error && /timeout|offline/i.test(err.message), + }); + const loading = s.load(); + await vi.advanceTimersByTimeAsync(0); + expect(s.loaded).toBe(true); + expect(s.value("light.exposure")).toBe(0.4); + await vi.advanceTimersByTimeAsync(8_000); + await loading; + expect(s.offline).toBe(true); + expect(s.value("light.exposure")).toBe(0.4); + }); }); diff --git a/apps/app/src/develop/session.ts b/apps/app/src/develop/session.ts index e4b66a8..61d4eca 100644 --- a/apps/app/src/develop/session.ts +++ b/apps/app/src/develop/session.ts @@ -43,6 +43,24 @@ interface Step { const SEND_DELAY_MS = 120; const RETRY_MAX_MS = 30_000; +/** A venue link can sit open without answering. Revelar opens on the last state instead of waiting on it. */ +const OPEN_WAIT_MS = 8_000; + +function answerOrGiveUp(work: Promise, ms: number): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error("timeout")), ms); + work.then( + (value) => { + clearTimeout(timer); + resolve(value); + }, + (err: unknown) => { + clearTimeout(timer); + reject(err); + }, + ); + }); +} let counter = 0; const newOpId = () => `${Date.now().toString(36)}-${(++counter).toString(36)}-${Math.random().toString(36).slice(2, 8)}`; @@ -76,31 +94,40 @@ export class DevelopSession { ) {} async load(): Promise { + const paint = (base: string, seq: number, offline: boolean) => { + this.base = base; + this.confirmedSeq = seq; + this.offline = offline; + this.pending = this.deps.outbox?.load(this.photoId).map((p) => ({ ...p, sent: false })) ?? []; + this.loaded = true; + this.changed(); + }; if (isLocal(this.photoId)) { // Not on the server yet: starts from scratch; the edits go up after the photo. - this.base = this.deps.engine.defaultSettings(); - this.confirmedSeq = 0; - this.offline = true; - } else { - try { - const state = await this.deps.api.developState(this.photoId); - let base = state.snapshot ? JSON.stringify(state.snapshot) : this.deps.engine.defaultSettings(); - for (const op of state.ops) base = this.safeApply(base, op.command); - this.base = base; - this.confirmedSeq = state.developSeq; - this.remember(); - } catch (err) { - // No network: the state last seen here (or a fresh start); the edits are sent when the connection is back. - if (!this.deps.isOffline?.(err)) throw err; - const kept = await this.deps.states?.get(this.photoId); - this.base = kept?.settings ?? this.deps.engine.defaultSettings(); - this.confirmedSeq = kept?.seq ?? 0; - this.offline = true; - } + paint(this.deps.engine.defaultSettings(), 0, true); + if (this.pending.length) this.schedule(0); + return; + } + // Open on the last state this computer had, so a slow link does not block the preview or the edits. + const kept = await this.deps.states?.get(this.photoId); + paint(kept?.settings ?? this.deps.engine.defaultSettings(), kept?.seq ?? 0, false); + try { + const state = await answerOrGiveUp(this.deps.api.developState(this.photoId), OPEN_WAIT_MS); + if (this.closed) return; + let base = state.snapshot ? JSON.stringify(state.snapshot) : this.deps.engine.defaultSettings(); + for (const op of state.ops) base = this.safeApply(base, op.command); + this.base = base; + this.confirmedSeq = state.developSeq; + this.offline = false; + this.remember(); + this.changed(); + } catch (err) { + // No answer: keep what was painted. Edits stay queued and go up when the connection is back. + const timedOut = err instanceof Error && err.message === "timeout"; + if (!timedOut && !this.deps.isOffline?.(err)) throw err; + this.offline = true; + this.changed(); } - this.pending = this.deps.outbox?.load(this.photoId).map((p) => ({ ...p, sent: false })) ?? []; - this.loaded = true; - this.changed(); if (this.pending.length) this.schedule(0); } diff --git a/apps/app/src/library/LocalFtp.test.tsx b/apps/app/src/library/LocalFtp.test.tsx index 8acb613..68413cc 100644 --- a/apps/app/src/library/LocalFtp.test.tsx +++ b/apps/app/src/library/LocalFtp.test.tsx @@ -63,8 +63,8 @@ describe("local FTP feed", () => { await act(() => result.current.start()); await waitFor(() => expect(added).toHaveLength(2)); - // Each shows in the library as soon as it arrives (before the upload), and leaves once settled. - await waitFor(() => expect(localPhotos.list()).toEqual([])); + // 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. expect(added).toEqual([ { name: "A.JPG", eventId: "ev1", size: "preview of /x/FTP/A.JPG".length, sha: "sha-/x/FTP/A.JPG" }, @@ -73,6 +73,7 @@ describe("local FTP feed", () => { await waitFor(() => expect(result.current.counts).toEqual({ received: 2, sent: 1, failed: 1 })); // Only the one the server has moves to the event's work folder; the failed one stays in ingest. expect(shell.sent).toEqual([{ path: "/x/FTP/A.JPG", event: "ABC x Benfica", date: "2026-10-12" }]); + for (const photo of localPhotos.list()) localPhotos.remove(photo.id); }); it("does nothing outside the desktop app", async () => { diff --git a/apps/app/src/library/LocalFtp.tsx b/apps/app/src/library/LocalFtp.tsx index 4edc306..9da3358 100644 --- a/apps/app/src/library/LocalFtp.tsx +++ b/apps/app/src/library/LocalFtp.tsx @@ -99,6 +99,9 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn const [checkState, setCheckState] = useState(null); const backlog = useRef([]); const inFlight = useRef(0); + /** One full original at a time. Several at once freeze the window, and the preview must not wait for that. */ + const reading = useRef(0); + const readQueue = useRef<(() => void)[]>([]); const targetRef = useRef(target); targetRef.current = target; const originalsRef = useRef(false); @@ -111,11 +114,24 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn }, []); const pump = useCallback(() => { + const takeOriginal = () => { + if (reading.current < 1) { + reading.current++; + return Promise.resolve(); + } + return new Promise((resume) => readQueue.current.push(resume)); + }; + const releaseOriginal = () => { + const resume = readQueue.current.shift(); + if (resume) resume(); + else reading.current--; + }; const room = originalsRef.current ? IN_FLIGHT_ORIGINALS : IN_FLIGHT; while (inFlight.current < room && backlog.current.length) { const f = backlog.current.shift()!; const to = targetRef.current; inFlight.current++; + let slot = true; void (async () => { try { // Working locally: a 2048 px preview with the original's metadata goes up, the original stays here. @@ -140,28 +156,59 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn // Culled before a restart (still offline): it comes back as it was left. for (const op of orgId ? offlineQueue(orgId).pending : []) if (op.kind === "patch" && op.ids.includes(localId(info.sha256))) localPhotos.patch(localId(info.sha256), op.patch as Partial); } - const bytes = full ? await invoke("ftp_read", { path: f.path }).then(asArrayBuffer) : preview; - const file = new File([bytes], f.name, { type: "image/jpeg", lastModified: f.modifiedMs }); + // The preview is on screen. The next photo does not wait for this one's upload: a slow network must + // not stop the grid or Revelar. + inFlight.current--; + slot = false; + pump(); // A full original from the camera still counts as FTP (the event's autopilot edits it), not a hand upload. const routed = pinned ? undefined : events.find((e) => e.id === eventId); - add([file], eventId ?? undefined, (_file, result, photo) => { - inFlight.current--; + const settle = (_file: File, result: UploadStatus, photo?: PhotoSummary) => { if (result === "done" || result === "duplicate") { setCounts((c) => ({ ...c, sent: c.sent + 1 })); invoke("ftp_sent", { path: f.path, event: pinned?.title ?? (routed ? eventLabel(routed) : ""), date: pinned?.date ?? (routed ? routed.startsAt.slice(0, 10) : "") }).catch(() => {}); // Changes made to it meanwhile now go to the server's copy. if (photo && orgId) offlineQueue(orgId).uploaded(info.sha256, photo.id); + localPhotos.remove(localId(info.sha256)); } else { + // The upload failed. The preview stays, so it can still be culled and edited; the file stays in + // the ingest folder for "Reenviar as que ficaram". setCounts((c) => ({ ...c, failed: c.failed + 1 })); } - localPhotos.remove(localId(info.sha256)); - pump(); - }, full ? "original" : info); + }; + if (!full) { + const file = new File([preview], f.name, { type: "image/jpeg", lastModified: f.modifiedMs }); + add([file], eventId ?? undefined, (_file, result, photo) => settle(_file, result, photo), info); + return; + } + // One original at a time, and only when it is this file's turn to go up. Several at once freeze the window. + await takeOriginal(); + let held = true; + const drop = () => { + if (!held) return; + held = false; + releaseOriginal(); + }; + try { + const bytes = await invoke("ftp_read", { path: f.path }).then(asArrayBuffer); + const file = new File([bytes], f.name, { type: "image/jpeg", lastModified: f.modifiedMs }); + add([file], eventId ?? undefined, (_file, result, photo) => { + drop(); + settle(_file, result, photo); + }, "original"); + } catch (err) { + drop(); + if (!isIncomplete(err)) setCounts((c) => ({ ...c, failed: c.failed + 1 })); + } + return; } catch (err) { - inFlight.current--; + if (slot) { + slot = false; + inFlight.current--; + pump(); + } // A pause mid-transfer is not a failed photo: the shell hands it out again once the file is whole. if (!isIncomplete(err)) setCounts((c) => ({ ...c, failed: c.failed + 1 })); - pump(); } })(); } diff --git a/apps/app/src/pages/DevelopPage.tsx b/apps/app/src/pages/DevelopPage.tsx index b082b9e..da655b9 100644 --- a/apps/app/src/pages/DevelopPage.tsx +++ b/apps/app/src/pages/DevelopPage.tsx @@ -111,6 +111,10 @@ export function DevelopPage() { if (!orgId) return; let alive = true; void (async () => { + const kept = scope ? await cache.photos(orgId, scope) : undefined; + if (!alive) return; + // The filmstrip (including photos still only on this computer) before the network answers. + setAll(kept ?? []); const got: PhotoSummary[] = []; try { for (let offset = 0; ; offset += PAGE) { diff --git a/apps/app/src/pages/LibraryPage.tsx b/apps/app/src/pages/LibraryPage.tsx index cd081c9..f8273fa 100644 --- a/apps/app/src/pages/LibraryPage.tsx +++ b/apps/app/src/pages/LibraryPage.tsx @@ -109,6 +109,10 @@ export function LibraryPage() { return; } prefs.set(`scope:${orgId}`, scope); + // The folder as last seen here, and photos still only on this computer, before the network answers. + const kept = await cache.photos(orgId, scope); + if (kept?.length) dispatch({ type: "loaded", scope, photos: kept, done: false }); + dispatch({ type: "local", photos: localPhotos.list() }); const all: PhotoSummary[] = []; try { for (let offset = 0; ; offset += PAGE) { @@ -121,8 +125,8 @@ export function LibraryPage() { void cache.setPhotos(orgId, scope, all); } catch (err) { if (!isNetworkError(err)) throw err; - // No network: the folder as last seen on this computer (plus what arrived here since). - dispatch({ type: "loaded", scope, photos: (await cache.photos(orgId, scope)) ?? [], done: true }); + // No network: stay on the cache already shown. Mark the folder loaded so the empty state can appear. + dispatch({ type: "loaded", scope, photos: [], done: true }); } dispatch({ type: "local", photos: localPhotos.list() }); }, @@ -158,12 +162,32 @@ export function LibraryPage() { useEffect(() => { if (!orgId) return; let alive = true; - void loadEvents().then((list) => { - if (!alive || !list) return; + let opened = false; + let fresh = false; + const choose = (list: { id: string; photoCount: number }[]) => { const remembered = prefs.get(`scope:${orgId}`); - const scope = remembered && (remembered === "inbox" || list.some((e) => e.id === remembered)) ? remembered : (list.find((e) => e.photoCount > 0) ?? list[0])?.id; - if (scope) void open(scope).catch(() => setError(t.unexpectedError)); + return remembered && (remembered === "inbox" || list.some((e) => e.id === remembered)) ? remembered : (list.find((e) => e.photoCount > 0) ?? list[0])?.id; + }; + const go = (list: { id: string; photoCount: number }[]) => { + if (!alive || opened) return; + const scope = choose(list); + if (!scope) return; + opened = true; + void open(scope).catch(() => setError(t.unexpectedError)); + }; + // The last event list, so a hanging request does not leave the library blank. + void cache.events(orgId).then((kept) => { + if (!alive || !kept || fresh) return; + setEvents(kept.events); + setInboxCount(kept.inboxCount); + go(kept.events); }); + void loadEvents() + .then((list) => { + fresh = true; + if (list) go(list); + }) + .catch(() => setError(t.unexpectedError)); if (canCull) api.listDeliveryTargets(orgId).then((r) => alive && setTargets(r.targets.filter((x) => !x.disabledAt)), () => {}); return () => { alive = false; -- 2.47.3