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

feat: remove visible Gemini/Nano-Banana corner watermark

Adam Eivy72162b639d38
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index bc3aea8153..88fe27130a 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,6 @@
## Added
+- **Image gallery: remove the Gemini / Nano-Banana ✦ sparkle** — gallery images now get a **Remove ✦** action in the lightbox that erases the visible sparkle logo Google stamps into the bottom-right corner of its image-gen output. It localizes just that corner and reconstructs it from the surrounding pixels (a dependency-free harmonic inpaint — no GPU, runs on every install), leaving the rest of the image untouched, and saves the result as a new variant alongside the original. This is distinct from the existing **Regenerate** (which overwrites the *invisible* SynthID watermark by re-rolling the whole image) — the sparkle is a visible, fixed-position logo, so it gets a surgical corner fix instead. Available everywhere the media lightbox appears (Image Gen, History, Collections, Universe Builder).
- **[issue-900] Autobiography: deeper follow-ups and a woven life story** — the autobiography's AI follow-up questions now get more reflective as a story thread grows, moving from "what happened" to "what it meant" so each round builds a richer narrative instead of circling the same details. Once a story is part of a follow-up chain, a new **Weave** button stitches the whole thread — every prompt and answer — into a single flowing first-person passage you can read and copy.
- **Local LLM catalog: Nex-N2-mini** — the local-model install picker now lists Nex AGI's Nex-N2-mini, a 35B/3B-active agentic MoE (Apache-2.0, built on Qwen3.5) strong at coding, tool calling, long-horizon agent tasks, and vision. The Q4 GGUF is ~22 GB — comfortable on a 32GB machine and trivial on a 128GB unified-memory Mac. Its 397B sibling Nex-N2-Pro is intentionally left out: it won't fit a 128GB Mac even at Q4.
- **[issue-1028] Songs: a practice mode to learn and memorize a song** — the song editor and reader gain a Training panel that turns the sheet music into a drill. Pick the whole song or a single section, get a one-bar count-in, sing it, and watch each note light up green/yellow/red with an accuracy score for the take — then repeat, or turn on Loop to keep cycling the same part. PortOS tracks your progress over time: each section earns a rolling average and flips to "learned" once you hit it accurately a few takes in a row, a memorization bar shows how much of the song you've got down, and it nudges you toward your weakest sections to practice next. As your accuracy on a part climbs, the lyrics fade and finally hide so you're singing it from memory. It runs entirely on the built-in pitch detection — no extra audio library — and completes the song system's vocal pitch-detection and training toolkit.
diff --git a/client/src/components/media/MediaLightbox.jsx b/client/src/components/media/MediaLightbox.jsx
index 5bf3f22fb3..11b61ef169 100644
--- a/client/src/components/media/MediaLightbox.jsx
+++ b/client/src/components/media/MediaLightbox.jsx
@@ -61,6 +61,11 @@ function describeCleanedLineage(item) {
const method = item.regenMethod === 'light-spatial' ? ' (light)' : '';
return `Regenerated${method} from ${item.cleanedFrom}${denoise}${fidelity}`;
}
+ // Visible-watermark removal (the Gemini ✦ corner inpaint) also reuses
+ // `cleanedFrom` for grouping — describe it as its own lineage, not a clean.
+ if (item.watermarkRemoved && item.cleanedFrom) {
+ return `Watermark removed from ${item.cleanedFrom}`;
+ }
if (item.cleanedFrom) {
return `${item.cleanLevel ? `Cleaned (${item.cleanLevel}) ` : 'Cleaned '}from ${item.cleanedFrom}`;
}
@@ -84,6 +89,7 @@ export default function MediaLightbox({
onContinue,
onClean,
onRegenerate,
+ onRemoveWatermark,
regenAvailable = false,
regenBounds = null,
onPrevious,
@@ -329,6 +335,7 @@ export default function MediaLightbox({
onContinue={onContinue}
onClean={onClean}
onRegenerate={onRegenerate}
+ onRemoveWatermark={onRemoveWatermark}
regenAvailable={regenAvailable}
regenBounds={regenBounds}
copy={copy}
@@ -372,7 +379,7 @@ function PeerNotes({ others }) {
function SettingsPane({
item, meta, isVideo,
- onClose, onRemix, onSendToImage, onSendToVideo, onContinue, onClean, onRegenerate, regenAvailable, regenBounds,
+ onClose, onRemix, onSendToImage, onSendToVideo, onContinue, onClean, onRegenerate, onRemoveWatermark, regenAvailable, regenBounds,
copy, onRefine,
annotation, onAnnotationChange,
variantGroup, onSelectVariant,
@@ -381,6 +388,7 @@ function SettingsPane({
const [cleaning, setCleaning] = useState(false);
const [regenerating, setRegenerating] = useState(false);
const [lightRegenerating, setLightRegenerating] = useState(false);
+ const [removingWatermark, setRemovingWatermark] = useState(false);
// Regen controls: the button toggles an inline panel (strength slider +
// optional prompt) so a watermark-defeat pass can be tuned without leaving the
// lightbox. Slider bounds come from the server (`regenBounds`) so the floor
@@ -658,6 +666,18 @@ function SettingsPane({
<Eraser className="w-3.5 h-3.5" /> {cleaning ? 'Cleaning…' : 'Clean'}
</button>
)}
+ {!isVideo && onRemoveWatermark && (
+ <button
+ type="button"
+ disabled={removingWatermark}
+ onClick={runBusyAction(removingWatermark, setRemovingWatermark, onRemoveWatermark)}
+ title="Erase the visible Gemini / Nano-Banana ✦ sparkle from the bottom-right corner. Reconstructs just that corner from its surroundings — the rest of the image is untouched. Creates a new variant; the original is kept."
+ aria-label="Remove Gemini watermark sparkle"
+ className="flex-1 flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs bg-port-warning/80 text-white hover:opacity-90 rounded disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ <Sparkles className="w-3.5 h-3.5" /> {removingWatermark ? 'Removing…' : 'Remove ✦'}
+ </button>
+ )}
{!isVideo && onRegenerate && regenAvailable && (
<button
type="button"
diff --git a/client/src/components/media/variants.js b/client/src/components/media/variants.js
index 80281e3cc0..c23e88ecea 100644
--- a/client/src/components/media/variants.js
+++ b/client/src/components/media/variants.js
@@ -53,6 +53,12 @@ export function computeImageVariantGroup(item, items) {
group.push({ label: 'Regenerated', item: c });
continue;
}
+ // Visible-watermark removal (Gemini ✦ corner inpaint) also reuses
+ // `cleanedFrom` for grouping — label it distinctly from a clean.
+ if (c.watermarkRemoved) {
+ group.push({ label: 'Watermark removed', item: c });
+ continue;
+ }
const levelTag = c.cleanLevel ? ` (${c.cleanLevel})` : '';
group.push({ label: `Cleaned${levelTag}`, item: c });
}
diff --git a/client/src/hooks/useMediaPreviewActions.js b/client/src/hooks/useMediaPreviewActions.js
index 66b39fb3f2..718c3783c0 100644
--- a/client/src/hooks/useMediaPreviewActions.js
+++ b/client/src/hooks/useMediaPreviewActions.js
@@ -1,7 +1,7 @@
import { useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import toast from '../components/ui/Toast';
-import { cleanGalleryImage, extractLastFrame } from '../services/apiImageVideo';
+import { cleanGalleryImage, extractLastFrame, removeImageWatermark } from '../services/apiImageVideo';
import { VIDEO_TILING_ENUM_SET } from '../lib/videoTilingOptions';
// Common image render-setting params shared by the image branch of Remix and by
@@ -160,5 +160,20 @@ export default function useMediaPreviewActions({ onCleanComplete = null } = {})
return cleaned;
}, [onCleanComplete]);
- return { handleRemix, handleSendToImage, handleSendToVideo, handleContinue, handleClean };
+ // Remove watermark: erase the visible Gemini/Nano-Banana ✦ from the
+ // bottom-right corner via a localized inpaint. Like Clean, it returns a new
+ // `_nowatermark.png` gallery variant — reuse the same `onCleanComplete`
+ // splice callback so the variant lands in the consumer's local state.
+ const handleRemoveWatermark = useCallback(async (img) => {
+ if (!img?.filename) throw new Error('Missing filename');
+ const variant = await removeImageWatermark(img.filename).catch((err) => {
+ toast.error(err.message || 'Failed to remove watermark');
+ throw err;
+ });
+ toast.success(`Watermark removed → ${variant.filename}`);
+ if (onCleanComplete) await onCleanComplete(variant);
+ return variant;
+ }, [onCleanComplete]);
+
+ return { handleRemix, handleSendToImage, handleSendToVideo, handleContinue, handleClean, handleRemoveWatermark };
}
diff --git a/client/src/hooks/useMediaPreviewActions.test.jsx b/client/src/hooks/useMediaPreviewActions.test.jsx
index d0afd742fd..be86e969b8 100644
--- a/client/src/hooks/useMediaPreviewActions.test.jsx
+++ b/client/src/hooks/useMediaPreviewActions.test.jsx
@@ -5,7 +5,13 @@ import useMediaPreviewActions from './useMediaPreviewActions';
const navigate = vi.fn();
vi.mock('react-router-dom', () => ({ useNavigate: () => navigate }));
vi.mock('../components/ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));
-vi.mock('../services/apiImageVideo', () => ({ cleanGalleryImage: vi.fn(), extractLastFrame: vi.fn() }));
+vi.mock('../services/apiImageVideo', () => ({
+ cleanGalleryImage: vi.fn(),
+ extractLastFrame: vi.fn(),
+ removeImageWatermark: vi.fn(),
+}));
+
+import { removeImageWatermark } from '../services/apiImageVideo';
const parseNav = () => {
const url = navigate.mock.calls.at(-1)?.[0] || '';
@@ -51,3 +57,24 @@ describe('useMediaPreviewActions.handleSendToImage', () => {
expect(navigate).not.toHaveBeenCalled();
});
});
+
+describe('useMediaPreviewActions.handleRemoveWatermark', () => {
+ beforeEach(() => removeImageWatermark.mockReset());
+
+ it('calls the API and fires onCleanComplete with the returned variant', async () => {
+ const variant = { filename: 'cat_nowatermark.png', watermarkRemoved: true };
+ removeImageWatermark.mockResolvedValue(variant);
+ const onCleanComplete = vi.fn();
+ const { result } = renderHook(() => useMediaPreviewActions({ onCleanComplete }));
+ const returned = await result.current.handleRemoveWatermark({ filename: 'cat.png' });
+ expect(removeImageWatermark).toHaveBeenCalledWith('cat.png');
+ expect(onCleanComplete).toHaveBeenCalledWith(variant);
+ expect(returned).toBe(variant);
+ });
+
+ it('throws when the image has no filename', async () => {
+ const { result } = renderHook(() => useMediaPreviewActions());
+ await expect(result.current.handleRemoveWatermark({})).rejects.toThrow('Missing filename');
+ expect(removeImageWatermark).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsx
index 110b815b01..cc2360028f 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -48,7 +48,7 @@ import { useModelDownloadStatus } from '../hooks/useModelDownloadStatus';
import {
getImageGenStatus, generateImage, listImageModels, listLorasFull, listImageGallery,
cancelImageGen, deleteImage, setImageHidden, cleanGalleryImage, getActiveImageJob, getSettings,
- buildFormData, listMediaJobs, regenerateGalleryImage, getRegenAvailability,
+ buildFormData, listMediaJobs, regenerateGalleryImage, getRegenAvailability, removeImageWatermark,
} from '../services/api';
// Multi-reference editing (FLUX.2 only) — 4 fixed slots, each carrying an
@@ -929,6 +929,19 @@ export default function ImageGen() {
toast.success(`Cleaned → ${cleaned.filename}`);
};
+ // Visible-watermark removal — erases the Gemini/Nano-Banana ✦. Synchronous
+ // like Clean: returns the new `_nowatermark.png` variant directly, so insert
+ // it into the gallery rather than waiting on the render queue.
+ const handleRemoveWatermark = async (img) => {
+ if (!img?.filename) throw new Error('Missing filename');
+ const variant = await removeImageWatermark(img.filename).catch((err) => {
+ toast.error(err.message || 'Failed to remove watermark');
+ throw err;
+ });
+ setGallery((g) => [variant, ...g.filter((x) => x.filename !== variant.filename)]);
+ toast.success(`Watermark removed → ${variant.filename}`);
+ };
+
// SynthID-defeat regen (issue #912) — unlike clean, this is a queued local
// FLUX render: it returns a job ack, and the finished variant lands in the
// gallery via the queue-completion refresh (useMediaCompletionRefresh /
@@ -1471,6 +1484,7 @@ export default function ImageGen() {
onSendToVideo={(item) => item?.raw?.filename && sendToVideo(item.raw)}
onClean={(item) => handleClean(item?.raw)}
onRegenerate={(item, opts) => handleRegenerate(item?.raw, opts)}
+ onRemoveWatermark={(item) => handleRemoveWatermark(item?.raw)}
regenAvailable={regenAvailable}
regenBounds={regenInfo}
/>
diff --git a/client/src/pages/MediaCollectionDetail.jsx b/client/src/pages/MediaCollectionDetail.jsx
index 298f305730..853dbfccb1 100644
--- a/client/src/pages/MediaCollectionDetail.jsx
+++ b/client/src/pages/MediaCollectionDetail.jsx
@@ -269,7 +269,7 @@ export default function MediaCollectionDetail() {
// the cleaned image to THIS collection + seed imagesByName so hydrate()
// renders it immediately, no refresh round-trip) is wired through
// `onCleanComplete`.
- const { handleRemix, handleSendToImage, handleSendToVideo, handleContinue, handleClean } = useMediaPreviewActions({
+ const { handleRemix, handleSendToImage, handleSendToVideo, handleContinue, handleClean, handleRemoveWatermark } = useMediaPreviewActions({
onCleanComplete: async (cleaned) => {
// The server's clean route auto-files the cleaned filename into every
// collection that contained the source — including this one — so this
@@ -559,6 +559,7 @@ export default function MediaCollectionDetail() {
onSendToVideo={handleSendToVideo}
onContinue={(i) => handleContinue(i.raw || i)}
onClean={(i) => handleClean(i?.raw || i)}
+ onRemoveWatermark={(i) => handleRemoveWatermark(i?.raw || i)}
/>
</div>
);
diff --git a/client/src/pages/MediaHistory.jsx b/client/src/pages/MediaHistory.jsx
index bf05ed748a..8b3f3b58c9 100644
--- a/client/src/pages/MediaHistory.jsx
+++ b/client/src/pages/MediaHistory.jsx
@@ -132,7 +132,7 @@ export default function MediaHistory() {
// the cleaned image to the top of the local list) is page-specific —
// wired through `onCleanComplete` so the cleaned record lands in `items`
// without a full gallery refetch.
- const { handleRemix, handleSendToImage, handleSendToVideo, handleContinue, handleClean } = useMediaPreviewActions({
+ const { handleRemix, handleSendToImage, handleSendToVideo, handleContinue, handleClean, handleRemoveWatermark } = useMediaPreviewActions({
onCleanComplete: (cleaned) => {
const normalized = normalizeImage(cleaned);
setItems((prev) => [normalized, ...prev.filter((x) => x.key !== normalized.key)]);
@@ -280,6 +280,7 @@ export default function MediaHistory() {
onSendToVideo={handleSendToVideo}
onContinue={handleContinue}
onClean={(item) => handleClean(item?.raw)}
+ onRemoveWatermark={(item) => handleRemoveWatermark(item?.raw)}
/>
</div>
);
diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsx
index acaa097704..eb328c79fb 100644
--- a/client/src/pages/UniverseBuilder.jsx
+++ b/client/src/pages/UniverseBuilder.jsx
@@ -2076,6 +2076,7 @@ export default function UniverseBuilder() {
onSendToImage={preview?.key?.startsWith('canon-sheet:') ? undefined : previewActions.handleSendToImage}
onSendToVideo={preview?.key?.startsWith('canon-sheet:') ? undefined : previewActions.handleSendToVideo}
onClean={preview?.key?.startsWith('canon-sheet:') ? undefined : (item) => previewActions.handleClean(item?.raw || item)}
+ onRemoveWatermark={preview?.key?.startsWith('canon-sheet:') ? undefined : (item) => previewActions.handleRemoveWatermark(item?.raw || item)}
onContinue={preview?.key?.startsWith('canon-sheet:') ? undefined : (item) => previewActions.handleContinue(item?.raw || item)}
/>
</div>
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index ddc0222c03..a698c5cc0d 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -26,6 +26,20 @@ export const cleanGalleryImage = (filename) => request(`/image-gen/${encodeURICo
method: 'POST',
body: JSON.stringify({}),
});
+// Visible-watermark removal — erases the Gemini / Nano-Banana bottom-right ✦
+// via a CPU-only localized inpaint. Synchronous (like Clean): returns the new
+// `_nowatermark.png` variant directly. `opts` may carry `{ size }` or an
+// explicit `{ region: { x, y, w, h } }` for off-spec placements; omit for the
+// auto-sized corner box. `silent` so the lightbox owns its own error toast.
+export const removeImageWatermark = (filename, opts = {}) =>
+ request(`/image-gen/${encodeURIComponent(filename)}/remove-watermark`, {
+ method: 'POST',
+ body: JSON.stringify({
+ ...(opts.size != null ? { size: opts.size } : {}),
+ ...(opts.region != null ? { region: opts.region } : {}),
+ }),
+ silent: true,
+ });
// SynthID-defeat regen (issue #912). Enqueues a local-FLUX img2img round-trip
// of a gallery image; returns the queue ack ({ jobId, position, ... }) — the
// finished render lands in the gallery via the normal queue-completion refresh.
diff --git a/server/lib/README.md b/server/lib/README.md
index 145b9d2dc4..286a02a9ef 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -101,6 +101,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `safeJSONParse`, `expandHome` (`~/foo` → absolute), JSONL append/read/write helpers, dir scans, hashes, JSON helpers. Most paths/file work goes through here. |
| `fileWriteQueue.js` | Single-tail promise chain for serializing writes to a file. |
| `imageClean.js` | `cleanImageBuffer` (sharp-based denoise + C2PA strip) + `autoCleanGeneratedImage` (in-place clean for post-generation hook). HTTP route in `routes/imageClean.js` wraps `cleanImageBuffer`. |
+| `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. |
| `multipart.js` | Streaming multipart/form-data parser. |
| `safetensors.js` | `readSafetensorsHeader(path)` reads only the JSON header of a `.safetensors` file (never the tensor payload). `detectFlux2VariantFromHeader(header)` / `detectFlux2Variant(path)` classify a LoRA as FLUX.2 Klein `'4b'` (hidden dim 3072) vs `'9b'` (4096) by transformer-block tensor shapes, so the LoRA picker can hide off-variant weights that would silently fail to load. |
| `pdfImageEmbed.js` | PDF image embed helpers for comic / volume PDFs. |
diff --git a/server/lib/imageWatermark.js b/server/lib/imageWatermark.js
new file mode 100644
index 0000000000..fa0b942731
--- /dev/null
+++ b/server/lib/imageWatermark.js
@@ -0,0 +1,232 @@
+// Visible-watermark removal — erases the Gemini / Nano-Banana "✦" sparkle that
+// Google stamps into the BOTTOM-RIGHT corner of its image-gen output.
+//
+// This is a DIFFERENT problem from SynthID (handled by `imageGen/regen.js`):
+// - SynthID is an *invisible* per-pixel signal → defeated by a generative
+// img2img round-trip / spatial resample.
+// - The sparkle is a *visible*, fixed-position opaque logo → no amount of
+// low-denoise img2img reliably erases a baked-in mark, and the local FLUX
+// runner has no masked-inpaint path. The honest fix is to localize the
+// corner box and reconstruct it from its surroundings.
+//
+// Method (dependency-free, sharp only — no GPU, runs on every install): solve
+// Laplace's equation over the corner box with the surrounding ring as a fixed
+// (Dirichlet) boundary. The result is the smooth harmonic membrane that the
+// background gradient/texture implies — seamless on plain/gradient corners
+// (sky, walls, bokeh), a soft smear on busy ones, but always far better than
+// the bright star. We extract only a small patch around the box so memory cost
+// is independent of the source resolution.
+//
+// Scope: post-hoc, gallery-only — a sibling action to "Clean" in the lightbox.
+// Never auto-applied. The corner box defaults to the sparkle's typical
+// footprint but the caller may override `region` for off-spec placements.
+
+import sharp from 'sharp';
+import { ServerError } from './errorHandler.js';
+
+// Cap decoded pixels to guard against decompression-bomb inputs (mirrors the
+// limit in imageClean.js — the patch extract reads from the same decode).
+const MAX_PIXELS = 96 * 1000 * 1000;
+
+// Default sparkle footprint as a fraction of the image's short side, clamped to
+// a sane pixel range. Google's mark sits flush-ish to the bottom-right with a
+// small inset; a box anchored to the corner (touching the right + bottom edges)
+// guarantees coverage regardless of the exact inset, while the left + top
+// borders supply the fill. Tuned generous enough to swallow the star + its
+// halo without eating a large slice of real content.
+const DEFAULT_REGION_FRACTION = 0.11;
+const DEFAULT_REGION_MIN_PX = 56;
+const DEFAULT_REGION_MAX_PX = 220;
+
+// Ring of real pixels kept around the box as the fill's boundary condition.
+// Proportional to the box so larger images get a proportionally thicker (and
+// thus more representative) boundary sample.
+const RING_FRACTION = 0.25;
+const RING_MIN_PX = 12;
+
+// Gauss-Seidel relaxation sweeps. The box is small (≤220px) so even a few
+// hundred sweeps are a few ms; 200 is comfortably past visual convergence for
+// this size. Over-relaxation (ω>1) speeds convergence without artifacts.
+const SOLVER_ITERATIONS = 200;
+const SOLVER_OMEGA = 1.8;
+
+const clampInt = (n, lo, hi) => Math.max(lo, Math.min(hi, Math.round(n)));
+
+/**
+ * Resolve the bottom-right corner box to inpaint. Pure. Returns
+ * `{ x, y, w, h }` in image pixel coordinates, anchored to the bottom-right
+ * (so the box always touches the right + bottom edges where the sparkle lives).
+ *
+ * `opts.region` (any subset of `{ x, y, w, h }`) overrides the computed box —
+ * each field is clamped to stay within the image. `opts.size` overrides just
+ * the square side length (still corner-anchored). The default size scales with
+ * the image's short side and is clamped to [MIN, MAX] px.
+ */
+export function resolveWatermarkRegion(width, height, opts = {}) {
+ const W = Math.round(Number(width));
+ const H = Math.round(Number(height));
+ if (!(W > 0) || !(H > 0)) return { x: 0, y: 0, w: 0, h: 0 };
+
+ const short = Math.min(W, H);
+ const defaultSize = clampInt(short * DEFAULT_REGION_FRACTION, DEFAULT_REGION_MIN_PX, DEFAULT_REGION_MAX_PX);
+ const size = opts.size != null ? clampInt(opts.size, 1, short) : Math.min(defaultSize, W, H);
+
+ // Corner-anchored default: bottom-right square of `size`.
+ let w = Math.min(size, W);
+ let h = Math.min(size, H);
+ let x = W - w;
+ let y = H - h;
+
+ // Optional explicit override — clamp every field into the image bounds so a
+ // hand-supplied region can't index outside the decoded buffer.
+ const r = opts.region;
+ if (r && typeof r === 'object') {
+ if (Number.isFinite(r.w)) w = clampInt(r.w, 1, W);
+ if (Number.isFinite(r.h)) h = clampInt(r.h, 1, H);
+ x = Number.isFinite(r.x) ? clampInt(r.x, 0, W - w) : W - w;
+ y = Number.isFinite(r.y) ? clampInt(r.y, 0, H - h) : H - h;
+ }
+ return { x, y, w, h };
+}
+
+/**
+ * Harmonic (Laplace) inpaint of a rectangular target inside a raw pixel patch.
+ * Pure: mutates `raw` in place for the target pixels and returns it.
+ *
+ * The target's surrounding pixels (still original) act as fixed boundary
+ * values; out-of-patch neighbors (the image edge, on the corner sides) are
+ * Neumann (zero-flux) — they contribute nothing, so the fill is driven only by
+ * the valid interior borders. Each channel is solved independently.
+ *
+ * - `raw` Uint8(Clamped)Array of the patch, row-major, `channels` deep.
+ * - `pw`/`ph` patch dimensions in pixels.
+ * - `channels` samples per pixel (3=RGB, 4=RGBA).
+ * - target `{ x, y, w, h }` rectangle WITHIN the patch to reconstruct.
+ */
+export function inpaintRegion(raw, pw, ph, channels, target) {
+ const { x: tx, y: ty, w: tw, h: th } = target;
+ if (!(tw > 0) || !(th > 0)) return raw;
+ const at = (px, py, c) => (py * pw + px) * channels + c;
+
+ for (let c = 0; c < channels; c++) {
+ // Seed the interior with the mean of the valid boundary ring so relaxation
+ // starts near the answer (fewer sweeps to converge).
+ let sum = 0;
+ let count = 0;
+ for (let px = tx; px < tx + tw; px++) {
+ if (ty - 1 >= 0) { sum += raw[at(px, ty - 1, c)]; count++; }
+ if (ty + th < ph) { sum += raw[at(px, ty + th, c)]; count++; }
+ }
+ for (let py = ty; py < ty + th; py++) {
+ if (tx - 1 >= 0) { sum += raw[at(tx - 1, py, c)]; count++; }
+ if (tx + tw < pw) { sum += raw[at(tx + tw, py, c)]; count++; }
+ }
+ const seed = count ? sum / count : raw[at(tx, ty, c)] || 0;
+ for (let py = ty; py < ty + th; py++) {
+ for (let px = tx; px < tx + tw; px++) raw[at(px, py, c)] = seed;
+ }
+
+ // Gauss-Seidel with successive over-relaxation. Neighbors outside the patch
+ // (image edge) are skipped (Neumann); in-bounds neighbors — whether fixed
+ // boundary or still-relaxing interior — are averaged.
+ for (let iter = 0; iter < SOLVER_ITERATIONS; iter++) {
+ for (let py = ty; py < ty + th; py++) {
+ for (let px = tx; px < tx + tw; px++) {
+ let acc = 0;
+ let n = 0;
+ if (px - 1 >= 0) { acc += raw[at(px - 1, py, c)]; n++; }
+ if (px + 1 < pw) { acc += raw[at(px + 1, py, c)]; n++; }
+ if (py - 1 >= 0) { acc += raw[at(px, py - 1, c)]; n++; }
+ if (py + 1 < ph) { acc += raw[at(px, py + 1, c)]; n++; }
+ if (!n) continue;
+ const i = at(px, py, c);
+ const next = raw[i] + SOLVER_OMEGA * (acc / n - raw[i]);
+ raw[i] = next < 0 ? 0 : next > 255 ? 255 : next;
+ }
+ }
+ }
+ }
+ return raw;
+}
+
+/**
+ * Remove the bottom-right Gemini/Nano-Banana sparkle from a PNG/JPEG/WebP
+ * buffer. Throws ServerError(400) on invalid input. Returns
+ * `{ data, format, width, height, region, sizeBefore, sizeAfter }` where `data`
+ * is the re-encoded PNG and `region` is the box that was reconstructed.
+ *
+ * Only a small patch around the corner box is decoded/inpainted/composited, so
+ * cost stays flat regardless of source resolution.
+ */
+export async function removeCornerWatermark(buffer, opts = {}) {
+ if (!Buffer.isBuffer(buffer) || buffer.length === 0) {
+ throw new ServerError('Decoded payload is empty', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+
+ const meta = await sharp(buffer, { limitInputPixels: MAX_PIXELS }).metadata().catch(() => null);
+ const width = meta?.width;
+ const height = meta?.height;
+ if (!(width > 0) || !(height > 0)) {
+ throw new ServerError('Invalid or corrupt image', { status: 400, code: 'INVALID_IMAGE' });
+ }
+
+ const region = resolveWatermarkRegion(width, height, opts);
+ if (!(region.w > 0) || !(region.h > 0)) {
+ throw new ServerError('Could not resolve a watermark region for this image', {
+ status: 400,
+ code: 'INVALID_IMAGE',
+ });
+ }
+
+ // Patch = the box grown by a boundary ring, clamped to the image. The ring is
+ // the fixed boundary the fill interpolates from. On the corner sides (right /
+ // bottom) the ring is zero-width — those neighbors are the image edge.
+ const ring = Math.max(RING_MIN_PX, Math.round(Math.max(region.w, region.h) * RING_FRACTION));
+ const px0 = Math.max(0, region.x - ring);
+ const py0 = Math.max(0, region.y - ring);
+ const px1 = Math.min(width, region.x + region.w + ring);
+ const py1 = Math.min(height, region.y + region.h + ring);
+ const pw = px1 - px0;
+ const ph = py1 - py0;
+
+ // Decode just the patch to raw pixels (preserving any alpha channel).
+ const { data: raw, info } = await sharp(buffer, { limitInputPixels: MAX_PIXELS })
+ .extract({ left: px0, top: py0, width: pw, height: ph })
+ .raw()
+ .toBuffer({ resolveWithObject: true })
+ .catch(() => ({ data: null, info: null }));
+ if (!raw || !info) {
+ throw new ServerError('Invalid or corrupt image', { status: 400, code: 'INVALID_IMAGE' });
+ }
+
+ // Target rectangle expressed in patch-local coordinates.
+ const target = { x: region.x - px0, y: region.y - py0, w: region.w, h: region.h };
+ inpaintRegion(raw, pw, ph, info.channels, target);
+
+ // Re-encode the filled patch and composite it back over the original at the
+ // patch offset. Compositing only the patch keeps the rest byte-faithful.
+ const patchPng = await sharp(raw, { raw: { width: pw, height: ph, channels: info.channels } })
+ .png()
+ .toBuffer();
+ const out = await sharp(buffer, { limitInputPixels: MAX_PIXELS })
+ .composite([{ input: patchPng, left: px0, top: py0 }])
+ .png({ compressionLevel: 9 })
+ .toBuffer()
+ .catch((err) => {
+ throw new ServerError('Failed to composite cleaned region', {
+ status: 400,
+ code: 'INVALID_IMAGE',
+ context: { details: { reason: err.message } },
+ });
+ });
+
+ return {
+ data: out,
+ format: 'png',
+ width,
+ height,
+ region,
+ sizeBefore: buffer.length,
+ sizeAfter: out.length,
+ };
+}
diff --git a/server/lib/imageWatermark.test.js b/server/lib/imageWatermark.test.js
new file mode 100644
index 0000000000..8a0dbe542d
--- /dev/null
+++ b/server/lib/imageWatermark.test.js
@@ -0,0 +1,128 @@
+import { describe, it, expect } from 'vitest';
+import sharp from 'sharp';
+import { resolveWatermarkRegion, inpaintRegion, removeCornerWatermark } from './imageWatermark.js';
+
+// Build an RGB PNG of `w×h` filled with `bg`, then stamp a bright `fg` square
+// in the bottom-right corner to simulate the Gemini ✦ sparkle.
+async function makeWatermarkedPng(w, h, { bg = [40, 60, 90], fg = [255, 255, 255], box = 24 } = {}) {
+ const raw = Buffer.alloc(w * h * 3);
+ for (let y = 0; y < h; y++) {
+ for (let x = 0; x < w; x++) {
+ const i = (y * w + x) * 3;
+ const inBox = x >= w - box && y >= h - box;
+ const [r, g, b] = inBox ? fg : bg;
+ raw[i] = r; raw[i + 1] = g; raw[i + 2] = b;
+ }
+ }
+ return sharp(raw, { raw: { width: w, height: h, channels: 3 } }).png().toBuffer();
+}
+
+describe('resolveWatermarkRegion', () => {
+ it('anchors the box to the bottom-right corner', () => {
+ const r = resolveWatermarkRegion(1000, 800);
+ expect(r.x + r.w).toBe(1000);
+ expect(r.y + r.h).toBe(800);
+ expect(r.w).toBeGreaterThan(0);
+ expect(r.h).toBeGreaterThan(0);
+ });
+
+ it('scales the default box with the short side, within clamp bounds', () => {
+ const small = resolveWatermarkRegion(200, 200);
+ const large = resolveWatermarkRegion(4000, 4000);
+ expect(small.w).toBeGreaterThanOrEqual(56); // DEFAULT_REGION_MIN_PX
+ expect(large.w).toBeLessThanOrEqual(220); // DEFAULT_REGION_MAX_PX
+ expect(large.w).toBeGreaterThan(small.w);
+ });
+
+ it('honors an explicit size override (still corner-anchored)', () => {
+ const r = resolveWatermarkRegion(1000, 1000, { size: 100 });
+ expect(r.w).toBe(100);
+ expect(r.h).toBe(100);
+ expect(r.x).toBe(900);
+ expect(r.y).toBe(900);
+ });
+
+ it('clamps an explicit region into the image bounds', () => {
+ const r = resolveWatermarkRegion(500, 500, { region: { x: 9999, y: 9999, w: 100, h: 100 } });
+ expect(r.x).toBe(400);
+ expect(r.y).toBe(400);
+ expect(r.x + r.w).toBeLessThanOrEqual(500);
+ expect(r.y + r.h).toBeLessThanOrEqual(500);
+ });
+
+ it('returns a zero box for degenerate dimensions', () => {
+ expect(resolveWatermarkRegion(0, 100)).toEqual({ x: 0, y: 0, w: 0, h: 0 });
+ });
+});
+
+describe('inpaintRegion', () => {
+ it('replaces target pixels with a value interpolated from the boundary', () => {
+ // 5×5 single-channel patch, all 100 except the center pixel = 255.
+ const pw = 5; const ph = 5;
+ const raw = new Uint8ClampedArray(pw * ph).fill(100);
+ raw[2 * pw + 2] = 255;
+ inpaintRegion(raw, pw, ph, 1, { x: 2, y: 2, w: 1, h: 1 });
+ // Surrounded entirely by 100 → the harmonic solution is 100.
+ expect(raw[2 * pw + 2]).toBeCloseTo(100, 0);
+ });
+
+ it('is a no-op for a zero-area target', () => {
+ const raw = new Uint8ClampedArray(9).fill(50);
+ const before = Array.from(raw);
+ inpaintRegion(raw, 3, 3, 1, { x: 0, y: 0, w: 0, h: 0 });
+ expect(Array.from(raw)).toEqual(before);
+ });
+});
+
+describe('removeCornerWatermark', () => {
+ it('erases a bright corner mark, blending it into the background', async () => {
+ const w = 256; const h = 256; const box = 24;
+ const png = await makeWatermarkedPng(w, h, { box });
+ const result = await removeCornerWatermark(png);
+ expect(result.format).toBe('png');
+ expect(result.width).toBe(w);
+ expect(result.height).toBe(h);
+
+ // Decode the result and sample a pixel that WAS inside the bright box.
+ const { data, info } = await sharp(result.data).raw().toBuffer({ resolveWithObject: true });
+ const px = w - 5; const py = h - 5;
+ const i = (py * info.width + px) * info.channels;
+ // The corner should now be near the background (40,60,90), not white (255).
+ expect(data[i]).toBeLessThan(160);
+ expect(data[i + 1]).toBeLessThan(180);
+ });
+
+ it('leaves a far-from-corner pixel byte-faithful', async () => {
+ const w = 256; const h = 256;
+ const png = await makeWatermarkedPng(w, h);
+ const result = await removeCornerWatermark(png);
+ const { data, info } = await sharp(result.data).raw().toBuffer({ resolveWithObject: true });
+ // Top-left pixel is well outside the inpaint patch → unchanged background.
+ const i = 0;
+ expect(data[i]).toBe(40);
+ expect(data[i + 1]).toBe(60);
+ expect(data[i + 2]).toBe(90);
+ expect(info.width).toBe(w);
+ });
+
+ it('records the region it reconstructed', async () => {
+ const png = await makeWatermarkedPng(300, 200);
+ const result = await removeCornerWatermark(png);
+ expect(result.region.x + result.region.w).toBe(300);
+ expect(result.region.y + result.region.h).toBe(200);
+ });
+
+ it('rejects an empty buffer', async () => {
+ await expect(removeCornerWatermark(Buffer.alloc(0))).rejects.toMatchObject({ status: 400 });
+ });
+
+ it('rejects a non-image buffer', async () => {
+ await expect(removeCornerWatermark(Buffer.from('not an image'))).rejects.toMatchObject({ status: 400 });
+ });
+
+ it('respects an explicit region override', async () => {
+ const png = await makeWatermarkedPng(256, 256, { box: 24 });
+ const result = await removeCornerWatermark(png, { region: { x: 200, y: 200, w: 56, h: 56 } });
+ expect(result.region).toEqual({ x: 200, y: 200, w: 56, h: 56 });
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index f5bc2d90e2..a230bd4200 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -92,6 +92,7 @@ export * from './fileUtils.js';
export * from './fileWriteQueue.js';
export * from './schemaVersions.js';
export * from './imageClean.js';
+export * from './imageWatermark.js';
export * from './multipart.js';
export * from './safetensors.js';
export * from './assetHash.js';
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index d21c449f91..90b9f552c5 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -38,6 +38,7 @@ import { join } from 'node:path';
import { readFile, writeFile, stat } from 'fs/promises';
import { STYLE_PRESETS } from '../lib/writersRoomStylePresets.js';
import { cleanImageBuffer } from '../lib/imageClean.js';
+import { removeCornerWatermark } from '../lib/imageWatermark.js';
import {
resolveRegenBackend, getRegenAvailability, readImageDimensions, buildRegenParams,
REGEN_STRENGTH_MIN, REGEN_STRENGTH_MAX,
@@ -172,6 +173,21 @@ const regenerateSchema = z.object({
method: z.enum(['flux', 'light']).optional(),
});
+// Visible-watermark removal — erases the Gemini / Nano-Banana bottom-right ✦.
+// Body is optional: with no fields the corner box is auto-sized to the
+// sparkle's typical footprint. `size` overrides the square side; `region`
+// pins an explicit box (each field clamped server-side into the image) for
+// off-spec placements. All ints in pixels.
+const removeWatermarkSchema = z.object({
+ size: z.number().int().min(1).max(4096).optional(),
+ region: z.object({
+ x: z.number().int().min(0).max(100000).optional(),
+ y: z.number().int().min(0).max(100000).optional(),
+ w: z.number().int().min(1).max(4096).optional(),
+ h: z.number().int().min(1).max(4096).optional(),
+ }).optional(),
+});
+
router.get('/status', asyncHandler(async (req, res) => {
// Optional ?mode= override lets the Image Gen page probe a specific
// backend (e.g. when the user flips the per-render chip to Codex but
@@ -646,6 +662,71 @@ router.post('/:filename/clean', asyncHandler(async (req, res) => {
});
}));
+// Visible-watermark removal — erases the Gemini / Nano-Banana bottom-right ✦.
+// Unlike SynthID regen (which round-trips the WHOLE image to overwrite an
+// invisible per-pixel signal), this localizes the corner logo and reconstructs
+// only that box via a dependency-free harmonic inpaint — so it's a CPU-only
+// sharp pass that runs on every install, GPU or not, and leaves the rest of the
+// image byte-faithful. Synchronous like Clean: writes a `_nowatermark.png`
+// variant + sidecar, files it into the source's collections, and returns it.
+router.post('/:filename/remove-watermark', asyncHandler(async (req, res) => {
+ const filename = req.params.filename;
+ local.assertGalleryFilename(filename);
+ const body = validateRequest(removeWatermarkSchema, req.body || {});
+
+ 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 removeCornerWatermark(buffer, { size: body.size, region: body.region });
+
+ const base = filename.slice(0, -'.png'.length);
+ const outFilename = `${base}_nowatermark.png`;
+ const outPath = join(PATHS.images, outFilename);
+ const sidecarPath = join(PATHS.images, `${base}_nowatermark.metadata.json`);
+ // Anchor the variant group at the root original (same rule as /clean):
+ // de-watermarking a cleaned/regenerated variant groups under the root.
+ const groupRoot = typeof sourceMeta.cleanedFrom === 'string' && sourceMeta.cleanedFrom
+ ? sourceMeta.cleanedFrom : filename;
+ const createdAt = new Date().toISOString();
+ // Strip hidden/filename/id so listGallery's `...metadata` spread doesn't
+ // overwrite the disk-derived filename or re-hide the deliberate variant.
+ const { hidden: _hidden, filename: _srcFilename, id: _srcId, ...sourceMetaForVariant } = sourceMeta;
+ const variantMeta = {
+ ...sourceMetaForVariant,
+ createdAt,
+ cleanedFrom: groupRoot,
+ watermarkRemoved: true,
+ watermarkRegion: result.region,
+ };
+ await Promise.all([
+ writeFile(outPath, result.data),
+ writeFile(sidecarPath, JSON.stringify(variantMeta, null, 2)),
+ ]);
+
+ const filedCollections = await autoFileCleanedToSourceCollections(filename, outFilename).catch((err) => {
+ console.warn(`⚠️ Auto-file de-watermarked ${outFilename} → collections failed: ${err?.message || err}`);
+ return [];
+ });
+ console.log(`✦ Removed watermark ${filename} → ${outFilename} (${result.region.w}×${result.region.h} @ ${result.region.x},${result.region.y}${filedCollections.length ? `, filed to ${filedCollections.length} collection(s)` : ''})`);
+
+ res.json({
+ ...variantMeta,
+ filename: outFilename,
+ path: `/data/images/${outFilename}`,
+ sizeBefore: result.sizeBefore,
+ sizeAfter: result.sizeAfter,
+ sizeBytes: result.sizeAfter,
+ width: result.width,
+ height: result.height,
+ });
+}));
+
// CPU-only "light" regen (issue #912). The no-GPU fallback: applies sharp's
// spatial-domain disruption stack (resize-squeeze + color nudge + median/sharpen)
// to overwrite SynthID's resolution-dependent carriers without a FLUX runner.
diff --git a/server/routes/imageGen.watermark.test.js b/server/routes/imageGen.watermark.test.js
new file mode 100644
index 0000000000..0fa746a0ae
--- /dev/null
+++ b/server/routes/imageGen.watermark.test.js
@@ -0,0 +1,179 @@
+import { describe, it, expect, beforeEach, beforeAll, afterAll, vi } from 'vitest';
+import express from 'express';
+import sharp from 'sharp';
+import { mkdtemp, rm, writeFile, readFile } 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 (same pattern as imageGen.clean.test.js) so
+// the remove-watermark endpoint reads/writes real files without touching
+// data/images/. Mock installed before the route module imports fileUtils.js.
+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 };
+ },
+ };
+});
+
+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(() => []),
+}));
+
+const { listCollectionsMock, addItemMock } = vi.hoisted(() => ({
+ listCollectionsMock: vi.fn(async () => []),
+ addItemMock: vi.fn(async () => ({})),
+}));
+vi.mock('../services/mediaCollections.js', () => ({
+ listCollections: listCollectionsMock,
+ addItem: addItemMock,
+ ERR_DUPLICATE: 'DUPLICATE',
+}));
+
+let imageGenRoutes;
+let watermarkedPng;
+
+// Build a 128×128 PNG with a flat background and a bright white box stamped
+// into the bottom-right corner — stands in for the Gemini ✦ sparkle.
+async function makeWatermarkedPng(w = 128, h = 128, box = 20) {
+ const raw = Buffer.alloc(w * h * 3);
+ for (let y = 0; y < h; y++) {
+ for (let x = 0; x < w; x++) {
+ const i = (y * w + x) * 3;
+ const inBox = x >= w - box && y >= h - box;
+ raw[i] = inBox ? 255 : 40;
+ raw[i + 1] = inBox ? 255 : 60;
+ raw[i + 2] = inBox ? 255 : 90;
+ }
+ }
+ return sharp(raw, { raw: { width: w, height: h, channels: 3 } }).png().toBuffer();
+}
+
+beforeAll(async () => {
+ sandbox = await mkdtemp(join(tmpdir(), 'portos-watermark-'));
+ ({ default: imageGenRoutes } = await import('./imageGen.js'));
+ watermarkedPng = await makeWatermarkedPng();
+});
+
+afterAll(async () => {
+ await rm(sandbox, { recursive: true, force: true });
+});
+
+describe('POST /api/image-gen/:filename/remove-watermark', () => {
+ let app;
+
+ beforeEach(() => {
+ app = express();
+ app.use(express.json());
+ app.use('/api/image-gen', imageGenRoutes);
+ app.use(errorMiddleware);
+ listCollectionsMock.mockReset();
+ listCollectionsMock.mockResolvedValue([]);
+ addItemMock.mockReset();
+ addItemMock.mockResolvedValue({});
+ });
+
+ it('writes a _nowatermark.png variant + sidecar and carries the source lineage', async () => {
+ await writeFile(join(sandbox, 'wm-1.png'), watermarkedPng);
+ await writeFile(join(sandbox, 'wm-1.metadata.json'), JSON.stringify({
+ prompt: 'a sunset', seed: 7, modelId: 'gemini',
+ }));
+
+ const res = await request(app).post('/api/image-gen/wm-1.png/remove-watermark').send({});
+ expect(res.status).toBe(200);
+ expect(res.body.filename).toBe('wm-1_nowatermark.png');
+ expect(res.body.cleanedFrom).toBe('wm-1.png');
+ expect(res.body.watermarkRemoved).toBe(true);
+ expect(res.body.watermarkRegion).toMatchObject({ x: expect.any(Number), w: expect.any(Number) });
+ // Source sidecar carried forward.
+ expect(res.body.prompt).toBe('a sunset');
+ expect(res.body.modelId).toBe('gemini');
+
+ expect(existsSync(join(sandbox, 'wm-1_nowatermark.png'))).toBe(true);
+ expect(existsSync(join(sandbox, 'wm-1_nowatermark.metadata.json'))).toBe(true);
+ });
+
+ it('actually erases the bright corner mark', async () => {
+ await writeFile(join(sandbox, 'wm-erase.png'), watermarkedPng);
+ const res = await request(app).post('/api/image-gen/wm-erase.png/remove-watermark').send({});
+ expect(res.status).toBe(200);
+ const out = await readFile(join(sandbox, res.body.filename));
+ const { data, info } = await sharp(out).raw().toBuffer({ resolveWithObject: true });
+ // A pixel that was inside the white box should now be near the background.
+ const px = info.width - 4; const py = info.height - 4;
+ const i = (py * info.width + px) * info.channels;
+ expect(data[i]).toBeLessThan(160);
+ });
+
+ it('anchors the region to the bottom-right corner of the image', async () => {
+ await writeFile(join(sandbox, 'wm-region.png'), watermarkedPng);
+ const res = await request(app).post('/api/image-gen/wm-region.png/remove-watermark').send({});
+ const r = res.body.watermarkRegion;
+ expect(r.x + r.w).toBe(res.body.width);
+ expect(r.y + r.h).toBe(res.body.height);
+ });
+
+ it('honors an explicit region override', async () => {
+ await writeFile(join(sandbox, 'wm-override.png'), watermarkedPng);
+ const res = await request(app)
+ .post('/api/image-gen/wm-override.png/remove-watermark')
+ .send({ region: { x: 60, y: 60, w: 40, h: 40 } });
+ expect(res.status).toBe(200);
+ expect(res.body.watermarkRegion).toEqual({ x: 60, y: 60, w: 40, h: 40 });
+ });
+
+ it('rejects non-PNG filenames (gallery is PNG-only)', async () => {
+ const res = await request(app).post('/api/image-gen/photo.jpg/remove-watermark').send({});
+ 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') + '/remove-watermark')
+ .send({});
+ 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/missing.png/remove-watermark').send({});
+ expect(res.status).toBe(404);
+ });
+
+ it('files the variant into every collection that contained the source', async () => {
+ await writeFile(join(sandbox, 'wm-coll.png'), watermarkedPng);
+ listCollectionsMock.mockResolvedValue([
+ { id: 'col-a', items: [{ kind: 'image', ref: 'wm-coll.png' }] },
+ { id: 'col-unrelated', items: [{ kind: 'image', ref: 'other.png' }] },
+ ]);
+ const res = await request(app).post('/api/image-gen/wm-coll.png/remove-watermark').send({});
+ expect(res.status).toBe(200);
+ expect(addItemMock).toHaveBeenCalledTimes(1);
+ expect(addItemMock).toHaveBeenCalledWith('col-a', { kind: 'image', ref: 'wm-coll_nowatermark.png' });
+ });
+});