mirror of
https://github.com/software-mansion/argent.git
synced 2026-09-14 19:27:14 +08:00
c52f2dba9e
Fixes #617. ## Reproduced three ways **The reported false green**, using an image whose 2× downscale is lossless so no resampling noise can mask it: ``` baseline 800x1600 current 400x800 (exact half) → status: unchanged pixel_mismatch: 0% (size difference never mentioned) ``` **Worse on real screenshots** — a 1152×648 capture vs its aspect-preserving half: ``` → status: changed pixel_mismatch: 0.35% changed_areas: 8 Text changes: Disappeared "General" / Appeared "Remotes and Devices" ``` The content is identical; every region and both OCR "text changes" are resampling artifacts. So the tool doesn't merely stay silent about the size difference — it manufactures a plausible-looking regression report out of noise. **The control shows the asymmetry is the bug** — aspect-*breaking* correctly reports `dimension_mismatch: expected=1,152x648 actual=1,152x400`. Sizes are disclosed exactly when the tool refuses to compare, and never when it silently rescales. ## The fix `PngDiffResult` gains `sizeNormalization` (both original sizes plus the size compared at), populated only when a rescale actually happened — so its presence *is* the signal that the comparison carries resampling uncertainty. The summary prints it directly under the status: ``` - status: resized_no_change - size_normalized: baseline=800x1,600 current=400x800 compared_at=400x800 - the inputs share an aspect ratio but not a resolution, so the larger was downscaled before comparing; any pixel or text differences below may include resampling artifacts, and the diff images are at compared_at rather than full size - re-capture the baseline at the same scale as the current image (screenshot with scale: 1.0) to compare without resampling ``` **`resized_no_change` is checked last**, after the difference checks, so a rescaled comparison that *did* find something is still a plain `changed` — a caveat status must never soften a real regression. There's a test pinning that ordering specifically. **The name matters.** `unchanged_after_resize` contains `"unchanged"`, so the one naive gate this protects — `summary.includes("status: unchanged")` — would still read it green. `resized_no_change` contains neither `"unchanged"` nor `"changed"`. ## What I deliberately did not do **Report `dimension_mismatch` whenever sizes differ** — the issue's primary suggestion. The normalization is deliberate: `screenshot-diff/index.ts:292-294` states that same-aspect normalization *"keeps a scaled capture diff-compatible with a baseline saved at any scale"*. The `screenshot` tool defaults to **0.3** for iOS/Android while the diff's live capture is full-res, and on Android the live side falls back to the default scale when full-res capture fails. Hard-failing would break the case this code exists for. **Expose the internal `normalizeSizes` flag.** `screenshot-diff-tool.test.ts:10-23` is titled *"rejects public tuning options so defaults stay internal"* and asserts exactly this kind of param is refused. And the better remedy is the one the summary now gives — re-capture the baseline at the same scale, which the skill already instructs and which removes the resampling rather than reporting it. Worth reconsidering separately if a user actually wants "green means byte-identical". *(An earlier draft proposed exposing it via `z.coerce.boolean()`. Worth recording why that was dropped beyond the posture conflict: in zod, `z.coerce.boolean("false")` is **`true`** — so a user asking for strict comparison would have silently got normalization anyway, re-creating this exact bug through the fix's own escape hatch.)* **Suppress the OCR noise.** Text analysis runs on each *original file at its own resolution* and only rescales the resulting bounds, so a diff-time filter cannot separate "OCR read a 576px image badly" from a real text change. Suppressing it whenever normalization occurred would silence text analysis on every scaled comparison — a new, worse false green of exactly the class this issue is about. Disclosure is the honest treatment; running OCR on the normalized pair is a separate change to `text-diff`'s contract. ## Tests Three new cases plus three strengthened ones: the false green now discloses and no longer reads `unchanged`; a normalized comparison with a real change still reports `changed` *and* still discloses; equal sizes say nothing; and the retina case still compares rather than hard-failing. Mutation-verified both halves — removing the status fails the #617 regression test; moving its check before the difference checks fails the ordering test. Full tool-server suite green — 3089 passed. No existing assertion needed changing, which is also why this survived: nothing pinned it. ## Notes for the reviewer - The flow snapshot path is untouched and **cannot** reach normalization: full-screen baselines key on the capture's own pixel dimensions (`flow-visual.ts:212`), so a differently-sized capture misses the baseline entirely and fails; `cropOn` diffs already pass `normalizeSizes: false`. - `SummaryStatus` is unexported and nothing switches on it — the status reaches the outside only as text inside `summary`, which the MCP layer passes through verbatim. No skill doc, flow assertion or e2e script matches on a status string. - The diff artifacts were already produced at the normalized size; that was simply never stated. The caveat now says so.
588 lines
22 KiB
TypeScript
588 lines
22 KiB
TypeScript
import fs from "fs/promises";
|
|
import os from "os";
|
|
import path from "path";
|
|
import { PNG } from "pngjs";
|
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { diffPngFiles, type Rgb } from "../src/tools/screenshot-diff/screenshot-diff";
|
|
|
|
const analyzeScreenshotTextChangesMock = vi.hoisted(() =>
|
|
vi.fn(async () => ({
|
|
status: "ok" as const,
|
|
provider: "ocr" as const,
|
|
changes: [],
|
|
}))
|
|
);
|
|
|
|
vi.mock("../src/tools/screenshot-diff/text-diff", async (importOriginal) => {
|
|
const actual = await importOriginal<typeof import("../src/tools/screenshot-diff/text-diff")>();
|
|
return {
|
|
...actual,
|
|
analyzeScreenshotTextChanges: analyzeScreenshotTextChangesMock,
|
|
};
|
|
});
|
|
|
|
interface Pixel {
|
|
x: number;
|
|
y: number;
|
|
rgb: Rgb;
|
|
}
|
|
|
|
describe("diffPngFiles", () => {
|
|
beforeEach(() => {
|
|
analyzeScreenshotTextChangesMock.mockReset();
|
|
analyzeScreenshotTextChangesMock.mockResolvedValue({
|
|
status: "ok",
|
|
provider: "ocr",
|
|
changes: [],
|
|
});
|
|
});
|
|
|
|
it("reports matching PNGs and writes full-size and context diff artifacts", async () => {
|
|
const dir = await makeTempDir();
|
|
const baselinePath = path.join(dir, "baseline.png");
|
|
const currentPath = path.join(dir, "current.png");
|
|
await writePng(baselinePath, 10, 10, { r: 100, g: 120, b: 140 });
|
|
await writePng(currentPath, 10, 10, { r: 100, g: 120, b: 140 });
|
|
|
|
const result = await diffPngFiles({ baselinePath, currentPath, outputDir: dir });
|
|
|
|
expect(result).toMatchObject({
|
|
totalPixels: 100,
|
|
differentPixels: 0,
|
|
mismatchPercentage: 0,
|
|
summary: expect.stringContaining("Screenshot diff summary"),
|
|
imageSize: { width: 10, height: 10 },
|
|
regions: [],
|
|
});
|
|
expect(result.diffPath).toBe(path.join(dir, "current-diff.png"));
|
|
expect(result.contextDiffPath).toBe(path.join(dir, "current-context-diff.png"));
|
|
|
|
const diff = PNG.sync.read(await fs.readFile(result.diffPath!));
|
|
expect(diff.width).toBe(10);
|
|
expect(diff.height).toBe(10);
|
|
expect(readRgb(diff, 0, 0)).toEqual({ r: 170, g: 181, b: 192 });
|
|
|
|
const contextDiff = PNG.sync.read(await fs.readFile(result.contextDiffPath!));
|
|
expect(contextDiff.width).toBe(3);
|
|
expect(contextDiff.height).toBe(3);
|
|
});
|
|
|
|
it("uses the hardcoded normalized threshold", async () => {
|
|
const dir = await makeTempDir();
|
|
const baselinePath = path.join(dir, "baseline.png");
|
|
const belowThresholdPath = path.join(dir, "below.png");
|
|
const aboveThresholdPath = path.join(dir, "above.png");
|
|
await writePng(baselinePath, 1, 20, { r: 0, g: 0, b: 0 });
|
|
await writePng(belowThresholdPath, 1, 20, { r: 0, g: 0, b: 0 }, [
|
|
{ x: 0, y: 10, rgb: { r: 25, g: 25, b: 25 } },
|
|
]);
|
|
await writePng(aboveThresholdPath, 1, 20, { r: 0, g: 0, b: 0 }, [
|
|
{ x: 0, y: 10, rgb: { r: 26, g: 26, b: 26 } },
|
|
]);
|
|
|
|
await expect(
|
|
diffPngFiles({ baselinePath, currentPath: belowThresholdPath, outputDir: dir })
|
|
).resolves.toMatchObject({ differentPixels: 0 });
|
|
await expect(
|
|
diffPngFiles({ baselinePath, currentPath: aboveThresholdPath, outputDir: dir })
|
|
).resolves.toMatchObject({ differentPixels: 1 });
|
|
});
|
|
|
|
it("returns dimension mismatch details without writing diff artifacts", async () => {
|
|
const dir = await makeTempDir();
|
|
const baselinePath = path.join(dir, "baseline.png");
|
|
const currentPath = path.join(dir, "current.png");
|
|
await writePng(baselinePath, 2, 1, { r: 0, g: 0, b: 0 });
|
|
await writePng(currentPath, 1, 2, { r: 0, g: 0, b: 0 });
|
|
|
|
const result = await diffPngFiles({ baselinePath, currentPath, outputDir: dir });
|
|
|
|
expect(result).toMatchObject({
|
|
totalPixels: 2,
|
|
differentPixels: 0,
|
|
mismatchPercentage: 0,
|
|
summary: expect.stringContaining("dimension_mismatch: expected=2x1 actual=1x2"),
|
|
dimensionMismatch: {
|
|
expected: { width: 2, height: 1 },
|
|
actual: { width: 1, height: 2 },
|
|
},
|
|
regions: [],
|
|
textAnalysis: { status: "skipped", provider: "ocr", changes: [] },
|
|
});
|
|
expect(result.diffPath).toBeUndefined();
|
|
expect(result.contextDiffPath).toBeUndefined();
|
|
});
|
|
|
|
it("compares same-aspect screenshots of different resolutions instead of failing", async () => {
|
|
const dir = await makeTempDir();
|
|
const baselinePath = path.join(dir, "baseline.png");
|
|
const currentPath = path.join(dir, "current.png");
|
|
// Same aspect ratio (0.5), different scale: a 0.3x-style saved baseline vs a
|
|
// full-res live capture. These must be normalized and compared, not rejected.
|
|
await writePng(baselinePath, 10, 20, { r: 30, g: 60, b: 90 });
|
|
await writePng(currentPath, 20, 40, { r: 30, g: 60, b: 90 });
|
|
|
|
const result = await diffPngFiles({ baselinePath, currentPath, outputDir: dir });
|
|
|
|
expect(result.dimensionMismatch).toBeUndefined();
|
|
expect(result.summary).not.toContain("dimension_mismatch");
|
|
// …but the rescale is now disclosed rather than absorbed silently.
|
|
expect(result.sizeNormalization).toBeDefined();
|
|
expect(result.imageSize).toEqual({ width: 10, height: 20 });
|
|
expect(result.diffPath).toBe(path.join(dir, "current-diff.png"));
|
|
const diff = PNG.sync.read(await fs.readFile(result.diffPath!));
|
|
expect(diff.width).toBe(10);
|
|
expect(diff.height).toBe(20);
|
|
});
|
|
|
|
it("does not call a rescaled comparison `unchanged` (issue #617)", async () => {
|
|
const dir = await makeTempDir();
|
|
const baselinePath = path.join(dir, "baseline.png");
|
|
const currentPath = path.join(dir, "current.png");
|
|
// A solid fill downscales to the identical colour under Lanczos3, so this is
|
|
// a genuine zero-diff — the false green exactly as reported: same aspect,
|
|
// different resolution, nothing said about it.
|
|
await writePng(baselinePath, 20, 40, { r: 30, g: 60, b: 90 });
|
|
await writePng(currentPath, 10, 20, { r: 30, g: 60, b: 90 });
|
|
|
|
const result = await diffPngFiles({ baselinePath, currentPath, outputDir: dir });
|
|
|
|
expect(result.differentPixels).toBe(0);
|
|
expect(result.dimensionMismatch).toBeUndefined();
|
|
expect(result.sizeNormalization).toEqual({
|
|
baseline: { width: 20, height: 40 },
|
|
current: { width: 10, height: 20 },
|
|
comparedAt: { width: 10, height: 20 },
|
|
});
|
|
// A gate reading the status must not see a plain pass.
|
|
expect(result.summary).toContain("- status: resized_no_change");
|
|
expect(result.summary).not.toContain("- status: unchanged");
|
|
expect(result.summary).toContain(
|
|
"- size_normalized: baseline=20x40 current=10x20 compared_at=10x20"
|
|
);
|
|
});
|
|
|
|
it("still reports a real difference as `changed` when sizes were normalized", async () => {
|
|
const dir = await makeTempDir();
|
|
const baselinePath = path.join(dir, "baseline.png");
|
|
const currentPath = path.join(dir, "current.png");
|
|
// The caveat must never soften an actual regression into a caveat status —
|
|
// this pins the ordering inside screenshotDiffStatus.
|
|
await writePng(baselinePath, 20, 40, { r: 20, g: 20, b: 20 });
|
|
await writePng(currentPath, 10, 20, { r: 20, g: 20, b: 20 }, [
|
|
// Clear of the ignored top band (ceil(20 * 0.06) = 2 rows).
|
|
...rectPixels(2, 12, 4, 4, { r: 255, g: 0, b: 0 }),
|
|
]);
|
|
|
|
const result = await diffPngFiles({ baselinePath, currentPath, outputDir: dir });
|
|
|
|
expect(result.differentPixels).toBeGreaterThan(0);
|
|
expect(result.summary).toContain("- status: changed");
|
|
// …and the rescale is still disclosed, so the figures can be read correctly.
|
|
expect(result.summary).toContain("- size_normalized:");
|
|
});
|
|
|
|
it("says nothing about normalization when the sizes already matched", async () => {
|
|
const dir = await makeTempDir();
|
|
const baselinePath = path.join(dir, "baseline.png");
|
|
const currentPath = path.join(dir, "current.png");
|
|
await writePng(baselinePath, 10, 20, { r: 30, g: 60, b: 90 });
|
|
await writePng(currentPath, 10, 20, { r: 30, g: 60, b: 90 });
|
|
|
|
const result = await diffPngFiles({ baselinePath, currentPath, outputDir: dir });
|
|
|
|
expect(result.sizeNormalization).toBeUndefined();
|
|
expect(result.summary).not.toContain("size_normalized");
|
|
expect(result.summary).toContain("- status: unchanged");
|
|
});
|
|
|
|
it("hard-fails same-aspect resolution differences when normalizeSizes is false", async () => {
|
|
const dir = await makeTempDir();
|
|
const baselinePath = path.join(dir, "baseline.png");
|
|
const currentPath = path.join(dir, "current.png");
|
|
// Exactly 2x with the same aspect ratio — the default path (test above)
|
|
// resamples and compares; normalizeSizes: false must bail instead, since
|
|
// for images whose dimensions carry meaning the drift IS the failure.
|
|
await writePng(baselinePath, 10, 20, { r: 30, g: 60, b: 90 });
|
|
await writePng(currentPath, 20, 40, { r: 30, g: 60, b: 90 });
|
|
|
|
const result = await diffPngFiles({
|
|
baselinePath,
|
|
currentPath,
|
|
outputDir: dir,
|
|
normalizeSizes: false,
|
|
});
|
|
|
|
expect(result).toMatchObject({
|
|
mismatchPercentage: 0,
|
|
dimensionMismatch: {
|
|
expected: { width: 10, height: 20 },
|
|
actual: { width: 20, height: 40 },
|
|
},
|
|
});
|
|
expect(result.diffPath).toBeUndefined();
|
|
expect(result.contextDiffPath).toBeUndefined();
|
|
});
|
|
|
|
it("compares equal-dimension images normally under normalizeSizes: false", async () => {
|
|
const dir = await makeTempDir();
|
|
const baselinePath = path.join(dir, "baseline.png");
|
|
const currentPath = path.join(dir, "current.png");
|
|
// The pass path every matching cropOn comparison takes: identical
|
|
// dimensions must flow through to a normal pixel compare, not a bail.
|
|
await writePng(baselinePath, 10, 20, { r: 30, g: 60, b: 90 });
|
|
await writePng(currentPath, 10, 20, { r: 30, g: 60, b: 90 }, [
|
|
...rectPixels(2, 10, 3, 2, { r: 255, g: 0, b: 0 }),
|
|
]);
|
|
|
|
const result = await diffPngFiles({
|
|
baselinePath,
|
|
currentPath,
|
|
outputDir: dir,
|
|
topMask: "none",
|
|
normalizeSizes: false,
|
|
});
|
|
|
|
expect(result.dimensionMismatch).toBeUndefined();
|
|
expect(result.differentPixels).toBe(6);
|
|
expect(result.diffPath).toBe(path.join(dir, "current-diff.png"));
|
|
});
|
|
|
|
it("merges same-line fragments but keeps separate rows distinct", async () => {
|
|
const dir = await makeTempDir();
|
|
const baselinePath = path.join(dir, "baseline.png");
|
|
const sameLinePath = path.join(dir, "same-line.png");
|
|
const rowsPath = path.join(dir, "rows.png");
|
|
await writePng(baselinePath, 80, 40, { r: 0, g: 0, b: 0 });
|
|
await writePng(sameLinePath, 80, 40, { r: 0, g: 0, b: 0 }, [
|
|
...rectPixels(4, 12, 10, 8, { r: 255, g: 0, b: 0 }),
|
|
...rectPixels(30, 12, 10, 8, { r: 255, g: 0, b: 0 }),
|
|
...rectPixels(55, 12, 10, 8, { r: 255, g: 0, b: 0 }),
|
|
]);
|
|
await writePng(rowsPath, 80, 40, { r: 0, g: 0, b: 0 }, [
|
|
...rectPixels(4, 4, 10, 8, { r: 255, g: 0, b: 0 }),
|
|
...rectPixels(24, 26, 10, 8, { r: 255, g: 0, b: 0 }),
|
|
]);
|
|
|
|
const sameLine = await diffPngFiles({
|
|
baselinePath,
|
|
currentPath: sameLinePath,
|
|
outputDir: dir,
|
|
});
|
|
const rows = await diffPngFiles({ baselinePath, currentPath: rowsPath, outputDir: dir });
|
|
|
|
expect(sameLine.regions).toHaveLength(1);
|
|
expect(sameLine.regions[0]).toMatchObject({
|
|
bounds: { x: 4, y: 12, width: 61, height: 8 },
|
|
pixelCount: 240,
|
|
});
|
|
expect(rows.regions).toHaveLength(2);
|
|
});
|
|
|
|
it("reports average colors and dominant luminance shifts per region", async () => {
|
|
const dir = await makeTempDir();
|
|
const baselinePath = path.join(dir, "baseline.png");
|
|
const currentPath = path.join(dir, "current.png");
|
|
await writePng(baselinePath, 2, 20, { r: 0, g: 0, b: 0 }, [
|
|
{ x: 0, y: 10, rgb: { r: 20, g: 40, b: 60 } },
|
|
{ x: 1, y: 10, rgb: { r: 20, g: 40, b: 60 } },
|
|
]);
|
|
await writePng(currentPath, 2, 20, { r: 0, g: 0, b: 0 }, [
|
|
{ x: 0, y: 10, rgb: { r: 80, g: 100, b: 120 } },
|
|
{ x: 1, y: 10, rgb: { r: 80, g: 100, b: 120 } },
|
|
]);
|
|
|
|
const result = await diffPngFiles({ baselinePath, currentPath, outputDir: dir });
|
|
|
|
expect(result).toMatchObject({
|
|
differentPixels: 2,
|
|
regions: [
|
|
{
|
|
bounds: { x: 0, y: 10, width: 2, height: 1 },
|
|
pixelCount: 2,
|
|
averageColor: {
|
|
delta: { r: 60, g: 60, b: 60 },
|
|
dominantChange: { channel: "luminance", direction: "increase", magnitude: 60 },
|
|
},
|
|
},
|
|
],
|
|
});
|
|
});
|
|
|
|
it("draws region rectangles and ignores changed pixels in the status-bar band", async () => {
|
|
const dir = await makeTempDir();
|
|
const baselinePath = path.join(dir, "baseline.png");
|
|
const currentPath = path.join(dir, "current.png");
|
|
await writePng(baselinePath, 12, 100, { r: 20, g: 20, b: 20 });
|
|
await writePng(currentPath, 12, 100, { r: 20, g: 20, b: 20 }, [
|
|
...rectPixels(0, 0, 12, 6, { r: 240, g: 240, b: 240 }),
|
|
...rectPixels(4, 20, 4, 4, { r: 255, g: 0, b: 0 }),
|
|
]);
|
|
|
|
const result = await diffPngFiles({
|
|
baselinePath,
|
|
currentPath,
|
|
outputDir: dir,
|
|
topMask: "status-bar",
|
|
});
|
|
|
|
expect(result.regions).toEqual([
|
|
expect.objectContaining({
|
|
bounds: { x: 4, y: 20, width: 4, height: 4 },
|
|
pixelCount: 16,
|
|
}),
|
|
]);
|
|
const diff = PNG.sync.read(await fs.readFile(result.diffPath!));
|
|
expect(readRgb(diff, 0, 0)).toEqual({ r: 247, g: 247, b: 247 });
|
|
expect(readRgb(diff, 4, 17)).toEqual({ r: 255, g: 220, b: 0 });
|
|
expect(readRgb(diff, 5, 21)).toEqual({ r: 0, g: 200, b: 0 });
|
|
});
|
|
|
|
it("compares the full image when the top mask is disabled", async () => {
|
|
const dir = await makeTempDir();
|
|
const baselinePath = path.join(dir, "baseline.png");
|
|
const currentPath = path.join(dir, "current.png");
|
|
await writePng(baselinePath, 12, 100, { r: 20, g: 20, b: 20 });
|
|
await writePng(
|
|
currentPath,
|
|
12,
|
|
100,
|
|
{ r: 20, g: 20, b: 20 },
|
|
rectPixels(0, 0, 12, 6, { r: 240, g: 240, b: 240 })
|
|
);
|
|
|
|
const result = await diffPngFiles({
|
|
baselinePath,
|
|
currentPath,
|
|
outputDir: dir,
|
|
topMask: "none",
|
|
});
|
|
|
|
expect(result).toMatchObject({
|
|
differentPixels: 72,
|
|
mismatchPercentage: 6,
|
|
regions: [
|
|
expect.objectContaining({
|
|
bounds: { x: 0, y: 0, width: 12, height: 6 },
|
|
pixelCount: 72,
|
|
}),
|
|
],
|
|
});
|
|
expect(analyzeScreenshotTextChangesMock).toHaveBeenCalledWith(
|
|
expect.objectContaining({ ignoreTopPixels: 0 })
|
|
);
|
|
});
|
|
|
|
it("does not mask an entire one-row image when the top mask is disabled", async () => {
|
|
const dir = await makeTempDir();
|
|
const baselinePath = path.join(dir, "baseline.png");
|
|
const currentPath = path.join(dir, "current.png");
|
|
await writePng(baselinePath, 2, 1, { r: 0, g: 0, b: 0 });
|
|
await writePng(currentPath, 2, 1, { r: 255, g: 255, b: 255 });
|
|
|
|
const masked = await diffPngFiles({ baselinePath, currentPath, outputDir: dir });
|
|
const unmasked = await diffPngFiles({
|
|
baselinePath,
|
|
currentPath,
|
|
outputDir: dir,
|
|
topMask: "none",
|
|
});
|
|
|
|
expect(masked).toMatchObject({ differentPixels: 0, mismatchPercentage: 0 });
|
|
expect(unmasked).toMatchObject({ differentPixels: 2, mismatchPercentage: 100 });
|
|
});
|
|
|
|
it("colors changed pixels green when they brightened and red when they darkened", async () => {
|
|
const dir = await makeTempDir();
|
|
const baselinePath = path.join(dir, "baseline.png");
|
|
const currentPath = path.join(dir, "current.png");
|
|
await writePng(baselinePath, 30, 60, { r: 20, g: 20, b: 20 }, [
|
|
...rectPixels(2, 20, 10, 10, { r: 240, g: 240, b: 240 }),
|
|
]);
|
|
await writePng(currentPath, 30, 60, { r: 20, g: 20, b: 20 }, [
|
|
...rectPixels(18, 20, 10, 10, { r: 240, g: 240, b: 240 }),
|
|
]);
|
|
|
|
const result = await diffPngFiles({ baselinePath, currentPath, outputDir: dir });
|
|
|
|
const diff = PNG.sync.read(await fs.readFile(result.diffPath!));
|
|
|
|
expect(readRgb(diff, 6, 24)).toEqual({ r: 255, g: 0, b: 0 });
|
|
expect(readRgb(diff, 22, 24)).toEqual({ r: 0, g: 200, b: 0 });
|
|
});
|
|
|
|
it("keeps pixel diff artifacts when text analysis fails unexpectedly", async () => {
|
|
analyzeScreenshotTextChangesMock.mockRejectedValueOnce(new Error("ocr crashed"));
|
|
const dir = await makeTempDir();
|
|
const baselinePath = path.join(dir, "baseline.png");
|
|
const currentPath = path.join(dir, "current.png");
|
|
await writePng(baselinePath, 2, 20, { r: 0, g: 0, b: 0 });
|
|
await writePng(currentPath, 2, 20, { r: 0, g: 0, b: 0 }, [
|
|
{ x: 1, y: 10, rgb: { r: 255, g: 0, b: 0 } },
|
|
]);
|
|
|
|
const result = await diffPngFiles({ baselinePath, currentPath, outputDir: dir });
|
|
|
|
expect(result).toMatchObject({
|
|
differentPixels: 1,
|
|
textAnalysis: { status: "unavailable", provider: "ocr", changes: [] },
|
|
});
|
|
await expect(fs.stat(result.diffPath!)).resolves.toMatchObject({ size: expect.any(Number) });
|
|
await expect(fs.stat(result.contextDiffPath!)).resolves.toMatchObject({
|
|
size: expect.any(Number),
|
|
});
|
|
});
|
|
|
|
it("passes the default text-change minimum confidence to OCR analysis", async () => {
|
|
const dir = await makeTempDir();
|
|
const baselinePath = path.join(dir, "baseline.png");
|
|
const currentPath = path.join(dir, "current.png");
|
|
await writePng(baselinePath, 2, 20, { r: 0, g: 0, b: 0 });
|
|
await writePng(currentPath, 2, 20, { r: 0, g: 0, b: 0 }, [
|
|
{ x: 1, y: 10, rgb: { r: 255, g: 0, b: 0 } },
|
|
]);
|
|
|
|
await diffPngFiles({ baselinePath, currentPath, outputDir: dir });
|
|
|
|
expect(analyzeScreenshotTextChangesMock).toHaveBeenCalledWith(
|
|
expect.objectContaining({ textChangeMinConfidence: 0.7, ignoreTopPixels: 2 })
|
|
);
|
|
});
|
|
|
|
// diffPngFiles normalizes two same-aspect, different-resolution screenshots to a
|
|
// common size, then hands the OCR/font pass BOTH the normalized images and each
|
|
// image's decoded->normalized region scale, so the rescaled text bounds and the
|
|
// pixels they crop share the pixel-diff coordinate space. normalizeToCommonSize
|
|
// only ever downscales the LARGER image and returns the smaller one untouched, so
|
|
// for any one fixture only the downscaled side's wiring is load-bearing: its
|
|
// normalized image and region scale differ from the raw decoded ones, so reverting
|
|
// baselineImage/currentImage (or the matching region scale) to the decoded value
|
|
// would surface the raw size and fail here. The untouched side's assertions hold
|
|
// for both the decoded and normalized value, so we exercise BOTH directions to pin
|
|
// both sides. Without this wiring the OCR pass would be handed the raw images and
|
|
// no region scales -- the mismatch #442 fixed.
|
|
it.each([
|
|
{
|
|
larger: "baseline",
|
|
baseline: { width: 480, height: 240 },
|
|
current: { width: 240, height: 120 },
|
|
baselineRegionScale: { x: 0.5, y: 0.5 },
|
|
currentRegionScale: { x: 1, y: 1 },
|
|
},
|
|
{
|
|
larger: "current",
|
|
baseline: { width: 240, height: 120 },
|
|
current: { width: 480, height: 240 },
|
|
baselineRegionScale: { x: 1, y: 1 },
|
|
currentRegionScale: { x: 0.5, y: 0.5 },
|
|
},
|
|
])(
|
|
"hands OCR the normalized images and decoded->normalized region scales when the $larger image is downscaled (diffPngFiles wiring)",
|
|
async ({ baseline, current, baselineRegionScale, currentRegionScale }) => {
|
|
const dir = await makeTempDir();
|
|
const baselinePath = path.join(dir, "baseline.png");
|
|
const currentPath = path.join(dir, "current.png");
|
|
await writePng(baselinePath, baseline.width, baseline.height, { r: 0, g: 0, b: 0 });
|
|
await writePng(currentPath, current.width, current.height, { r: 0, g: 0, b: 0 });
|
|
|
|
await diffPngFiles({ baselinePath, currentPath, outputDir: dir });
|
|
|
|
// Both images are normalized to the common 240x120 size; each region scale
|
|
// maps that image's OCR bounds from its decoded size into the shared space.
|
|
expect(analyzeScreenshotTextChangesMock).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
baselineImage: expect.objectContaining({ width: 240, height: 120 }),
|
|
currentImage: expect.objectContaining({ width: 240, height: 120 }),
|
|
baselineRegionScale,
|
|
currentRegionScale,
|
|
})
|
|
);
|
|
}
|
|
);
|
|
|
|
// diffPngFiles always calls the OCR/font pass, but tells it whether the pixel diff
|
|
// found any changes via hasPixelDiff; the pass uses that to skip text analysis when
|
|
// nothing moved. Pin the wiring in both directions -- identical images -> false, a
|
|
// real pixel change -> true -- so hardcoding the source (e.g. to false, which would
|
|
// silently disable text analysis for every real diff) fails here instead of staying
|
|
// green.
|
|
it.each([
|
|
{ name: "no pixel diff", changePixel: false, expected: false },
|
|
{ name: "a pixel diff", changePixel: true, expected: true },
|
|
])(
|
|
"tells OCR whether the pixel diff found changes ($name -> hasPixelDiff=$expected)",
|
|
async ({ changePixel, expected }) => {
|
|
const dir = await makeTempDir();
|
|
const baselinePath = path.join(dir, "baseline.png");
|
|
const currentPath = path.join(dir, "current.png");
|
|
await writePng(baselinePath, 2, 20, { r: 0, g: 0, b: 0 });
|
|
await writePng(
|
|
currentPath,
|
|
2,
|
|
20,
|
|
{ r: 0, g: 0, b: 0 },
|
|
changePixel ? [{ x: 1, y: 10, rgb: { r: 255, g: 0, b: 0 } }] : []
|
|
);
|
|
|
|
await diffPngFiles({ baselinePath, currentPath, outputDir: dir });
|
|
|
|
expect(analyzeScreenshotTextChangesMock).toHaveBeenCalledWith(
|
|
expect.objectContaining({ hasPixelDiff: expected })
|
|
);
|
|
}
|
|
);
|
|
});
|
|
|
|
async function makeTempDir(): Promise<string> {
|
|
return fs.mkdtemp(path.join(os.tmpdir(), "argent-screenshot-diff-"));
|
|
}
|
|
|
|
async function writePng(
|
|
filePath: string,
|
|
width: number,
|
|
height: number,
|
|
fill: Rgb,
|
|
pixels: Pixel[] = []
|
|
): Promise<void> {
|
|
const png = new PNG({ width, height });
|
|
|
|
for (let y = 0; y < height; y++) {
|
|
for (let x = 0; x < width; x++) {
|
|
writeRgb(png, x, y, fill);
|
|
}
|
|
}
|
|
|
|
for (const pixel of pixels) {
|
|
writeRgb(png, pixel.x, pixel.y, pixel.rgb);
|
|
}
|
|
|
|
await fs.writeFile(filePath, PNG.sync.write(png));
|
|
}
|
|
|
|
function rectPixels(x: number, y: number, width: number, height: number, rgb: Rgb): Pixel[] {
|
|
const pixels: Pixel[] = [];
|
|
for (let py = y; py < y + height; py++) {
|
|
for (let px = x; px < x + width; px++) {
|
|
pixels.push({ x: px, y: py, rgb });
|
|
}
|
|
}
|
|
return pixels;
|
|
}
|
|
|
|
function writeRgb(png: PNG, x: number, y: number, rgb: Rgb): void {
|
|
const offset = (png.width * y + x) * 4;
|
|
png.data[offset] = rgb.r;
|
|
png.data[offset + 1] = rgb.g;
|
|
png.data[offset + 2] = rgb.b;
|
|
png.data[offset + 3] = 255;
|
|
}
|
|
|
|
function readRgb(png: PNG, x: number, y: number): Rgb {
|
|
const offset = (png.width * y + x) * 4;
|
|
return {
|
|
r: png.data[offset],
|
|
g: png.data[offset + 1],
|
|
b: png.data[offset + 2],
|
|
};
|
|
}
|