Files
SnapOtter/tests/integration/blur-background.test.ts
T
SnapOtterandGitHub d50e8e42a7 QA + image-tool depth pass: codec/eraser/PDF fixes, modality renames, 13 image tools deepened (#249)
* fix(media): mux container-correct codecs in video tools

Video tools hardcoded H.264 (and AAC) while keeping the input's container extension, so a .webm input produced an invalid file (ffmpeg exit 234: H.264 cannot be muxed into WebM). Add shared videoEncodeArgsForContainer/audioEncodeArgsForContainer helpers (vp9+opus for webm, theora+vorbis for ogv, h264+aac otherwise) and apply them across 14 tools; re-encode audio to AAC in burn-subtitles (forced mp4). Adds a webm regression test for change-fps.

* fix(eraser): recover Object Eraser when its progress SSE drops

The eraser used a bespoke EventSource with no recovery, so a dropped SSE left the UI stuck at ~25% forever even though the backend job had finished and saved its result. Add a resilient subscription (reconnect on tab refocus, which replays the cached terminal frame; 5-minute stall timeout) mirroring the standard processor's PR #203/#204 recovery.

* feat(ui): rename the Documents modality to PDF and Data to Files

Updates modality display names, the home-page tabs, the tool-page breadcrumb, and the homePage.documents/data + modalities labels across all 21 locales. URL slugs are unchanged for link stability.

* feat(compress-pdf): add quality and target-size compression modes

Mirror the image Compress tool: a quality slider (1-100) and a target file size, replacing the screen/ebook/printer preset. Adds gsCompressPdfQuality to doc-engine (quality maps to image downsample DPI, the dominant size lever for PDFs); target-size binary-searches the DPI for the highest quality under the target. The frontend reuses the shared CompressControls component, so no new translation strings are needed.

* feat(ocr-pdf): show the PDF preview and extracted text side by side

ocr-pdf fell back to the image viewer, which cannot render a PDF, so the right pane showed 'Preview not available' and the extracted text was only a download. It now uses a custom results view (custom-results display mode) rendering the input PDF via pdf.js (DocumentView gains an inputOnly prop, since the tool's output is a .txt) next to the extracted OCR text, with a copy button.

* feat(ui): link the modality breadcrumb to its tools tab

The modality segment of the tool breadcrumb (PDF, Image, Video, Audio, Files) is now a link to /?modality=<tab>. The home page reads the param, activates the matching tab, and cleans the URL, so it returns to the existing Tools page filtered to that modality without a new page. Handles the file modality whose tab key is 'data'.

* feat(circle-crop): add zoom/offset framing, border, background, and output size

Upgrade the circle-crop tool from a bare centered crop into a framing and
styling tool. New settings (all backward-compatible with the old empty
payload):

- zoom (1-5x) plus offsetX/offsetY (0-1) to control how tight the circle is
  and where it sits in the source image
- borderWidth (0-200px) plus borderColor for an optional ring
- background: transparent (clear corners) or a hex fill
- outputSize for a square output; omitted keeps native size

The settings panel gains an inline draggable circular preview that mirrors
the framing live, a zoom slider, a border slider with color, a
transparent/color background toggle, and an output-size field. Adds an
integration test covering output size, border, and a solid background.

* feat(image-tools): flesh out five thin tools (gif-webp, histogram, favicon, color-palette, lqip)

Tier A of the image-tool depth pass. Each of these was as bare as the old
circle-crop (empty settings, opaque or invisible output). Now:

- gif-webp: quality, lossless, and resize-percent controls; shows before/after size
- histogram: returns full per-channel bins + stats; the settings panel renders an
  inline interactive histogram with R/G/B/Luma toggles, linear/log scale, and a
  mean/median/stdev readout (server PNG still downloadable)
- favicon: background fill, padding, corner-radius, theme color, and a per-size
  checklist, with a live preview grid; the route applies the styling and honors
  the size filter
- color-palette: count (2-16) and hex/rgb/hsl format controls, median-cut
  extraction, a palette strip, and CSS/JSON export
- lqip-placeholder: blur/pixelate/solid strategies, format and quality; the
  output panel now surfaces the data URI with copy plus HTML/CSS snippets and a
  preview (previously the deliverable was never shown)

Also expose resultPayload from useToolProcessor so a tool can render the route's
extra result fields (histogram bins, lqip data URI) in its own panel. Updates the
five integration tests to cover the new settings.

* feat(image-tools): deepen five thin tools (duotone, vignette, pixelate, background-replace, blur-background)

Tier B of the image-tool depth pass.

- duotone: preset palettes, an intensity slider that blends the duotone with
  the original, and a true live duotone preview (a self-contained grayscale +
  lighten/darken overlay so the pane filter cannot wash it out)
- vignette: radius, softness, roundness, and center-x/y controls driving a
  rebuilt radial gradient, with a matching live overlay
- pixelate: a selection mode that exposes the route's region support via a
  draggable box over the image plus width/height sliders, so a face or plate
  can be pixelated in isolation
- background-replace: gradient backgrounds, edge feather, and webp output on top
  of the existing solid color; now shown before/after
- blur-background: edge feather and webp output; now shown before/after

The live previews for duotone and vignette needed onImageStyle to mount the
overlay branch in image-viewer. The duotone intensity blend and both AI tools'
edge feather were rewritten to splice the alpha channel through raw buffers;
joinChannel did not reliably re-tag the merged channel as alpha and a
raw-without-encoder buffer broke the next decode. Updates the five integration
tests.

* fix(data): rename Files modality to Data + 20 Data-tool bug fixes (#247)

* fix(ui): restore the Data modality name (revert Files rename)

The 'file' modality reverts to the 'Data' label in modality.ts, the home-page tab, and the tools.data + documentsAndFiles i18n keys across all 21 locales. The separate Documents to PDF rename is kept. The URL slug was already /data, so name and slug realign; the tool breadcrumb follows modality.ts automatically.

* fix(create-zip): require at least two files before enabling submit

create-zip enabled its submit button with a single file, but the backend rejects fewer than two files ('Zipping needs at least two files'), producing a 422 error. Gate the button on files.length >= 2 to match the sibling merge-csvs tool. Found during the Data-modality QA sweep.

* fix(data): resolve 17 bugs found in a deeper Data-tool review

Crashes (threw an internal error on otherwise-valid input):
- csv-json: a primitive JSON array like [1,2,3] threw "Unable to serialize"; now a clear error.
- json-xml: a null or primitive JSON root crashed the XML builder; now a clear 4xx.
- yaml-json: an empty or comment-only YAML returned undefined and threw on Buffer.from; now emits null.

Data loss / wrong output:
- csv-json: nested objects rendered as "[object Object]" (now serialized to JSON); heterogeneous objects dropped columns (now the union of all keys).
- xml-to-csv: leaked fast-xml-parser markers ("@_" on attributes, "#text") into CSV headers (now cleaned); a single-record XML failed to tabulate (now a 1-row table); heterogeneous records dropped columns (now the union of all keys).
- csv-excel: xlsx date cells were rendered in the server timezone via Date.toString (now ISO 8601, round-trippable).
- create-zip and extract-zip: filename/basename collisions overwrote zip entries and silently lost a file; dedup now checks generated names and guarantees uniqueness.
- chart-maker: negative values produced invalid/degenerate SVG that Sharp silently dropped; now rejected with a clear message.

Empty output / validation:
- split-csv: a header-only CSV produced an empty zip; now errors with "No data rows to split".
- extract-zip: a directory-only zip produced an empty zip; now errors with "No extractable files found".
- create-zip and merge-csvs: a single-file request fell through to the worker and returned 422; the factory now supports minInputs and returns 400 pre-enqueue.

UI:
- review-panel: the result card showed "Saved +X%" when the output grew; the savings row now appears only when the file is actually smaller (Original/Processed sizes always shown).

Found via two adversarial code-review passes over the 10 Data routes. All 24 fix + regression checks pass against a fresh Docker stack on :1359.

* fix(data): clean 400 for unsafe-zip entries; drop header on split keepHeader=false

- tool-factory: add an opt-in preValidate hook that runs after input prep and
  before enqueue. Throwing InputValidationError there returns its statusCode
  (400) instead of the worker's generic 422. BullMQ loses the error class across
  the job boundary, so InputValidationErrors thrown in the worker cannot be
  mapped to their status; pre-enqueue validation can.
- extract-zip: validate entry paths via preValidate, rejecting path-traversal
  and absolute-path archives (and unreadable/corrupt zips) with a clear 400. The
  processV2 guards remain as defense-in-depth for the pipeline/batch path.
- split-csv: keepHeader=false now drops the header (parts contain only data
  rows) instead of keeping it as the first data row of part-1.

Verified against a fresh Docker stack: unsafe / absolute / corrupt zips -> 400,
normal zip still 200; split keepHeader=false drops the header while true repeats
it in each part. No regressions across 51 fix + scenario checks.

* feat(image-tools): deepen image-pad and sprite-sheet, fix sprite-sheet multi-file submit

Tier C of the image-tool depth pass.

- image-pad: a custom W:H ratio alongside the presets, a background mode
  (solid color, transparent, or an Instagram-style blurred cover fill), and an
  extra padding margin. The settings panel gains a real live preview of the
  padded canvas (it previously declared live-preview but rendered nothing) via
  onImageStyle + onImageOverlay.
- sprite-sheet: PNG/WebP/JPEG output with a quality control, and the coordinate
  map it already computes is now returned and surfaced as Copy CSS (per-frame
  background-position rules) and Copy JSON exports.

Also fix a pre-existing sprite-sheet bug: with more than one image the panel
called processAllFiles, fanning out to the per-file batch route (422). It now
calls processFiles, which packs all images into a single sheet request (it is a
MULTI_FILE tool). Updates both integration tests.

* fix(media): preserve source sample rate after loudnorm (#243)

ffmpeg's loudnorm filter runs internally at 192 kHz and emits 192 kHz
unless the chain resamples back. normalize-audio and video-loudnorm
therefore produced 192 kHz output (4.3x larger files) regardless of the
input rate. Append aresample to restore the input's sample rate.
runMediaTool now exposes the input audio sample rate to its args callback.

* fix(color-palette): collapse solid-color images to one swatch

The median-cut bucket selector started bestRange at -1, so a uniform bucket
(range 0) still satisfied the > comparison and kept splitting, yielding N
identical swatches for a solid-color image. Start at 0 so only buckets with
real color spread are split.

* fix(lint): annotate implicit-any lets in saml and user-files

biome noImplicitAnyLet flagged the bare let in saml.ts (profile) and user-files.ts (stream); add derived type annotations (type-only, no behavior change). Latent on main via the turbo lint cache; surfaced when the Data changes busted the apps/api lint cache.
2026-06-16 15:16:13 +08:00

182 lines
6.0 KiB
TypeScript

/**
* Integration tests for the blur-background tool (/api/v1/tools/blur-background).
*
* This tool reuses the rembg bundle (background-removal). The 501 gate fires
* before any settings validation when the bundle is absent. Locally and in CI,
* the bundle is never installed, so the 501 surface is always exercised.
*
* The blurBackground helper has dedicated unit coverage in
* tests/unit/api/background-composite.test.ts. The rembg model never runs
* locally; bundle-gated happy paths are in a skipped describe.
*/
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { buildTestApp, createMultipartPayload, loginAsAdmin, type TestApp } from "./test-server.js";
const FIXTURES = join(__dirname, "..", "fixtures");
const PNG = readFileSync(join(FIXTURES, "test-200x150.png"));
let testApp: TestApp;
let app: TestApp["app"];
let adminToken: string;
beforeAll(async () => {
testApp = await buildTestApp();
app = testApp.app;
adminToken = await loginAsAdmin(app);
}, 30_000);
afterAll(async () => {
await testApp.cleanup();
}, 10_000);
describe("blur-background", () => {
// -- 501 gate (always fires locally: background-removal bundle never installed) --
it("returns 501 FEATURE_NOT_INSTALLED when bundle is absent", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{ name: "settings", content: JSON.stringify({ intensity: 50, feather: 5, format: "png" }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/blur-background",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(501);
const json = JSON.parse(res.body);
expect(json.code).toBe("FEATURE_NOT_INSTALLED");
expect(json.feature).toBe("background-removal");
expect(json.featureName).toBe("Background Removal");
expect(json.estimatedSize).toBeDefined();
});
// -- Auth gate --
it("rejects unauthenticated requests (401)", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{ name: "settings", content: JSON.stringify({}) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/blur-background",
headers: { "content-type": contentType },
body,
});
expect(res.statusCode).toBe(401);
});
// -- Validation: 501 fires before settings parse, so intensity=0 also 501s --
it("returns 501 even with invalid intensity (gate fires first)", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{ name: "settings", content: JSON.stringify({ intensity: 0, feather: 25, format: "bmp" }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/blur-background",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
// 501 because the bundle gate fires before settings validation
expect(res.statusCode).toBe(501);
const json = JSON.parse(res.body);
expect(json.code).toBe("FEATURE_NOT_INSTALLED");
});
// -- 501 with webp format (still gated) --
it("returns 501 with webp format and feather settings", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{ name: "settings", content: JSON.stringify({ intensity: 80, feather: 10, format: "webp" }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/blur-background",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(501);
const json = JSON.parse(res.body);
expect(json.code).toBe("FEATURE_NOT_INSTALLED");
});
// -- 501 with defaults (empty settings object, Zod fills defaults) --
it("returns 501 with empty settings (defaults applied by Zod)", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{ name: "settings", content: JSON.stringify({}) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/blur-background",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(501);
const json = JSON.parse(res.body);
expect(json.code).toBe("FEATURE_NOT_INSTALLED");
});
// -- Bundle-gated happy path (skipped: background-removal bundle is 4-5 GB) --
// The background-removal bundle is not installed in any verification environment.
// These tests exist for future in-container runs after bundle install.
// The 501 contract + blurBackground unit tests carry the verification.
describe.skip("with background-removal bundle installed", () => {
it("blurs background with full settings (202 + async)", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{
name: "settings",
content: JSON.stringify({ intensity: 75, feather: 3, format: "webp" }),
},
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/blur-background",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(202);
const json = JSON.parse(res.body);
expect(json.jobId).toBeDefined();
expect(json.async).toBe(true);
}, 300_000);
});
});