Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

perf: serve compact thumbnails in media grids (#8406)

[._.]/ Adam Eivy047f428352aa
diff --git a/client/src/components/MediaImage.jsx b/client/src/components/MediaImage.jsx
index 6b6b970161..a1edc0ebe1 100644
--- a/client/src/components/MediaImage.jsx
+++ b/client/src/components/MediaImage.jsx
@@ -13,6 +13,8 @@
*
* Props:
* src: string — same as <img>; expected to be `/data/...`
+ * fallbackSrc?: string — original to try once if a thumbnail fails
+ * assetSrc?: string — original URL whose filename peer sync reports
* alt: string — same as <img>
* className?: string — applies to BOTH the live <img> and the placeholder wrapper
* placeholderClassName?: string — extra classes for the placeholder only
@@ -42,17 +44,20 @@ function basenameOf(src) {
export default function MediaImage({
src,
+ fallbackSrc,
+ assetSrc = src,
alt = '',
className = '',
placeholderClassName = '',
...rest
}) {
const [errored, setErrored] = useState(false);
+ const [usingFallback, setUsingFallback] = useState(false);
// Bumping `nonce` forces the <img> to re-fetch (cache-busted) when the
// socket says our asset arrived — without it the browser would serve the
// cached 404 forever.
const [nonce, setNonce] = useState(0);
- const filename = basenameOf(src);
+ const filename = basenameOf(assetSrc);
const filenameRef = useRef(filename);
filenameRef.current = filename;
@@ -60,8 +65,9 @@ export default function MediaImage({
// different filename that we DO have locally.
useEffect(() => {
setErrored(false);
+ setUsingFallback(false);
setNonce(0);
- }, [src]);
+ }, [src, assetSrc]);
// Listen for the receiver's asset-arrived event. Match on filename only
// (kind is implicit from the directory in the src URL) so the listener
@@ -72,6 +78,7 @@ export default function MediaImage({
const handler = (payload) => {
if (payload?.filename === filenameRef.current) {
setErrored(false);
+ setUsingFallback(false);
setNonce((n) => n + 1);
}
};
@@ -94,7 +101,8 @@ export default function MediaImage({
// The cache-buster appears only after the first arrival event; the very
// first load (before any 404) uses the bare src so HTTP caching still
// works the way the rest of the UI expects.
- const cacheBustedSrc = nonce > 0 ? `${src}${src.includes('?') ? '&' : '?'}_t=${nonce}` : src;
+ const displaySrc = usingFallback ? fallbackSrc : src;
+ const cacheBustedSrc = nonce > 0 ? `${displaySrc}${displaySrc.includes('?') ? '&' : '?'}_t=${nonce}` : displaySrc;
// Spread `rest` FIRST so the explicit `onError` below wins over a caller-
// provided one — we still forward the event by capturing the caller's
// handler before composing. Putting {...rest} last would silently override
@@ -113,7 +121,8 @@ export default function MediaImage({
// listener still gates the swap-back, so a permanent network error
// doesn't lock the placeholder on forever — user-visible state then
// accurately reflects "asset not loadable right now."
- setErrored(true);
+ if (!usingFallback && fallbackSrc && fallbackSrc !== src) setUsingFallback(true);
+ else setErrored(true);
callerOnError?.(e);
}}
/>
diff --git a/client/src/components/media/MediaCard.jsx b/client/src/components/media/MediaCard.jsx
index c25685fa00..b47b80ee91 100644
--- a/client/src/components/media/MediaCard.jsx
+++ b/client/src/components/media/MediaCard.jsx
@@ -41,7 +41,7 @@ function MediaCard({
onToggleStar,
onAnnotate,
}) {
- const { kind, prompt, modelId, previewUrl, downloadUrl } = item;
+ const { kind, prompt, modelId, previewUrl, thumbnailUrl, downloadUrl } = item;
const isVideo = kind === 'video';
const handleTileClick = onClick || (() => onPreview?.(item));
const [confirmingDelete, setConfirmingDelete] = useState(false);
@@ -62,7 +62,7 @@ function MediaCard({
className="block w-full h-full disabled:cursor-not-allowed disabled:opacity-40"
>
{previewUrl ? (
- <MediaImage src={previewUrl} alt={prompt} className="w-full h-full object-cover" loading="lazy" />
+ <MediaImage src={thumbnailUrl || previewUrl} fallbackSrc={kind === 'image' ? previewUrl : undefined} assetSrc={previewUrl} alt={prompt} className="w-full h-full object-cover" loading="lazy" />
) : (
<div className="w-full h-full flex items-center justify-center text-gray-600">
{isVideo ? <Film className="w-10 h-10" /> : <ImageIcon className="w-10 h-10" />}
diff --git a/client/src/components/media/MediaCard.test.jsx b/client/src/components/media/MediaCard.test.jsx
index bcb6c458b6..1cfa6497ff 100644
--- a/client/src/components/media/MediaCard.test.jsx
+++ b/client/src/components/media/MediaCard.test.jsx
@@ -24,6 +24,7 @@ const imageItem = {
key: 'image:late.png',
filename: 'late.png',
previewUrl: '/data/images/late.png',
+ thumbnailUrl: '/data/image-thumbnails/late.webp',
downloadUrl: '/data/images/late.png',
prompt: 'late synced image',
};
@@ -78,6 +79,9 @@ describe('MediaCard', () => {
it('uses MediaImage for grid thumbnails so peer-synced assets show and recover from the syncing placeholder', () => {
render(<MediaCard item={imageItem} showCollectionMenu={false} />);
+ expect(screen.getByAltText('late synced image')).toHaveAttribute('src', '/data/image-thumbnails/late.webp');
+ fireEvent.error(screen.getByAltText('late synced image'));
+ expect(screen.getByAltText('late synced image')).toHaveAttribute('src', '/data/images/late.png');
fireEvent.error(screen.getByAltText('late synced image'));
expect(screen.getByText(/Syncing/i)).toBeInTheDocument();
@@ -87,7 +91,7 @@ describe('MediaCard', () => {
expect(screen.queryByText(/Syncing/i)).not.toBeInTheDocument();
expect(screen.getByAltText('late synced image').getAttribute('src')).toMatch(
- /^\/data\/images\/late\.png\?_t=/
+ /^\/data\/image-thumbnails\/late\.webp\?_t=/
);
});
diff --git a/client/src/components/media/normalize.js b/client/src/components/media/normalize.js
index 4cb7c1b029..b1725c52f1 100644
--- a/client/src/components/media/normalize.js
+++ b/client/src/components/media/normalize.js
@@ -19,6 +19,10 @@ export function loraDisplayName(filename) {
// consumed by <MediaCard>. Lets the same card render in any history grid.
export function normalizeImage(i) {
const loraNames = (pickLoraFilenames(i) || []).filter(Boolean);
+ const originalUrl = i.path || `/data/images/${i.filename}`;
+ const thumbnailUrl = /^\/data\/images\/[^/]+\.png(?:\?.*)?$/i.test(originalUrl)
+ ? `/data/image-thumbnails/${originalUrl.split('/').pop().replace(/\.png(?=\?|$)/i, '.webp')}`
+ : originalUrl;
// modelId display falls back through several sidecar shapes:
// 1. modelId — local-runner sidecars (mflux/flux2/z-image/ernie)
// 2. model — codex sidecars (older path), and future Gemini etc.
@@ -30,8 +34,9 @@ export function normalizeImage(i) {
kind: 'image',
key: `image:${i.filename}`,
filename: i.filename,
- previewUrl: i.path || `/data/images/${i.filename}`,
- downloadUrl: i.path || `/data/images/${i.filename}`,
+ previewUrl: originalUrl,
+ thumbnailUrl,
+ downloadUrl: originalUrl,
prompt: i.prompt || i.metadata?.prompt || '(no prompt)',
negativePrompt: i.negativePrompt || i.negative_prompt || null,
modelId,
diff --git a/client/src/components/media/normalize.test.js b/client/src/components/media/normalize.test.js
index 478afc3776..929ca08491 100644
--- a/client/src/components/media/normalize.test.js
+++ b/client/src/components/media/normalize.test.js
@@ -1,6 +1,17 @@
import { describe, it, expect } from 'vitest';
import { getRenderConfigForItem, normalizeImage, normalizeVideo } from './normalize.js';
+describe('image grid thumbnail URL', () => {
+ it('uses a derivative only for local gallery images while keeping originals for actions', () => {
+ const local = normalizeImage({ filename: 'example.png' });
+ expect(local.thumbnailUrl).toBe('/data/image-thumbnails/example.webp');
+ expect(local.previewUrl).toBe('/data/images/example.png');
+ expect(local.downloadUrl).toBe(local.previewUrl);
+ const external = normalizeImage({ filename: 'remote.png', path: 'https://example.com/remote.png' });
+ expect(external.thumbnailUrl).toBe(external.previewUrl);
+ });
+});
+
// These tests pin the sidecar field-name knowledge in normalize.js. If a new
// field surfaces in a render sidecar, surface it here so the requeue path in
// <PromptRefineModal> stays in lockstep with the writers.
diff --git a/server/lib/README.md b/server/lib/README.md
index 288b7a586c..bbfb30549a 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -352,6 +352,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `forgeIssueState.js` | `normalizeIssueState(state)` — collapse a forge issue/PR/MR state string to `open`/`closed`. GitHub reports `OPEN`/`CLOSED`; GitLab reports `opened`/`closed`/`locked`; anything unrecognized is treated as open so an unfamiliar state can never read as "already resolved". Shared by `layeredIntelligence/forgeFiler.js` and `services/blockedIssueReconcile.js`. |
| `imageClean.js` | `cleanImageBuffer(buf, { metadata, denoise })` (composable opt-in pipeline: lossless metadata/C2PA strip + optional median/sharpen denoise) · `stripPngMetadataChunks` / `stripPngC2PAChunk` (lossless PNG-chunk removers) · `compositeIgnoreZone(base, original, mask, { feather })` (preserve-region compositing: restore original pixels into a feathered mask over a diffused result) · `autoCleanGeneratedImage` (in-place clean for post-generation hook). HTTP route in `routes/imageClean.js` wraps `cleanImageBuffer` and appends a CPU light diffusion pass (`applyLightRegen` from `services/imageGen/regen.js`) for the `diffusion=light` SynthID-disruption step. |
| `imageFrameStats.js` | Degenerate-frame classifier (#4173) — `describeFrameStats(bufferOrPath)` runs one `sharp` `.stats()` decode and returns `{ ok, reason, perChannel }`, rejecting `solid-fill` (every colour channel stdev under `SOLID_FILL_STDEV_EPSILON`), `fully-transparent` (alpha max 0) and `near-empty` (greyscale entropy under `NEAR_EMPTY_ENTROPY_FLOOR`), except when a non-opaque alpha channel carries a substantial silhouette itself. Deliberately NOT a quality judge: a legitimately dark or minimalist render keeps real per-channel variance and is accepted. `ok` is three-valued — `true`/`false`/`null`, where `null` means could-not-measure (undecodable buffer, or under `MIN_JUDGEABLE_PIXELS`) and must never read as degenerate; gate on `isDegenerateFrame(stats)` / `ok === false`, never `!ok`. Called by the Image Gen provider completion seams, sprite reference normalization, and `visionTest.js` (so a paid vision call is never spent on a blank frame). A **buffer** verdict is memoized on the sha256 of its bytes (#6004) — the probe costs ~4ms regardless of pixel count and the sprite compiler re-probes identical frames dozens of times per run; a **path** is never memoized (the file behind it can change), so hand it bytes you already read. `stats-unavailable` is never memoized either — that branch catches transient probe failures too, and pinning `ok: null` on valid bytes would disable the gate for them. `__resetFrameStatsCache()` drops the memo in tests. |
+| `imageThumbnail.js` | Lazy, single-flight WebP previews for flat gallery PNG files, refreshed when the source changes. |
| `imageRgba.js` | Sharp-backed RGBA boundary: `decodeRgbaFrame` decodes an image to `{ data, width, height }`, and `encodePng` turns a raw frame into PNG bytes for the caller's destination/hash policy. |
| `imageWatermark.js` | `removeCornerWatermark` (erases the visible Gemini/Nano-Banana bottom-right ✦ via dependency-free harmonic/Laplace inpaint) + pure helpers `resolveWatermarkRegion` / `inpaintRegion`. Distinct from SynthID regen — this targets the *visible* corner logo. |
| `localImageFilename.js` | `localImageFilename(urlOrPath)` resolves a stored image reference to the bare gallery-image filename under `data/images/` (or null for empty/external-URL/non-image-path) — the unit the peer-sync asset pipeline hashes + transfers. Single source of truth for the authors/artists/albums/Creative-Director filename resolvers (`headshotImageFilename`/`portraitImageFilename`/`coverImageFilename`/`startingImageFilename` are thin wrappers). Also exports `assetBasename(pathOrName)`, the shared strip-querystring→basename primitive (reused by moodBoard's `imageUrlToAppAsset`). |
diff --git a/server/lib/assetRoutePrefixes.js b/server/lib/assetRoutePrefixes.js
index 95336ff6ee..4654efaa36 100644
--- a/server/lib/assetRoutePrefixes.js
+++ b/server/lib/assetRoutePrefixes.js
@@ -29,6 +29,7 @@
/** Every `/data/**` static mount, in the order `server/index.js` mounts them. */
export const ASSET_ROUTE_PREFIXES = [
'/data/images',
+ '/data/image-thumbnails',
'/data/image-refs',
'/data/lora-datasets',
'/data/videos',
diff --git a/server/lib/imageThumbnail.js b/server/lib/imageThumbnail.js
new file mode 100644
index 0000000000..554d76a56b
--- /dev/null
+++ b/server/lib/imageThumbnail.js
@@ -0,0 +1,38 @@
+import { lstat } from 'node:fs/promises';
+import { join } from 'node:path';
+import sharp from 'sharp';
+import { atomicWrite, PATHS } from './fileUtils.js';
+
+const pending = new Map();
+
+const optionalStat = async (path) => lstat(path).catch((error) => {
+ if (error.code === 'ENOENT') return null;
+ throw error;
+});
+
+/** Lazily build a small WebP for a gallery PNG. Returns false if its source is absent. */
+export async function ensureImageThumbnail(filename) {
+ if (typeof filename !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]*\.webp$/i.test(filename)) return false;
+ if (pending.has(filename)) return pending.get(filename);
+
+ const work = (async () => {
+ const source = join(PATHS.images, filename.replace(/\.webp$/i, '.png'));
+ const target = join(PATHS.imageThumbnails, filename);
+ const sourceStat = await optionalStat(source);
+ if (!sourceStat?.isFile()) return false;
+ const targetStat = await optionalStat(target);
+ if (!targetStat?.isFile() || targetStat.mtimeMs < sourceStat.mtimeMs) {
+ const bytes = await sharp(source).rotate()
+ .resize({ width: 512, height: 512, fit: 'outside', withoutEnlargement: true })
+ .webp({ quality: 78 }).toBuffer();
+ await atomicWrite(target, bytes);
+ }
+ return true;
+ })();
+ pending.set(filename, work);
+ try {
+ return await work;
+ } finally {
+ pending.delete(filename);
+ }
+}
diff --git a/server/lib/imageThumbnail.test.js b/server/lib/imageThumbnail.test.js
new file mode 100644
index 0000000000..c130e84eed
--- /dev/null
+++ b/server/lib/imageThumbnail.test.js
@@ -0,0 +1,52 @@
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdirSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { createTempDataRoot, makePathsProxy } from './mockPathsDataRoot.js';
+
+const tempRoot = createTempDataRoot('portos-image-thumbnails-');
+const sharpCalls = vi.hoisted(() => ({ count: 0 }));
+vi.mock('./fileUtils.js', async (original) => makePathsProxy(await original(), { dataRoot: tempRoot }));
+vi.mock('sharp', async (original) => {
+ const real = (await original()).default;
+ return { default: (...args) => { sharpCalls.count += 1; return real(...args); } };
+});
+
+const { default: sharp } = await import('sharp');
+const { ensureImageThumbnail } = await import('./imageThumbnail.js');
+afterAll(() => rmSync(tempRoot, { recursive: true, force: true }));
+beforeEach(() => { sharpCalls.count = 0; });
+
+async function source(name) {
+ const dir = join(tempRoot, 'images');
+ mkdirSync(dir, { recursive: true });
+ const bytes = await sharp({ create: { width: 1024, height: 768, channels: 3, background: '#123456' } }).png().toBuffer();
+ writeFileSync(join(dir, name), bytes);
+}
+
+describe('image thumbnails', () => {
+ it('builds one derivative for concurrent requests and refreshes after a source edit', async () => {
+ await source('example.png');
+ sharpCalls.count = 0;
+ expect(await Promise.all(Array.from({ length: 8 }, () => ensureImageThumbnail('example.webp'))))
+ .toEqual(Array(8).fill(true));
+ expect(sharpCalls.count).toBe(1);
+ const target = join(tempRoot, 'image-thumbnails/example.webp');
+ const info = await sharp(target).metadata();
+ expect(info.format).toBe('webp');
+ expect(info.width).toBe(683);
+ sharpCalls.count = 0;
+ expect(await ensureImageThumbnail('example.webp')).toBe(true);
+ expect(sharpCalls.count).toBe(0);
+ const newer = new Date(statSync(target).mtimeMs + 2000);
+ utimesSync(join(tempRoot, 'images/example.png'), newer, newer);
+ expect(await ensureImageThumbnail('example.webp')).toBe(true);
+ expect(sharpCalls.count).toBe(1);
+ });
+
+ it('refuses absent sources, paths, and non-image names', async () => {
+ for (const name of ['missing.webp', '../example.webp', 'example.png', 'nested/example.webp', '.webp']) {
+ expect(await ensureImageThumbnail(name)).toBe(false);
+ }
+ expect(sharpCalls.count).toBe(0);
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index b0db6c62a5..9fcd572415 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -312,6 +312,7 @@ export * from './secretText.js';
export * from './piiRedactionPatterns.js';
export * from './imageClean.js';
export * from './imageFrameStats.js';
+export * from './imageThumbnail.js';
export * from './imageRgba.js';
export * from './imageWatermark.js';
export * from './localImageFilename.js';
diff --git a/server/lib/paths.js b/server/lib/paths.js
index 41c5b8d334..fd685334cb 100644
--- a/server/lib/paths.js
+++ b/server/lib/paths.js
@@ -102,6 +102,7 @@ export const PATHS = {
voiceProfiles: join(INSTALL_ROOT, 'data/voice-profiles'),
videos: join(INSTALL_ROOT, 'data/videos'),
videoThumbnails: join(INSTALL_ROOT, 'data/video-thumbnails'),
+ imageThumbnails: join(INSTALL_ROOT, 'data/image-thumbnails'),
// Sprite Manager (issue #2895): per-record asset trees
// (sprites/<id>/{reference,walk,runs,runtime,atlas}/...). Records live in
// Postgres (sprite_records); only binary artifacts + manifests live here.
diff --git a/server/services/assetMounts.js b/server/services/assetMounts.js
index e646dc0100..0ec2d7a5ba 100644
--- a/server/services/assetMounts.js
+++ b/server/services/assetMounts.js
@@ -21,6 +21,7 @@ import { ServerError, sendErrorResponse } from '../lib/errorHandler.js';
import { ASSET_ROUTE_PREFIXES, SERVER_OWNED_PREFIXES } from '../lib/assetRoutePrefixes.js';
import { wrWorksDir, WORK_ID_RE } from './writersRoom/_shared.js';
import { escapeRegExp } from '../lib/textUtils.js';
+import { ensureImageThumbnail } from '../lib/imageThumbnail.js';
// `acceptRanges: true` is the serve-static default already, but we set it
// explicitly because the federated peer-sync receiver
@@ -37,6 +38,7 @@ const ASSET_STATIC_OPTS = {
res.setHeader('Content-Security-Policy', "sandbox; default-src 'none'; img-src 'self' data: blob:; media-src 'self'; style-src 'unsafe-inline'");
},
};
+const IMAGE_THUMBNAIL_STATIC_OPTS = { ...ASSET_STATIC_OPTS, maxAge: 24 * 60 * 60 * 1000 };
// Vite names every chunk, entry, stylesheet and imported asset it emits under
// `dist/assets/` by content hash (`index-B5J1S4I5.js`), so the bytes behind one
@@ -70,6 +72,7 @@ const writersRoomAssetsOnly = (req, res, next) => {
// mounted at all — silently — so `assetMounts.test.js` pins the two together.
const ASSET_DIRS = {
'/data/images': () => PATHS.images,
+ '/data/image-thumbnails': () => PATHS.imageThumbnails,
// Reference images (multi-ref upload inputs + generated character reference
// sheets) — served read-only so the UI can render thumbnails by URL.
'/data/image-refs': () => PATHS.imageRefs,
@@ -106,7 +109,21 @@ const ASSET_DIRS = {
'/data/writers-room/works': wrWorksDir,
};
-const ASSET_GATES = { '/data/writers-room/works': writersRoomAssetsOnly };
+const imageThumbnailGate = async (req, res, next) => {
+ // Only flat WebP names are valid. The helper also checks the PNG source
+ // before an existing derivative can be served.
+ if (!/^\/[A-Za-z0-9][A-Za-z0-9._-]*\.webp$/i.test(req.path)) return res.status(404).end();
+ const filename = req.path.slice(1);
+ const ready = await ensureImageThumbnail(filename);
+ if (!ready) return res.status(404).end();
+ res.setHeader('Cache-Control', 'public, max-age=86400');
+ next();
+};
+
+const ASSET_GATES = {
+ '/data/image-thumbnails': imageThumbnailGate,
+ '/data/writers-room/works': writersRoomAssetsOnly,
+};
/** The routes `ASSET_DIRS` knows a directory for — exported so a key that never
* reaches `ASSET_ROUTE_PREFIXES` (and is therefore never mounted) fails a test
@@ -159,7 +176,8 @@ function toRouteMatcher(pattern) {
*/
export function mountAssetRoutes(app, ownedPrefixes = SERVER_OWNED_PREFIXES) {
ASSET_MOUNTS.forEach(({ route, dir, gate }) => {
- app.use(route, ...(gate ? [gate] : []), express.static(dir(), ASSET_STATIC_OPTS));
+ const options = route === '/data/image-thumbnails' ? IMAGE_THUMBNAIL_STATIC_OPTS : ASSET_STATIC_OPTS;
+ app.use(route, ...(gate ? [gate] : []), express.static(dir(), options));
});
ownedPrefixes.forEach(({ prefix, spaPaths }) => {
const spaMatchers = spaPaths.map(toRouteMatcher);
diff --git a/server/services/assetMounts.test.js b/server/services/assetMounts.test.js
index 93d057dd85..e668ace4cb 100644
--- a/server/services/assetMounts.test.js
+++ b/server/services/assetMounts.test.js
@@ -16,6 +16,7 @@ import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
import express from 'express';
import { mkdirSync, rmSync, writeFileSync } from 'fs';
import { join } from 'path';
+import sharp from 'sharp';
import { request } from '../lib/testHelper.js';
import { createTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
@@ -43,11 +44,14 @@ const spaFallback = (req, res, next) => {
let app;
-beforeAll(() => {
+beforeAll(async () => {
// Real files under real mounts, so "the asset mounts still work" is proved by
// bytes coming back rather than by the absence of a 404.
mkdirSync(join(tempRoot, 'images'), { recursive: true });
writeFileSync(join(tempRoot, 'images', 'probe.png'), 'PNGBYTES');
+ writeFileSync(join(tempRoot, 'images', 'tile.png'), await sharp({
+ create: { width: 1024, height: 1024, channels: 3, background: '#123456' },
+ }).png().toBuffer());
const voiceProfiles = join(tempRoot, 'voice-profiles', 'voice-profile-1', 'benchmarks', 'v1');
mkdirSync(voiceProfiles, { recursive: true });
writeFileSync(join(voiceProfiles, '01-identity.wav'), 'WAVBYTES');
@@ -136,6 +140,19 @@ describe('the server-owned namespace terminators', () => {
expect(res.text).toBe('PNGBYTES');
});
+ it('generates a cached thumbnail only for a flat image source', async () => {
+ const res = await request(app).get('/data/image-thumbnails/tile.webp');
+ expect(res.status).toBe(200);
+ expect(res.headers['content-type']).toContain('image/webp');
+ expect(res.headers['cache-control']).toContain('max-age=86400');
+ expect(res.headers.etag).toBeTruthy();
+ expect(await sharp(join(tempRoot, 'image-thumbnails/tile.webp')).metadata())
+ .toMatchObject({ format: 'webp', width: 512, height: 512 });
+ for (const path of ['missing.webp', 'tile.png', 'nested/tile.webp', '..%2Ftile.webp']) {
+ expect((await request(app).get(`/data/image-thumbnails/${path}`)).status).toBe(404);
+ }
+ });
+
it('sandboxes directly opened peer asset files on every media mount', async () => {
for (const dir of ['images', 'image-refs', 'videos', 'music', 'audio']) {
mkdirSync(join(tempRoot, dir), { recursive: true });
diff --git a/server/services/backup.js b/server/services/backup.js
index 57124be766..8d7c580caa 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -151,6 +151,7 @@ const queueStateWrite = createFileWriteQueue();
// matches any `loras/` directory anywhere under data/ (e.g. a user's
// brain/.../loras/ collection), which would silently exclude unrelated user data.
export const DEFAULT_EXCLUDES = [
+ { path: '/image-thumbnails/', reason: 'Regenerable image grid previews', overridable: false },
{ path: '/python/laya-mlx/', reason: 'Rebuildable Laya-MLX experiment runtime and pinned model weights', overridable: false },
{ path: '/browser-profile/', reason: 'Browser CDP profile — cache/cookies, can be several GB', overridable: false },
{ path: '/cos/worktrees/', reason: 'Ephemeral agent git worktrees — recreated on demand', overridable: false },
diff --git a/server/services/dataManager.js b/server/services/dataManager.js
index 10f98fb406..55f97fde54 100644
--- a/server/services/dataManager.js
+++ b/server/services/dataManager.js
@@ -168,6 +168,7 @@ export const CATEGORIES = {
'update-detached': { label: 'Update Control', description: 'Control files for a detached self-update run — safe to purge when no update is running', archivable: false, deletable: true, purgeScope: 'category', busyCheck: updateDetachedBusy },
'uploads': { label: 'Uploads', description: 'Files uploaded through the UI and referenced by records', archivable: true, deletable: false },
'video-thumbnails': { label: 'Video Thumbnails', description: 'JPEG thumbnails for generated videos', archivable: false, deletable: true, purgeScope: 'category' },
+ 'image-thumbnails': { label: 'Image Thumbnails', description: 'Regenerable WebP previews for generated images', archivable: false, deletable: true, purgeScope: 'category' },
'videos': { label: 'Videos', description: 'Locally generated videos — delete individually; the render is the only copy and re-rendering costs provider spend', archivable: true, deletable: true, purgeScope: 'items' },
'voice-profiles': { label: 'Voice Profiles', description: 'Machine-local voice profile source recordings, benchmarks, and local engine artifacts', archivable: true, deletable: false },
'writers-room': { label: 'Writers Room', description: 'Writers Room works and story bibles', archivable: true, deletable: false },
diff --git a/server/services/imageGen/deleteImage.test.js b/server/services/imageGen/deleteImage.test.js
index 9b8711a2f9..bf1f0bc0bc 100644
--- a/server/services/imageGen/deleteImage.test.js
+++ b/server/services/imageGen/deleteImage.test.js
@@ -84,10 +84,14 @@ function seedImage(filename) {
describe('deleteImage → media asset index delete hook', () => {
it('unindexes the deleted image by its gallery filename', async () => {
seedImage('img-1.png');
+ const thumbnail = join(imagesDir, 'image-thumbnails', 'img-1.webp');
+ mkdirSync(join(imagesDir, 'image-thumbnails'), { recursive: true });
+ writeFileSync(thumbnail, 'derived preview');
const res = await deleteImage('img-1.png');
expect(res).toEqual({ ok: true });
expect(existsSync(join(imagesDir, 'img-1.png'))).toBe(false);
+ expect(existsSync(thumbnail)).toBe(false);
// The ref must be the gallery filename — the key the index wrote the row under.
expect(unindexImage).toHaveBeenCalledWith('img-1.png');
});
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index 62c4645aa4..0e38d934c6 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -1228,6 +1228,7 @@ export async function listGallery() {
export async function deleteImage(filename) {
assertGalleryFilename(filename);
+ await unlinkGuarded(join(PATHS.imageThumbnails, filename.replace(/\.png$/i, '.webp'))).catch(() => {});
await unlinkGuarded(join(PATHS.images, filename)).catch(() => {});
await unlinkGuarded(join(PATHS.images, filename.replace('.png', '.metadata.json'))).catch(() => {});
await unlinkGuarded(join(PATHS.images, `${filename}.metadata.json`)).catch(() => {});