From 158dccddf14c8d8fd87ad803aa0cfd150247eb57 Mon Sep 17 00:00:00 2001
From: Brian Hursey
Date: Sat, 28 Nov 2026 06:20:44 +0000
Subject: [PATCH] Add an admin action that rebuilds preview proxies
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
A library imported by an older pipeline keeps whatever proxy it was given, and
the editor can only show those bytes. The Storage tab now re-decodes every
camera raw from its original, writing a fresh JPEG proxy, thumbnail, 16-bit
sidecar and denoise prune, then stamps previewVersion so browsers refetch.
The decode loop runs one photo at a time on the server behind a status route:
an hour of LibRaw work would time out as a request, and parallel decodes would
starve the editor. The single-photo reprocess route shares the same helper.
🤖 Generated with Codebuff
Co-Authored-By: Codebuff
---
README.md | 2 +
server/index.mjs | 118 ++++++++++++++++++++++++---------
server/previewRebuild.mjs | 52 +++++++++++++++
server/previewRebuild.test.mjs | 71 ++++++++++++++++++++
src/components/AdminPanel.tsx | 103 ++++++++++++++++++++++++++++
src/lib/api.ts | 26 ++++++++
6 files changed, 342 insertions(+), 30 deletions(-)
create mode 100644 server/previewRebuild.mjs
create mode 100644 server/previewRebuild.test.mjs
diff --git a/README.md b/README.md
index 3957772..97b345c 100644
--- a/README.md
+++ b/README.md
@@ -599,6 +599,8 @@ routes are public and are gated only by the share token.
| POST | `/api/admin/catalog` | Restore a backup produced by the GET |
| GET | `/api/admin/storage` | Current and default storage roots, custom flag |
| PUT | `/api/admin/storage` | Move image storage to another absolute path |
+| GET | `/api/admin/previews/rebuild` | Progress of the raw proxy rebuild |
+| POST | `/api/admin/previews/rebuild` | Re-decode every camera raw into a fresh proxy, thumbnail and 16-bit sidecar |
| PATCH | `/api/admin/quotas/:id` | Set an account's byte limit |
| POST | `/api/admin/quotas/:id/prune` | Compute the oldest-first plan and schedule it 24 h out |
| DELETE | `/api/admin/quotas/:id/prune` | Cancel a scheduled cleanup |
diff --git a/server/index.mjs b/server/index.mjs
index db62bde..f566b3a 100644
--- a/server/index.mjs
+++ b/server/index.mjs
@@ -77,6 +77,7 @@ import {
writeThumb,
writeThumb16,
} from './storage.mjs';
+import { previewRebuildTargets, startPreviewRebuild } from './previewRebuild.mjs';
import { decodeRaw, isRawName, rawSupport } from './raw.mjs';
import {
bridgeConfigured,
@@ -969,6 +970,48 @@ route('PUT', '/api/admin/storage', async ({ req, res }) => {
}
});
+/* --------------------------------------------------------- preview rebuild */
+
+let previewRebuild = null;
+
+function previewRebuildStatus() {
+ return (
+ previewRebuild?.snapshot() ?? {
+ state: 'idle',
+ total: 0,
+ done: 0,
+ failed: 0,
+ sidecars: 0,
+ startedAt: null,
+ finishedAt: null,
+ errors: [],
+ }
+ );
+}
+
+route('GET', '/api/admin/previews/rebuild', async ({ req, res }) => {
+ if (!requireAdmin(req, res)) return;
+ json(res, 200, { rebuild: previewRebuildStatus() });
+});
+
+/**
+ * Regenerate every raw proxy from its original, which is what a library
+ * imported by an older pipeline needs after the decode changes. The loop is CPU
+ * bound and can run for an hour, so the request only starts it and the panel
+ * polls the status route.
+ */
+route('POST', '/api/admin/previews/rebuild', async ({ req, res }) => {
+ if (!requireAdmin(req, res)) return;
+ const current = previewRebuildStatus();
+ if (current.state === 'running') return json(res, 202, { rebuild: current });
+ const targets = previewRebuildTargets(listPhotos());
+ previewRebuild = startPreviewRebuild({
+ targets,
+ regenerate: (photo) => regenerateRawPreview(photo.id, photo, photoOwner(photo.id) ?? ''),
+ });
+ json(res, 202, { rebuild: previewRebuild.snapshot() });
+});
+
route('GET', '/api/quota', async ({ req, res }) => {
const user = currentUser(req);
if (!user) return error(res, 401, 'Not signed in');
@@ -2039,10 +2082,48 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
});
/**
- * Re-decode a stored RAW with the current pipeline settings. The original is
- * never touched; only the editable proxy, its thumbnail and the cached denoise
- * renders are replaced, so existing edits keep working on fresh pixels.
+ * Re-decode one stored RAW and replace everything derived from it. Shared by the
+ * single-photo route and the admin rebuild so the two cannot drift apart.
+ *
+ * The original is never touched; only the editable proxy, its thumbnail, the
+ * 16-bit sidecar and the cached denoise renders are replaced, so existing edits
+ * keep working on fresh pixels.
*/
+async function regenerateRawPreview(id, photo, ownerId) {
+ const original = findOriginal(id);
+ if (!original) throw new Error('The RAW original is missing from storage');
+ const decoded = await decodeRaw(await fsp.readFile(original));
+ await writePreview(id, decoded.jpeg, decoded.ext);
+ if (decoded.preview16) {
+ await writePreview16(id, decoded.preview16.data);
+ // The thumbnail may not exist yet; drop any camera-native tile so the grid
+ // rebuilds it from the new pixels.
+ await removeThumb16(id);
+ } else {
+ await removePreview16(id);
+ await removeThumb16(id);
+ }
+ const thumb = await makeThumb(decoded.jpeg, 560);
+ if (thumb) await writeThumb(id, thumb);
+ // The old denoised renders were made from the previous proxy.
+ clearDenoised(id);
+ const info = await jpegInfo(decoded.jpeg);
+ const width = info?.width || decoded.width || photo.width;
+ const height = info?.height || decoded.height || photo.height;
+ // Stamp the record so cached previews and thumbnails are fetched again.
+ const previewVersion = Date.now();
+ // Pass the owner explicitly: savePhoto defaults to '' and would orphan the row.
+ savePhoto({ ...photo, width, height, mime: 'image/jpeg', previewVersion }, Date.now(), ownerId);
+ return {
+ width,
+ height,
+ engine: decoded.engine,
+ note: decoded.note ?? null,
+ previewVersion,
+ sidecar: Boolean(decoded.preview16),
+ };
+}
+
route('POST', '/api/photos/:id/reprocess', async ({ req, res, params }) => {
const user = currentUser(req);
if (!user) return error(res, 401, 'Not signed in');
@@ -2052,34 +2133,11 @@ route('POST', '/api/photos/:id/reprocess', async ({ req, res, params }) => {
const original = findOriginal(params.id);
if (!original) return error(res, 404, 'The RAW original is missing from storage');
try {
- const decoded = await decodeRaw(await fsp.readFile(original));
- await writePreview(params.id, decoded.jpeg, decoded.ext);
- if (decoded.preview16) {
- await writePreview16(params.id, decoded.preview16.data);
- await removeThumb16(params.id);
- } else {
- await removePreview16(params.id);
- await removeThumb16(params.id);
- }
- const thumb = await makeThumb(decoded.jpeg, 560);
- if (thumb) await writeThumb(params.id, thumb);
- // The old denoised renders were made from the previous proxy.
- clearDenoised(params.id);
- const info = await jpegInfo(decoded.jpeg);
- const width = info?.width || decoded.width || photo.width;
- const height = info?.height || decoded.height || photo.height;
- // Stamp the record so cached previews and thumbnails are fetched again.
- const previewVersion = Date.now();
- // Pass the owner explicitly: savePhoto defaults to '' and would orphan the row.
- savePhoto({ ...photo, width, height, mime: 'image/jpeg', previewVersion }, Date.now(), user.id);
+ const result = await regenerateRawPreview(params.id, photo, user.id);
json(res, 200, {
- width,
- height,
- engine: decoded.engine,
- note: decoded.note ?? null,
- previewVersion,
- previewUrl: `/api/photos/${params.id}/preview?v=${previewVersion}`,
- thumbUrl: `/api/photos/${params.id}/thumb?v=${previewVersion}`,
+ ...result,
+ previewUrl: `/api/photos/${params.id}/preview?v=${result.previewVersion}`,
+ thumbUrl: `/api/photos/${params.id}/thumb?v=${result.previewVersion}`,
});
} catch (err) {
return error(res, 422, err instanceof Error ? err.message : 'Could not reprocess this RAW file');
diff --git a/server/previewRebuild.mjs b/server/previewRebuild.mjs
new file mode 100644
index 0000000..6209b0b
--- /dev/null
+++ b/server/previewRebuild.mjs
@@ -0,0 +1,52 @@
+/**
+ * Rebuilds stored raw proxies from their originals.
+ *
+ * A decode is CPU bound and holds a LibRaw worker for seconds, so the work runs
+ * one photo at a time behind a snapshot: a request that blocked for an hour
+ * would time out, and decoding in parallel would starve the editor. Progress
+ * lives in memory only, so an interrupted rebuild simply starts again.
+ */
+
+/** Photos that have a proxy worth regenerating: camera raws that still exist. */
+export function previewRebuildTargets(photos) {
+ return photos.filter((photo) => photo && photo.raw === true && !photo.deletedAt);
+}
+
+/**
+ * Runs `regenerate(photo)` for every target and reports progress.
+ *
+ * A photo that fails is counted and recorded, and the run continues: one
+ * unreadable original must not strand the rest of the library.
+ */
+export function startPreviewRebuild({ targets, regenerate, now = Date.now }) {
+ const job = {
+ state: 'running',
+ total: targets.length,
+ done: 0,
+ failed: 0,
+ sidecars: 0,
+ startedAt: now(),
+ finishedAt: null,
+ errors: [],
+ };
+
+ const finished = (async () => {
+ for (const photo of targets) {
+ try {
+ const result = await regenerate(photo);
+ if (result?.sidecar) job.sidecars += 1;
+ } catch (err) {
+ job.failed += 1;
+ if (job.errors.length < 5) {
+ const label = photo?.name || photo?.id || 'photo';
+ job.errors.push(`${label}: ${err instanceof Error ? err.message : String(err)}`);
+ }
+ }
+ job.done += 1;
+ }
+ job.state = 'done';
+ job.finishedAt = now();
+ })();
+
+ return { snapshot: () => ({ ...job, errors: [...job.errors] }), finished };
+}
diff --git a/server/previewRebuild.test.mjs b/server/previewRebuild.test.mjs
new file mode 100644
index 0000000..70a5a12
--- /dev/null
+++ b/server/previewRebuild.test.mjs
@@ -0,0 +1,71 @@
+import { describe, expect, it } from 'vitest';
+import { previewRebuildTargets, startPreviewRebuild } from './previewRebuild.mjs';
+
+describe('preview rebuild targets', () => {
+ it('takes live camera raws and nothing else', () => {
+ const photos = [
+ { id: 'raw', raw: true },
+ { id: 'jpeg', raw: false },
+ { id: 'trashed', raw: true, deletedAt: 1 },
+ { id: 'unknown' },
+ ];
+ expect(previewRebuildTargets(photos).map((photo) => photo.id)).toEqual(['raw']);
+ });
+});
+
+describe('preview rebuild job', () => {
+ it('walks every target in order and counts the 16-bit sidecars', async () => {
+ const seen = [];
+ const job = startPreviewRebuild({
+ targets: [{ id: 'a' }, { id: 'b' }],
+ regenerate: async (photo) => {
+ seen.push(photo.id);
+ return { sidecar: photo.id === 'a' };
+ },
+ now: () => 7,
+ });
+ expect(job.snapshot()).toMatchObject({ state: 'running', total: 2, done: 0 });
+ await job.finished;
+ expect(seen).toEqual(['a', 'b']);
+ expect(job.snapshot()).toMatchObject({
+ state: 'done',
+ done: 2,
+ failed: 0,
+ sidecars: 1,
+ startedAt: 7,
+ finishedAt: 7,
+ });
+ });
+
+ it('keeps going after a photo that cannot be decoded', async () => {
+ const job = startPreviewRebuild({
+ targets: [{ id: 'a', name: 'A.CR2' }, { id: 'b', name: 'B.CR2' }],
+ regenerate: async (photo) => {
+ if (photo.id === 'a') throw new Error('the original is missing');
+ return { sidecar: false };
+ },
+ });
+ await job.finished;
+ const snapshot = job.snapshot();
+ expect(snapshot).toMatchObject({ state: 'done', done: 2, failed: 1, sidecars: 0 });
+ expect(snapshot.errors[0]).toContain('A.CR2');
+ expect(snapshot.errors[0]).toContain('the original is missing');
+ });
+
+ it('hands out copies, so a caller cannot edit the live progress', async () => {
+ const job = startPreviewRebuild({
+ targets: [{ id: 'a' }],
+ regenerate: async () => ({ sidecar: false }),
+ });
+ const snapshot = job.snapshot();
+ snapshot.errors.push('tampered');
+ await job.finished;
+ expect(job.snapshot().errors).toEqual([]);
+ });
+
+ it('finishes immediately when there is nothing to rebuild', async () => {
+ const job = startPreviewRebuild({ targets: [], regenerate: async () => ({ sidecar: false }) });
+ await job.finished;
+ expect(job.snapshot()).toMatchObject({ state: 'done', total: 0, done: 0, failed: 0 });
+ });
+});
diff --git a/src/components/AdminPanel.tsx b/src/components/AdminPanel.tsx
index 9cbe500..713b965 100644
--- a/src/components/AdminPanel.tsx
+++ b/src/components/AdminPanel.tsx
@@ -6,6 +6,7 @@ import type {
AdminUser,
CatalogBackup,
MailStatus,
+ PreviewRebuildStatus,
SessionUser,
StorageChange,
} from '../lib/api';
@@ -19,6 +20,8 @@ import {
adminRestoreCatalog,
adminRevokeInvite,
adminOverview,
+ adminPreviewRebuildStatus,
+ adminRebuildPreviews,
adminRenameEvent,
adminSaveImmich,
adminSaveMail,
@@ -73,6 +76,18 @@ const planSummary = (quota: AdminQuota) => {
type Tab = 'users' | 'invites' | 'content' | 'storage' | 'quotas' | 'immich' | 'backup';
+/** No rebuild has run in this process yet. */
+const idleRebuild: PreviewRebuildStatus = {
+ state: 'idle',
+ total: 0,
+ done: 0,
+ failed: 0,
+ sidecars: 0,
+ startedAt: null,
+ finishedAt: null,
+ errors: [],
+};
+
const inviteUrl = (token: string) => `${window.location.origin}/join/${token}`;
const inviteStatusLabel: Record = {
@@ -109,6 +124,8 @@ export default function AdminPanel({ user, onClose, onChanged, onRestored }: Pro
const [rootInput, setRootInput] = useState('');
const [change, setChange] = useState(null);
+ const [rebuild, setRebuild] = useState(idleRebuild);
+ const [rebuildBusy, setRebuildBusy] = useState(false);
const restoreInput = useRef(null);
const [restoreNote, setRestoreNote] = useState(null);
@@ -117,6 +134,51 @@ export default function AdminPanel({ user, onClose, onChanged, onRestored }: Pro
const [mail, setMail] = useState(null);
const [immichDraft, setImmichDraft] = useState({ url: '', apiKey: '', enabled: true });
+ // The rebuild runs inside the server, so the panel reads its progress instead
+ // of holding the work: closing the modal does not stop it, and reopening the
+ // tab picks up a run that is already in flight.
+ useEffect(() => {
+ if (tab !== 'storage') return;
+ let alive = true;
+ adminPreviewRebuildStatus()
+ .then((next) => {
+ if (alive) setRebuild(next);
+ })
+ .catch(() => undefined);
+ return () => {
+ alive = false;
+ };
+ }, [tab]);
+
+ const rebuildRunning = rebuild.state === 'running';
+ useEffect(() => {
+ if (tab !== 'storage' || !rebuildRunning) return;
+ const timer = setInterval(() => {
+ adminPreviewRebuildStatus()
+ .then(setRebuild)
+ .catch(() => undefined);
+ }, 2000);
+ return () => clearInterval(timer);
+ }, [tab, rebuildRunning]);
+
+ const rebuildPreviews = async () => {
+ setRebuildBusy(true);
+ setError(null);
+ setNote(null);
+ try {
+ const started = await adminRebuildPreviews();
+ setRebuild(started);
+ setNote(
+ started.state === 'done'
+ ? 'Nothing to rebuild: every camera raw is a JPEG-only import'
+ : `Rebuilding ${started.total} preview proxies`,
+ );
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Could not rebuild the previews');
+ } finally {
+ setRebuildBusy(false);
+ }
+ };
const restoreCatalog = async (file: File | undefined) => {
if (!file || busy) return;
@@ -1188,6 +1250,47 @@ export default function AdminPanel({ user, onClose, onChanged, onRestored }: Pro
container first (for example -v /photos:/photos), then use that container path.
+
+
Preview proxies
+
+ Re-decode every camera raw from its original and replace its JPEG proxy, grid thumbnail
+ and 16-bit sidecar. Run this after a change to the raw pipeline: edits, ratings and
+ events are kept, and the originals are never modified.
+
+
+
+
+
+ {rebuildRunning && (
+
+ {rebuild.done} of {rebuild.total} raws rebuilt
+ {rebuild.failed ? ` · ${rebuild.failed} failed` : ''} · the server keeps going when
+ this panel closes.
+
+ )}
+ {rebuild.state === 'done' && (
+
+ Rebuilt {rebuild.done - rebuild.failed} of {rebuild.total} raws
+ {rebuild.sidecars ? `, ${rebuild.sidecars} with a 16-bit sidecar` : ''}
+ {rebuild.failed ? ` · ${rebuild.failed} failed` : ''}.
+ {rebuild.errors.length > 0 ? ` First failure: ${rebuild.errors[0]}` : ''}
+
+ )}
)}
diff --git a/src/lib/api.ts b/src/lib/api.ts
index 47436ac..324d497 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -760,6 +760,32 @@ export function adminTestImmich(): Promise {
return request('/api/admin/immich/test', { method: 'POST' });
}
+export interface PreviewRebuildStatus {
+ state: 'idle' | 'running' | 'done';
+ total: number;
+ /** Photos attempted so far, including the failures. */
+ done: number;
+ failed: number;
+ /** Rebuilt proxies that also wrote a 16-bit sidecar. */
+ sidecars: number;
+ startedAt: number | null;
+ finishedAt: number | null;
+ errors: string[];
+}
+
+/** Starts a server-side rebuild and returns its first progress snapshot. */
+export function adminRebuildPreviews(): Promise {
+ return request<{ rebuild: PreviewRebuildStatus }>('/api/admin/previews/rebuild', {
+ method: 'POST',
+ }).then((res) => res.rebuild);
+}
+
+export function adminPreviewRebuildStatus(): Promise {
+ return request<{ rebuild: PreviewRebuildStatus }>('/api/admin/previews/rebuild').then(
+ (res) => res.rebuild,
+ );
+}
+
export function adminDisconnectImmich(): Promise {
return request<{ immich: ImmichStatus }>('/api/admin/immich', { method: 'DELETE' }).then(
(res) => res.immich,