The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Watermark Remover: plain words when a step fails, the good result kept, large photos and setup
Adarshf91ef8e21680
diff --git a/scripts/comfy/build-library.mjs b/scripts/comfy/build-library.mjsindex 5ddcbab7..cd793a06 100644--- a/scripts/comfy/build-library.mjs+++ b/scripts/comfy/build-library.mjs@@ -190,8 +190,8 @@ export const BINDING_KEYS = new Set(['maskBlur', 'pasteBack',// Photo to 3D (Idol): SplatToMesh's grid and the turn that faces the subject's front'meshDetail', 'frontYaw',- // Watermark Remover (ComfyUI-Qwen-Watermark): the kept marks and how the pack finds what to repair- 'boxes', 'detectMode',+ // Watermark Remover (ComfyUI-Qwen-Watermark): the kept marks, how the pack finds what to repair and how far past each mark+ 'boxes', 'detectMode', 'detectExpand',]);// Sizes in GB: two decimals, and three where two would read 0 (a 4 MB DBS model), so no other entry's size changes.diff --git a/scripts/comfy/install-comfyui.sh b/scripts/comfy/install-comfyui.shindex 6df15fec..97584c00 100755--- a/scripts/comfy/install-comfyui.sh+++ b/scripts/comfy/install-comfyui.sh@@ -51,7 +51,7 @@ declare -A NODES=(# Watermark Remover (image-watermark-*): overflowofedge's Qwen watermark nodes (MIT), read at this commit (no network,# subprocess, eval or file writes). Its requirements.txt is NOT installed: it asks for opencv-contrib-python-headless,# which next to opencv-python can leave cv2 broken; core cv2 has every function it uses, and segment-anything is in the- # union below. Its SAM ViT-B file goes in models/sams (SAM_WEIGHTS block at the end).+ # union below. Its SAM ViT-B file goes in models/sams (the SAM ViT-B block near the end).[ComfyUI-Qwen-Watermark]="https://github.com/overflowofedge/ComfyUI-Qwen-Watermark eef829d34d6e9d0d2ae0c1386fab7371a864cf34")# Licences are information (Settings → Models & licences has the switches): every pack is installed, the@@ -294,8 +294,6 @@ SHAfi# --- end ComfyUI-RE-USE-echo "ComfyUI installed in $COMFYUI_DIR. Start it with: $SCRIPT_DIR/start-comfyui.sh"-# --- SAM ViT-B (image-watermark-remove-qwen21: sticker outlines), 375 MB (Meta's file, from a pinned Hugging Face mirror), into models/sams, checked with# sha256sum -c before it is kept (a .pth can run code when it loads). Only with REAL_MODELS=1 (validation needs no weights).if [ "${REAL_MODELS:-0}" = "1" ]; then@@ -311,3 +309,6 @@ if [ "${REAL_MODELS:-0}" = "1" ]; thenfififi+# --- end SAM ViT-B++echo "ComfyUI installed in $COMFYUI_DIR. Start it with: $SCRIPT_DIR/start-comfyui.sh"diff --git a/scripts/comfy/library.spec.mjs b/scripts/comfy/library.spec.mjsindex c159c90e..0aa541d1 100644--- a/scripts/comfy/library.spec.mjs+++ b/scripts/comfy/library.spec.mjs@@ -159,6 +159,7 @@// boxes* (QWMDetect boxes_json: the marks the visitor kept, params.extra.boxes, checked and rebuilt// by src/lib/watermark.ts: pixels, 1-32 boxes clamped to the picture, known types only)// detectMode* (QWMDetect mode: manual_boxes with boxes, manual_mask on the brush graph, else auto_qwen)+// detectExpand* (QWMDetect expand: 0 for the kept marks, whose boxes carry the scan's margin; 20 in auto_qwen)// maxSize* (here QWMPrepare max_side on both passes: 1024; 1536 past 3000 px; 768 on a GPU under 16 GB)// Output role "quality": a node's JSON verdict on the run (QWMFinal), folded into the image outputs' meta.quality.@@ -2858,6 +2859,7 @@ export const SPEC = [seed: [b('12', 'seed'), b('30', 'seed')],detectMode: [b('3', 'mode')],boxes: [b('3', 'boxes_json')],+ detectExpand: [b('3', 'expand')],maxSize: [b('5', 'max_side'), b('28', 'max_side')],},outputs: [{ node: '33', kind: 'image' }, { node: '38', kind: 'text', role: 'quality' }],@@ -2866,12 +2868,13 @@ export const SPEC = [license: 'Qwen Research License Agreement (Qwen-Image 2.1): NON-COMMERCIAL, research and evaluation only; Qwen3-VL 8B Apache-2.0; SAM ViT-B (segment-anything) Apache-2.0; ComfyUI-Qwen-Watermark nodes MIT',notes:'The pack\'s main workflow (qwen21_watermark.api.json, plain settings) with the int8 UNET (qwen_image_2.1_int8_convrot, as Live edit) and without its ' +- 'debug save and preview nodes. QWMDetect (manual_boxes with the kept boxes, auto_qwen for API callers) -> QWMRefineMask (a rectangle for text, logos, ' ++ 'debug save and preview nodes. QWMDetect (manual_boxes with the kept boxes and no extra margin, since the scan\'s boxes carry it; auto_qwen with ' ++ 'expand 20 for API callers) -> QWMRefineMask (a rectangle for text, logos, ' +'blocks and mosaics, a SAM ViT-B outline for stickers) -> QWMPrepare (context 96, max side maxSize, OpenCV pre-fill) -> Qwen-Image 2.1 edit, 20 steps, ' +'cfg 1 -> QWMComposite (feather 6, align, colour match) -> QWMResidualDetect (Qwen3-VL looks for leftovers inside the first mask) -> one more pass ' +'when it finds some -> QWMFinal keeps the better pass and raises when any pixel outside the mask changed. Outputs: the picture (SaveImage, PNG) and ' +'the quality report (PreviewAny, role quality: folded into the picture\'s meta, never a result of its own). Seeds are random per run. ' +- 'The structure settings (denoise 0.65 / 0.55, context 384, no pre-fill) are the pack\'s alternative for faces; the GPU test decides between them.',+ 'The structure settings (denoise 0.65 / 0.55, context 384, no pre-fill) are the pack\'s alternative for faces.',},{id: 'image-watermark-remove-qwen21-brush',diff --git a/src/components/guest-prompt.tsx b/src/components/guest-prompt.tsxindex 59c5ceb7..f54f97af 100644--- a/src/components/guest-prompt.tsx+++ b/src/components/guest-prompt.tsx@@ -53,13 +53,15 @@ export function GuestPrompt() {const [look, setLook] = useState(false);// The owner's refused run (Demo mode off, nothing connected): what would run it. A GPU when not said.const [needs, setNeeds] = useState<ConnectNeeds>("gpu");+ // Opened by a tool only a GPU runs: no key offers on this card.+ const [gpuOnly, setGpuOnly] = useState(false);const close = useCallback(() => {setOpen(false);setRetry(null);}, []);const viewer = useStatus().data?.viewer;// A studio that runs open-source models only takes no keys: its cards offer the GPU alone.- const keysAllowed = viewer?.kind !== "account" || viewer.paidAllowed !== false;+ const keysAllowed = (viewer?.kind !== "account" || viewer.paidAllowed !== false) && !gpuOnly;const qc = useQueryClient();// Who this page was for, for the refusal that comes when that sign-in ended elsewhere: "owner", "account", or null.const who = useViewer().data;@@ -111,6 +113,7 @@ export function GuestPrompt() {setAction(d.action ?? "connect");setLook(!!d.look);setNeeds(d.needs ?? "gpu");+ setGpuOnly(!!d.gpuOnly);};window.addEventListener(GUEST_PROMPT_EVENT, guest);window.addEventListener(CONNECT_GPU_EVENT, gpu);@@ -157,12 +160,12 @@ export function GuestPrompt() {)}</DialogDescription>{/* Paid models run on the account's own key instead (Your keys), when the studio allows them. */}- {viewer?.kind === "account" && viewer.paidAllowed !== false && !!viewer.keys?.length && (+ {viewer?.kind === "account" && keysAllowed && !!viewer.keys?.length && (<p className="text-[13px] text-muted-foreground">{`Or switch to Cloud to use your ${viewer.keys.map((k) => CLOUD_KEY[k].label).join(" or ")} key.`}</p>)}</DialogHeader>{/* No key yet: "Add a key" opens here, over the studio (this card makes room). */}- <KeyInstead onOpen={close} />+ {keysAllowed && <KeyInstead onOpen={close} />}{!keyOnly && <ConnectChoice fromRun={!!retry} kind={retry?.kind} reason={reason} look={look} onStart={start} onNotNow={() => setRetry(null)} />}{/* The owner's refused run a fal.ai or Replicate key would run: the key right here, and the run starts once it's saved. */}{ownerRun && needs !== "gpu" && <OwnerKey alone={keyOnly} onConnected={start} />}diff --git a/src/components/studio/sketch-editor.tsx b/src/components/studio/sketch-editor.tsxindex 49233220..b0c2ec89 100644--- a/src/components/studio/sketch-editor.tsx+++ b/src/components/studio/sketch-editor.tsx@@ -129,6 +129,8 @@ export function SketchEditor(props: {mode: SketchMode;/** Strokes of the drawing being touched up (empty for a new one). */initialStrokes?: Stroke[];+ /** The dialog's own words for one tool (its title, the line under it and the done button); the defaults otherwise. */+ words?: SketchWords;onDone: (r: SketchResult) => void;}) {// The canvas answers Escape first: it closes an open note instead of the whole editor.@@ -154,11 +156,18 @@ export function SketchEditor(props: {);}+export interface SketchWords {+ title: string;+ hint: string;+ done: string;+}+function SketchCanvas({onOpenChange,image,mode,initialStrokes,+ words,onDone,escapeRef,}: {@@ -166,6 +175,7 @@ function SketchCanvas({image: string;mode: SketchMode;initialStrokes?: Stroke[];+ words?: SketchWords;onDone: (r: SketchResult) => void;escapeRef: React.RefObject<() => boolean>;}) {@@ -437,11 +447,12 @@ function SketchCanvas({return (<><DialogHeader>- <DialogTitle>{mode === "mask" ? "Paint what should change" : "Draw your edit"}</DialogTitle>+ <DialogTitle>{words?.title ?? (mode === "mask" ? "Paint what should change" : "Draw your edit")}</DialogTitle><DialogDescription>- {mode === "mask"- ? "Brush over the area to replace. Everything you don't paint stays as it is."- : "Sketch arrows, shapes or write short notes — the model follows them and removes the marks."}+ {words?.hint ??+ (mode === "mask"+ ? "Brush over the area to replace. Everything you don't paint stays as it is."+ : "Sketch arrows, shapes or write short notes — the model follows them and removes the marks.")}</DialogDescription></DialogHeader><div className="flex flex-wrap items-center gap-1.5">@@ -525,11 +536,11 @@ function SketchCanvas({</div><DialogFooter className="items-center"><p className="mr-auto hidden text-[12px] text-muted-foreground sm:block">[ ] brush size · {keyCombo("Z", { mod })} undo · {keyCombo("Z", { mod, shift: true })} redo{mode === "draw" ? " · T note" : ""}</p>- <Button variant="ghost" onClick={() => onOpenChange(false)}>+ <Button variant="ghost" className="min-h-11 sm:min-h-9" onClick={() => onOpenChange(false)}>Cancel</Button>- <Button onClick={save} disabled={!hasPaint || saving}>- {saving && <Loader2 className="animate-spin" />} {mode === "mask" ? "Use this mask" : "Use this drawing"}+ <Button className="min-h-11 sm:min-h-9" onClick={save} disabled={!hasPaint || saving}>+ {saving && <Loader2 className="animate-spin" />} {words?.done ?? (mode === "mask" ? "Use this mask" : "Use this drawing")}</Button></DialogFooter></>diff --git a/src/components/watermark/regions.tsx b/src/components/watermark/regions.tsxindex 2467c9ff..dde88a49 100644--- a/src/components/watermark/regions.tsx+++ b/src/components/watermark/regions.tsx@@ -1,12 +1,14 @@"use client";import { Check } from "lucide-react";-import { useRef } from "react";-import { regionAt, type Region } from "@/lib/watermark";+import { useEffect, useRef, useState } from "react";+import { pickRegion, type Region } from "@/lib/watermark";import { cn } from "@/lib/utils";/** The finger's reach: small marks are hit within this many CSS pixels of their outline. */const REACH_PX = 22;+/** A chip sits this many CSS pixels above its outline; nearer the top than that, it goes inside the outline. */+const CHIP_PX = 26;const pct = (n: number, of: number) => `${(n / of) * 100}%`;@@ -37,13 +39,23 @@ export function RegionsView({children?: React.ReactNode;}) {const box = useRef<HTMLDivElement>(null);+ // The picture's height on screen: a chip that wouldn't fit above its outline goes inside it.+ const [shownHeight, setShownHeight] = useState(0);+ useEffect(() => {+ const el = box.current;+ if (!el || typeof ResizeObserver === "undefined") return;+ const ro = new ResizeObserver(() => setShownHeight(el.clientHeight));+ ro.observe(el);+ setShownHeight(el.clientHeight);+ return () => ro.disconnect();+ }, []);const tap = (e: React.MouseEvent) => {if (!onToggle || !box.current) return;const r = box.current.getBoundingClientRect();if (!r.width || !r.height) return;const x = ((e.clientX - r.left) / r.width) * width;const y = ((e.clientY - r.top) / r.height) * height;- const hit = regionAt(regions, x, y, (REACH_PX / r.width) * width);+ const hit = pickRegion(regions, x, y, (REACH_PX / r.width) * width);if (hit) onToggle(hit.id);};return (@@ -58,7 +70,7 @@ export function RegionsView({<img src={src} alt="Your photo" draggable={false} className={cn("absolute inset-0 block size-full object-contain transition-opacity duration-300", dim && "opacity-55")} />{regions.map((g) => {const [x0, y0, x1, y1] = g.box;- const atTop = y0 / height < 0.06;+ const atTop = shownHeight ? (y0 / height) * shownHeight < CHIP_PX : y0 / height < 0.12;return (<divkey={g.id}diff --git a/src/components/watermark/watermark-tool.tsx b/src/components/watermark/watermark-tool.tsxindex 50e6b479..1435167d 100644--- a/src/components/watermark/watermark-tool.tsx+++ b/src/components/watermark/watermark-tool.tsx@@ -1,6 +1,6 @@"use client";-import { Brush, ChevronRight, Download, ImagePlus, Library, Loader2, MoreHorizontal, RotateCcw, ScanLine, Undo2, Upload, Wand2, Zap } from "lucide-react";+import { Brush, ChevronRight, Download, ImagePlus, Library, Loader2, Minimize2, MoreHorizontal, RotateCcw, ScanLine, Undo2, Upload, Wand2, Zap } from "lucide-react";import Link from "next/link";import { nanoid } from "nanoid";import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";@@ -12,19 +12,21 @@ import { useGeneration } from "@/components/av/use-generation";import { fileToSlot, LibraryGrid, type SlotValue } from "@/components/studio/media-slot";import { TileActions } from "@/components/studio/result-actions";import { SketchEditor, type SketchResult } from "@/components/studio/sketch-editor";-import { useAskBeforeUpload, useCreateGeneration, useGenerationActions, useHydrated, useViewer } from "@/lib/api";+import { useAskBeforeUpload, useCreateGeneration, useGenerationActions, useHydrated, useIsGuest, useStatus, useViewer } from "@/lib/api";import type { Generation, OutputFile } from "@/lib/catalog/types";import { downloadHref } from "@/lib/library";import type { PresetCover } from "@/lib/preset-covers";import { toastError } from "@/lib/refusals";import { cn } from "@/lib/utils";import {+ cleanFileName,COPY,foundLine,keptBoxesJson,MAX_SIDE,parseScanReport,removeLabel,+ visitorError,WATERMARK_APP_ID,WATERMARK_FEATURE,WATERMARK_REMOVE_MODEL,@@ -39,7 +41,7 @@ import { RegionChips, RegionsView } from "./regions";/*** The Watermark Remover (app-watermark-remover): add a photo and it is scanned at once; every mark found is outlined with a* chip; tap any to keep it; Remove takes the rest off. The result flips with a tap (hold for the original), a brush covers- * anything missed, and Download gives the PNG as it was made. Phone first, taps only. Both steps are ordinary runs+ * anything missed, and Download gives the file as it was made. Phone first, taps only. Both steps are ordinary runs* (POST /api/generations) on the person's own GPU; the scan is a helper row the Library hides.*/@@ -57,7 +59,14 @@ interface Size {}const HINT_KEY = "fuobe.watermark.hint";+const ADD_A_PHOTO = "Add a photo: JPG, PNG or WebP";+const PHOTO_TYPES = /^image\/(png|jpeg|webp)$/;+const PHOTO_URL = /\.(png|jpe?g|webp)(?:[?#]|$)/i;+const ANY_EXT = /\.[a-z0-9]{2,5}(?:[?#]|$)/i;+/** The brush's own words here: the mark, never the tool's inner workings. */+const BRUSH_WORDS = { title: "Brush over the mark", hint: "Paint over what's left. The rest of the photo stays as it is.", done: "Remove it" };const busy = (g?: Generation | null) => !!g && (g.status === "queued" || g.status === "running");+const ended = (g?: Generation | null) => g?.status === "failed" || g?.status === "canceled";const imageOf = (g?: Generation | null): OutputFile | undefined => g?.outputs.find((o) => o.kind === "image");const reportOf = (g?: Generation | null): string | undefined => g?.outputs.find((o) => o.kind === "text")?.text;const baseName = (name: string) => name.replace(/\.[a-z0-9]{2,4}$/i, "") || "photo";@@ -72,6 +81,31 @@ function readSize(src: string): Promise<Size | null> {});}+/** The photo made 4096 px on its longest side, here in the browser: a JPEG stays a JPEG (at high quality), else a PNG. */+async function shrinkPhoto(src: string, name: string): Promise<File> {+ const blob = await (await fetch(src)).blob();+ const bitmap = await createImageBitmap(blob);+ try {+ const k = Math.min(1, MAX_SIDE / Math.max(bitmap.width, bitmap.height));+ const width = Math.max(1, Math.min(MAX_SIDE, Math.round(bitmap.width * k)));+ const height = Math.max(1, Math.min(MAX_SIDE, Math.round(bitmap.height * k)));+ const canvas = document.createElement("canvas");+ canvas.width = width;+ canvas.height = height;+ const ctx = canvas.getContext("2d");+ if (!ctx) throw new Error("no canvas");+ ctx.imageSmoothingEnabled = true;+ ctx.imageSmoothingQuality = "high";+ ctx.drawImage(bitmap, 0, 0, width, height);+ const jpeg = blob.type === "image/jpeg";+ const out = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, jpeg ? "image/jpeg" : "image/png", 0.95));+ if (!out) throw new Error("no picture");+ return new File([out], `${baseName(name)}.${jpeg ? "jpg" : "png"}`, { type: out.type });+ } finally {+ bitmap.close();+ }+}+function readHint(): boolean {try {return window.localStorage.getItem(HINT_KEY) === "1";@@ -88,28 +122,43 @@ function writeHint() {}}-/** ?image= from a Library result's "Remove watermark", the Edit studio or ⌘K, read once after hydration: scanned at once. */-function useHandoff(take: (s: Source) => void) {+/**+ * ?image= from a Library result's "Remove watermark", the Edit studio or ⌘K, read once after hydration, once who is looking+ * is known (an account with no GPU is asked for one first): scanned at once. Only this site's own files (a path, never+ * "//host/…"); the stored name is an id, so the download is named "photo".+ */+function useHandoff(take: (s: Source) => void, ready: boolean) {+ const done = useRef(false);useEffect(() => {+ if (!ready || done.current) return;+ done.current = true;const url = new URLSearchParams(window.location.search).get("image");- if (url?.startsWith("/")) take({ id: nanoid(8), ref: url, preview: url, name: decodeURIComponent(url.split("/").pop() ?? "photo") });+ if (url && /^\/(?!\/)/.test(url)) take({ id: nanoid(8), ref: url, preview: url, name: "photo" });// Once, on arrival.// eslint-disable-next-line react-hooks/exhaustive-deps- }, []);+ }, [ready]);}export function WatermarkTool({ app, cover }: { app: { name: string; description: string }; cover?: PresetCover }) {const create = useCreateGeneration();const actions = useGenerationActions();- const askFirst = useAskBeforeUpload();+ // No key runs this app: an account with no GPU is asked for one, never for a key.+ const askFirst = useAskBeforeUpload({ gpuOnly: true });+ const guest = useIsGuest();+ const status = useStatus();const viewer = useViewer().data;+ const owner = !!viewer?.owner;const [source, setSource] = useState<Source | null>(null);+ /** The photo being worked on: a scan asked for an earlier one (started over meanwhile) is stopped when it arrives. */+ const sourceId = useRef<string | null>(null);+ const pendingUpload = useRef<string | null>(null);const [size, setSize] = useState<Size | null>(null);const [tooBig, setTooBig] = useState(false);+ const [shrinking, setShrinking] = useState(false);const [scanId, setScanId] = useState<string | null>(null);/** The visitor's choices by region id (a mark kept or taken back); the scan's own default otherwise. */const [toggles, setToggles] = useState<Record<string, boolean>>({});- /** Every removal pass, oldest first (each is its own Library item); the newest succeeded one is shown. */+ /** Every removal pass, oldest first (each is its own Library item). Only the newest may still be running or have failed. */const [passes, setPasses] = useState<string[]>([]);const [brushOpen, setBrushOpen] = useState(false);const hydrated = useHydrated();@@ -117,6 +166,8 @@ export function WatermarkTool({ app, cover }: { app: { name: string; descriptionconst hintSeen = !hydrated || hintDismissed || readHint();/** Why the scan didn't start (a guest, no GPU connected, setup needed): said in words, with Try again. */const [scanError, setScanError] = useState<string | null>(null);+ /** Why the first removal didn't work, shown over the marks (still as the visitor left them): Remove tries again. */+ const [removeError, setRemoveError] = useState<string | null>(null);/** How the newest pass was asked: the kept marks (their outlines show while it runs) or a brushed area. */const [lastMode, setLastMode] = useState<"boxes" | "brush">("boxes");const scan = useGeneration(scanId);@@ -128,6 +179,8 @@ export function WatermarkTool({ app, cover }: { app: { name: string; descriptionconst g = last.data;const reset = useCallback(() => {+ sourceId.current = null;+ pendingUpload.current = null;setSource(null);setSize(null);setTooBig(false);@@ -135,36 +188,53 @@ export function WatermarkTool({ app, cover }: { app: { name: string; descriptionsetToggles({});setPasses([]);setScanError(null);+ setRemoveError(null);}, []);const startScan = useCallback((src: Source) => {+ // An account with nothing that runs this (a picture handed over from the Library): the GPU card, never a key's.+ // A guest's run is refused by the server, whose card says the same.+ if (!guest && askFirst("run")) return setScanError(COPY.connectGpu);create.mutate({ feature: WATERMARK_SCAN_FEATURE, modelId: WATERMARK_SCAN_MODEL, op: "watermark-scan", inputs: { images: [src.ref] }, title: "Find marks" },{- onSuccess: (items) => setScanId(items[0]?.id ?? null),+ onSuccess: (items) => {+ const item = items[0];+ // Started over (or another photo) while this scan was being asked for: it stops at once.+ if (sourceId.current !== src.id) {+ if (item && busy(item)) void actions.cancel(item);+ return;+ }+ setScanId(item?.id ?? null);+ },onError: (e) => {+ if (sourceId.current !== src.id) return;toastError(e);setScanId(null);- setScanError((e as { gpuSetup?: boolean }).gpuSetup ? "Finish setting up your GPU, then try again." : (e as Error).message || "The scan didn't start. Try again.");+ setScanError((e as { gpuSetup?: boolean }).gpuSetup ? "Finish setting up your GPU, then try again." : (e as Error).message || COPY.scanFailed);},},);},- [create],+ [create, actions, guest, askFirst],);/** A picture to work on: its size is read first (over 4096 px it stops there), then the scan starts by itself. */const take = useCallback((src: Source) => {+ if (sourceId.current !== src.id) setSize(null);+ sourceId.current = src.id;setSource(src);setScanId(null);setToggles({});setPasses([]);setTooBig(false);setScanError(null);+ setRemoveError(null);if (src.uploading) return;void readSize(src.preview).then((sz) => {+ if (sourceId.current !== src.id) return;setSize(sz);if (sz && Math.max(sz.width, sz.height) > MAX_SIDE) return setTooBig(true);startScan(src);@@ -173,12 +243,71 @@ export function WatermarkTool({ app, cover }: { app: { name: string; description[startScan],);- useHandoff(take);+ useHandoff(take, status.isFetched || status.isError);++ /** A file of the visitor's own (chosen, dropped, or made smaller here): uploaded, then scanned. */+ const upload = useCallback(+ (f: File | undefined) => {+ if (!f || askFirst()) return;+ if (!PHOTO_TYPES.test(f.type)) return void toast(ADD_A_PHOTO);+ const id = nanoid(8);+ pendingUpload.current = id;+ void fileToSlot(+ f,+ (v) => {+ if (pendingUpload.current !== id) return;+ if (!v) {+ if (sourceId.current === id) reset();+ return;+ }+ take({ id, ref: v.ref, preview: v.preview, name: f.name, uploading: v.uploading });+ },+ "image",+ );+ },+ [askFirst, reset, take],+ );++ const fromLibrary = (v: SlotValue) => {+ // Vectors, GIFs and the like can't be cleaned: only photos.+ const photo = PHOTO_URL.test(v.ref) || (!ANY_EXT.test(v.ref) && PHOTO_URL.test(v.name ?? ""));+ if (!photo) return void toast(ADD_A_PHOTO);+ take({ id: nanoid(8), ref: v.ref, preview: v.preview, name: v.name ?? "photo" });+ };++ const shrink = async () => {+ if (!source || shrinking) return;+ setShrinking(true);+ try {+ upload(await shrinkPhoto(source.preview, source.name));+ } catch {+ toast("This photo couldn't be made smaller here. Try another photo.");+ } finally {+ setShrinking(false);+ }+ };// The scan's report as regions, each on or kept as the visitor chose.const report = s?.status === "succeeded" ? reportOf(s) : undefined;const parsed = useMemo(() => parseScanReport(report), [report]);const regions = useMemo(() => parsed?.regions.map((r) => (r.id in toggles ? { ...r, on: toggles[r.id] } : r)) ?? null, [parsed, toggles]);+ /** The scan finished but its report can't be read: a failed scan, with Try again (never a page that waits forever). */+ const unreadable = s?.status === "succeeded" && !parsed;++ // A pass that failed or was stopped leaves the list: the page goes back to where it was (the marks as the visitor left+ // them, or the last clean result with its Download and Undo) and says why in plain words. A stop says nothing.+ useEffect(() => {+ if (!g || g.id !== lastId || !ended(g)) return;+ const why = visitorError(g, owner, COPY.retry);+ /* eslint-disable react-hooks/set-state-in-effect -- the run's end comes from the server (its poll): the page follows it once */+ if (passes.length > 1) {+ if (why) toast(why);+ } else setRemoveError(why);+ setPasses((p) => (p.at(-1) === g.id ? p.slice(0, -1) : p));+ /* eslint-enable react-hooks/set-state-in-effect */+ // The newest pass's end, once.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [g?.id, g?.status]);const toggle = (id: string) => {const r = regions?.find((x) => x.id === id);@@ -186,15 +315,18 @@ export function WatermarkTool({ app, cover }: { app: { name: string; description};const onCount = regions?.filter((r) => r.on).length ?? 0;- // The picture shown: the newest clean result, else the original.+ // The picture shown: the newest clean result, else the original. A pass that is running or has just ended shows the one+ // before it.const okPasses = [g, prev].filter((x): x is Generation => x?.status === "succeeded");- const latest = imageOf(g?.status === "succeeded" ? g : busy(g) || g?.status === "failed" || g?.status === "canceled" ? prev : undefined);+ const shownPass = g?.status === "succeeded" ? g : (busy(g) || ended(g)) && prev?.status === "succeeded" ? prev : undefined;+ const latest = imageOf(shownPass);const current = latest?.url ?? source?.ref ?? null;const shownSize = size ?? (parsed ? { width: parsed.width, height: parsed.height } : null);const run = (extra: { boxes?: string; mask?: string }) => {if (!source || !current) return;setLastMode(extra.mask ? "brush" : "boxes");+ setRemoveError(null);create.mutate({feature: WATERMARK_FEATURE,@@ -224,14 +356,22 @@ export function WatermarkTool({ app, cover }: { app: { name: string; descriptionrun({ mask: r.mask });};const undo = () => setPasses((p) => p.slice(0, -1));+ const cancelScan = () => {+ if (s && busy(s)) void actions.cancel(s);+ reset();+ };+ const cancelRemove = () => {+ if (g && busy(g)) void actions.cancel(g);+ };const removing = busy(g) || (create.isPending && !!regions);- const result = g?.status === "succeeded" ? imageOf(g) : undefined;+ const resultPass = g?.status === "succeeded" ? g : ended(g) && prev?.status === "succeeded" ? prev : undefined;+ const result = imageOf(resultPass);const quality = result?.meta?.quality as WatermarkQuality | undefined;- const scanFailed = !!scanError || s?.status === "failed" || s?.status === "canceled";+ const scanFailed = !!scanError || s?.status === "failed" || s?.status === "canceled" || unreadable;const empty = !!regions && regions.length === 0 && !passes.length;- const phase: "start" | "uploading" | "too-big" | "scanning" | "scan-failed" | "empty" | "regions" | "removing" | "result" | "remove-failed" = !source+ const phase: "start" | "uploading" | "too-big" | "scanning" | "scan-failed" | "empty" | "regions" | "removing" | "result" = !source? "start": source.uploading? "uploading"@@ -241,15 +381,15 @@ export function WatermarkTool({ app, cover }: { app: { name: string; description? "removing": result? "result"- : g?.status === "failed" || g?.status === "canceled"- ? "remove-failed"- : scanFailed- ? "scan-failed"- : empty- ? "empty"- : regions- ? "regions"- : "scanning";+ : scanFailed+ ? "scan-failed"+ : empty+ ? "empty"+ : regions+ ? "regions"+ : "scanning";++ const scanMessage = scanError ?? (unreadable ? COPY.scanUnreadable : s?.status === "canceled" ? COPY.scanFailed : visitorError(s, owner, COPY.scanFailed));const dismissHint = () => {if (hintSeen) return;@@ -257,10 +397,15 @@ export function WatermarkTool({ app, cover }: { app: { name: string; descriptionwriteHint();};+ // Tall pictures stay on one screen: the column (heading, picture, chips) is as wide as the height left for the picture+ // allows. The result leaves room for its own buttons under the picture.+ const ratio = shownSize ? shownSize.width / shownSize.height : 4 / 3;+ const column = { maxWidth: `min(100%, calc((100svh - ${phase === "result" ? 330 : 260}px) * ${ratio.toFixed(4)}))` };+return (<ToolShelltitle="Apps"- selfHostedOnly+ engineSwitch={false}header={<nav aria-label="Breadcrumb" className="hidden items-center gap-1 text-[13px] text-muted-foreground sm:flex"><Link href="/apps" className="hover:text-foreground">@@ -272,17 +417,21 @@ export function WatermarkTool({ app, cover }: { app: { name: string; description}><div className="mx-auto w-full max-w-[960px] pt-4" data-wm-phase={phase}>- {phase === "start" && <Start app={app} cover={cover} onPick={take} onUpdate={(next) => setSource((cur) => next(cur))} askFirst={askFirst} />}+ {/* The app's name on a phone, where the breadcrumb is hidden. */}+ <p className="mb-2 text-center text-[13px] font-medium text-muted-foreground sm:hidden">{app.name}</p>++ {phase === "start" && <Start app={app} cover={cover} onUpload={upload} onLibrary={fromLibrary} askFirst={askFirst} />}{source && phase !== "start" && (- <div className="space-y-3">- <Header phase={phase} found={regions?.length ?? 0} />+ <div className="mx-auto space-y-3" style={column}>+ <Header phase={phase} found={regions?.length ?? 0} on={onCount} /><Picturephase={phase}source={source}src={latest?.url ?? source.preview}sweep={lastMode === "boxes" && passes.length <= 1}size={shownSize}+ space={parsed ? { width: parsed.width, height: parsed.height } : shownSize}regions={regions ?? []}onToggle={phase === "regions" ? toggle : undefined}after={result?.url}@@ -293,14 +442,16 @@ export function WatermarkTool({ app, cover }: { app: { name: string; description{COPY.hint}</p>)}- {phase === "regions" && regions && regions.length > 0 && <RegionChips regions={regions} onToggle={toggle} />}- {phase === "regions" && onCount === 0 && <p className="text-[13px] text-muted-foreground">Tap a mark to remove it</p>}- {phase === "result" && result && g && (- <ResultBar g={g} out={result} name={baseName(source.name)} owner={!!viewer?.owner} quality={quality} />+ {removeError && (phase === "regions" || phase === "empty") && (+ <p className="text-[13px] text-destructive" role="alert" data-wm-error>+ {removeError}+ </p>)}- {(phase === "scan-failed" || phase === "remove-failed") && (- <p className="text-[13px] text-destructive" role="alert">- {phase === "scan-failed" ? (scanError ?? s?.error ?? "The scan didn't finish. Try again.") : (g?.error ?? COPY.rejected)}+ {phase === "regions" && regions && regions.length > 0 && <RegionChips regions={regions} onToggle={toggle} />}+ {phase === "result" && result && resultPass && <ResultBar g={resultPass} out={result} name={baseName(source.name)} owner={owner} quality={quality} />}+ {phase === "scan-failed" && (+ <p className="text-[13px] text-destructive" role="alert" data-wm-error>+ {scanMessage}</p>)}{phase === "too-big" && (@@ -309,23 +460,28 @@ export function WatermarkTool({ app, cover }: { app: { name: string; description</p>)}{phase === "empty" && <p className="text-[15px]">{COPY.empty}</p>}- <Details /></div>)}</div>{source && phase !== "start" && (<BottomBar>- {phase === "scanning" || phase === "uploading" ? (+ {phase === "uploading" ? (+ <p className="inline-flex min-w-0 flex-1 items-center gap-2 text-[14px]" role="status">+ <Loader2 className="size-4 shrink-0 animate-spin" /> Adding your photo…+ </p>+ ) : phase === "scanning" || phase === "removing" ? (<>- <p className="inline-flex min-w-0 flex-1 items-center gap-2 text-[14px]" role="status">- <Loader2 className="size-4 shrink-0 animate-spin" /> {phase === "uploading" ? "Adding your photo…" : COPY.scanning}- </p>- {s && busy(s) && (- <Button variant="ghost" className="min-h-11 rounded-full" onClick={() => void actions.cancel(s)}>- Cancel- </Button>- )}+ <Loader2 aria-hidden="true" className="size-5 shrink-0 animate-spin text-muted-foreground" />+ <Button+ variant="outline"+ className="min-h-11 flex-1 rounded-full"+ onClick={phase === "scanning" ? cancelScan : cancelRemove}+ disabled={phase === "removing" && !busy(g)}+ data-wm-cancel+ >+ Cancel+ </Button></>) : phase === "regions" ? (<>@@ -336,17 +492,6 @@ export function WatermarkTool({ app, cover }: { app: { name: string; description<Wand2 className="size-4" /> {removeLabel(onCount)}</Button></>- ) : phase === "removing" ? (- <>- <p className="inline-flex min-w-0 flex-1 items-center gap-2 text-[14px]" role="status">- <Loader2 className="size-4 shrink-0 animate-spin" /> {COPY.removing}- </p>- {g && busy(g) && (- <Button variant="ghost" className="min-h-11 rounded-full" onClick={() => void actions.cancel(g)}>- Cancel- </Button>- )}- </>) : phase === "result" && result ? (<><Button variant="outline" className="min-h-11 rounded-full" onClick={() => setBrushOpen(true)} data-wm-brush>@@ -354,12 +499,12 @@ export function WatermarkTool({ app, cover }: { app: { name: string; description<span className="hidden sm:inline">Missed a spot? Brush it</span></Button><Button className="min-h-11 flex-1 rounded-full" asChild>- <a href={downloadHref(result.url, `${baseName(source.name)} · clean.png`)} download={`${baseName(source.name)} · clean.png`} data-wm-download>+ <a href={downloadHref(result.url, cleanFileName(source.name, result.url))} download={cleanFileName(source.name, result.url)} data-wm-download><Download className="size-4" /> Download</a></Button></>- ) : phase === "empty" || phase === "remove-failed" ? (+ ) : phase === "empty" ? (<><Button variant="outline" className="min-h-11 rounded-full" onClick={reset}>Try another photo@@ -373,10 +518,20 @@ export function WatermarkTool({ app, cover }: { app: { name: string; description<Button variant="outline" className="min-h-11 rounded-full" onClick={reset}>Try another photo</Button>- <Button className="min-h-11 flex-1 rounded-full" onClick={() => source && take({ ...source })}>+ <Button className="min-h-11 flex-1 rounded-full" onClick={() => source && take({ ...source })} data-wm-retry><RotateCcw className="size-4" /> Try again</Button></>+ ) : phase === "too-big" ? (+ <>+ <Button variant="outline" className="min-h-11 rounded-full" onClick={reset}>+ Try another photo+ </Button>+ <Button className="min-h-11 flex-1 rounded-full" onClick={() => void shrink()} disabled={shrinking} data-wm-shrink>+ {shrinking ? <Loader2 className="size-4 animate-spin" /> : <Minimize2 className="size-4" />} <span className="sm:hidden">Make it smaller</span>+ <span className="hidden sm:inline">Make it 4096 pixels and continue</span>+ </Button>+ </>) : (<Button className="min-h-11 flex-1 rounded-full" onClick={reset}><ImagePlus className="size-4" /> Try another photo@@ -385,29 +540,28 @@ export function WatermarkTool({ app, cover }: { app: { name: string; description</BottomBar>)}- {source && phase !== "start" && (+ {source && (phase === "regions" || phase === "result") && (<div className="mx-auto mt-3 flex w-full max-w-[960px] flex-wrap items-center gap-2">{phase === "result" && okPasses.length > 1 && (<Button variant="ghost" size="sm" className="min-h-11 rounded-full" onClick={undo}><Undo2 className="size-4" /> Undo</Button>)}- {phase !== "scanning" && phase !== "removing" && phase !== "uploading" && (- <Button variant="ghost" size="sm" className="min-h-11 rounded-full" onClick={reset} data-wm-start-over>- <RotateCcw className="size-4" /> Start over- </Button>- )}+ <Button variant="ghost" size="sm" className="min-h-11 rounded-full" onClick={reset} data-wm-start-over>+ <RotateCcw className="size-4" /> Start over+ </Button></div>)}- {brushOpen && current && <SketchEditor open onOpenChange={setBrushOpen} image={latest?.url ?? source?.preview ?? current} mode="mask" onDone={onBrush} />}+ {brushOpen && current && (+ <SketchEditor open onOpenChange={setBrushOpen} image={latest?.url ?? source?.preview ?? current} mode="mask" words={BRUSH_WORDS} onDone={onBrush} />+ )}</ToolShell>);}-function Header({ phase, found }: { phase: string; found: number }) {- const line =- phase === "regions" ? foundLine(found) : phase === "result" ? "Done. Tap the picture to compare." : phase === "removing" ? COPY.removing : phase === "scanning" ? COPY.scanning : null;+function Header({ phase, found, on }: { phase: string; found: number; on: number }) {+ const line = phase === "regions" ? foundLine(found, on) : phase === "result" ? "Done." : phase === "removing" ? COPY.removing : phase === "scanning" ? COPY.scanning : null;if (!line) return null;return (<h2 className="font-heading text-[22px] leading-tight text-balance sm:text-[26px]" aria-live="polite">@@ -422,6 +576,7 @@ function Picture({src,sweep,size,+ space,regions,onToggle,after,@@ -433,41 +588,39 @@ function Picture({src: string;/** The kept marks' outlines show while the removal runs (not for a brushed pass). */sweep: boolean;+ /** The picture's size as the browser reads it. */size: Size | null;+ /** The pixels the scan's boxes are in (its report's own size). */+ space: Size | null;regions: Region[];onToggle?: (id: string) => void;after?: string;onCompare: () => void;}) {- // Tall pictures stay on one screen: the width follows the height left for them.- const ratio = size ? size.width / size.height : 4 / 3;- const style = { maxWidth: `min(100%, calc((100svh - 260px) * ${ratio.toFixed(4)}))` };if (phase === "result" && after && size) {return (- <div className="mx-auto" style={style} onPointerDown={onCompare}>+ <div onPointerDown={onCompare}><FlipCompare key={after} before={source.preview} after={after} width={size.width} height={size.height} /></div>);}- if (!size) {+ if (!size || !space) {return (- <div className="mx-auto grid aspect-[4/3] w-full place-items-center rounded-2xl bg-media" style={style}>+ <div className="grid aspect-[4/3] w-full place-items-center rounded-2xl bg-media"><Loader2 className="size-5 animate-spin text-white/70" /></div>);}const scanning = phase === "scanning";return (- <div className="mx-auto" style={style}>- <RegionsView src={src} width={size.width} height={size.height} regions={phase === "regions" || (phase === "removing" && sweep) ? regions : []} onToggle={onToggle} dim={phase === "removing"} working={phase === "removing"}>- {scanning && (- <>- <span aria-hidden="true" className="pointer-events-none absolute inset-x-0 h-[3px] animate-wm-scan bg-gradient-to-r from-transparent via-white to-transparent shadow-[0_0_18px_4px_rgb(255_255_255/.55)] motion-reduce:hidden" />- <span aria-hidden="true" className="pointer-events-none absolute inset-0 hidden animate-pulse bg-white/10 motion-reduce:block" />- </>- )}- </RegionsView>- </div>+ <RegionsView src={src} width={space.width} height={space.height} regions={phase === "regions" || (phase === "removing" && sweep) ? regions : []} onToggle={onToggle} dim={phase === "removing"} working={phase === "removing"}>+ {scanning && (+ <>+ <span aria-hidden="true" className="pointer-events-none absolute inset-x-0 h-[3px] animate-wm-scan bg-gradient-to-r from-transparent via-white to-transparent shadow-[0_0_18px_4px_rgb(255_255_255/.55)] motion-reduce:hidden" />+ <span aria-hidden="true" className="pointer-events-none absolute inset-0 hidden animate-pulse bg-white/10 motion-reduce:block" />+ </>+ )}+ </RegionsView>);}@@ -509,9 +662,9 @@ function ResultBar({ g, out, name, owner, quality }: { g: Generation; out: Outpu);}-function Details() {+function Details({ className }: { className?: string }) {return (- <ul className="space-y-1 pt-2 text-[12px] text-muted-foreground">+ <ul className={cn("space-y-1 pt-2 text-[12px] text-muted-foreground", className)}>{COPY.details.map((d) => (<li key={d}>{d}</li>))}@@ -531,41 +684,20 @@ function BottomBar({ children }: { children: React.ReactNode }) {function Start({app,cover,- onPick,- onUpdate,+ onUpload,+ onLibrary,askFirst,}: {app: { name: string; description: string };/** The app's cover (its before and after), handed over by the server page: the demo. */cover?: PresetCover;- onPick: (s: Source) => void;- onUpdate: (next: (cur: Source | null) => Source | null) => void;+ onUpload: (f: File | undefined) => void;+ onLibrary: (v: SlotValue) => void;askFirst: () => boolean;}) {const inputId = useId();const [over, setOver] = useState(false);const [picking, setPicking] = useState(false);- const pending = useRef<string | null>(null);- const upload = (f: File | undefined) => {- if (!f || askFirst()) return;- if (!f.type.startsWith("image/")) return void toast("Add a photo: JPG, PNG or WebP");- const id = nanoid(8);- pending.current = id;- void fileToSlot(- f,- (v) => {- if (!v) return onUpdate((cur) => (cur?.id === id ? null : cur));- const src: Source = { id, ref: v.ref, preview: v.preview, name: f.name, uploading: v.uploading };- if (v.uploading) onPick(src);- else if (pending.current === id) onPick(src);- },- "image",- );- };- const fromLibrary = (v: SlotValue) => {- setPicking(false);- onPick({ id: nanoid(8), ref: v.ref, preview: v.preview, name: v.name ?? "photo" });- };return (<div className="space-y-5"><div className="text-center">@@ -601,13 +733,13 @@ function Start({onDrop={(e) => {e.preventDefault();setOver(false);- upload(e.dataTransfer.files?.[0]);+ onUpload(e.dataTransfer.files?.[0]);}}><span className="grid size-12 place-items-center rounded-2xl bg-brand-faint text-brand-text"><ScanLine className="size-5" /></span>- <p className="text-[13px] text-muted-foreground">{app.description}.</p>+ <p className="text-[13px] text-muted-foreground">{COPY.sizeLine}</p><div className="flex w-full flex-col items-stretch gap-2 sm:w-auto sm:flex-row sm:items-center"><Button className="min-h-11 rounded-full" onClick={() => askFirst() || document.getElementById(inputId)?.click()} data-wm-add><Upload className="size-4" /> Add a photo@@ -620,7 +752,15 @@ function Start({</PopoverTrigger><PopoverContent className="w-[min(92vw,360px)] p-2" collisionPadding={12}><p className="px-1 pb-2 text-[13px] font-medium">From your library</p>- {picking && <LibraryGrid kinds={["image"]} onPick={fromLibrary} />}+ {picking && (+ <LibraryGrid+ kinds={["image"]}+ onPick={(v) => {+ setPicking(false);+ onLibrary(v);+ }}+ />+ )}</PopoverContent></Popover></div>@@ -631,12 +771,12 @@ function Start({hiddendata-wm-fileonChange={(e) => {- upload(e.target.files?.[0]);+ onUpload(e.target.files?.[0]);e.target.value = "";}}/></div>- <Details />+ <Details className="mx-auto max-w-[760px]" /></div>);}diff --git a/src/lib/api.ts b/src/lib/api.tsindex ef684445..f30b5438 100644--- a/src/lib/api.ts+++ b/src/lib/api.ts@@ -1312,6 +1312,8 @@ export interface ConnectGpuDetail extends RefusalDetail {reason?: "setting" | "find" | "browser";look?: boolean;needs?: ConnectNeeds;+ /** A tool only a GPU runs (no fal.ai or Replicate key can): the card offers the GPU alone, to accounts too. */+ gpuOnly?: boolean;}export type ConnectNeeds = "gpu" | "key" | "any";const asNeeds = (v: string | null): ConnectNeeds | undefined => (v === "gpu" || v === "key" || v === "any" ? v : undefined);@@ -1355,18 +1357,20 @@ export function askToSignUp(action: RefusalAction = "upload"): void {* for nothing. A guest gets "Create a free account", an account with neither its own GPU nor its own key "Connect your* GPU or add a key". The function returns true when it asked (the chooser stays shut, the file stays out), and false* for anyone the upload takes, and while who is looking isn't known yet (the server's refusal opens the same card).+ * `action` "run" asks the same way before a run of a picture already on the site (a GPU-only tool's hand-off).*/-export function useAskBeforeUpload(): () => boolean {+export function useAskBeforeUpload({ gpuOnly = false }: { gpuOnly?: boolean } = {}): (action?: RefusalAction) => boolean {const guest = useIsGuest();const seen = useStatus().data?.viewer;// With hosted runs on, an account adds pictures for runs on this studio's GPUs: the upload says if a kind isn't taken.- const nowhere = seen?.kind === "account" && !seen.gpu.connected && !seen.keys?.length && !seen.hosted;- return useCallback(() => {- if (guest) askToSignUp("upload");- else if (nowhere) window.dispatchEvent(new CustomEvent<RefusalDetail>(CONNECT_GPU_EVENT, { detail: { action: "upload" } }));+ // A GPU-only tool (gpuOnly) asks for the GPU even when the account has a key: no key runs it.+ const nowhere = seen?.kind === "account" && !seen.gpu.connected && (gpuOnly || !seen.keys?.length) && !seen.hosted;+ return useCallback((action: RefusalAction = "upload") => {+ if (guest) askToSignUp(action);+ else if (nowhere) window.dispatchEvent(new CustomEvent<ConnectGpuDetail>(CONNECT_GPU_EVENT, { detail: { action, ...(gpuOnly && { gpuOnly }) } }));else return false;return true;- }, [guest, nowhere]);+ }, [guest, nowhere, gpuOnly]);}/**diff --git a/src/lib/gpu/commands.ts b/src/lib/gpu/commands.tsindex 1a9f5de2..b4c5691c 100644--- a/src/lib/gpu/commands.ts+++ b/src/lib/gpu/commands.ts@@ -1,4 +1,4 @@-import type { GpuInventory, IndexPack, RequirementIndex, StepKind } from "./types";+import type { GpuInventory, IndexFile, IndexPack, RequirementIndex, StepKind } from "./types";/*** Copy-paste commands for a fix plan (SPEC §8.3, review item 4): bash for Mac / Linux and PowerShell for@@ -114,7 +114,32 @@ function restartLine(inv: GpuInventory | null): string {return "Press Ctrl+C in the ComfyUI window, then start it again with the same flags";}-function packLines(shell: Shell, l: Layout, name: string, p: IndexPack, kind: StepKind): string[] {+/**+ * A file a pack reads by its own path (no listing shows it, so no step asks for it): fetched with the pack when it isn't+ * there yet, from its pinned link, and kept only when its SHA-256 matches (a .pth can run code when it loads).+ */+function packFileLines(shell: Shell, l: Layout, f: IndexFile): string[] {+ const url = cleanUrl(f.pinnedUrl) ?? cleanUrl(f.url);+ if (!url || !f.sha256 || !/^[0-9a-f]{64}$/.test(f.sha256) || !plain(f.file) || !plain(f.folder)) return [];+ const dir = l.modelDir(shell, f.folder);+ const target = l.modelDir(shell, f.folder, f.file);+ if (shell === "ps") {+ return [+ comment(shell, `${f.file}, if you don't have it yet`),+ `New-Item -ItemType Directory -Force -Path ${dir} | Out-Null`,+ `if (-not (Test-Path ${target})) { curl.exe -L --fail -o ${target} "${url}" }`,+ `if ((Get-FileHash -Algorithm SHA256 ${target}).Hash -ne "${f.sha256.toUpperCase()}") { Remove-Item -Force ${target}; Write-Error "${f.file} didn't match its checksum and was removed" }`,+ ];+ }+ return [+ comment(shell, `${f.file}, if you don't have it yet`),+ `mkdir -p ${dir}`,+ `[ -s ${target} ] || curl -L --fail -o ${target} "${url}"`,+ `printf '%s %s\\n' ${f.sha256} ${target} | sha256sum -c - || rm -f ${target}`,+ ];+}++function packLines(shell: Shell, l: Layout, name: string, p: IndexPack, kind: StepKind, files: IndexFile[] = []): string[] {// A node file Fuobe ships itself: nothing to clone. Live edit's setup card and Settings → Your GPU download it.if (p.bundled) {if (!plain(p.bundled)) return [];@@ -136,6 +161,7 @@ function packLines(shell: Shell, l: Layout, name: string, p: IndexPack, kind: Streturn [...download(shell, dest, l.under(shell, "custom_nodes", name, "__init__.py"), url, "", kind === "pack-update"), ...pip];}if (kind === "pack-update") return [`git -C ${dest} fetch origin`, `git -C ${dest} checkout ${p.commit}`, ...pip];+ const own = files.flatMap((f) => packFileLines(shell, l, f));if (p.subdir && plain(p.subdir)) {const src = l.under(shell, "custom_nodes", `.${name}-src`);const from = l.under(shell, "custom_nodes", `.${name}-src`, ...p.subdir.split("/"));@@ -145,9 +171,10 @@ function packLines(shell: Shell, l: Layout, name: string, p: IndexPack, kind: St`git -C ${src} checkout ${p.commit}`,shell === "ps" ? `Copy-Item -Recurse -Force ${from} ${dest}` : `cp -r ${from} ${dest}`,...pip,+ ...own,];}- return [`git clone ${p.repo} ${dest}`, `git -C ${dest} checkout ${p.commit}`, ...pip];+ return [`git clone ${p.repo} ${dest}`, `git -C ${dest} checkout ${p.commit}`, ...pip, ...own];}function download(shell: Shell, dir: string, target: string, url: string, auth: "" | "hf" | "civitai", replace: boolean, sha256?: string): string[] {@@ -172,7 +199,9 @@ function stepLines(shell: Shell, l: Layout, s: CommandStep, ctx: CommandContext)case "pack-update":case "pack-repair": {const p = s.pack ? idx.packs[s.pack] : undefined;- return p && s.pack ? packLines(shell, l, s.pack, p, s.kind) : [];+ // The files the pack reads by its own path (ComfyUI-Qwen-Watermark's SAM file), pinned and checked.+ const own = Object.values(idx.files).filter((f) => f.packFolder === s.pack && f.presence === "unobservable" && !!f.sha256);+ return p && s.pack ? packLines(shell, l, s.pack, p, s.kind, own) : [];}case "restart":return [comment(shell, restartLine(inv))];diff --git a/src/lib/output-actions.ts b/src/lib/output-actions.tsindex 6664fc2b..e1b8b457 100644--- a/src/lib/output-actions.ts+++ b/src/lib/output-actions.ts@@ -17,7 +17,7 @@ import { CLEAN_FEATURE } from "./av/clean-voice";import { anyAngleHref } from "./catalog/any-angle";import { isInstrumental, lyricsOf, songFormat, STEMS_FORMATS } from "./lyrics";import { CLEAN_DIALOGUE_FEATURE, cleanDialogueHref } from "./av/clean-dialogue";-import { WATERMARK_APP_ID, WATERMARK_FEATURE } from "./watermark";+import { MAX_SIDE as MAX_WATERMARK_SIDE, WATERMARK_APP_ID, WATERMARK_FEATURE } from "./watermark";export type OutputActionId =| "animate"@@ -156,8 +156,8 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =link("upscale", "Upscale", `/upscale?image=${q(o.url)}`);// Any Angle: the same photo from another camera (its 3D view is built once per photo).link("new-angle", "New angle", anyAngleHref(o.url));- // The Watermark Remover's own results go back through its brush instead.- if (g.feature !== WATERMARK_FEATURE) link("remove-watermark", "Remove watermark", `/apps/${WATERMARK_APP_ID}?image=${q(o.url)}`);+ // The Watermark Remover's own results go back through its brush instead; a picture known to be past its size limit isn't offered.+ if (g.feature !== WATERMARK_FEATURE && !(Math.max(o.width ?? 0, o.height ?? 0, Number(o.meta?.width) || 0, Number(o.meta?.height) || 0) > MAX_WATERMARK_SIDE)) link("remove-watermark", "Remove watermark", `/apps/${WATERMARK_APP_ID}?image=${q(o.url)}`);link("reference", "Use as reference", `/image?ref=${q(o.url)}`);link("grade", "Color grade", `/color-grade?image=${q(o.url)}`);link("layers", "Open in Layers", layersHref(g, o.url));@@ -265,7 +265,8 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =if (ctx.reuse) out.push({ id: "reuse", label: "Reuse settings", placement: "menu" });// The steps behind a finished result, as a skill that runs again with new inputs (src/components/skills).if (g.status === "succeeded") out.push({ id: "make-skill", label: "Make a skill from this…", placement: "menu" });- if (g.prompt) out.push({ id: "copy-prompt", label: "Copy prompt", placement: "menu" });+ // The Watermark Remover's prompt is its own fixed instruction, not the visitor's words: nothing to copy.+ if (g.prompt && g.feature !== WATERMARK_FEATURE) out.push({ id: "copy-prompt", label: "Copy prompt", placement: "menu" });// A read-only link (src/lib/share.ts): finished results whose files Fuobe keeps.if (g.status === "succeeded" && g.outputs.some((x) => storedPath(x.url))) out.push({ id: "share", label: "Share link…", placement: "menu" });// Library: pinned results stay at the top of their view; the review status is a sub-menu of its own.diff --git a/src/lib/preset-cards.ts b/src/lib/preset-cards.tsindex 09f5664d..6b9ef292 100644--- a/src/lib/preset-cards.ts+++ b/src/lib/preset-cards.ts@@ -285,7 +285,8 @@ export function motionMove(p: Pick<Preset, "id" | "name" | "category">): CameraMfunction keywordFx(n: string): PreviewFx | null {if (has(n, "firework", "confetti", "glitter", "fairies", "northern lights", "spark") || word(n, "rain", "money")) return "sparkle";if (has(n, "fire", "flame", "lava", "burn", "inferno", "volcano")) return "fire";- if (has(n, "water", "flood", "splash", "ocean", "aquarium", "bubble", "jelly", "dolphin") || word(n, "pool", "fish")) return "water";+ // "Watermark" names a mark on a photo, not water.+ if ((has(n, "water", "flood", "splash", "ocean", "aquarium", "bubble", "jelly", "dolphin") || word(n, "pool", "fish")) && !has(n, "watermark")) return "water";if (has(n, "freez", "frozen", "snow") || word(n, "ice")) return "ice";if (has(n, "air bending", "storm", "tornado", "smoke") || word(n, "wind", "air", "sand", "gas")) return "wind";if (has(n, "thunder", "lightning", "plasma", "atomic")) return "lightning";@@ -384,7 +385,7 @@ export function previewScene(p: Pick<Preset, "type" | "name" | "category"> & { i}if (c === "commercial") return "product";if (has(n, "car", "building", "street", "city", "train", "helicopter", "road", "giant", "colossus", "concert", "tiny planet")) return "city";- if (has(n, "fish", "ocean", "flood", "water", "sand", "earth", "nature", "garden", "northern", "timelapse", "planet")) return "landscape";+ if (has(n, "fish", "ocean", "flood", "water", "sand", "earth", "nature", "garden", "northern", "timelapse", "planet") && !has(n, "watermark")) return "landscape";if (has(n, "head", "face", "eyes", "body", "hair", "skin", "tears", "mask")) return "portrait";if (["destruction", "scale"].includes(c)) return pick(p.id, ["city", "landscape", "portrait"] as const);if (["elements", "nature", "color grade", "transitions"].includes(c)) return pick(p.id, ["landscape", "city", "portrait"] as const);diff --git a/src/lib/watermark.ts b/src/lib/watermark.tsindex bb7ff22a..6b00e2ad 100644--- a/src/lib/watermark.ts+++ b/src/lib/watermark.ts@@ -26,6 +26,21 @@ export const MAX_LABEL = 80;export const MAX_SIDE = 4096;/** Marks the scan was less sure of are shown off (kept) at first. */export const SURE = 0.65;+/**+ * The scan's own margin around a mark (the scan graph's QWMDetect: expand 20, padding 0.35, capped per kind as the pack+ * caps it). The sure marks come back with it; the less sure ones come back tight and get it here.+ */+export const SCAN_EXPAND = 20;+const PAD: Record<(typeof OVERLAY_TYPES)[number], number> = {+ text_logo: 0.12,+ translucent_text_logo: 0.35,+ rectangle: 0.12,+ mosaic: 0.12,+ irregular_sticker: 0.25,+ unknown: 0.25,+};+/** A GPU with less memory than this repairs at 768 px (a "16 GB" card reports a little under 16 GiB). */+export const SMALL_GPU_BYTES = 15 * 2 ** 30;/** Visitor words. */export const COPY = {@@ -46,8 +61,42 @@ export const COPY = {tooBig: "Use a picture up to 4096 pixels on its longest side.",noneKept: "Pick at least one mark to remove",hint: "Tap to compare. Hold to see the original.",+ /** A run that failed for a reason with no plain words of its own. */+ retry: "That didn't work this time. Try again, or brush just the mark.",+ scanFailed: "The scan didn't finish. Try again.",+ scanUnreadable: "We couldn't finish checking this photo. Try again.",+ brushAgain: "Brush on the picture again, then try again.",+ connectGpu: "Connect your GPU, then try again.",+ sizeLine: "JPG, PNG or WebP, up to 4096 pixels on the longest side.",} as const;+/** The app's own words a failed run may carry: shown as they are. Anything else (a node's own error) never reaches a visitor. */+const PLAIN_ERRORS = new Set<string>([COPY.rejected, COPY.tooBig, COPY.noneKept, COPY.scanFailed, COPY.scanUnreadable, COPY.brushAgain, COPY.connectGpu]);+const PLAIN_CHECKS = /^(Pick up to \d+ marks at a time|The marks to remove couldn't be read\. Scan the picture again\.)$/;++/**+ * What a failed or stopped run says on the page: nothing for a cancel, the app's own words as they are, the raw error to+ * the owner only, else `fallback`.+ */+export function visitorError(run: { status?: string; error?: string | null } | null | undefined, owner: boolean, fallback: string): string | null {+ if (!run || run.status === "canceled") return null;+ const e = run.error?.trim();+ if (e && (PLAIN_ERRORS.has(e) || PLAIN_CHECKS.test(e) || owner)) return e;+ return fallback;+}++/** The download's file name: "catwalk-clean.png" (the picture's own name, made safe, and the result's own extension). */+export function cleanFileName(name: string, url: string): string {+ const ext = (/\.(png|jpe?g|webp)(?:[?#]|$)/i.exec(url)?.[1] ?? "png").toLowerCase().replace("jpeg", "jpg");+ const base =+ name+ .replace(/\.[a-z0-9]{2,4}$/i, "")+ .replace(/[^A-Za-z0-9_]+/g, "-")+ .replace(/^-+|-+$/g, "")+ .slice(0, 60) || "photo";+ return `${base}-clean.${ext}`;+}+const TEXT_WORDS = /text|caption|word|letter|url|www|@|©|date|signature/i;export function normalizeType(value: unknown): OverlayType {@@ -77,6 +126,8 @@ export interface Region {repair: Box;/** On at first (the scan was sure of it); a less sure mark starts kept. */on: boolean;+ /** The material around the mark in the scan's words ("fabric", "skin"…): the repair's hint. Empty when it said none. */+ background: string;}export interface ScanResult {@@ -96,9 +147,17 @@ function ordered(b: Box, width: number, height: number): Box | null {return x1 > x0 && y1 > y0 ? [Math.floor(x0), Math.floor(y0), Math.ceil(x1), Math.ceil(y1)] : null;}+/** A tight box with the scan's margin for its kind (the pack's parse_boxes, adaptive padding), inside the picture. */+export function padBox(b: Box, type: OverlayType, width: number, height: number): Box {+ const ex = Math.ceil(SCAN_EXPAND + (b[2] - b[0]) * PAD[type]);+ const ey = Math.ceil(SCAN_EXPAND + (b[3] - b[1]) * PAD[type]);+ return [Math.max(0, b[0] - ex), Math.max(0, b[1] - ey), Math.min(width, b[2] + ex), Math.min(height, b[3] + ey)];+}+/*** The scan's report (QWMDetect's JSON, pixels) as regions: the sure marks first and on, the less sure ones (rejected_boxes)- * after them and off. Null when the words aren't a report.+ * after them and off. The sure marks' boxes already carry the scan's margin; the less sure ones come back tight and get the+ * same margin here. Null when the words aren't a report.*/export function parseScanReport(text: string | undefined | null): ScanResult | null {if (!text) return null;@@ -118,14 +177,15 @@ export function parseScanReport(text: string | undefined | null): ScanResult | nif (!Array.isArray(list)) return;for (const item of list) {if (!item || typeof item !== "object") continue;- const it = item as { bbox?: unknown; source_bbox?: unknown; overlay_type?: unknown; label?: unknown; confidence?: unknown };- const repair = box4(it.bbox) && ordered(box4(it.bbox)!, width, height);- if (!repair) continue;- const tight = (box4(it.source_bbox) && ordered(box4(it.source_bbox)!, width, height)) || repair;+ const it = item as { bbox?: unknown; source_bbox?: unknown; overlay_type?: unknown; label?: unknown; confidence?: unknown; background?: unknown };+ const given = box4(it.bbox) && ordered(box4(it.bbox)!, width, height);+ if (!given) continue;const type = normalizeType(it.overlay_type);+ const tight = (box4(it.source_bbox) && ordered(box4(it.source_bbox)!, width, height)) || given;+ const repair = on ? given : padBox(tight, type, width, height);const label = cleanLabel(it.label);const sure = on && (!finite(it.confidence) || it.confidence >= SURE);- regions.push({ id: `r${regions.length + 1}`, type, label, chip: chipFor(type, label), box: tight, repair, on: sure });+ regions.push({ id: `r${regions.length + 1}`, type, label, chip: chipFor(type, label), box: tight, repair, on: sure, background: cleanLabel(it.background) });}};take(d.boxes, true);@@ -149,9 +209,19 @@ export function regionAt(regions: Region[], x: number, y: number, margin = 0): Rreturn best;}-/** The header over the regions: "Found 3. Tap any you want to keep." */-export function foundLine(count: number): string {- return count === 1 ? "Found 1. Tap it if you want to keep it." : `Found ${count}. Tap any you want to keep.`;+/**+ * A tap at (x, y) in pixels: a mark the finger is inside wins (the smallest one), else the nearest small mark within+ * `margin` of it. A tap inside a big caption never flips the small logo beside it.+ */+export function pickRegion(regions: Region[], x: number, y: number, margin: number): Region | null {+ return regionAt(regions, x, y, 0) ?? regionAt(regions, x, y, margin);+}++/** The header over the regions, as the marks stand: "Found 3. Tap any you want to keep." */+export function foundLine(count: number, on = count): string {+ if (on >= count) return count === 1 ? "Found 1. Tap it if you want to keep it." : `Found ${count}. Tap any you want to keep.`;+ if (on <= 0) return count === 1 ? "Found 1. Tap it to remove it." : `Found ${count}. Tap the ones to remove.`;+ return `Found ${count}. Tap a mark to keep or remove it.`;}/** The main button: "Remove 3", or "Everything is kept" when every mark is kept. */@@ -163,7 +233,7 @@ export function removeLabel(on: number): string {export function keptBoxesJson(regions: Region[]): string {const boxes = regions.filter((r) => r.on)- .map((r) => ({ bbox: r.repair, source_bbox: r.box, overlay_type: r.type, label: r.label }));+ .map((r) => ({ bbox: r.repair, source_bbox: r.box, overlay_type: r.type, label: r.label, ...(r.background && { background: r.background }) }));return JSON.stringify({ coordinate_space: "pixels", boxes });}@@ -177,8 +247,8 @@ function cleanLabel(v: unknown): string {/*** The kept marks as they may reach the graph: JSON, 1–32 boxes of 4 finite numbers, clamped to the picture (its size when- * known, else 16384 px), each with an area, a known type (else "unknown"), a label of at most 80 characters with no control- * characters, in pixels. Rebuilt from scratch: nothing the client sent passes through as it was. Throws in words.+ * known, else 16384 px), each with an area, a known type (else "unknown"), a label and a background hint of at most 80+ * characters with no control characters, in pixels. Rebuilt from scratch: nothing the client sent passes through as it was. Throws in words.*/export function checkWatermarkBoxes(raw: unknown, size?: { width?: number; height?: number }): { json: string; count: number } {let doc: unknown = raw;@@ -194,24 +264,25 @@ export function checkWatermarkBoxes(raw: unknown, size?: { width?: number; heighif (list.length > MAX_BOXES) throw new Error(`Pick up to ${MAX_BOXES} marks at a time`);const width = size?.width && size.width > 0 ? size.width : 16384;const height = size?.height && size.height > 0 ? size.height : 16384;- const boxes: { bbox: Box; source_bbox?: Box; overlay_type: OverlayType; label: string }[] = [];+ const boxes: { bbox: Box; source_bbox?: Box; overlay_type: OverlayType; label: string; background?: string }[] = [];for (const item of list) {if (!item || typeof item !== "object") continue;- const it = item as { bbox?: unknown; source_bbox?: unknown; overlay_type?: unknown; label?: unknown };+ const it = item as { bbox?: unknown; source_bbox?: unknown; overlay_type?: unknown; label?: unknown; background?: unknown };const b = box4(it.bbox);const bbox = b && ordered(b, width, height);if (!bbox) continue;const s = box4(it.source_bbox);const source = s && ordered(s, width, height);- boxes.push({ bbox, ...(source && { source_bbox: source }), overlay_type: normalizeType(it.overlay_type), label: cleanLabel(it.label) || "watermark" });+ const bg = cleanLabel(it.background);+ boxes.push({ bbox, ...(source && { source_bbox: source }), overlay_type: normalizeType(it.overlay_type), label: cleanLabel(it.label) || "watermark", ...(bg && { background: bg }) });}if (!boxes.length) throw Object.assign(new Error(COPY.noneKept), { status: 400 });return { json: JSON.stringify({ coordinate_space: "pixels", boxes }), count: boxes.length };}-/** The longest side the repair works at: 1024; 1536 for a picture past 3000 px; 768 on a GPU with under 16 GB. */+/** The longest side the repair works at: 1024; 1536 for a picture past 3000 px; 768 on a GPU smaller than a 16 GB card. */export function maxSideFor(width?: number, height?: number, vramBytes?: number): number {- if (vramBytes && vramBytes > 0 && vramBytes < 16 * 2 ** 30) return 768;+ if (vramBytes && vramBytes > 0 && vramBytes < SMALL_GPU_BYTES) return 768;if (Math.max(width ?? 0, height ?? 0) > 3000) return 1536;return 1024;}diff --git a/src/server/generations.ts b/src/server/generations.tsindex 97826385..ab990050 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -12,7 +12,7 @@ import { withSignatureWords } from "@/lib/catalog/palettes";import { applySketch, stripMotionPaths } from "@/lib/catalog/sketch";import { cueText, type Cue } from "@/lib/cues";import { HELPER_FEATURES, HELPER_SUFFIX, isReviewStatus, type AssetUse, type ReviewFilter } from "@/lib/library";-import { COPY as WATERMARK_COPY, rejectedRepair, type WatermarkQuality } from "@/lib/watermark";+import { checkWatermarkBoxes, COPY as WATERMARK_COPY, parseScanReport, rejectedRepair, type WatermarkQuality } from "@/lib/watermark";import { upscaleTier } from "@/lib/av/upscale";import { chainedWaitMessage, framesWait, keyframeChain } from "@/lib/catalog/keyframes";import { clipFpsProblem, clipSizeProblem, clipTotalProblem, clipWindowProblem, elementClipProblem, insertRangeProblem, portraitShapeProblem, sourceFrames, voiceWindowProblem } from "@/lib/catalog/clip-windows";@@ -2203,6 +2203,24 @@ async function pollOne(r: Row): Promise<void> {update(r.id, { status: "failed", error: WATERMARK_COPY.rejected, completed_at: Date.now(), message: null });return;}+ // A Watermark Remover scan with no report the page can read fails in words (never a page that waits for marks forever).+ if (r.op === "watermark-scan" && !(res.outputs as RichOutput[]).some((o) => parseScanReport(o.text))) {+ update(r.id, { status: "failed", error: WATERMARK_COPY.scanFailed, completed_at: Date.now(), message: null });+ return;+ }+ // A Watermark Remover result keeps how it was asked, next to the repair's verdict: the marks removed (as checked) and how.+ if (r.op === "watermark-remove") {+ const req = JSON.parse(r.request_json) as GenerationRequest;+ const asked = req.params?.extra?.boxes;+ const mode = req.inputs?.mask ? "manual_mask" : asked !== undefined ? "manual_boxes" : "auto_qwen";+ let marks: unknown[] | undefined;+ try {+ marks = mode === "manual_boxes" ? (JSON.parse(checkWatermarkBoxes(asked).json) as { boxes: unknown[] }).boxes : undefined;+ } catch {+ marks = undefined;+ }+ res = { ...res, outputs: (res.outputs as RichOutput[]).map((o) => (o.kind === "image" ? { ...o, meta: { ...o.meta, watermark: { mode, ...(marks && { marks }) } } } : o)) };+ }// Mark first so a slow download isn't polled twice.update(r.id, { status: "running", progress: 0.99, message: "Saving results" });const outputs: OutputFile[] = [];diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex 06eb35f3..cebb66bf 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -45,7 +45,7 @@ import { fpsPlan } from "@/lib/av/fps";import { resolveWorkflowId } from "@/lib/comfy-variants";import { MOTION_GRAPHS, motionTransferPrompt, neutralPrompt, WORDS_NEEDED } from "@/lib/comfy-prompts";import { DECODER_PARAM, editCanvas, GPU_PARAM, LIGHTNING_GRAPHS, lightningSigmas, SPEED_PARAM, ZEN_ADAPTER, ZEN_ENCODER } from "@/lib/qwen21-speed";-import { checkWatermarkBoxes, COPY as WATERMARK_COPY, MAX_SIDE as MAX_WATERMARK_SIDE, maxSideFor, qualityOf } from "@/lib/watermark";+import { checkWatermarkBoxes, COPY as WATERMARK_COPY, MAX_SIDE as MAX_WATERMARK_SIDE, maxSideFor, qualityOf, SCAN_EXPAND as WATERMARK_SCAN_EXPAND } from "@/lib/watermark";import { h3Canvas, h3Frames, isH3Graph } from "@/lib/h3-prompt";import { draftSizeFor, REGEN_COPY, REGEN_WINDOW_SECONDS, REGEN_WORKFLOW, regenFrames, regenOnePassRefusal, regenResolution } from "@/lib/catalog/regenerate";import { carriesBoxes, LAYOUT_PARAM } from "@/lib/layout-prompt";@@ -1740,13 +1740,18 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,const sourceChannels = b.channels || b.separationModel ? (ctx.media?.(String(values.audio ?? ""))?.channels ?? (Number(extra.sourceChannels) || undefined)) : undefined;if (b.channels) values.channels = dbsChannelsFor(extra.channels, sourceChannels);for (const k of ["separationModel", "channels", "sourceChannels"]) delete extra[k];- // Options → Prompt helper (FLUX 3 Image Klein) and a layout's draft (kept for Reuse): read here, never bound.- // Watermark Remover: the marks kept (checked and rebuilt again, clamped to this picture), how QWMDetect finds what to repair,- // and the size the repair works at (the picture's size and the GPU's memory). Never what the request says for these.+ // Watermark Remover: the marks kept (checked and rebuilt again, clamped to this picture), how QWMDetect finds what to repair+ // and how far past each mark, and the size the repair works at (the picture's size and the GPU's memory). Never what the+ // request says for these, nor for the picture, the brush, the seeds or the file names already bound.if (manifest.capability === "watermark-remove") {const still = ctx.media?.(String(values.image ?? ""));if (still?.width && still.height && Math.max(still.width, still.height) > MAX_WATERMARK_SIDE) throw new ProviderError(WATERMARK_COPY.tooBig, 400);const brushed = !!b.mask;+ // A brush painted on another size of the picture can't line up with it (QWMDetect refuses it): said in words up front.+ const painted = brushed ? ctx.media?.(String(values.mask ?? "")) : undefined;+ if (painted?.width && painted.height && still?.width && still.height && (painted.width !== still.width || painted.height !== still.height)) {+ throw new ProviderError(WATERMARK_COPY.brushAgain, 400);+ }if (!brushed && extra.boxes !== undefined) {try {values.boxes = checkWatermarkBoxes(extra.boxes, { width: still?.width, height: still?.height }).json;@@ -1755,13 +1760,17 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,}values.detectMode = "manual_boxes";} else if (b.detectMode) values.detectMode = brushed ? "manual_mask" : "auto_qwen";+ // The kept marks already carry the scan's margin; marks the pack finds itself (an API caller's run) get it here.+ if (b.detectExpand) values.detectExpand = values.detectMode === "manual_boxes" ? 0 : WATERMARK_SCAN_EXPAND;if (b.maxSize) values.maxSize = maxSideFor(still?.width, still?.height, await ctx.vram?.().catch(() => undefined));- for (const k of ["boxes", "detectMode", "maxSize"]) delete extra[k];+ for (const k of ["boxes", "detectMode", "detectExpand", "maxSize", "image", "mask", "seed", "filenamePrefix"]) delete extra[k];}if (manifest.capability === "watermark-scan") {const still = ctx.media?.(String(values.image ?? ""));if (still?.width && still.height && Math.max(still.width, still.height) > MAX_WATERMARK_SIDE) throw new ProviderError(WATERMARK_COPY.tooBig, 400);+ for (const k of ["image", "filenamePrefix"]) delete extra[k];}+ // Options → Prompt helper (FLUX 3 Image Klein) and a layout's draft (kept for Reuse): read here, never bound.const helper = extra[PROMPT_HELPER_PARAM];const laidOut = carriesBoxes(extra);delete extra[PROMPT_HELPER_PARAM];diff --git a/tests/e2e/watermark-remover.mjs b/tests/e2e/watermark-remover.mjsindex 434f717b..413a2146 100644--- a/tests/e2e/watermark-remover.mjs+++ b/tests/e2e/watermark-remover.mjs@@ -5,8 +5,10 @@// Checks, at 390 x 844 (taps) and 1440 px: the start screen; a photo added is scanned at once and its marks show with Text and// Logo chips; a tap keeps a mark ("Remove 1"); Remove gives the result; a tap flips Before and After and a held press shows// Before until it lets go; "Brush it" opens the brush and a stroke makes another pass (Undo then shows); Download is the PNG;-// ?image= scans at once; an empty scan says so and offers the brush; no sideways scroll; and, with --guest, that a guest-// is asked to sign up. Screenshots go to outDir. A page error fails the run.+// ?image= scans at once; an empty scan says so and offers the brush; a scan with no readable report, a failed or stopped+// removal and a failed later pass each leave the page where it was, in plain words; Cancel stops a scan; a photo over 4096 px+// is made smaller and goes on; no sideways scroll; and, with --guest, that a guest is asked to sign up. Screenshots go to+// outDir. A page error fails the run.import { spawnSync } from "node:child_process";import fs from "node:fs";import path from "node:path";@@ -21,10 +23,17 @@ const out = args[1] ?? fs.mkdtempSync("/tmp/fuobe-watermark-");fs.mkdirSync(out, { recursive: true });const PAGE = "/apps/app-watermark-remover";-// A 1200 x 900 test photo.-const photo = path.join(out, "photo.png");-const r = spawnSync("ffmpeg", ["-hide_banner", "-loglevel", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=1200x900:d=1", "-frames:v", "1", photo]);-if (r.status !== 0) throw new Error(`ffmpeg failed: ${r.stderr}`);+// A 1200 x 900 test photo, and one past 4096 px.+const still = (file, size) => {+ const r = spawnSync("ffmpeg", ["-hide_banner", "-loglevel", "error", "-y", "-f", "lavfi", "-i", `testsrc2=s=${size}:d=1`, "-frames:v", "1", file]);+ if (r.status !== 0) throw new Error(`ffmpeg failed: ${r.stderr}`);+ return file;+};+const photo = still(path.join(out, "photo.png"), "1200x900");+const bigPhoto = still(path.join(out, "big-photo.jpg"), "4800x3600");+const DETAIL = "Everything outside the marks stays pixel for pixel the same.";+const RETRY = "That didn't work this time. Try again, or brush just the mark.";+const phaseOf = (page) => page.evaluate(() => document.querySelector("[data-wm-phase]")?.getAttribute("data-wm-phase"));const failures = [];const check = (ok, what) => {@@ -47,6 +56,46 @@ async function setup(browser, device, theme = "light", base = app) {await ctx.route((u) => u.origin !== new URL(base).origin && /^https?:$/.test(u.protocol), (rt) => rt.abort());return ctx;}+/**+ * A phone page whose runs read as `rewrite(run)` says (the live stream is cut, so the poll carries every answer):+ * the run to show, or null to leave it as the server sent it.+ */+async function rewritten(browser, rewrite) {+ const ctx = await setup(browser, PHONE, "dark");+ await ctx.addInitScript(() => {+ try {+ localStorage.setItem("fuobe.watermark.hint", "1");+ } catch {}+ });+ await ctx.route("**/api/generations/stream", (rt) => rt.abort());+ await ctx.route(/\/api\/generations\/[^/?]+(\?.*)?$/, async (rt) => {+ if (/\/stream(\?|$)/.test(rt.request().url())) return rt.abort();+ if (rt.request().method() !== "GET") return rt.continue();+ let res;+ try {+ res = await rt.fetch();+ } catch {+ return;+ }+ const g = await res.json();+ await rt.fulfill({ response: res, json: (g && rewrite(g)) ?? g });+ });+ return ctx;+}+/** One brush stroke across the middle of the picture, then "Remove it". */+async function brushOnce(page) {+ const dialog = page.getByRole("dialog");+ await dialog.waitFor({ timeout: 15_000 });+ const canvas = dialog.locator("canvas").last();+ await canvas.waitFor({ timeout: 15_000 });+ await page.waitForTimeout(400);+ const c = await canvas.boundingBox();+ await page.mouse.move(c.x + c.width * 0.3, c.y + c.height * 0.5);+ await page.mouse.down();+ await page.mouse.move(c.x + c.width * 0.6, c.y + c.height * 0.55, { steps: 8 });+ await page.mouse.up();+ return dialog;+}async function waitPhase(page, want, ms = 45_000) {await page.waitForFunction((w) => w.includes(document.querySelector("[data-wm-phase]")?.getAttribute("data-wm-phase") ?? ""), want, { timeout: ms });}@@ -72,6 +121,7 @@ try {check(await page.getByRole("heading", { name: "Clean up a photo" }).isVisible(), `${label}: the start screen says what it does`);check(await page.getByRole("button", { name: "Add a photo" }).isVisible(), `${label}: Add a photo`);check(await page.getByRole("button", { name: "From Library" }).isVisible(), `${label}: From Library`);+ check(await page.getByText(DETAIL).isVisible(), `${label}: the start screen says what to expect`);await page.screenshot({ path: path.join(out, `wm-start-${dname}.png`), fullPage: true });await noSideScroll(page, `${label} start`);@@ -101,7 +151,9 @@ try {// Remove.await page.locator("[data-wm-remove]").click();await waitPhase(page, ["result"]);- check(true, `${label}: the result shows`);+ check(await page.getByRole("heading", { name: "Done." }).isVisible(), `${label}: the result says Done.`);+ check((await page.getByText(DETAIL).count()) === 0, `${label}: the details stay on the start screen`);+ check(await page.locator("[data-wm-start-over]").isVisible(), `${label}: Start over under the result`);const cmp = page.locator("[data-wm-compare]");check((await cmp.getAttribute("data-wm-compare")) === "after", `${label}: the result opens on After`);await tapAt(page, cmp, touch);@@ -116,23 +168,18 @@ try {await page.mouse.up();check((await cmp.getAttribute("data-wm-compare")) === "after", `${label}: letting go shows After`);const dl = page.locator("[data-wm-download]");- check(!!(await dl.getAttribute("download")) && /\.png$/.test(await dl.getAttribute("download")), `${label}: Download is a PNG (${await dl.getAttribute("download")})`);+ check((await dl.getAttribute("download")) === "photo-clean.png", `${label}: Download is the PNG, named after the photo (${await dl.getAttribute("download")})`);await page.screenshot({ path: path.join(out, `wm-result-${dname}.png`), fullPage: true });await noSideScroll(page, `${label} result`);// Brush a missed spot.await page.locator("[data-wm-brush]").click();- const dialog = page.getByRole("dialog");- await dialog.waitFor({ timeout: 15_000 });- const canvas = dialog.locator("canvas").last();- await canvas.waitFor({ timeout: 15_000 });- const c = await canvas.boundingBox();- await page.mouse.move(c.x + c.width * 0.3, c.y + c.height * 0.5);- await page.mouse.down();- await page.mouse.move(c.x + c.width * 0.6, c.y + c.height * 0.55, { steps: 8 });- await page.mouse.up();+ const dialog = await brushOnce(page);await page.screenshot({ path: path.join(out, `wm-brush-${dname}.png`) });- await dialog.getByRole("button", { name: /^Use this/ }).click();+ check(await dialog.getByRole("heading", { name: "Brush over the mark" }).isVisible(), `${label}: the brush says what to paint`);+ check(!/\bmask\b/i.test(await dialog.innerText()), `${label}: the brush never says "mask"`);+ if (touch) check(((await dialog.getByRole("button", { name: "Remove it" }).boundingBox())?.height ?? 0) >= 44, `${label}: the brush's button is big enough to tap`);+ await dialog.getByRole("button", { name: "Remove it" }).click();await waitPhase(page, ["removing", "result"]);await page.waitForFunction(() => document.querySelector("[data-wm-phase]")?.getAttribute("data-wm-phase") === "result" && [...document.querySelectorAll("button")].some((x) => x.textContent?.includes("Undo")), null, { timeout: 45_000 });check(true, `${label}: a brushed pass makes a new result, with Undo`);@@ -176,6 +223,130 @@ try {await ctx.close();}+ // A scan that finished with no report the page can read: it says so, with Try again (never a page that waits forever).+ {+ const ctx = await rewritten(browser, (g) => (g.op === "watermark-scan" && g.status === "succeeded" ? { ...g, outputs: g.outputs.map((o) => (o.kind === "text" ? { ...o, text: "not a report" } : o)) } : null));+ const page = await ctx.newPage();+ await openRoute(page, `${app}${PAGE}`);+ await page.locator("[data-wm-file]").setInputFiles(photo);+ await waitPhase(page, ["scan-failed"]);+ check(await page.getByText("We couldn't finish checking this photo. Try again.").isVisible(), "an unreadable scan says so");+ check(await page.locator("[data-wm-retry]").isVisible(), "and offers Try again");+ check((await page.locator("[data-wm-start-over]").count()) === 0, "with one way out, not two");+ await page.screenshot({ path: path.join(out, "wm-scan-unreadable-390.png") });+ await ctx.close();+ }++ // Cancel while scanning: back to the start, no error.+ {+ const ctx = await rewritten(browser, (g) => (g.op === "watermark-scan" ? { ...g, status: "running", outputs: [] } : null));+ const page = await ctx.newPage();+ await openRoute(page, `${app}${PAGE}`);+ await page.locator("[data-wm-file]").setInputFiles(photo);+ await waitPhase(page, ["scanning"]);+ check((await page.getByText("Looking for marks…").count()) === 1, "scanning says so once");+ await page.locator("[data-wm-cancel]").click();+ await waitPhase(page, ["start"]);+ check((await page.locator("[data-wm-error]").count()) === 0, "Cancel while scanning goes back to the start, with no error");+ await ctx.close();+ }++ // The first removal fails (with no words of its own), the second is stopped: both go back to the marks as they were left.+ // (Signed in as the owner here, who sees a run's own error as it is; a visitor never does: the unit tests check that.)+ {+ const ids = [];+ let how = "running";+ let shownRunning = false;+ const ctx = await rewritten(browser, (g) => {+ if (g.op !== "watermark-remove") return null;+ if (!ids.includes(g.id)) ids.push(g.id);+ const n = ids.indexOf(g.id);+ if (n === 0) return { ...g, status: "failed", error: null, outputs: [] };+ if (n === 1) {+ if (how === "running") shownRunning = true;+ return { ...g, status: how, error: null, outputs: [] };+ }+ return null;+ });+ const page = await ctx.newPage();+ await openRoute(page, `${app}${PAGE}`);+ await page.locator("[data-wm-file]").setInputFiles(photo);+ await waitPhase(page, ["regions"]);+ await page.locator('[data-wm-chip="r2"]').click();+ check(await page.getByRole("heading", { name: "Found 2. Tap a mark to keep or remove it." }).isVisible(), "with one mark kept, the header says tap to keep or remove");+ await page.locator("[data-wm-remove]").click();+ await page.waitForFunction(() => !!document.querySelector("[data-wm-error]"), null, { timeout: 45_000 });+ check((await phaseOf(page)) === "regions", "a failed first removal goes back to the marks");+ const said = await page.locator("[data-wm-error]").innerText();+ check(said === RETRY, `it says so in plain words (${said})`);+ check((await page.locator('[data-wm-chip="r2"]').getAttribute("aria-pressed")) === "true", "the mark kept stays kept");+ check((await page.locator("[data-wm-remove]").innerText()).includes("Remove 1"), "and Remove tries again");+ await page.screenshot({ path: path.join(out, "wm-remove-failed-390.png") });+ // The next pass runs until Cancel, then reads as stopped (the rewrite stands in for the stop arriving).+ await page.locator("[data-wm-remove]").click();+ await waitPhase(page, ["removing"]);+ for (let i = 0; i < 150 && !shownRunning; i++) await page.waitForTimeout(100);+ await page.locator("[data-wm-cancel]:not([disabled])").waitFor({ timeout: 15_000 });+ check((await page.getByText("Removing…").count()) === 1, "removing says so once");+ await page.locator("[data-wm-cancel]").click();+ how = "canceled";+ await waitPhase(page, ["regions"]);+ check((await page.locator("[data-wm-error]").count()) === 0, "a stopped removal goes back to the marks and says nothing");+ await page.locator("[data-wm-remove]").click();+ await waitPhase(page, ["result"]);+ check(true, "Remove again gives the result");+ await ctx.close();+ }++ // A later pass that fails keeps the good result, with its Download.+ {+ let first = null;+ const ctx = await rewritten(browser, (g) => {+ if (g.op !== "watermark-remove") return null;+ first ??= g.id;+ return g.id === first ? null : { ...g, status: "failed", error: null, outputs: [] };+ });+ const page = await ctx.newPage();+ await openRoute(page, `${app}${PAGE}`);+ await page.locator("[data-wm-file]").setInputFiles(photo);+ await waitPhase(page, ["regions"]);+ await page.locator("[data-wm-remove]").click();+ await waitPhase(page, ["result"]);+ await page.locator("[data-wm-brush]").click();+ const dialog = await brushOnce(page);+ await dialog.getByRole("button", { name: "Remove it" }).click();+ const told = await page+ .getByText(RETRY)+ .first()+ .waitFor({ timeout: 45_000 })+ .then(() => true)+ .catch(() => false);+ check(told, "a failed later pass says so in a note");+ await waitPhase(page, ["result"]);+ check(await page.locator("[data-wm-download]").isVisible(), "and the good result stays, with its Download");+ await page.screenshot({ path: path.join(out, "wm-brush-failed-390.png") });+ await ctx.close();+ }++ // A photo past 4096 px: made 4096 px here, then scanned.+ {+ const ctx = await setup(browser, PHONE);+ const page = await ctx.newPage();+ await openRoute(page, `${app}${PAGE}`);+ await page.locator("[data-wm-file]").setInputFiles(bigPhoto);+ await waitPhase(page, ["too-big"], 90_000);+ check(await page.locator("[data-wm-shrink]").isVisible(), "a photo past 4096 px offers to make it smaller");+ const shrinkBox = await page.locator("[data-wm-shrink]").boundingBox();+ const shrinkFits = await page.locator("[data-wm-shrink]").evaluate((el) => el.scrollWidth <= el.clientWidth + 1);+ check(!!shrinkBox && shrinkBox.x + shrinkBox.width <= 390 && shrinkFits, "and its button fits on a phone");+ await noSideScroll(page, "390 too big");+ await page.screenshot({ path: path.join(out, "wm-too-big-390.png") });+ await page.locator("[data-wm-shrink]").click();+ await waitPhase(page, ["regions"], 90_000);+ check(true, "made smaller, it is scanned");+ await ctx.close();+ }+// A guest is asked to sign up before a photo goes anywhere.if (guestApp) {const ctx = await setup(browser, PHONE, "light", guestApp);@@ -205,6 +376,44 @@ try {await page.screenshot({ path: path.join(out, "wm-guest-handoff-390.png") });await ctx.close();}++ // A new account with no GPU: asked for the GPU (no key runs this app), on adding a photo and on a hand-off.+ if (guestApp) {+ const ctx = await setup(browser, PHONE, "light", guestApp);+ const page = await ctx.newPage();+ await openRoute(page, `${guestApp}/apps`);+ const made = await page.evaluate(async () => {+ const res = await fetch("/api/auth/signup", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ email: `wm${Date.now()}@example.com`, password: "watermark-check-12345" }) });+ return res.status;+ });+ check(made < 300, `account: signed up (${made})`);+ await openRoute(page, `${guestApp}${PAGE}`);+ const chooser = page.waitForEvent("filechooser", { timeout: 3000 }).then(() => true).catch(() => false);+ await page.getByRole("button", { name: "Add a photo" }).click();+ const card = page.getByRole("dialog");+ const asked = await card+ .getByText("Connect your GPU to add your own files")+ .waitFor({ timeout: 10_000 })+ .then(() => true)+ .catch(() => false);+ check(asked, "account: Add a photo asks for the GPU");+ check(!(await chooser), "account: no file chooser opens");+ check(!/fal\.ai|Replicate|\bkey\b/i.test(await card.innerText()), "account: the card offers no key");+ await page.screenshot({ path: path.join(out, "wm-account-390.png") });+ await page.keyboard.press("Escape");+ await openRoute(page, `${guestApp}${PAGE}?image=${encodeURIComponent("/previews/presets/app-remove-background.jpg")}`);+ const runCard = await page+ .getByRole("dialog")+ .getByText("Fuobe runs this on the ComfyUI on your computer.", { exact: false })+ .waitFor({ timeout: 15_000 })+ .then(() => true)+ .catch(() => false);+ check(runCard, "account: a hand-off asks for the GPU to run it");+ check(!/fal\.ai|Replicate|\bkey\b/i.test(await page.getByRole("dialog").innerText().catch(() => "")), "account: that card offers no key either");+ check(await page.getByText("Connect your GPU, then try again.").isVisible(), "account: the page says it in words");+ await page.screenshot({ path: path.join(out, "wm-account-handoff-390.png") });+ await ctx.close();+ }} finally {await browser.close();}diff --git a/tests/watermark-remover.test.ts b/tests/watermark-remover.test.tsindex d549d4ce..6b630e59 100644--- a/tests/watermark-remover.test.ts+++ b/tests/watermark-remover.test.ts@@ -1,7 +1,7 @@import fs from "node:fs";import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";import type { Generation, GenInput } from "@/lib/catalog/types";import type { ComfyWorkflow, Manifest, ManifestWorkflow } from "@/lib/comfy";@@ -65,7 +65,7 @@ const REPORT = JSON.stringify({coordinate_space: "pixels",image_size: [1000, 800],boxes: [- { label: "stock site URL text", bbox: [80, 560, 920, 700], source_bbox: [120, 590, 880, 670], overlay_type: "translucent_text_logo", confidence: 0.93 },+ { label: "stock site URL text", bbox: [80, 560, 920, 700], source_bbox: [120, 590, 880, 670], overlay_type: "translucent_text_logo", confidence: 0.93, background: "sandy beach\u0000 and sky" },{ label: "round brand mark", bbox: [760, 40, 980, 220], source_bbox: [790, 60, 950, 200], overlay_type: "text_logo", confidence: 0.81 },{ label: "pasted cartoon", bbox: [10, 10, 200, 260], source_bbox: [30, 30, 180, 240], overlay_type: "irregular_sticker", confidence: 0.9 },],@@ -136,9 +136,10 @@ describe("4. the manifest entries", () => {expect(e.outputs).toEqual([{ node: "33", kind: "image" }, { node: "38", kind: "text", role: "quality" }]);expect(e.limits).toMatchObject({ maxWidth: 4096, maxHeight: 4096 });}- expect(entry(REMOVE).bindings).toMatchObject({ detectMode: [{ node: "3", input: "mode" }], boxes: [{ node: "3", input: "boxes_json" }] });+ expect(entry(REMOVE).bindings).toMatchObject({ detectMode: [{ node: "3", input: "mode" }], boxes: [{ node: "3", input: "boxes_json" }], detectExpand: [{ node: "3", input: "expand" }] });expect(entry(BRUSH).bindings.mask).toEqual([{ node: "50", input: "image" }]);expect(entry(BRUSH).bindings.boxes).toBeUndefined();+ expect(entry(BRUSH).bindings.detectExpand).toBeUndefined();});it("names the pack and uses Live edit's Qwen files plus SAM ViT-B", () => {@@ -185,7 +186,16 @@ describe("6. requirements and pins", () => {expect(shell).toContain("-m pip install segment-anything==1.0");expect(shell).not.toContain("requirements.txt");expect(shell).toContain(`checkout ${PIN}`);+ // The SAM file the pack reads by its own path comes with it, from its pinned link, kept only when its checksum matches.+ expect(shell).toContain(`"${SAM_URL}"`);}+ const target = '"$COMFY/models/sams/sam_vit_b_01ec64.pth"';+ expect(c.bash).toContain(`[ -s ${target} ] || curl -L --fail -o ${target} "${SAM_URL}"`);+ expect(c.bash).toContain(`printf '%s %s\\n' ${SAM_SHA} ${target} | sha256sum -c - || rm -f ${target}`);+ expect(c.powershell).toContain(`.Hash -ne "${SAM_SHA.toUpperCase()}") { Remove-Item -Force`);+ // Other packs' files a listing can't see but that have no checksum (DBS configs) aren't fetched this way.+ const dbs = commandsFor([{ kind: "pack-install", pack: "ComfyUI-DBS" }], { inv, idx: requirements });+ expect(dbs.bash).not.toContain("sha256sum");});});@@ -220,6 +230,29 @@ describe("8. how the provider fills the removal", () => {expect(wf["1"].inputs.image).toBe("a.png");expect(wf["3"].inputs.mode).toBe("manual_boxes");expect(JSON.parse(String(wf["3"].inputs.boxes_json))).toEqual({ coordinate_space: "pixels", boxes: [{ bbox: [0, 20, 1200, 120], overlay_type: "unknown", label: "caption" }] });+ // The kept boxes carry the scan's margin already: no second one.+ expect(wf["3"].inputs.expand).toBe(0);+ });++ it("kept marks keep the scan's words for what is around them, for the repair", async () => {+ const withBg = JSON.stringify({ boxes: [{ bbox: [10, 20, 300, 120], overlay_type: "text_logo", label: "caption", background: "knit wool" }] });+ const { wf } = await prepare(REMOVE, { images: ["a.png"], extra: { boxes: withBg } });+ expect(JSON.parse(String(wf["3"].inputs.boxes_json)).boxes[0].background).toBe("knit wool");+ });++ it("never takes the picture, the brush, the seeds or the file name from the request's extras", async () => {+ const { wf } = await prepare(REMOVE, { images: ["a.png"], extra: { boxes, image: "elsewhere.png", seed: 802146, filenamePrefix: "../x", mask: "m.png" } }, { media: { "a.png": { width: 800, height: 600 }, "elsewhere.png": { width: 9000, height: 9000 } } });+ expect(wf["1"].inputs.image).toBe("a.png");+ expect(wf["12"].inputs.seed).not.toBe(802146);+ expect(wf["33"].inputs.filename_prefix).not.toBe("../x");+ expect(wf["3"].inputs.mode).toBe("manual_boxes");+ const scan = (await prepare(SCAN, { images: ["a.png"], extra: { image: "elsewhere.png" } }, { media: { "a.png": { width: 800, height: 600 } } })).wf;+ expect(scan["1"].inputs.image).toBe("a.png");+ });++ it("refuses a brush painted on another size of the picture, in words", async () => {+ await expect(prepare(REMOVE, { images: ["a.png"], mask: "m.png" }, { media: { "a.png": { width: 1200, height: 800 }, "m.png": { width: 600, height: 400 } } })).rejects.toThrow(W.COPY.brushAgain);+ expect((await prepare(REMOVE, { images: ["a.png"], mask: "m.png" }, { media: { "a.png": { width: 1200, height: 800 }, "m.png": { width: 1200, height: 800 } } })).id).toBe(BRUSH);});it("a brush: manual_mask on the brush graph, the mask on its loader", async () => {@@ -228,8 +261,10 @@ describe("8. how the provider fills the removal", () => {expect(wf["50"].inputs.image).toBe("m.png");});- it("no marks from an API caller: the pack finds them itself", async () => {- expect((await prepare(REMOVE, { images: ["a.png"] })).wf["3"].inputs.mode).toBe("auto_qwen");+ it("no marks from an API caller: the pack finds them itself, with the scan's margin", async () => {+ const { wf } = await prepare(REMOVE, { images: ["a.png"], extra: { detectExpand: 0 } });+ expect(wf["3"].inputs.mode).toBe("auto_qwen");+ expect(wf["3"].inputs.expand).toBe(W.SCAN_EXPAND);});it("the repair size follows the picture and the GPU, never the request", async () => {@@ -241,6 +276,9 @@ describe("8. how the provider fills the removal", () => {expect((await size({ width: 4000, height: 3000 }))["5"].inputs.max_side).toBe(1536);expect((await size({ width: 4000, height: 3000 }, 12 * 2 ** 30))["28"].inputs.max_side).toBe(768);expect(W.maxSideFor(1000, 1000, 32 * 2 ** 30)).toBe(1024);+ // A 16 GB card reports a little under 16 GiB: it still gets the full size.+ expect(W.maxSideFor(1000, 1000, 17_170_432_000)).toBe(1024);+ expect(W.maxSideFor(1000, 1000, 12 * 2 ** 30)).toBe(768);});it("refuses a picture over 4096 px in words", async () => {@@ -268,6 +306,10 @@ describe("9. the kept marks' checks", () => {expect(r.boxes[0].label).toHaveLength(80);expect(r.boxes[0].label.startsWith("x y")).toBe(true);expect(Object.keys(r.boxes[0]).sort()).toEqual(["bbox", "label", "overlay_type", "source_bbox"]);+ const bg = JSON.parse(check({ boxes: [{ bbox: [0, 0, 5, 5], background: `wet\u0007 asphalt${"!".repeat(200)}` }] }).json).boxes[0];+ expect(Object.keys(bg).sort()).toEqual(["background", "bbox", "label", "overlay_type"]);+ expect(bg.background).toHaveLength(80);+ expect(bg.background.startsWith("wet asphalt")).toBe(true);});it("is checked when the run is planned: a 400 in words, and a brushed run drops the boxes", () => {@@ -291,6 +333,12 @@ describe("10. the scan report, read into regions", () => {]);expect(s.regions[0].box).toEqual([120, 590, 880, 670]);expect(s.regions[0].repair).toEqual([80, 560, 920, 700]);+ expect(s.regions[0].background).toBe("sandy beach and sky");+ expect(s.regions[1].background).toBe("");+ // A less sure mark comes back tight: it gets the scan's margin for its kind (20 px plus 12 % for a block).+ expect(s.regions[3].box).toEqual([410, 310, 510, 350]);+ expect(s.regions[3].repair).toEqual([378, 285, 542, 375]);+ expect(W.padBox([0, 0, 100, 40], "translucent_text_logo", 110, 1000)).toEqual([0, 0, 110, 74]);expect(W.parseScanReport("not json")).toBeNull();expect(W.parseScanReport(JSON.stringify({ coordinate_space: "xyxy_1000", image_size: [10, 10], boxes: [] }))).toBeNull();expect(W.parseScanReport(JSON.stringify({ coordinate_space: "pixels", image_size: [10, 10], boxes: [] }))!.regions).toEqual([]);@@ -314,14 +362,30 @@ describe("10. the scan report, read into regions", () => {const overlapping = [...regions, { ...regions[0], id: "big", box: [0, 0, 1000, 800] as [number, number, number, number] }];expect(W.regionAt(overlapping, 800, 100)?.chip).toBe("Logo");expect(W.foundLine(3)).toBe("Found 3. Tap any you want to keep.");+ expect(W.foundLine(3, 3)).toBe("Found 3. Tap any you want to keep.");+ expect(W.foundLine(1, 0)).toBe("Found 1. Tap it to remove it.");+ expect(W.foundLine(3, 0)).toBe("Found 3. Tap the ones to remove.");+ expect(W.foundLine(3, 1)).toBe("Found 3. Tap a mark to keep or remove it.");expect(W.removeLabel(3)).toBe("Remove 3");expect(W.removeLabel(0)).toBe("Everything is kept");const sent = JSON.parse(W.keptBoxesJson(regions.map((r) => (r.chip === "Logo" ? { ...r, on: false } : r))));expect(sent.coordinate_space).toBe("pixels");expect(sent.boxes.map((b: { overlay_type: string }) => b.overlay_type)).toEqual(["translucent_text_logo", "irregular_sticker"]);- expect(sent.boxes[0]).toMatchObject({ bbox: [80, 560, 920, 700], source_bbox: [120, 590, 880, 670] });+ expect(sent.boxes[0]).toMatchObject({ bbox: [80, 560, 920, 700], source_bbox: [120, 590, 880, 670], background: "sandy beach and sky" });+ expect(sent.boxes[1]).not.toHaveProperty("background");expect(() => W.checkWatermarkBoxes(W.keptBoxesJson(regions))).not.toThrow();});++ it("a tap inside a big mark never flips the small one beside it", () => {+ const at = (id: string, box: [number, number, number, number]) => ({ ...W.parseScanReport(REPORT)!.regions[0], id, box });+ const caption = at("caption", [100, 500, 900, 600]);+ const logo = at("logo", [910, 500, 990, 600]);+ // Shown 358 px wide, the 22 px reach is about 61 picture pixels.+ expect(W.pickRegion([caption, logo], 895, 550, 61)?.id).toBe("caption");+ expect(W.pickRegion([caption, logo], 905, 550, 61)?.id).toBe("logo");+ expect(W.pickRegion([caption, logo], 50, 550, 61)?.id).toBe("caption");+ expect(W.pickRegion([caption, logo], 500, 100, 61)).toBeNull();+ });});describe("11. the repair's verdict and the Library", () => {@@ -406,13 +470,85 @@ describe("15. the demo", () => {const r = await settled(removal.id);expect(r.status).toBe("succeeded");expect(r.outputs[0].kind).toBe("image");+ // The result keeps how it was asked: the marks removed, as checked, and the way they were found.+ const kept = r.outputs[0].meta?.watermark as { mode: string; marks: { bbox: number[]; overlay_type: string }[] };+ expect(kept.mode).toBe("manual_boxes");+ expect(kept.marks.map((m) => m.overlay_type)).toEqual(parsed.regions.filter((x) => x.on).map((x) => x.type));+ });+});++describe("17. what a failed run says, and the download's name", () => {+ it("shows the app's own words, nothing on a cancel, and never a node's raw error to a visitor", () => {+ const raw = "QWMDetect: 手动遮罩尺寸必须与原图相同。";+ expect(W.visitorError({ status: "canceled", error: null }, false, W.COPY.retry)).toBeNull();+ expect(W.visitorError({ status: "failed", error: W.COPY.rejected }, false, W.COPY.retry)).toBe(W.COPY.rejected);+ expect(W.visitorError({ status: "failed", error: "Pick up to 32 marks at a time" }, false, W.COPY.retry)).toBe("Pick up to 32 marks at a time");+ expect(W.visitorError({ status: "failed", error: raw }, false, W.COPY.retry)).toBe(W.COPY.retry);+ expect(W.visitorError({ status: "failed", error: null }, false, W.COPY.scanFailed)).toBe(W.COPY.scanFailed);+ expect(W.visitorError({ status: "failed", error: raw }, true, W.COPY.retry)).toBe(raw);+ // The page renders a run's error only through visitorError.+ const page = read("src/components/watermark/watermark-tool.tsx");+ expect(page).not.toMatch(/\b[gs]\?\.error\b/);+ expect(page).not.toMatch(/\{\s*[gs]\.error\s*\}/);+ });++ it("names the download after the picture, safely, with the result's own extension", () => {+ expect(W.cleanFileName("catwalk.jpg", "/api/files/out/a.png")).toBe("catwalk-clean.png");+ expect(W.cleanFileName("My photo · final (2).jpeg", "/api/files/out/a.jpg?x=1")).toBe("My-photo-final-2-clean.jpg");+ expect(W.cleanFileName("", "/api/files/out/a.webp")).toBe("photo-clean.webp");+ expect(W.cleanFileName("../../etc", "data:")).toBe("etc-clean.png");+ });++ it("a removal whose repair was refused fails in words and keeps nothing; a scan with no readable report fails too", { timeout: 60_000 }, async () => {+ ensureRunner();+ const poll = mockProvider.poll.bind(mockProvider);+ const spy = vi.spyOn(mockProvider, "poll").mockImplementation(async (ctx) => {+ const res = await poll(ctx);+ if (res.state !== "succeeded") return res;+ return {+ ...res,+ outputs: res.outputs.map((o) => ((o as { kind?: string }).kind === "image" ? { ...o, meta: { ...(o as { meta?: object }).meta, quality: { status: "rejected_first_pass" } } } : { ...o, text: "not a report" })),+ };+ });+ try {+ const picture = saveFile({ data: png(64, 48), contentType: "image/png", source: "upload" });+ const [scan] = createGenerations({ feature: W.WATERMARK_SCAN_FEATURE, modelId: "oss-watermark-scan", op: "watermark-scan", inputs: { images: [picture.url] } });+ const s = await settled(scan.id);+ expect([s.status, s.error, s.outputs.length]).toEqual(["failed", W.COPY.scanFailed, 0]);+ const boxes = JSON.stringify({ boxes: [{ bbox: [2, 2, 30, 20], overlay_type: "text_logo", label: "caption" }] });+ const [removal] = createGenerations({ feature: W.WATERMARK_FEATURE, presetId: "app-watermark-remover", modelId: "oss-watermark-remover", op: "watermark-remove", inputs: { images: [picture.url] }, params: { extra: { boxes } } });+ const r = await settled(removal.id);+ expect([r.status, r.error, r.outputs.length]).toEqual(["failed", W.COPY.rejected, 0]);+ } finally {+ spy.mockRestore();+ }});});describe("16. visitor words", () => {it("never name models, masks, nodes, graphs or internal status", () => {const BANNED = /\b(model|mask|node|graph|LoRA|SAM|Qwen|seed|confidence|review|needs_review|VLM)\b/i;- const visitor = [W.COPY.name, W.COPY.tagline, W.COPY.hero, W.COPY.subline, ...W.COPY.details, W.COPY.scanning, W.COPY.removing, W.COPY.empty, W.COPY.rejected, W.COPY.tooBig, W.COPY.noneKept, W.COPY.hint];+ const visitor = [+ W.COPY.name,+ W.COPY.tagline,+ W.COPY.hero,+ W.COPY.subline,+ ...W.COPY.details,+ W.COPY.scanning,+ W.COPY.removing,+ W.COPY.empty,+ W.COPY.rejected,+ W.COPY.tooBig,+ W.COPY.noneKept,+ W.COPY.hint,+ W.COPY.retry,+ W.COPY.scanFailed,+ W.COPY.scanUnreadable,+ W.COPY.brushAgain,+ W.COPY.connectGpu,+ W.COPY.sizeLine,+ ...[3, 1, 0].map((on) => W.foundLine(3, on)),+ ];for (const s of visitor) expect(s, s).not.toMatch(BANNED);const app = APPS.find((a) => a.id === "app-watermark-remover")!;for (const s of [app.name, app.description, app.parity ?? ""]) expect(s, s).not.toMatch(BANNED);@@ -424,7 +560,10 @@ describe("16. visitor words", () => {.replace(/\{owner && quality[\s\S]*?<\/p>\s*\)\}/, "");const texts = [...src.matchAll(/>([^<>{}]+)</g)].map((m) => m[1].trim()).filter(Boolean);const quoted = [...src.matchAll(/"([A-Z][^"]{3,})"/g)].map((m) => m[1]);- for (const t of [...texts, ...quoted]) expect(t, `${f}: ${t}`).not.toMatch(BANNED);+ // Template strings and aria labels too (the run's own errors are filtered by group 17).+ const templated = [...src.matchAll(/`([^`]*[A-Za-z]{3,}[^`]*)`/g)].map((m) => m[1]).filter((t) => !/^[\w-]+(\/|\?|=)|^\$\{|^(min|calc)\(|className|bg-|text-|\bpx\b/.test(t));+ const labels = [...src.matchAll(/aria-label=\{?[`"]([^`"]+)[`"]/g)].map((m) => m[1]);+ for (const t of [...texts, ...quoted, ...templated, ...labels]) expect(t, `${f}: ${t}`).not.toMatch(BANNED);}});});diff --git a/workflows/comfyui/manifest.json b/workflows/comfyui/manifest.jsonindex 7b3bebd5..745ab5f2 100644--- a/workflows/comfyui/manifest.json+++ b/workflows/comfyui/manifest.json@@ -10930,6 +10930,12 @@"input": "boxes_json"}],+ "detectExpand": [+ {+ "node": "3",+ "input": "expand"+ }+ ],"maxSize": [{"node": "5",@@ -11000,7 +11006,7 @@"vramGb": 20,"license": "Qwen Research License Agreement (Qwen-Image 2.1): NON-COMMERCIAL, research and evaluation only; Qwen3-VL 8B Apache-2.0; SAM ViT-B (segment-anything) Apache-2.0; ComfyUI-Qwen-Watermark nodes MIT","validated": false,- "notes": "The pack's main workflow (qwen21_watermark.api.json, plain settings) with the int8 UNET (qwen_image_2.1_int8_convrot, as Live edit) and without its debug save and preview nodes. QWMDetect (manual_boxes with the kept boxes, auto_qwen for API callers) -> QWMRefineMask (a rectangle for text, logos, blocks and mosaics, a SAM ViT-B outline for stickers) -> QWMPrepare (context 96, max side maxSize, OpenCV pre-fill) -> Qwen-Image 2.1 edit, 20 steps, cfg 1 -> QWMComposite (feather 6, align, colour match) -> QWMResidualDetect (Qwen3-VL looks for leftovers inside the first mask) -> one more pass when it finds some -> QWMFinal keeps the better pass and raises when any pixel outside the mask changed. Outputs: the picture (SaveImage, PNG) and the quality report (PreviewAny, role quality: folded into the picture's meta, never a result of its own). Seeds are random per run. The structure settings (denoise 0.65 / 0.55, context 384, no pre-fill) are the pack's alternative for faces; the GPU test decides between them."+ "notes": "The pack's main workflow (qwen21_watermark.api.json, plain settings) with the int8 UNET (qwen_image_2.1_int8_convrot, as Live edit) and without its debug save and preview nodes. QWMDetect (manual_boxes with the kept boxes and no extra margin, since the scan's boxes carry it; auto_qwen with expand 20 for API callers) -> QWMRefineMask (a rectangle for text, logos, blocks and mosaics, a SAM ViT-B outline for stickers) -> QWMPrepare (context 96, max side maxSize, OpenCV pre-fill) -> Qwen-Image 2.1 edit, 20 steps, cfg 1 -> QWMComposite (feather 6, align, colour match) -> QWMResidualDetect (Qwen3-VL looks for leftovers inside the first mask) -> one more pass when it finds some -> QWMFinal keeps the better pass and raises when any pixel outside the mask changed. Outputs: the picture (SaveImage, PNG) and the quality report (PreviewAny, role quality: folded into the picture's meta, never a result of its own). Seeds are random per run. The structure settings (denoise 0.65 / 0.55, context 384, no pre-fill) are the pack's alternative for faces."},{"id": "image-watermark-remove-qwen21-brush",