fix: release QA hardening across processing, media, security, and CI gates (#649)

A release-readiness QA pass over the whole product. The commits split into
defects a user would hit and gates that were reporting green while measuring
nothing.

## Fixes that change behaviour

Rate limiting was bypassable on every install: TRUST_PROXY defaulted to true, so
request.ip came from a client-set header and a forged X-Forwarded-For got past
the login limiter. The default is now a private-network trust list.

A transient Postgres outage stranded in-flight jobs, leaving finished output on
disk with no row pointing at it. A reconciler now resolves those rows and adopts
the bytes rather than dropping the work.

A Redis connection that moved to a new address wedged every read-blocked
consumer, so completions stopped signalling while health still answered 200.
Socket timeouts plus subscriber pings recover it.

Installing more than one AI bundle left the shared venv multi-versioned and
silently broke three tools. The installer now reconciles distributions to one
version each.

Converting an image to JXL at quality 1 through 4 returned a 500, because
libjxl 0.7 rejects the distance those values compute. The quality is floored at
what the encoder honours. A missing ffmpeg was also reported to the user as a
corrupt upload; it now says the engine is unavailable.

RAW uploads reached an unpatched LibRaw on arm64, so it is built from source at
0.22.2, and the release scan was split so it can fail on an unfixed critical
instead of hiding it behind ignore-unfixed.

## Gates that could not fail

Two mutation lanes ran zero mutants because Stryker crawled the gitignored docs
build; coverage discarded its whole report on any failing test; the lint gate
skipped root tests, scripts, and two workspaces; and several generated matrices
counted a host missing ffmpeg as a passing tool. Each now measures what it
claims.

Full evidence and the outstanding release items are tracked locally and are not
part of this branch.
This commit is contained in:
SnapOtter
2026-07-27 15:37:30 +08:00
committed by GitHub
parent bc32f86a07
commit d10d0f544f
855 changed files with 54564 additions and 13092 deletions
@@ -69,8 +69,8 @@ describe.skipIf(!ffmpegAvailable())("merge-audio (requires ffmpeg)", () => {
body,
});
expect(res.statusCode).toBe(422);
expect(res.statusCode).toBe(400);
const parsed = JSON.parse(res.body);
expect(parsed.details).toMatch(/at least two/i);
expect(parsed.error).toMatch(/at least 2 files/i);
}, 60_000);
});
@@ -39,6 +39,13 @@ async function runTool(settings: Record<string, unknown>) {
}
describe.skipIf(!ffmpegAvailable())("pitch-shift (requires ffmpeg)", () => {
it("encodes small positive shifts without MP3 frame padding errors", async () => {
const res = await runTool({ semitones: 2 });
expect(res.statusCode).toBe(200);
const envelope = JSON.parse(res.body);
expect(envelope.downloadUrl).toBeDefined();
}, 60_000);
it("shifts +12 semitones with duration roughly unchanged", async () => {
const res = await runTool({ semitones: 12 });
expect(res.statusCode).toBe(200);
@@ -77,4 +77,11 @@ describe.skipIf(!ffmpegAvailable())("ringtone-maker (requires ffmpeg)", () => {
expect(res.statusCode).toBe(422);
expect(res.body).toMatch(/beyond the end/i);
}, 60_000);
it("normalizes sub-microsecond offsets instead of emitting exponential ffmpeg syntax", async () => {
const res = await runTool({ startS: Number.MIN_VALUE, durationS: 1 });
expect(res.statusCode).toBe(200);
const envelope = JSON.parse(res.body);
expect(envelope.downloadUrl).toBeDefined();
}, 60_000);
});
@@ -1,15 +1,21 @@
/**
* Integration tests for the transcribe-audio tool (/api/v1/tools/audio/transcribe-audio).
*
* The transcription bundle (faster-whisper) is not installed locally, so the
* 501 gate is always hit. Validation paths (bad settings) are tested after
* the 501 check fires first. The bundle-gated happy path lives in a skipped
* describe for in-container-after-install runs.
* Missing-bundle contracts run only when the transcription capability is
* absent. Installed happy paths run when the capability is detected or when
* REQUIRE_AI_FEATURES makes its absence a release-gate failure.
*/
import { readFileSync } from "node:fs";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { isToolInstalled } from "../../../../apps/api/src/lib/feature-status.js";
import { fixtures } from "../../../fixtures/index.js";
import { installedAiCapabilityGate } from "../../../helpers/installed-ai-capability-gate.js";
import {
expectKnownTranscript,
expectSrtArtifact,
} from "../../../helpers/installed-ai-output-oracles.js";
import { waitForDownloadedJobArtifact } from "../../settle-job.js";
import {
buildTestApp,
createMultipartPayload,
@@ -18,6 +24,13 @@ import {
} from "../../test-server.js";
const MP3 = readFileSync(fixtures.audio.tiny("mp3"));
const SPEECH_WAV = readFileSync(fixtures.audio.speech.wav);
const REQUIRE_AI_FEATURES = process.env.REQUIRE_AI_FEATURES === "1";
const AI_CAPABILITY = installedAiCapabilityGate(
"transcribe-audio",
REQUIRE_AI_FEATURES,
isToolInstalled,
);
let testApp: TestApp;
let app: TestApp["app"];
@@ -34,68 +47,74 @@ afterAll(async () => {
}, 10_000);
describe("transcribe-audio", () => {
// -- 501 gate (always fires locally: bundle never installed) --
// -- Missing-capability contract --
it("returns 501 FEATURE_NOT_INSTALLED when bundle is absent", async () => {
const { body, contentType } = createMultipartPayload([
{
name: "file",
filename: "tiny.mp3",
contentType: "audio/mpeg",
content: MP3,
},
{ name: "settings", content: JSON.stringify({}) },
]);
it.skipIf(!AI_CAPABILITY.runUnavailableContract)(
"returns 501 FEATURE_NOT_INSTALLED when bundle is absent",
async () => {
const { body, contentType } = createMultipartPayload([
{
name: "file",
filename: "tiny.mp3",
contentType: "audio/mpeg",
content: MP3,
},
{ name: "settings", content: JSON.stringify({}) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/audio/transcribe-audio",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/audio/transcribe-audio",
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("transcription");
expect(json.featureName).toBe("Transcription");
expect(json.estimatedSize).toBeDefined();
});
expect(res.statusCode).toBe(501);
const json = JSON.parse(res.body);
expect(json.code).toBe("FEATURE_NOT_INSTALLED");
expect(json.feature).toBe("transcription");
expect(json.featureName).toBe("Transcription");
expect(json.estimatedSize).toBeDefined();
},
);
// -- Validation (501 fires before settings parse, so these also 501) --
it("returns 501 even with invalid outputFormat (gate fires first)", async () => {
const { body, contentType } = createMultipartPayload([
{
name: "file",
filename: "tiny.mp3",
contentType: "audio/mpeg",
content: MP3,
},
{
name: "settings",
content: JSON.stringify({ outputFormat: "doc" }),
},
]);
it.skipIf(!AI_CAPABILITY.runUnavailableContract)(
"returns 501 even with invalid outputFormat (gate fires first)",
async () => {
const { body, contentType } = createMultipartPayload([
{
name: "file",
filename: "tiny.mp3",
contentType: "audio/mpeg",
content: MP3,
},
{
name: "settings",
content: JSON.stringify({ outputFormat: "doc" }),
},
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/audio/transcribe-audio",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/audio/transcribe-audio",
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 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");
},
);
it("rejects unauthenticated requests (401)", async () => {
const { body, contentType } = createMultipartPayload([
@@ -118,72 +137,93 @@ describe("transcribe-audio", () => {
expect(res.statusCode).toBe(401);
});
// -- Bundle-gated happy path (skipped locally, runs after bundle install) --
// -- Installed/required capability contract --
// The transcription bundle is ~600 MB and only available in Docker.
// These tests run when the bundle is installed (e.g., during Task 7 smoke).
// Locally they always skip.
describe.skip("with transcription bundle installed", () => {
it("transcribes audio to txt (202 + async)", async () => {
const { body, contentType } = createMultipartPayload([
{
name: "file",
filename: "tiny.mp3",
contentType: "audio/mpeg",
content: MP3,
},
{
name: "settings",
content: JSON.stringify({ outputFormat: "txt" }),
},
]);
describe.skipIf(!AI_CAPABILITY.runInstalledContract)(
"with transcription bundle installed",
() => {
it("transcribes audio to txt (202 + async)", async () => {
const { body, contentType } = createMultipartPayload([
{
name: "file",
filename: "speech-10s.wav",
contentType: "audio/wav",
content: SPEECH_WAV,
},
{
name: "settings",
content: JSON.stringify({ outputFormat: "txt" }),
},
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/audio/transcribe-audio",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/audio/transcribe-audio",
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);
}, 120_000);
expect(res.statusCode).toBe(202);
const json = JSON.parse(res.body);
expect(json.jobId).toBeDefined();
expect(json.async).toBe(true);
const artifact = await waitForDownloadedJobArtifact(
app,
adminToken,
"transcribe-audio",
json.jobId as string,
240_000,
);
expect(artifact.filename).toBe("speech-10s.txt");
expect(artifact.contentType).toBe("text/plain");
expect(artifact.result.resultPayload?.segments).toEqual(expect.any(Number));
expect(artifact.result.resultPayload?.segments as number).toBeGreaterThan(0);
expectKnownTranscript(artifact.buffer.toString("utf8"));
}, 300_000);
it("transcribes audio to srt with correct structure", async () => {
const { body, contentType } = createMultipartPayload([
{
name: "file",
filename: "tiny.mp3",
contentType: "audio/mpeg",
content: MP3,
},
{
name: "settings",
content: JSON.stringify({ outputFormat: "srt" }),
},
]);
it("transcribes audio to srt with correct structure", async () => {
const { body, contentType } = createMultipartPayload([
{
name: "file",
filename: "speech-10s.wav",
contentType: "audio/wav",
content: SPEECH_WAV,
},
{
name: "settings",
content: JSON.stringify({ outputFormat: "srt" }),
},
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/audio/transcribe-audio",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/audio/transcribe-audio",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(202);
const json = JSON.parse(res.body);
expect(json.jobId).toBeDefined();
// Full SRT structure validation happens after polling completes.
// The sine tone fixture may produce empty or noise text;
// we assert mechanics (counter line "1", arrow timestamp), not words.
}, 120_000);
});
expect(res.statusCode).toBe(202);
const json = JSON.parse(res.body);
expect(json.jobId).toBeDefined();
const artifact = await waitForDownloadedJobArtifact(
app,
adminToken,
"transcribe-audio",
json.jobId as string,
240_000,
);
expect(artifact.filename).toBe("speech-10s.srt");
expect(artifact.contentType).toBe("application/x-subrip");
const subtitles = artifact.buffer.toString("utf8");
expectSrtArtifact(subtitles);
expectKnownTranscript(subtitles);
}, 300_000);
},
);
});
@@ -46,8 +46,9 @@ describe.skipIf(!ffmpegAvailable())("engine tweaks", () => {
});
expect(res.statusCode).toBe(202);
const row = await poll(JSON.parse(res.body).jobId);
expect(row?.status).toBe("completed");
expect((row?.outputRefs as string[])[0].endsWith(".avi")).toBe(true);
if (!row) throw new Error("job row not found after polling");
expect(row.status).toBe("completed");
expect((row.outputRefs as string[])[0].endsWith(".avi")).toBe(true);
}, 90_000);
it("convert-video outputs mkv", async () => {
@@ -62,8 +63,9 @@ describe.skipIf(!ffmpegAvailable())("engine tweaks", () => {
body,
});
const row = await poll(JSON.parse(res.body).jobId);
expect(row?.status).toBe("completed");
expect((row?.outputRefs as string[])[0].endsWith(".mkv")).toBe(true);
if (!row) throw new Error("job row not found after polling");
expect(row.status).toBe("completed");
expect((row.outputRefs as string[])[0].endsWith(".mkv")).toBe(true);
}, 90_000);
it("extract-audio outputs ogg", async () => {
@@ -78,7 +80,8 @@ describe.skipIf(!ffmpegAvailable())("engine tweaks", () => {
body,
});
const row = await poll(JSON.parse(res.body).jobId);
expect(row?.status).toBe("completed");
expect((row?.outputRefs as string[])[0].endsWith(".ogg")).toBe(true);
if (!row) throw new Error("job row not found after polling");
expect(row.status).toBe("completed");
expect((row.outputRefs as string[])[0].endsWith(".ogg")).toBe(true);
}, 90_000);
});
@@ -6,10 +6,6 @@
* inputs, numeric validation, SVG label escaping, and invalid kind rejection.
*/
import { randomUUID } from "node:crypto";
import { writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import sharp from "sharp";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import {
@@ -157,7 +153,7 @@ describe("Chart Maker", () => {
expect(res.statusCode).toBe(422);
const result = JSON.parse(res.body);
expect(result.error + " " + (result.details ?? "")).toMatch(/numeric/i);
expect(`${result.error} ${result.details ?? ""}`).toMatch(/numeric/i);
});
it("escapes SVG-injection labels and produces valid PNG", async () => {
@@ -59,8 +59,9 @@ describe.skipIf(!sofficeAvailable())("convert-document (requires soffice)", () =
expect(res.statusCode).toBe(202);
const { jobId } = JSON.parse(res.body);
const row = await pollJob(jobId);
expect(row?.status).toBe("completed");
const outName = (row?.outputRefs as string[])[0].split("/").pop() as string;
if (!row) throw new Error("job row not found after polling");
expect(row.status).toBe("completed");
const outName = (row.outputRefs as string[])[0].split("/").pop() as string;
const dl = await testApp.app.inject({
method: "GET",
url: `/api/v1/download/${jobId}/${encodeURIComponent(outName)}`,
@@ -75,8 +76,9 @@ describe.skipIf(!sofficeAvailable())("convert-document (requires soffice)", () =
expect(res.statusCode).toBe(202);
const { jobId } = JSON.parse(res.body);
const row = await pollJob(jobId);
expect(row?.status).toBe("completed");
const outName = (row?.outputRefs as string[])[0].split("/").pop() as string;
if (!row) throw new Error("job row not found after polling");
expect(row.status).toBe("completed");
const outName = (row.outputRefs as string[])[0].split("/").pop() as string;
const dl = await testApp.app.inject({
method: "GET",
url: `/api/v1/download/${jobId}/${encodeURIComponent(outName)}`,
@@ -91,8 +93,9 @@ describe.skipIf(!sofficeAvailable())("convert-document (requires soffice)", () =
expect(res.statusCode).toBe(202);
const { jobId } = JSON.parse(res.body);
const row = await pollJob(jobId);
expect(row?.status).toBe("completed");
const outName = (row?.outputRefs as string[])[0].split("/").pop() as string;
if (!row) throw new Error("job row not found after polling");
expect(row.status).toBe("completed");
const outName = (row.outputRefs as string[])[0].split("/").pop() as string;
const dl = await testApp.app.inject({
method: "GET",
url: `/api/v1/download/${jobId}/${encodeURIComponent(outName)}`,
@@ -58,8 +58,9 @@ describe.skipIf(!sofficeAvailable())("convert-presentation (requires soffice)",
expect(res.statusCode).toBe(202);
const { jobId } = JSON.parse(res.body);
const row = await pollJob(jobId);
expect(row?.status).toBe("completed");
const outName = (row?.outputRefs as string[])[0].split("/").pop() as string;
if (!row) throw new Error("job row not found after polling");
expect(row.status).toBe("completed");
const outName = (row.outputRefs as string[])[0].split("/").pop() as string;
const dl = await testApp.app.inject({
method: "GET",
url: `/api/v1/download/${jobId}/${encodeURIComponent(outName)}`,
@@ -58,8 +58,9 @@ describe.skipIf(!sofficeAvailable())("convert-spreadsheet (requires soffice)", (
expect(res.statusCode).toBe(202);
const { jobId } = JSON.parse(res.body);
const row = await pollJob(jobId);
expect(row?.status).toBe("completed");
const outName = (row?.outputRefs as string[])[0].split("/").pop() as string;
if (!row) throw new Error("job row not found after polling");
expect(row.status).toBe("completed");
const outName = (row.outputRefs as string[])[0].split("/").pop() as string;
const dl = await testApp.app.inject({
method: "GET",
url: `/api/v1/download/${jobId}/${encodeURIComponent(outName)}`,
@@ -75,8 +76,9 @@ describe.skipIf(!sofficeAvailable())("convert-spreadsheet (requires soffice)", (
expect(res.statusCode).toBe(202);
const { jobId } = JSON.parse(res.body);
const row = await pollJob(jobId);
expect(row?.status).toBe("completed");
const outName = (row?.outputRefs as string[])[0].split("/").pop() as string;
if (!row) throw new Error("job row not found after polling");
expect(row.status).toBe("completed");
const outName = (row.outputRefs as string[])[0].split("/").pop() as string;
const dl = await testApp.app.inject({
method: "GET",
url: `/api/v1/download/${jobId}/${encodeURIComponent(outName)}`,
@@ -201,8 +201,9 @@ describe.skipIf(!pandocAvailable() || !pythonWith("weasyprint"))(
if (row && ["completed", "failed", "canceled"].includes(row.status)) break;
await new Promise((r) => setTimeout(r, 500));
}
expect(row?.status).toBe("completed");
const outName = (row?.outputRefs as string[])[0].split("/").pop() as string;
if (!row) throw new Error("job row not found after polling");
expect(row.status).toBe("completed");
const outName = (row.outputRefs as string[])[0].split("/").pop() as string;
const dl = await testApp.app.inject({
method: "GET",
url: `/api/v1/download/${jobId}/${encodeURIComponent(outName)}`,
@@ -54,8 +54,9 @@ describe.skipIf(!sofficeAvailable())("excel-to-pdf (requires soffice)", () => {
if (row && ["completed", "failed", "canceled"].includes(row.status)) break;
await new Promise((r) => setTimeout(r, 500));
}
expect(row?.status).toBe("completed");
const outName = (row?.outputRefs as string[])[0].split("/").pop() as string;
if (!row) throw new Error("job row not found after polling");
expect(row.status).toBe("completed");
const outName = (row.outputRefs as string[])[0].split("/").pop() as string;
const dl = await testApp.app.inject({
method: "GET",
url: `/api/v1/download/${jobId}/${encodeURIComponent(outName)}`,
@@ -55,8 +55,9 @@ describe.skipIf(!hasWeasyprint)("html-to-pdf (requires weasyprint)", () => {
if (row && ["completed", "failed", "canceled"].includes(row.status)) break;
await new Promise((r) => setTimeout(r, 500));
}
expect(row?.status).toBe("completed");
const outName = (row?.outputRefs as string[])[0].split("/").pop() as string;
if (!row) throw new Error("job row not found after polling");
expect(row.status).toBe("completed");
const outName = (row.outputRefs as string[])[0].split("/").pop() as string;
const dl = await testApp.app.inject({
method: "GET",
url: `/api/v1/download/${jobId}/${encodeURIComponent(outName)}`,
@@ -57,8 +57,9 @@ describe.skipIf(!hasWeasyprint || !hasMarkdownMod)(
if (row && ["completed", "failed", "canceled"].includes(row.status)) break;
await new Promise((r) => setTimeout(r, 500));
}
expect(row?.status).toBe("completed");
const outName = (row?.outputRefs as string[])[0].split("/").pop() as string;
if (!row) throw new Error("job row not found after polling");
expect(row.status).toBe("completed");
const outName = (row.outputRefs as string[])[0].split("/").pop() as string;
const dl = await testApp.app.inject({
method: "GET",
url: `/api/v1/download/${jobId}/${encodeURIComponent(outName)}`,
@@ -62,7 +62,7 @@ describe.skipIf(!qpdfAvailable())("merge-pdf (requires qpdf)", () => {
}
}, 60_000);
it("returns 422 when only one PDF is provided", async () => {
it("returns 400 before enqueue when only one PDF is provided", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "only.pdf", contentType: "application/pdf", content: PDF },
{ name: "settings", content: JSON.stringify({}) },
@@ -73,11 +73,8 @@ describe.skipIf(!qpdfAvailable())("merge-pdf (requires qpdf)", () => {
headers: { authorization: `Bearer ${adminToken}`, "content-type": contentType },
body,
});
// The worker throws "Merging needs at least two PDFs" which surfaces as 422
// with a generic "Processing failed" error (the factory strips internal details)
expect(res.statusCode).toBe(422);
expect(res.statusCode).toBe(400);
const parsed = JSON.parse(res.body);
expect(parsed.error).toBe("Processing failed");
expect(parsed.details).toMatch(/at least two/i);
expect(parsed.error).toMatch(/at least 2 files/i);
}, 60_000);
});
@@ -158,33 +158,33 @@ describe("OCR PDF path-backed batch and pipeline ingress", () => {
}
});
it.each([
"file-first",
"field-first",
] as const)("rejects oversized pipeline OCR PDFs with %s multipart ordering", async (ordering) => {
const originalLimit = env.MAX_UPLOAD_SIZE_MB;
env.MAX_UPLOAD_SIZE_MB = 1 / (1024 * 1024);
try {
const oversized = {
name: "file",
filename: "oversized.pdf",
contentType: "application/pdf",
content: Buffer.from("12"),
};
const pipelinePart = { name: "pipeline", content: OCR_PIPELINE };
const parts =
ordering === "file-first" ? [oversized, pipelinePart] : [pipelinePart, oversized];
it.each(["file-first", "field-first"] as const)(
"rejects oversized pipeline OCR PDFs with %s multipart ordering",
async (ordering) => {
const originalLimit = env.MAX_UPLOAD_SIZE_MB;
env.MAX_UPLOAD_SIZE_MB = 1 / (1024 * 1024);
try {
const oversized = {
name: "file",
filename: "oversized.pdf",
contentType: "application/pdf",
content: Buffer.from("12"),
};
const pipelinePart = { name: "pipeline", content: OCR_PIPELINE };
const parts =
ordering === "file-first" ? [oversized, pipelinePart] : [pipelinePart, oversized];
const execute = await postMultipart("/api/v1/pipeline/execute", parts);
const batch = await postMultipart("/api/v1/pipeline/batch", parts);
const execute = await postMultipart("/api/v1/pipeline/execute", parts);
const batch = await postMultipart("/api/v1/pipeline/batch", parts);
expect(execute.statusCode).toBe(413);
expect(batch.statusCode).toBe(413);
expect(prepareSpy).not.toHaveBeenCalled();
} finally {
env.MAX_UPLOAD_SIZE_MB = originalLimit;
}
});
expect(execute.statusCode).toBe(413);
expect(batch.statusCode).toBe(413);
expect(prepareSpy).not.toHaveBeenCalled();
} finally {
env.MAX_UPLOAD_SIZE_MB = originalLimit;
}
},
);
it("enforces the OCR stream cap before a trailing pipeline field reveals the modality", async () => {
const originalLimit = env.MAX_UPLOAD_SIZE_MB;
@@ -254,39 +254,39 @@ describe("OCR PDF path-backed batch and pipeline ingress", () => {
expect(prepareSpy).not.toHaveBeenCalled();
});
it.each([
"file-first",
"field-first",
] as const)("validates execute-pipeline OCR PDF input by path with %s multipart ordering", async (ordering) => {
const pipelinePart = { name: "pipeline", content: OCR_PIPELINE };
const parts =
ordering === "file-first"
? [invalidPdfPart(), pipelinePart]
: [pipelinePart, invalidPdfPart()];
it.each(["file-first", "field-first"] as const)(
"validates execute-pipeline OCR PDF input by path with %s multipart ordering",
async (ordering) => {
const pipelinePart = { name: "pipeline", content: OCR_PIPELINE };
const parts =
ordering === "file-first"
? [invalidPdfPart(), pipelinePart]
: [pipelinePart, invalidPdfPart()];
const response = await postMultipart("/api/v1/pipeline/execute", parts);
const response = await postMultipart("/api/v1/pipeline/execute", parts);
expect(response.statusCode).toBe(400);
expect(JSON.parse(response.body).error).toMatch(/PDF header/i);
expect(prepareSpy).not.toHaveBeenCalled();
});
expect(response.statusCode).toBe(400);
expect(JSON.parse(response.body).error).toMatch(/PDF header/i);
expect(prepareSpy).not.toHaveBeenCalled();
},
);
it.each([
"file-first",
"field-first",
] as const)("validates batch-pipeline OCR PDF files by path with %s multipart ordering", async (ordering) => {
const pipelinePart = { name: "pipeline", content: OCR_PIPELINE };
const parts =
ordering === "file-first"
? [invalidPdfPart(), pipelinePart]
: [pipelinePart, invalidPdfPart()];
it.each(["file-first", "field-first"] as const)(
"validates batch-pipeline OCR PDF files by path with %s multipart ordering",
async (ordering) => {
const pipelinePart = { name: "pipeline", content: OCR_PIPELINE };
const parts =
ordering === "file-first"
? [invalidPdfPart(), pipelinePart]
: [pipelinePart, invalidPdfPart()];
const response = await postMultipart("/api/v1/pipeline/batch", parts);
const response = await postMultipart("/api/v1/pipeline/batch", parts);
expect(response.statusCode).toBe(422);
expect(JSON.parse(response.body).errors[0].error).toMatch(/PDF header/i);
expect(prepareSpy).not.toHaveBeenCalled();
});
expect(response.statusCode).toBe(422);
expect(JSON.parse(response.body).errors[0].error).toMatch(/PDF header/i);
expect(prepareSpy).not.toHaveBeenCalled();
},
);
it("rolls back tool-batch OCR objects when BullMQ rejects the flow handoff", async () => {
mocks.flowAdd.mockRejectedValueOnce(new Error("Redis unavailable"));
@@ -61,8 +61,9 @@ async function downloadCompletedDocx(
if (row && ["completed", "failed", "canceled"].includes(row.status)) break;
await new Promise((resolve) => setTimeout(resolve, 500));
}
expect(row?.status).toBe("completed");
const outName = (row?.outputRefs as string[])[0].split("/").pop() as string;
if (!row) throw new Error("job row not found after polling");
expect(row.status).toBe("completed");
const outName = (row.outputRefs as string[])[0].split("/").pop() as string;
const download = await testApp.app.inject({
method: "GET",
url: `/api/v1/download/${jobId}/${encodeURIComponent(outName)}`,
@@ -54,8 +54,9 @@ describe.skipIf(!sofficeAvailable())("powerpoint-to-pdf (requires soffice)", ()
if (row && ["completed", "failed", "canceled"].includes(row.status)) break;
await new Promise((r) => setTimeout(r, 500));
}
expect(row?.status).toBe("completed");
const outName = (row?.outputRefs as string[])[0].split("/").pop() as string;
if (!row) throw new Error("job row not found after polling");
expect(row.status).toBe("completed");
const outName = (row.outputRefs as string[])[0].split("/").pop() as string;
const dl = await testApp.app.inject({
method: "GET",
url: `/api/v1/download/${jobId}/${encodeURIComponent(outName)}`,
@@ -52,6 +52,11 @@ describe.skipIf(!pdfcpuAvailable())("watermark-pdf (requires pdfcpu)", () => {
});
describe("watermark-pdf validation (ungated)", () => {
it("rejects whitespace-only watermark text with 400", async () => {
const res = await runTool({ text: " \t" });
expect(res.statusCode).toBe(400);
}, 30_000);
it("rejects text longer than 200 characters with 400", async () => {
const longText = "A".repeat(201);
const res = await runTool({ text: longText });
@@ -54,8 +54,9 @@ describe.skipIf(!sofficeAvailable())("word-to-pdf (requires soffice)", () => {
if (row && ["completed", "failed", "canceled"].includes(row.status)) break;
await new Promise((r) => setTimeout(r, 500));
}
expect(row?.status).toBe("completed");
const outName = (row?.outputRefs as string[])[0].split("/").pop() as string;
if (!row) throw new Error("job row not found after polling");
expect(row.status).toBe("completed");
const outName = (row.outputRefs as string[])[0].split("/").pop() as string;
const dl = await testApp.app.inject({
method: "GET",
url: `/api/v1/download/${jobId}/${encodeURIComponent(outName)}`,
@@ -1,17 +1,24 @@
/**
* Integration tests for the background-replace tool (/api/v1/tools/image/background-replace).
*
* 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.
* This tool reuses the rembg bundle (background-removal). Missing-bundle
* contracts run only when that capability is absent; installed happy paths run
* when it is detected or REQUIRE_AI_FEATURES makes absence a release failure.
*
* The compositeOnColor 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.
* tests/unit/api/background-composite.test.ts.
*/
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { isToolInstalled } from "../../../../apps/api/src/lib/feature-status.js";
import { fixtures, readFixture } from "../../../fixtures/index.js";
import { installedAiCapabilityGate } from "../../../helpers/installed-ai-capability-gate.js";
import {
expectConfiguredBackground,
expectForegroundPreserved,
expectObservablePixelChange,
} from "../../../helpers/installed-ai-output-oracles.js";
import { waitForDownloadedJobArtifact } from "../../settle-job.js";
import {
buildTestApp,
createMultipartPayload,
@@ -20,6 +27,13 @@ import {
} from "../../test-server.js";
const PNG = readFixture(fixtures.image.base.png200);
const PORTRAIT = readFixture(fixtures.image.portrait.jpg);
const REQUIRE_AI_FEATURES = process.env.REQUIRE_AI_FEATURES === "1";
const AI_CAPABILITY = installedAiCapabilityGate(
"background-replace",
REQUIRE_AI_FEATURES,
isToolInstalled,
);
let testApp: TestApp;
let app: TestApp["app"];
@@ -36,31 +50,34 @@ afterAll(async () => {
}, 10_000);
describe("background-replace", () => {
// -- 501 gate (always fires locally: background-removal bundle never installed) --
// -- Missing-capability contract --
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({}) },
]);
it.skipIf(!AI_CAPABILITY.runUnavailableContract)(
"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({}) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/background-replace",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/background-replace",
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();
});
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 --
@@ -82,96 +99,12 @@ describe("background-replace", () => {
// -- Validation: 501 fires before settings parse, so bad hex also 501s --
it("returns 501 even with invalid color hex (gate fires first)", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{ name: "settings", content: JSON.stringify({ color: "not-a-hex" }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/background-replace",
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");
});
it("returns 501 with gradient settings (gate fires first)", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{
name: "settings",
content: JSON.stringify({
backgroundType: "gradient",
gradientColor1: "#ff0000",
gradientColor2: "#0000ff",
gradientAngle: 90,
}),
},
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/background-replace",
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");
});
it("returns 501 with feather and webp format (gate fires first)", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{
name: "settings",
content: JSON.stringify({
backgroundType: "color",
color: "#00ff00",
feather: 5,
format: "webp",
}),
},
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/background-replace",
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 + compositeOnColor unit tests carry the verification.
describe.skip("with background-removal bundle installed", () => {
it("replaces background with color (202 + async)", async () => {
it.skipIf(!AI_CAPABILITY.runUnavailableContract)(
"returns 501 even with invalid color hex (gate fires first)",
async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{ name: "settings", content: JSON.stringify({ color: "#ff0000" }) },
{ name: "settings", content: JSON.stringify({ color: "not-a-hex" }) },
]);
const res = await app.inject({
@@ -184,13 +117,16 @@ describe("background-replace", () => {
body,
});
expect(res.statusCode).toBe(202);
// 501 because the bundle gate fires before settings validation
expect(res.statusCode).toBe(501);
const json = JSON.parse(res.body);
expect(json.jobId).toBeDefined();
expect(json.async).toBe(true);
}, 300_000);
expect(json.code).toBe("FEATURE_NOT_INSTALLED");
},
);
it("replaces background with gradient (202 + async)", async () => {
it.skipIf(!AI_CAPABILITY.runUnavailableContract)(
"returns 501 with gradient settings (gate fires first)",
async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{
@@ -199,8 +135,38 @@ describe("background-replace", () => {
backgroundType: "gradient",
gradientColor1: "#ff0000",
gradientColor2: "#0000ff",
gradientAngle: 45,
feather: 3,
gradientAngle: 90,
}),
},
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/background-replace",
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");
},
);
it.skipIf(!AI_CAPABILITY.runUnavailableContract)(
"returns 501 with feather and webp format (gate fires first)",
async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{
name: "settings",
content: JSON.stringify({
backgroundType: "color",
color: "#00ff00",
feather: 5,
format: "webp",
}),
},
@@ -216,10 +182,104 @@ describe("background-replace", () => {
body,
});
expect(res.statusCode).toBe(202);
expect(res.statusCode).toBe(501);
const json = JSON.parse(res.body);
expect(json.jobId).toBeDefined();
expect(json.async).toBe(true);
}, 300_000);
});
expect(json.code).toBe("FEATURE_NOT_INSTALLED");
},
);
// -- Installed/required capability contract --
describe.skipIf(!AI_CAPABILITY.runInstalledContract)(
"with background-removal bundle installed",
() => {
it("replaces background with color (202 + async)", async () => {
const { body, contentType } = createMultipartPayload([
{
name: "file",
filename: "portrait-color.jpg",
contentType: "image/jpeg",
content: PORTRAIT,
},
{ name: "settings", content: JSON.stringify({ color: "#ff0000" }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/background-replace",
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);
const artifact = await waitForDownloadedJobArtifact(
app,
adminToken,
"background-replace",
json.jobId as string,
240_000,
);
expect(artifact.filename).toBe("portrait-color_bg.png");
expect(artifact.contentType).toBe("image/png");
await expectObservablePixelChange(PORTRAIT, artifact.buffer);
await expectConfiguredBackground(artifact.buffer, "solid-red");
await expectForegroundPreserved(PORTRAIT, artifact.buffer);
}, 300_000);
it("replaces background with gradient (202 + async)", async () => {
const { body, contentType } = createMultipartPayload([
{
name: "file",
filename: "portrait-color.jpg",
contentType: "image/jpeg",
content: PORTRAIT,
},
{
name: "settings",
content: JSON.stringify({
backgroundType: "gradient",
gradientColor1: "#ff0000",
gradientColor2: "#0000ff",
gradientAngle: 45,
feather: 3,
format: "webp",
}),
},
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/background-replace",
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);
const artifact = await waitForDownloadedJobArtifact(
app,
adminToken,
"background-replace",
json.jobId as string,
240_000,
);
expect(artifact.filename).toBe("portrait-color_bg.webp");
expect(artifact.contentType).toBe("image/webp");
await expectObservablePixelChange(PORTRAIT, artifact.buffer);
await expectConfiguredBackground(artifact.buffer, "red-blue-gradient");
await expectForegroundPreserved(PORTRAIT, artifact.buffer);
}, 300_000);
},
);
});
@@ -9,6 +9,7 @@
import sharp from "sharp";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { getToolConfig } from "../../../../apps/api/src/routes/tool-factory.js";
import { fixtures, readFixture } from "../../../fixtures/index.js";
import {
buildTestApp,
@@ -769,6 +770,22 @@ describe("Beautify", () => {
expect(meta.hasAlpha).toBe(true);
});
it("pipeline image background without a second input falls back to transparent", async () => {
const config = getToolConfig("beautify");
if (!config) throw new Error("beautify must be registered");
const settings = config.settingsSchema.parse({
backgroundType: "image",
shadowPreset: "none",
padding: 20,
});
const result = await config.process(PNG, settings, "test.png");
const meta = await sharp(result.buffer).metadata();
expect(result.filename).toBe("test.png");
expect(meta.hasAlpha).toBe(true);
});
it("shadow with zero padding (shadow extends beyond image)", async () => {
const payload = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
@@ -931,6 +948,19 @@ describe("Beautify", () => {
expect(res.statusCode).toBe(400);
});
it("empty custom shadow color returns 400 instead of reaching Sharp", async () => {
const payload = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{
name: "settings",
content: JSON.stringify({ shadowPreset: "custom", shadowColor: "" }),
},
]);
const res = await post("/api/v1/tools/image/beautify", payload);
expect(res.statusCode).toBe(400);
});
it("invalid background type returns 400", async () => {
const payload = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
@@ -1,17 +1,23 @@
/**
* Integration tests for the blur-background tool (/api/v1/tools/image/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.
* This tool reuses the rembg bundle (background-removal). Missing-bundle
* contracts run only when that capability is absent; installed happy paths run
* when it is detected or REQUIRE_AI_FEATURES makes absence a release failure.
*
* 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.
* tests/unit/api/background-composite.test.ts.
*/
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { isToolInstalled } from "../../../../apps/api/src/lib/feature-status.js";
import { fixtures, readFixture } from "../../../fixtures/index.js";
import { installedAiCapabilityGate } from "../../../helpers/installed-ai-capability-gate.js";
import {
expectForegroundPreserved,
expectObservablePixelChange,
} from "../../../helpers/installed-ai-output-oracles.js";
import { waitForDownloadedJobArtifact } from "../../settle-job.js";
import {
buildTestApp,
createMultipartPayload,
@@ -20,6 +26,13 @@ import {
} from "../../test-server.js";
const PNG = readFixture(fixtures.image.base.png200);
const PORTRAIT = readFixture(fixtures.image.portrait.jpg);
const REQUIRE_AI_FEATURES = process.env.REQUIRE_AI_FEATURES === "1";
const AI_CAPABILITY = installedAiCapabilityGate(
"blur-background",
REQUIRE_AI_FEATURES,
isToolInstalled,
);
let testApp: TestApp;
let app: TestApp["app"];
@@ -36,31 +49,34 @@ afterAll(async () => {
}, 10_000);
describe("blur-background", () => {
// -- 501 gate (always fires locally: background-removal bundle never installed) --
// -- Missing-capability contract --
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" }) },
]);
it.skipIf(!AI_CAPABILITY.runUnavailableContract)(
"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/image/blur-background",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/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();
});
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 --
@@ -82,86 +98,41 @@ describe("blur-background", () => {
// -- 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" }) },
]);
it.skipIf(!AI_CAPABILITY.runUnavailableContract)(
"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/image/blur-background",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/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 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/image/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/image/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 () => {
it.skipIf(!AI_CAPABILITY.runUnavailableContract)(
"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: 75, feather: 3, format: "webp" }),
content: JSON.stringify({ intensity: 80, feather: 10, format: "webp" }),
},
]);
@@ -175,10 +146,83 @@ describe("blur-background", () => {
body,
});
expect(res.statusCode).toBe(202);
expect(res.statusCode).toBe(501);
const json = JSON.parse(res.body);
expect(json.jobId).toBeDefined();
expect(json.async).toBe(true);
}, 300_000);
});
expect(json.code).toBe("FEATURE_NOT_INSTALLED");
},
);
// -- 501 with defaults (empty settings object, Zod fills defaults) --
it.skipIf(!AI_CAPABILITY.runUnavailableContract)(
"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/image/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");
},
);
// -- Installed/required capability contract --
describe.skipIf(!AI_CAPABILITY.runInstalledContract)(
"with background-removal bundle installed",
() => {
it("blurs background with full settings (202 + async)", async () => {
const { body, contentType } = createMultipartPayload([
{
name: "file",
filename: "portrait-color.jpg",
contentType: "image/jpeg",
content: PORTRAIT,
},
{
name: "settings",
content: JSON.stringify({ intensity: 75, feather: 3, format: "webp" }),
},
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/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);
const artifact = await waitForDownloadedJobArtifact(
app,
adminToken,
"blur-background",
json.jobId as string,
240_000,
);
expect(artifact.filename).toBe("portrait-color_blurbg.webp");
expect(artifact.contentType).toBe("image/webp");
await expectObservablePixelChange(PORTRAIT, artifact.buffer);
await expectForegroundPreserved(PORTRAIT, artifact.buffer);
}, 300_000);
},
);
});
@@ -6,8 +6,6 @@
* Consolidated adjust-colors tool replaces the old brightness-contrast, saturation, etc.
*/
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { apiToolPath } from "@snapotter/shared";
import sharp from "sharp";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
@@ -7,7 +7,7 @@
import sharp from "sharp";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { fixtureDir, fixtures, readFixture } from "../../../fixtures/index.js";
import { fixtures, readFixture } from "../../../fixtures/index.js";
import {
buildTestApp,
createMultipartPayload,
@@ -15,7 +15,6 @@ import {
type TestApp,
} from "../../test-server.js";
const FORMATS = fixtureDir.formats;
const PNG = readFixture(fixtures.image.base.png200);
const _JPG = readFixture(fixtures.image.base.jpg100);
const WEBP = readFixture(fixtures.image.base.webp50);
@@ -173,6 +173,11 @@ describe("Field removal", () => {
if (res.statusCode === 422) return;
expect(res.statusCode).toBe(200);
});
it("rejects empty and unsafe field names at the API boundary", async () => {
expect((await postTool({ fieldsToRemove: [""] })).statusCode).toBe(400);
expect((await postTool({ fieldsToRemove: ["bad field"] })).statusCode).toBe(400);
});
});
// ── Keywords ────────────────────────────────────────────────────
@@ -5,8 +5,10 @@
* plus the metadata endpoint. Uses a real Fastify server with in-memory SQLite.
*/
import { isToolInputError } from "@snapotter/shared";
import sharp from "sharp";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { getToolConfig } from "../../../../apps/api/src/routes/tool-factory.js";
import { fixtures, readFixture } from "../../../fixtures/index.js";
import {
buildTestApp,
@@ -105,6 +107,47 @@ describe("POST /api/v1/tools/image/gif-tools/info", () => {
// ── Resize mode ───────────────────────────────────────────────────
describe("Resize mode", () => {
it("rejects an animated resize whose aggregate output exceeds the pixel budget", async () => {
const { body: payload, contentType } = makePayload({
mode: "resize",
width: 5_000,
height: 5_000,
});
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/gif-tools",
payload,
headers: {
"content-type": contentType,
authorization: `Bearer ${adminToken}`,
},
});
expect(res.statusCode).toBe(400);
expect(res.json().error).toMatch(/total pixel/i);
});
it("rejects the same oversized workload through the worker contract", async () => {
const config = getToolConfig("gif-tools");
expect(config).toBeDefined();
const settings = config?.settingsSchema.parse({
mode: "resize",
width: 5_000,
height: 5_000,
});
let caught: unknown;
try {
await config?.process(animatedGif, settings, "test.gif");
} catch (error) {
caught = error;
}
expect(isToolInputError(caught)).toBe(true);
expect(caught).toHaveProperty("message", expect.stringMatching(/total pixel/i));
});
it("resizes animated GIF by pixel dimensions", async () => {
const { body: payload, contentType } = makePayload({
mode: "resize",
@@ -5,7 +5,6 @@
* and extension validation.
*/
import { join } from "node:path";
import sharp from "sharp";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { fixtures, readFixture } from "../../../fixtures/index.js";
@@ -1,5 +1,4 @@
import sharp from "sharp";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { buildTestApp, loginAsAdmin, type TestApp } from "../../test-server.js";
// Mock the browser service -- Chromium may not be available in CI
@@ -181,39 +181,40 @@ describe("ocr tier execution coverage", () => {
expect(maxActive).toBe(1);
});
it.each(
OCR_FORMAT_FIXTURES,
)("prepares %s through the real image ingress before mocked recognition", async (fixture) => {
mocks.getOcrRuntimeCapability.mockReturnValue({
available: false,
qualities: [],
providers: [],
});
mocks.extractText.mockImplementationOnce(async (_input, _scratch, options) => ({
text: "format accepted",
engine: "tesseract",
requestedQuality: options.quality,
actualQuality: options.quality,
device: "cpu",
provider: "tesseract",
degraded: false,
warnings: [],
}));
it.each(OCR_FORMAT_FIXTURES)(
"prepares %s through the real image ingress before mocked recognition",
async (fixture) => {
mocks.getOcrRuntimeCapability.mockReturnValue({
available: false,
qualities: [],
providers: [],
});
mocks.extractText.mockImplementationOnce(async (_input, _scratch, options) => ({
text: "format accepted",
engine: "tesseract",
requestedQuality: options.quality,
actualQuality: options.quality,
device: "cpu",
provider: "tesseract",
degraded: false,
warnings: [],
}));
const response = await postOcrFile(
{ quality: "fast", language: "en" },
readFileSync(join(fixtureDir.formats, fixture)),
fixture,
);
const result = await awaitAcceptedOcr(response);
const response = await postOcrFile(
{ quality: "fast", language: "en" },
readFileSync(join(fixtureDir.formats, fixture)),
fixture,
);
const result = await awaitAcceptedOcr(response);
expect(result).toMatchObject({
text: "format accepted",
requestedQuality: "fast",
actualQuality: "fast",
});
expect(mocks.extractText).toHaveBeenCalledTimes(1);
});
expect(result).toMatchObject({
text: "format accepted",
requestedQuality: "fast",
actualQuality: "fast",
});
expect(mocks.extractText).toHaveBeenCalledTimes(1);
},
);
it("fails closed when the selected best runtime crashes", async () => {
mocks.extractText.mockRejectedValueOnce(new Error("OCR runtime exited unexpectedly"));
@@ -141,6 +141,12 @@ describe("Resize", () => {
expect(meta.height).toBe(75);
});
it("treats 1000 percent as 10x at the product boundary", async () => {
const meta = await resizeAndMeta({ percentage: 1000 }, TINY, "tiny.png", "image/png");
expect(meta.width).toBe(10);
expect(meta.height).toBe(10);
});
it("respects withoutEnlargement flag", async () => {
const meta = await resizeAndMeta({ width: 400, height: 300, withoutEnlargement: true });
// Should not enlarge beyond original 200x150
@@ -259,6 +265,52 @@ describe("Resize", () => {
expect(result.error).toMatch(/invalid settings/i);
});
it("rejects the deterministic oversized percentage before processing", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{
name: "settings",
content: JSON.stringify({ percentage: 896202.8004871072 }),
},
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/resize",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(400);
expect(JSON.parse(res.body).details).toMatch(/less than or equal to 1000/i);
});
it("rejects a percentage immediately above the product boundary", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "tiny.png", contentType: "image/png", content: TINY },
{
name: "settings",
content: JSON.stringify({ percentage: 1000.000001 }),
},
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/resize",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(400);
expect(JSON.parse(res.body).details).toMatch(/less than or equal to 1000/i);
});
it("rejects unauthenticated requests", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
@@ -112,6 +112,12 @@ describe("Rotate", () => {
expect(meta.height).toBe(200);
});
it("normalizes large finite angles before passing them to Sharp", async () => {
const meta = await rotateAndMeta({ angle: 10_000_000.000000002 });
expect(meta.width).toBeGreaterThan(0);
expect(meta.height).toBeGreaterThan(0);
});
it("rotates 0 degrees (no-op)", async () => {
const meta = await rotateAndMeta({ angle: 0 });
expect(meta.width).toBe(200);
@@ -149,8 +149,7 @@ describe("Sprite Sheet", () => {
body,
});
// The factory wraps InputValidationError as 422
expect(res.statusCode).toBeGreaterThanOrEqual(400);
expect(res.statusCode).toBeLessThan(500);
expect(res.statusCode).toBe(400);
expect(JSON.parse(res.body).error).toMatch(/at least 2 files/i);
});
});
@@ -80,28 +80,25 @@ describe("watermark-image", () => {
expect(Buffer.from(dlRes.rawPayload).equals(PNG)).toBe(false);
});
it.each([
"center",
"top-left",
"top-right",
"bottom-left",
"bottom-right",
] as const)("supports position: %s", async (position) => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "main.png", contentType: "image/png", content: PNG },
{ name: "watermark", filename: "wm.png", contentType: "image/png", content: SMALL_PNG },
{ name: "settings", content: JSON.stringify({ position }) },
]);
it.each(["center", "top-left", "top-right", "bottom-left", "bottom-right"] as const)(
"supports position: %s",
async (position) => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "main.png", contentType: "image/png", content: PNG },
{ name: "watermark", filename: "wm.png", contentType: "image/png", content: SMALL_PNG },
{ name: "settings", content: JSON.stringify({ position }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/watermark-image",
headers: { authorization: `Bearer ${adminToken}`, "content-type": contentType },
body,
});
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/watermark-image",
headers: { authorization: `Bearer ${adminToken}`, "content-type": contentType },
body,
});
expect(res.statusCode).toBe(200);
});
expect(res.statusCode).toBe(200);
},
);
it("respects custom opacity and scale", async () => {
const { body, contentType } = createMultipartPayload([
@@ -77,30 +77,26 @@ describe("watermark-text", () => {
expect(Buffer.from(dlRes.rawPayload).equals(PNG)).toBe(false);
});
it.each([
"center",
"top-left",
"top-right",
"bottom-left",
"bottom-right",
"tiled",
] as const)("supports position: %s", async (position) => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{ name: "settings", content: JSON.stringify({ text: "Pos", position }) },
]);
it.each(["center", "top-left", "top-right", "bottom-left", "bottom-right", "tiled"] as const)(
"supports position: %s",
async (position) => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "test.png", contentType: "image/png", content: PNG },
{ name: "settings", content: JSON.stringify({ text: "Pos", position }) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/watermark-text",
headers: { authorization: `Bearer ${adminToken}`, "content-type": contentType },
body,
});
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/image/watermark-text",
headers: { authorization: `Bearer ${adminToken}`, "content-type": contentType },
body,
});
expect(res.statusCode).toBe(200);
const json = JSON.parse(res.body);
expect(json.downloadUrl).toBeDefined();
});
expect(res.statusCode).toBe(200);
const json = JSON.parse(res.body);
expect(json.downloadUrl).toBeDefined();
},
);
it("respects custom opacity and font size", async () => {
const { body, contentType } = createMultipartPayload([
@@ -1,15 +1,22 @@
/**
* Integration tests for the auto-subtitles tool (/api/v1/tools/video/auto-subtitles).
*
* The transcription bundle (faster-whisper) is not installed locally, so the
* 501 gate is always hit. Validation paths (bad settings) fire after the 501
* check. The bundle-gated happy path lives in a skipped describe for
* in-container-after-install runs.
* Missing-bundle contracts run only when the transcription capability is
* absent. Installed happy paths run when the capability is detected or when
* REQUIRE_AI_FEATURES makes its absence a release-gate failure.
*/
import { readFileSync } from "node:fs";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { isToolInstalled } from "../../../../apps/api/src/lib/feature-status.js";
import { fixtures } from "../../../fixtures/index.js";
import { installedAiCapabilityGate } from "../../../helpers/installed-ai-capability-gate.js";
import {
expectKnownTranscript,
expectSrtArtifact,
expectVttArtifact,
} from "../../../helpers/installed-ai-output-oracles.js";
import { waitForDownloadedJobArtifact } from "../../settle-job.js";
import {
buildTestApp,
createMultipartPayload,
@@ -18,6 +25,13 @@ import {
} from "../../test-server.js";
const MP4 = readFileSync(fixtures.video.tiny("mp4"));
const SPEECH_MP4 = readFileSync(fixtures.video.speech.mp4);
const REQUIRE_AI_FEATURES = process.env.REQUIRE_AI_FEATURES === "1";
const AI_CAPABILITY = installedAiCapabilityGate(
"auto-subtitles",
REQUIRE_AI_FEATURES,
isToolInstalled,
);
let testApp: TestApp;
let app: TestApp["app"];
@@ -34,68 +48,74 @@ afterAll(async () => {
}, 10_000);
describe("auto-subtitles", () => {
// -- 501 gate (always fires locally: bundle never installed) --
// -- Missing-capability contract --
it("returns 501 FEATURE_NOT_INSTALLED when bundle is absent", async () => {
const { body, contentType } = createMultipartPayload([
{
name: "file",
filename: "tiny.mp4",
contentType: "video/mp4",
content: MP4,
},
{ name: "settings", content: JSON.stringify({}) },
]);
it.skipIf(!AI_CAPABILITY.runUnavailableContract)(
"returns 501 FEATURE_NOT_INSTALLED when bundle is absent",
async () => {
const { body, contentType } = createMultipartPayload([
{
name: "file",
filename: "tiny.mp4",
contentType: "video/mp4",
content: MP4,
},
{ name: "settings", content: JSON.stringify({}) },
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/video/auto-subtitles",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/video/auto-subtitles",
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("transcription");
expect(json.featureName).toBe("Transcription");
expect(json.estimatedSize).toBeDefined();
});
expect(res.statusCode).toBe(501);
const json = JSON.parse(res.body);
expect(json.code).toBe("FEATURE_NOT_INSTALLED");
expect(json.feature).toBe("transcription");
expect(json.featureName).toBe("Transcription");
expect(json.estimatedSize).toBeDefined();
},
);
// -- Validation (501 fires before settings parse, so these also 501) --
it("returns 501 even with invalid format (gate fires first)", async () => {
const { body, contentType } = createMultipartPayload([
{
name: "file",
filename: "tiny.mp4",
contentType: "video/mp4",
content: MP4,
},
{
name: "settings",
content: JSON.stringify({ format: "ass" }),
},
]);
it.skipIf(!AI_CAPABILITY.runUnavailableContract)(
"returns 501 even with invalid format (gate fires first)",
async () => {
const { body, contentType } = createMultipartPayload([
{
name: "file",
filename: "tiny.mp4",
contentType: "video/mp4",
content: MP4,
},
{
name: "settings",
content: JSON.stringify({ format: "ass" }),
},
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/video/auto-subtitles",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/video/auto-subtitles",
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 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");
},
);
it("rejects unauthenticated requests (401)", async () => {
const { body, contentType } = createMultipartPayload([
@@ -118,71 +138,93 @@ describe("auto-subtitles", () => {
expect(res.statusCode).toBe(401);
});
// -- Bundle-gated happy path (skipped locally, runs after bundle install) --
// -- Installed/required capability contract --
// The transcription bundle is ~600 MB and only available in Docker.
// These tests run when the bundle is installed (e.g., during Task 7 smoke).
// Locally they always skip.
describe.skip("with transcription bundle installed", () => {
it("generates subtitles from video (202 + async)", async () => {
const { body, contentType } = createMultipartPayload([
{
name: "file",
filename: "tiny.mp4",
contentType: "video/mp4",
content: MP4,
},
{
name: "settings",
content: JSON.stringify({ format: "srt" }),
},
]);
describe.skipIf(!AI_CAPABILITY.runInstalledContract)(
"with transcription bundle installed",
() => {
it("generates subtitles from video (202 + async)", async () => {
const { body, contentType } = createMultipartPayload([
{
name: "file",
filename: "speech-10s.mp4",
contentType: "video/mp4",
content: SPEECH_MP4,
},
{
name: "settings",
content: JSON.stringify({ format: "srt" }),
},
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/video/auto-subtitles",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/video/auto-subtitles",
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);
}, 120_000);
expect(res.statusCode).toBe(202);
const json = JSON.parse(res.body);
expect(json.jobId).toBeDefined();
expect(json.async).toBe(true);
const artifact = await waitForDownloadedJobArtifact(
app,
adminToken,
"auto-subtitles",
json.jobId as string,
240_000,
);
expect(artifact.filename).toBe("speech-10s.srt");
expect(artifact.contentType).toBe("application/x-subrip");
const subtitles = artifact.buffer.toString("utf8");
expectSrtArtifact(subtitles);
expectKnownTranscript(subtitles);
}, 300_000);
it("generates VTT subtitles from video", async () => {
const { body, contentType } = createMultipartPayload([
{
name: "file",
filename: "tiny.mp4",
contentType: "video/mp4",
content: MP4,
},
{
name: "settings",
content: JSON.stringify({ format: "vtt" }),
},
]);
it("generates VTT subtitles from video", async () => {
const { body, contentType } = createMultipartPayload([
{
name: "file",
filename: "speech-10s.mp4",
contentType: "video/mp4",
content: SPEECH_MP4,
},
{
name: "settings",
content: JSON.stringify({ format: "vtt" }),
},
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/video/auto-subtitles",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/video/auto-subtitles",
headers: {
authorization: `Bearer ${adminToken}`,
"content-type": contentType,
},
body,
});
expect(res.statusCode).toBe(202);
const json = JSON.parse(res.body);
expect(json.jobId).toBeDefined();
// Full VTT structure validation (WEBVTT header, dot timestamps)
// happens after polling completes in the Task 7 smoke.
}, 120_000);
});
expect(res.statusCode).toBe(202);
const json = JSON.parse(res.body);
expect(json.jobId).toBeDefined();
const artifact = await waitForDownloadedJobArtifact(
app,
adminToken,
"auto-subtitles",
json.jobId as string,
240_000,
);
expect(artifact.filename).toBe("speech-10s.vtt");
expect(artifact.contentType).toBe("text/vtt");
const subtitles = artifact.buffer.toString("utf8");
expectVttArtifact(subtitles);
expectKnownTranscript(subtitles);
}, 300_000);
},
);
});
@@ -57,7 +57,10 @@ async function resolveResult(res: Awaited<ReturnType<typeof testApp.app.inject>>
await new Promise((r) => setTimeout(r, 500));
}
expect(row?.status).toBe("completed");
const outName = (row?.outputRefs as string[])[0].split("/").pop() as string;
if (!Array.isArray(row?.outputRefs) || typeof row.outputRefs[0] !== "string") {
throw new Error("Completed burn-subtitles job has no output reference");
}
const outName = row.outputRefs[0].split("/").pop() as string;
const dl = await testApp.app.inject({
method: "GET",
url: `/api/v1/download/${jobId}/${encodeURIComponent(outName)}`,
@@ -132,4 +135,20 @@ describe.skipIf(!ffmpegAvailable())("burn-subtitles (requires ffmpeg)", () => {
const parsed = JSON.parse(res.body);
expect(parsed.error).toMatch(/subtitle/i);
}, 60_000);
it("rejects a missing subtitle before enqueue", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "tiny.mp4", contentType: "video/mp4", content: MP4 },
{ name: "settings", content: JSON.stringify({}) },
]);
const res = await testApp.app.inject({
method: "POST",
url: "/api/v1/tools/video/burn-subtitles",
headers: { authorization: `Bearer ${adminToken}`, "content-type": contentType },
body,
});
expect(res.statusCode).toBe(400);
expect(JSON.parse(res.body).error).toMatch(/at least 2 files/i);
});
});
@@ -71,4 +71,20 @@ describe.skipIf(!ffmpegAvailable())("embed-subtitles (requires ffmpeg)", () => {
expect(res.statusCode).toBe(400);
}, 60_000);
it("rejects a missing subtitle before enqueue", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "tiny.mp4", contentType: "video/mp4", content: MP4 },
{ name: "settings", content: JSON.stringify({}) },
]);
const res = await testApp.app.inject({
method: "POST",
url: "/api/v1/tools/video/embed-subtitles",
headers: { authorization: `Bearer ${adminToken}`, "content-type": contentType },
body,
});
expect(res.statusCode).toBe(400);
expect(JSON.parse(res.body).error).toMatch(/at least 2 files/i);
});
});
@@ -65,7 +65,7 @@ describe.skipIf(!ffmpegAvailable())("images-to-video (requires ffmpeg)", () => {
expect(v?.height).toBe(720);
}, 60_000);
it("rejects a single image with 422", async () => {
it("rejects a single image with 400 before enqueue", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "photo.jpg", contentType: "image/jpeg", content: JPG },
{ name: "settings", content: JSON.stringify({}) },
@@ -77,9 +77,8 @@ describe.skipIf(!ffmpegAvailable())("images-to-video (requires ffmpeg)", () => {
body,
});
// fast hint: inline 422
expect(res.statusCode).toBe(422);
expect(res.statusCode).toBe(400);
const parsed = JSON.parse(res.body);
expect(parsed.details).toMatch(/at least two images/i);
expect(parsed.error).toMatch(/at least 2 files/i);
}, 60_000);
});
@@ -54,7 +54,10 @@ async function resolveResult(res: Awaited<ReturnType<typeof testApp.app.inject>>
await new Promise((r) => setTimeout(r, 500));
}
expect(row?.status).toBe("completed");
const outName = (row?.outputRefs as string[])[0].split("/").pop() as string;
if (!Array.isArray(row?.outputRefs) || typeof row.outputRefs[0] !== "string") {
throw new Error("Completed merge-videos job has no output reference");
}
const outName = row.outputRefs[0].split("/").pop() as string;
const dl = await testApp.app.inject({
method: "GET",
url: `/api/v1/download/${jobId}/${encodeURIComponent(outName)}`,
@@ -116,28 +119,7 @@ describe.skipIf(!ffmpegAvailable())("merge-videos (requires ffmpeg)", () => {
body,
});
// merge-videos has executionHint "long", so 202 is returned immediately.
// The worker then fails with InputValidationError. Poll for the failure.
expect(res.statusCode).toBe(202);
const { jobId } = JSON.parse(res.body);
expect(jobId).toBeDefined();
const { db, schema } = await import("../../../../apps/api/src/db/index.js");
const { eq } = await import("drizzle-orm");
let row: { status: string; error: unknown } | undefined;
for (let i = 0; i < 60; i++) {
[row] = await db
.select({ status: schema.jobs.status, error: schema.jobs.error })
.from(schema.jobs)
.where(eq(schema.jobs.id, jobId));
if (row && ["completed", "failed", "canceled"].includes(row.status)) break;
await new Promise((r) => setTimeout(r, 500));
}
// Observed behavior: 202 (async) -> job status "failed" with error message.
// The plan noted "400/422" but long-hint tools skip the sync window.
expect(row?.status).toBe("failed");
const error = row?.error as { message?: string } | null;
expect(error?.message).toMatch(/at least two/i);
expect(res.statusCode).toBe(400);
expect(JSON.parse(res.body).error).toMatch(/at least 2 files/i);
}, 60_000);
});
@@ -94,10 +94,8 @@ describe.skipIf(!ffmpegAvailable())("replace-audio (requires ffmpeg)", () => {
body,
});
// Fast-hint tool: processV2 checks input count and throws,
// caught by the factory's generic catch -> 422.
expect(res.statusCode).toBe(422);
expect(res.statusCode).toBe(400);
const parsed = JSON.parse(res.body);
expect(parsed.details).toMatch(/video and an audio/i);
expect(parsed.error).toMatch(/at least 2 files/i);
}, 60_000);
});
@@ -1,6 +1,11 @@
import { mkdtemp, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { ffmpegAvailable } from "@snapotter/media-engine";
import sharp from "sharp";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { InputValidationError } from "../../../../apps/api/src/modality/contract.js";
import { getToolConfig } from "../../../../apps/api/src/routes/tool-factory.js";
import { fixtures, readFixture } from "../../../fixtures/index.js";
import {
buildTestApp,
@@ -36,6 +41,48 @@ async function pollJob(jobId: string) {
}
describe.skipIf(!ffmpegAvailable())("video-to-gif (requires ffmpeg)", () => {
it("normalizes sub-microsecond offsets instead of emitting exponential ffmpeg syntax", async () => {
const config = getToolConfig("video-to-gif");
if (!config?.processV2) throw new Error("video-to-gif processV2 must be registered");
const scratchDir = await mkdtemp(join(tmpdir(), "snapotter-video-to-gif-test-"));
try {
const result = await config.processV2({
inputs: [{ buffer: MP4, filename: "tiny.mp4", ref: "test/tiny.mp4" }],
settings: { fps: 1, width: 120, startS: Number.MIN_VALUE, durationS: 1 },
scratchDir,
signal: new AbortController().signal,
report: () => undefined,
});
if (!result.scratchPath) throw new Error("video-to-gif must return a scratch path");
const output = await readFile(result.scratchPath);
expect(output.subarray(0, 4).toString("ascii")).toBe("GIF8");
} finally {
await rm(scratchDir, { recursive: true, force: true });
}
});
it("rejects a start time beyond the video instead of running an empty encode", async () => {
const config = getToolConfig("video-to-gif");
if (!config?.processV2) throw new Error("video-to-gif processV2 must be registered");
const processV2 = config.processV2;
const scratchDir = await mkdtemp(join(tmpdir(), "snapotter-video-to-gif-test-"));
try {
await expect(
processV2({
inputs: [{ buffer: MP4, filename: "tiny.mp4", ref: "test/tiny.mp4" }],
settings: { fps: 1, width: 672, startS: 2, durationS: 1 },
scratchDir,
signal: new AbortController().signal,
report: () => undefined,
}),
).rejects.toBeInstanceOf(InputValidationError);
} finally {
await rm(scratchDir, { recursive: true, force: true });
}
});
it("returns 202 (long hint) and produces a GIF with GIF8 magic", async () => {
const { body, contentType } = createMultipartPayload([
{ name: "file", filename: "tiny.mp4", contentType: "video/mp4", content: MP4 },