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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(image-gen): Clean button on lightbox runs Image Cleaner over a render
Adam Eivy57a4707fc982
diff --git a/client/src/components/media/MediaLightbox.jsx b/client/src/components/media/MediaLightbox.jsxindex ac947aa7dd..29e39c6b16 100644--- a/client/src/components/media/MediaLightbox.jsx+++ b/client/src/components/media/MediaLightbox.jsx@@ -1,12 +1,15 @@-import { useEffect } from 'react';-import { X, Copy, Sparkles, Film, Image as ImageIcon, Download } from 'lucide-react';+import { useEffect, useState } from 'react';+import { X, Copy, Sparkles, Film, Image as ImageIcon, Download, Eraser } from 'lucide-react';import toast from '../ui/Toast';-// Full-screen preview for a normalized media item (image or video). Shows the-// media on the left, all generation settings on the right with copy buttons-// for the prompts, plus contextual actions (Remix, Send to Video, Continue-// from last frame). Esc + backdrop click close. Caller wires action handlers.-export default function MediaLightbox({ item, onClose, onRemix, onSendToVideo, onContinue }) {+// Mirror of CLEAN_LEVELS in server/routes/imageClean.js. If the server adds a+// new level, drop a label here and the pill renders automatically.+const CLEAN_LEVEL_LABELS = { light: 'Light', aggressive: 'Aggressive' };++// onClean(item, level) — optional. Returning a rejected promise keeps the+// lightbox open (e.g. on error) so the user can retry.+export default function MediaLightbox({ item, onClose, onRemix, onSendToVideo, onContinue, onClean }) {+ const [cleaning, setCleaning] = useState(null);useEffect(() => {if (!item) return;const onKey = (e) => { if (e.key === 'Escape') onClose(); };@@ -144,6 +147,41 @@ export default function MediaLightbox({ item, onClose, onRemix, onSendToVideo, o<Film className="w-3.5 h-3.5" /> Send to Video</button>)}+ {!isVideo && onClean && (+ <div+ className="flex items-stretch rounded overflow-hidden border border-port-border"+ role="group"+ aria-label="Clean image"+ >+ <span className="flex items-center gap-1 px-2 py-1.5 text-xs bg-port-border/40 text-gray-300">+ <Eraser className="w-3.5 h-3.5" /> Clean+ </span>+ {Object.entries(CLEAN_LEVEL_LABELS).map(([level, label]) => (+ <button+ key={level}+ type="button"+ disabled={cleaning != null}+ onClick={async () => {+ if (cleaning) return;+ setCleaning(level);+ let ok = false;+ try {+ await onClean(item, level);+ ok = true;+ } catch {+ // Caller toasts its own error; stay open so the user can retry.+ } finally {+ setCleaning(null);+ }+ if (ok) onClose();+ }}+ className={`px-2 py-1.5 text-xs border-l border-port-border text-white hover:opacity-90 disabled:opacity-50 disabled:cursor-not-allowed ${level === 'aggressive' ? 'bg-port-warning/80' : 'bg-port-border/70'}`}+ >+ {cleaning === level ? '…' : label}+ </button>+ ))}+ </div>+ )}{isVideo && onContinue && (<buttontype="button"diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsxindex 2e54cc4aa1..845adc946d 100644--- a/client/src/pages/ImageGen.jsx+++ b/client/src/pages/ImageGen.jsx@@ -30,7 +30,7 @@ import BrailleSpinner from '../components/BrailleSpinner';import { useImageGenProgress } from '../hooks/useImageGenProgress';import {getImageGenStatus, generateImage, listImageModels, listLoras, listImageGallery,- cancelImageGen, deleteImage, setImageHidden, getActiveImageJob, getSettings,+ cancelImageGen, deleteImage, setImageHidden, cleanGalleryImage, getActiveImageJob, getSettings,buildFormData, listMediaJobs,} from '../services/api';import { randomSeed, safeParseJSON } from '../lib/genUtils';@@ -609,6 +609,16 @@ export default function ImageGen() {if (result) toast.success(nextHidden ? 'Image hidden' : 'Image unhidden');};+ const handleClean = async (img, level) => {+ if (!img?.filename) throw new Error('Missing filename');+ const cleaned = await cleanGalleryImage(img.filename, level).catch((err) => {+ toast.error(err.message || 'Failed to clean image');+ throw err;+ });+ setGallery((g) => [cleaned, ...g.filter((x) => x.filename !== cleaned.filename)]);+ toast.success(`Cleaned (${level}) → ${cleaned.filename}`);+ };+const sendToVideo = (img) => {if (!img?.filename) return;const params = new URLSearchParams({ sourceImageFile: img.filename });@@ -1144,6 +1154,7 @@ export default function ImageGen() {// preview.filename access.onRemix={() => preview && handleRemix(preview)}onSendToVideo={() => preview?.filename && sendToVideo(preview)}+ onClean={(_item, level) => handleClean(preview, level)}/>diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.jsindex c318861652..4db5f9f500 100644--- a/client/src/services/apiImageVideo.js+++ b/client/src/services/apiImageVideo.js@@ -19,6 +19,10 @@ export const setImageHidden = (filename, hidden) => request(`/image-gen/${encodemethod: 'POST',body: JSON.stringify({ hidden }),});+export const cleanGalleryImage = (filename, level = 'light') => request(`/image-gen/${encodeURIComponent(filename)}/clean`, {+ method: 'POST',+ body: JSON.stringify({ level }),+});// Video genexport const getVideoGenStatus = () => request('/video-gen/status');diff --git a/server/routes/imageClean.js b/server/routes/imageClean.jsindex d4ab651441..1f1a6766b5 100644--- a/server/routes/imageClean.js+++ b/server/routes/imageClean.js@@ -102,20 +102,10 @@ function applyEncoder(pipeline, format) {return pipeline.webp({ quality: 92 });}-router.post('/', asyncHandler(async (req, res) => {- const { data, level } = validateRequest(cleanBodySchema, req.body);-- // Cap by base64 length BEFORE allocating the decoded Buffer so an oversized- // payload doesn't briefly balloon RSS.- if (data.length > MAX_BASE64_CHARS) {- throw new ServerError(`Image exceeds ${MAX_INPUT_BYTES / 1024 / 1024}MB limit`, {- status: 400,- code: 'FILE_TOO_LARGE',- });- }-- const buffer = Buffer.from(data, 'base64');- if (buffer.length === 0) {+// Throws ServerError (400) on invalid input so callers get a consistent+// status instead of a sharp stack trace surfacing as a 500.+export async function cleanImageBuffer(buffer, level = 'light') {+ if (!Buffer.isBuffer(buffer) || buffer.length === 0) {throw new ServerError('Decoded payload is empty', { status: 400, code: 'VALIDATION_ERROR' });}if (buffer.length > MAX_INPUT_BYTES) {@@ -140,38 +130,58 @@ router.post('/', asyncHandler(async (req, res) => {// browser showed in the Before preview (browsers honor EXIF orientation but// sharp does not by default). resolveWithObject gives us output dimensions// (post-rotation), avoiding a second decode for metadata.- // Wrap sharp errors (truncated/corrupt buffer that still passed the magic-byte- // sniff) into a 400 so bad client input doesn't surface as a 500. Pass the- // libvips reason through context.details so asyncHandler logs it once- // (instead of an extra console.error duplicating its own log line) — the- // sanitized client-facing message stays generic so libvips internals don't- // leak in the API response or socket broadcast.const base = sharp(buffer, { limitInputPixels: MAX_PIXELS }).rotate();- let cleaned;- let info;try {- ({ data: cleaned, info } = await applyEncoder(applyDenoise(base, level), format)- .toBuffer({ resolveWithObject: true }));+ const { data, info } = await applyEncoder(applyDenoise(base, level), format)+ .toBuffer({ resolveWithObject: true });+ return {+ data,+ format,+ mimeType: MIME_TYPES[format],+ sizeBefore: buffer.length,+ sizeAfter: data.length,+ width: info.width || null,+ height: info.height || null,+ c2paStripped,+ };} catch (err) {+ // Wrap sharp errors (truncated/corrupt buffer that still passed the+ // magic-byte sniff) into a 400 so bad input doesn't surface as a 500.throw new ServerError('Invalid or corrupt image', {status: 400,code: 'INVALID_IMAGE',context: { details: { format, reason: err.message } },});}+}++router.post('/', asyncHandler(async (req, res) => {+ const { data, level } = validateRequest(cleanBodySchema, req.body);++ // Cap by base64 length BEFORE allocating the decoded Buffer so an oversized+ // payload doesn't briefly balloon RSS.+ if (data.length > MAX_BASE64_CHARS) {+ throw new ServerError(`Image exceeds ${MAX_INPUT_BYTES / 1024 / 1024}MB limit`, {+ status: 400,+ code: 'FILE_TOO_LARGE',+ });+ }++ const buffer = Buffer.from(data, 'base64');+ const result = await cleanImageBuffer(buffer, level);- console.log(`🧼 Image cleaned: ${format} ${buffer.length}B → ${cleaned.length}B (level=${level}, c2pa=${c2paStripped})`);+ console.log(`🧼 Image cleaned: ${result.format} ${result.sizeBefore}B → ${result.sizeAfter}B (level=${level}, c2pa=${result.c2paStripped})`);res.json({- data: cleaned.toString('base64'),- mimeType: MIME_TYPES[format],- format,+ data: result.data.toString('base64'),+ mimeType: result.mimeType,+ format: result.format,level,- sizeBefore: buffer.length,- sizeAfter: cleaned.length,- width: info.width || null,- height: info.height || null,- c2paStripped,+ sizeBefore: result.sizeBefore,+ sizeAfter: result.sizeAfter,+ width: result.width,+ height: result.height,+ c2paStripped: result.c2paStripped,});}));diff --git a/server/routes/imageGen.clean.test.js b/server/routes/imageGen.clean.test.jsnew file mode 100644index 0000000000..49dc4a4eff--- /dev/null+++ b/server/routes/imageGen.clean.test.js@@ -0,0 +1,191 @@+import { describe, it, expect, beforeEach, beforeAll, afterAll, vi } from 'vitest';+import express from 'express';+import sharp from 'sharp';+import { mkdtemp, rm, writeFile, readFile, stat } from 'fs/promises';+import { existsSync } from 'fs';+import { join } from 'path';+import { tmpdir } from 'os';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++// Sandbox PATHS.images to a tmp dir so the clean endpoint can read/write real+// files without touching data/images/. The mock has to be installed BEFORE the+// route module imports fileUtils.js, hence the dynamic import below.+let sandbox;++vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ return {+ ...actual,+ get PATHS() {+ return { ...actual.PATHS, images: sandbox };+ },+ };+});++// Partial mock: keep the real `local` namespace (for assertGalleryFilename /+// readImageSidecar / etc.) and just stub out the dispatcher entry points so+// /generate doesn't try to spin up an actual provider during tests.+vi.mock('../services/imageGen/index.js', async () => {+ const actual = await vi.importActual('../services/imageGen/index.js');+ return {+ ...actual,+ checkConnection: vi.fn(),+ generateImage: vi.fn(),+ generateAvatar: vi.fn(),+ attachSseClient: vi.fn(() => false),+ cancel: vi.fn(() => false),+ };+});++vi.mock('../services/settings.js', () => ({+ getSettings: vi.fn(async () => ({ imageGen: { mode: 'external' } })),+}));++vi.mock('../services/mediaJobQueue/index.js', () => ({+ enqueueJob: vi.fn(),+ attachSseClient: vi.fn(() => false),+ cancelJob: vi.fn(),+ listJobs: vi.fn(() => []),+}));++let imageGenRoutes;+let pngFixture;++beforeAll(async () => {+ // Tmp dir created before route import so the mocked PATHS.images resolves+ // to a real path when the route reads from it.+ sandbox = await mkdtemp(join(tmpdir(), 'portos-imageclean-'));+ ({ default: imageGenRoutes } = await import('./imageGen.js'));+ // Noisy 16×16 RGB so light vs aggressive denoise produce visibly different+ // outputs. A solid-color fixture would round-trip identically through both.+ const raw = Buffer.alloc(16 * 16 * 3);+ for (let i = 0; i < raw.length; i += 1) raw[i] = (i * 73 + 11) % 256;+ pngFixture = await sharp(raw, { raw: { width: 16, height: 16, channels: 3 } })+ .png()+ .toBuffer();+});++afterAll(async () => {+ await rm(sandbox, { recursive: true, force: true });+});++describe('POST /api/image-gen/:filename/clean', () => {+ let app;++ beforeEach(() => {+ app = express();+ app.use(express.json());+ app.use('/api/image-gen', imageGenRoutes);+ app.use(errorMiddleware);+ });++ it('cleans an existing PNG and writes _clean-light.png back to the gallery', async () => {+ await writeFile(join(sandbox, 'render-1.png'), pngFixture);+ await writeFile(join(sandbox, 'render-1.metadata.json'), JSON.stringify({+ prompt: 'a red square', seed: 42, modelId: 'flux-v1',+ }));++ const res = await request(app).post('/api/image-gen/render-1.png/clean').send({ level: 'light' });+ expect(res.status).toBe(200);+ expect(res.body.filename).toBe('render-1_clean-light.png');+ expect(res.body.cleanedFrom).toBe('render-1.png');+ expect(res.body.cleanLevel).toBe('light');+ // Source sidecar carried forward so the cleaned copy retains lineage.+ expect(res.body.prompt).toBe('a red square');+ expect(res.body.seed).toBe(42);+ expect(res.body.modelId).toBe('flux-v1');++ expect(existsSync(join(sandbox, 'render-1_clean-light.png'))).toBe(true);+ expect(existsSync(join(sandbox, 'render-1_clean-light.metadata.json'))).toBe(true);+ });++ it('aggressive level produces a different output than light (different denoise)', async () => {+ await writeFile(join(sandbox, 'render-2.png'), pngFixture);++ const lightRes = await request(app).post('/api/image-gen/render-2.png/clean').send({ level: 'light' });+ const aggRes = await request(app).post('/api/image-gen/render-2.png/clean').send({ level: 'aggressive' });+ expect(lightRes.status).toBe(200);+ expect(aggRes.status).toBe(200);+ expect(lightRes.body.filename).toBe('render-2_clean-light.png');+ expect(aggRes.body.filename).toBe('render-2_clean-aggressive.png');++ const lightBuf = await readFile(join(sandbox, lightRes.body.filename));+ const aggBuf = await readFile(join(sandbox, aggRes.body.filename));+ expect(lightBuf.equals(aggBuf)).toBe(false);+ });++ it('idempotent: running the same level twice overwrites instead of accumulating', async () => {+ await writeFile(join(sandbox, 'render-3.png'), pngFixture);+ const first = await request(app).post('/api/image-gen/render-3.png/clean').send({ level: 'light' });+ const second = await request(app).post('/api/image-gen/render-3.png/clean').send({ level: 'light' });+ expect(first.body.filename).toBe(second.body.filename);+ expect(first.body.filename).toBe('render-3_clean-light.png');+ });++ it('defaults to light when level omitted', async () => {+ await writeFile(join(sandbox, 'render-4.png'), pngFixture);+ const res = await request(app).post('/api/image-gen/render-4.png/clean').send({});+ expect(res.status).toBe(200);+ expect(res.body.cleanLevel).toBe('light');+ });++ it('rejects unknown level', async () => {+ await writeFile(join(sandbox, 'render-5.png'), pngFixture);+ const res = await request(app).post('/api/image-gen/render-5.png/clean').send({ level: 'extreme' });+ expect(res.status).toBe(400);+ });++ it('rejects non-PNG filenames (gallery is PNG-only)', async () => {+ const res = await request(app).post('/api/image-gen/render.jpg/clean').send({ level: 'light' });+ expect(res.status).toBe(400);+ });++ it('rejects path-traversal in filename', async () => {+ const res = await request(app).post('/api/image-gen/' + encodeURIComponent('../etc/passwd.png') + '/clean').send({ level: 'light' });+ expect(res.status).toBe(400);+ });++ it('returns 404 when the source image does not exist', async () => {+ const res = await request(app).post('/api/image-gen/does-not-exist.png/clean').send({ level: 'light' });+ expect(res.status).toBe(404);+ });++ it('writes a sidecar that records the cleaning lineage', async () => {+ await writeFile(join(sandbox, 'render-6.png'), pngFixture);+ await request(app).post('/api/image-gen/render-6.png/clean').send({ level: 'aggressive' });+ const sidecar = JSON.parse(await readFile(join(sandbox, 'render-6_clean-aggressive.metadata.json'), 'utf-8'));+ expect(sidecar.cleanedFrom).toBe('render-6.png');+ expect(sidecar.cleanLevel).toBe('aggressive');+ expect(typeof sidecar.createdAt).toBe('string');+ });++ it('strips hidden=true from the cleaned copy so it surfaces in the gallery', async () => {+ await writeFile(join(sandbox, 'render-hidden.png'), pngFixture);+ await writeFile(join(sandbox, 'render-hidden.metadata.json'), JSON.stringify({+ prompt: 'a hidden render', hidden: true,+ }));+ const res = await request(app).post('/api/image-gen/render-hidden.png/clean').send({ level: 'light' });+ expect(res.status).toBe(200);+ expect(res.body.hidden).toBeUndefined();+ expect(res.body.prompt).toBe('a hidden render');++ const sidecar = JSON.parse(await readFile(join(sandbox, 'render-hidden_clean-light.metadata.json'), 'utf-8'));+ expect(sidecar.hidden).toBeUndefined();+ });++ it('accepts legitimate filenames containing `..` substring (not exact `..`)', async () => {+ await writeFile(join(sandbox, 'my..render.png'), pngFixture);+ const res = await request(app).post(`/api/image-gen/${encodeURIComponent('my..render.png')}/clean`).send({ level: 'light' });+ expect(res.status).toBe(200);+ expect(res.body.filename).toBe('my..render_clean-light.png');+ });++ it('output file size is reflected in sizeBytes / sizeAfter', async () => {+ await writeFile(join(sandbox, 'render-7.png'), pngFixture);+ const res = await request(app).post('/api/image-gen/render-7.png/clean').send({ level: 'light' });+ const s = await stat(join(sandbox, res.body.filename));+ expect(res.body.sizeBytes).toBe(s.size);+ expect(res.body.sizeAfter).toBe(s.size);+ });+});diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex 7273d3539f..f822519d45 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -30,7 +30,9 @@ import {} from '../lib/pythonSetup.js';import { PATHS, ensureDir } from '../lib/fileUtils.js';import { join, basename, resolve as resolvePath, sep as PATH_SEP } from 'node:path';+import { readFile, writeFile } from 'fs/promises';import { STYLE_PRESETS } from '../lib/writersRoomStylePresets.js';+import { cleanImageBuffer, CLEAN_LEVELS } from './imageClean.js';const router = Router();@@ -321,6 +323,70 @@ router.post('/:filename/visibility', asyncHandler(async (req, res) => {res.json(await local.setImageHidden(req.params.filename, !!req.body?.hidden));}));+router.post('/:filename/clean', asyncHandler(async (req, res) => {+ const { level } = validateRequest(+ z.object({ level: z.enum(CLEAN_LEVELS).optional().default('light') }),+ req.body,+ );+ const filename = req.params.filename;+ local.assertGalleryFilename(filename);++ const sourcePath = join(PATHS.images, filename);+ const [buffer, { metadata: sourceMeta }] = await Promise.all([+ readFile(sourcePath).catch((err) => {+ if (err.code === 'ENOENT') throw new ServerError('Image not found', { status: 404, code: 'NOT_FOUND' });+ throw err;+ }),+ local.readImageSidecar(filename),+ ]);++ const result = await cleanImageBuffer(buffer, level);+ if (result.format !== 'png') {+ throw new ServerError('Gallery images must be PNG', { status: 400, code: 'UNSUPPORTED_FORMAT' });+ }++ const base = filename.slice(0, -'.png'.length);+ const outFilename = `${base}_clean-${level}.png`;+ const outPath = join(PATHS.images, outFilename);+ const sidecarPath = join(PATHS.images, `${base}_clean-${level}.metadata.json`);++ const createdAt = new Date().toISOString();+ // Strip `hidden` so a clean of a hidden source still surfaces in the gallery+ // — cleaning is a deliberate user action that implies wanting to see the result.+ const { hidden: _hidden, ...sourceMetaForCleaned } = sourceMeta;+ const cleanedMeta = {+ ...sourceMetaForCleaned,+ createdAt,+ cleanedFrom: filename,+ cleanLevel: level,+ c2paStripped: result.c2paStripped,+ };++ await Promise.all([+ writeFile(outPath, result.data),+ writeFile(sidecarPath, JSON.stringify(cleanedMeta, null, 2)),+ ]);++ console.log(`🧼 Cleaned ${filename} → ${outFilename} (level=${level}, ${result.sizeBefore}B → ${result.sizeAfter}B, c2pa=${result.c2paStripped})`);++ // sourceMeta first so explicit fields below win on key collisions (the+ // cleaned copy's createdAt must reflect the cleaning, not the original).+ res.json({+ ...sourceMetaForCleaned,+ filename: outFilename,+ path: `/data/images/${outFilename}`,+ createdAt,+ sizeBefore: result.sizeBefore,+ sizeAfter: result.sizeAfter,+ sizeBytes: result.sizeAfter,+ width: result.width,+ height: result.height,+ cleanedFrom: filename,+ cleanLevel: level,+ c2paStripped: result.c2paStripped,+ });+}));+// --- Local-mode setup automation ---router.get('/setup/python', asyncHandler(async (_req, res) => {diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsindex 421eadce7a..f0584bf54b 100644--- a/server/services/imageGen/local.js+++ b/server/services/imageGen/local.js@@ -428,6 +428,30 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', mreturn { jobId, filename, path: `/data/images/${filename}`, generationId: jobId, mode: 'local', model: modelId, seed: actualSeed };}+// Validate a gallery filename: PNG-only, basename only, no path separators.+// `.endsWith('.png')` already rejects `.` and `..` so substring-`..` matching+// would over-reject legitimate names like `my..render.png`. Throws a 400 so+// callers don't have to repeat the check.+export function assertGalleryFilename(filename) {+ if (!filename || !filename.endsWith('.png')+ || filename.includes('/') || filename.includes('\\')) {+ throw new ServerError('Invalid filename', { status: 400, code: 'VALIDATION_ERROR' });+ }+}++// Returns `{ path, metadata }`. `path` is the resolved sidecar location, or+// the preferred Portos location on miss — callers writing back land at the+// canonical path automatically.+export async function readImageSidecar(filename) {+ const portosSidecar = join(PATHS.images, filename.replace('.png', '.metadata.json'));+ const altSidecar = join(PATHS.images, `${filename}.metadata.json`);+ for (const path of [portosSidecar, altSidecar]) {+ const raw = await readFile(path, 'utf-8').catch(() => null);+ if (raw != null) return { path, metadata: safeJSONParse(raw, {}) };+ }+ return { path: portosSidecar, metadata: {} };+}+export async function listGallery() {if (!existsSync(PATHS.images)) return [];const files = await readdir(PATHS.images);@@ -436,15 +460,7 @@ export async function listGallery() {const fullPath = join(PATHS.images, f);const s = await stat(fullPath).catch(() => null);if (!s) return null;- // Try our sidecar first, fall back to mflux's own .metadata.json shape.- const portosSidecar = join(PATHS.images, f.replace('.png', '.metadata.json'));- const altSidecar = join(PATHS.images, `${f}.metadata.json`);- const path = existsSync(portosSidecar) ? portosSidecar : (existsSync(altSidecar) ? altSidecar : null);- let metadata = {};- if (path) {- const raw = await readFile(path, 'utf-8').catch(() => null);- if (raw) metadata = safeJSONParse(raw, {});- }+ const { metadata } = await readImageSidecar(f);return {filename: f,path: `/data/images/${f}`,@@ -456,9 +472,7 @@ export async function listGallery() {}export async function deleteImage(filename) {- if (!filename.endsWith('.png') || filename.includes('/') || filename.includes('\\') || filename.includes('..')) {- throw new ServerError('Invalid filename', { status: 400, code: 'VALIDATION_ERROR' });- }+ assertGalleryFilename(filename);await unlink(join(PATHS.images, filename)).catch(() => {});await unlink(join(PATHS.images, filename.replace('.png', '.metadata.json'))).catch(() => {});await unlink(join(PATHS.images, `${filename}.metadata.json`)).catch(() => {});@@ -467,17 +481,11 @@ export async function deleteImage(filename) {}export async function setImageHidden(filename, hidden) {- if (!filename.endsWith('.png') || filename.includes('/') || filename.includes('\\') || filename.includes('..')) {- throw new ServerError('Invalid filename', { status: 400, code: 'VALIDATION_ERROR' });- }- const portosSidecar = join(PATHS.images, filename.replace('.png', '.metadata.json'));- const altSidecar = join(PATHS.images, `${filename}.metadata.json`);- const sidecarPath = existsSync(portosSidecar) ? portosSidecar : (existsSync(altSidecar) ? altSidecar : portosSidecar);- const raw = await readFile(sidecarPath, 'utf-8').catch(() => null);- const meta = raw ? safeJSONParse(raw, {}) : {};- meta.hidden = !!hidden;- await writeFile(sidecarPath, JSON.stringify(meta, null, 2));- return { ok: true, hidden: meta.hidden };+ assertGalleryFilename(filename);+ const { path: sidecarPath, metadata } = await readImageSidecar(filename);+ metadata.hidden = !!hidden;+ await writeFile(sidecarPath, JSON.stringify(metadata, null, 2));+ return { ok: true, hidden: metadata.hidden };}// Returns just `{ filename, name }` — clients send `filename` back in the