High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat: add pure-go visual diff engine with annotated diff images
Luigi Agosti17570aa58083
diff --git a/internal/audit/visualdiff/annotate.go b/internal/audit/visualdiff/annotate.gonew file mode 100644index 00000000..bc943be9--- /dev/null+++ b/internal/audit/visualdiff/annotate.go@@ -0,0 +1,62 @@+package visualdiff++import (+ "image"+ "image/color"+ "image/draw"+ "image/png"+ "io"+)++var (+ highlight = color.RGBA{R: 0xff, A: 0xff}+ background = color.RGBA{R: 0xff, G: 0xff, B: 0xff, A: 0xff}+)++// RenderAnnotated draws baseline on a canvas sized to the compared area,+// tints every changed pixel red, and outlines each changed region. The+// output depends only on the baseline pixels and the Result, so it is+// deterministic.+func RenderAnnotated(baseline image.Image, res Result) *image.RGBA {+ canvas := image.NewRGBA(image.Rect(0, 0, res.Width, res.Height))+ draw.Draw(canvas, canvas.Bounds(), image.NewUniform(background), image.Point{}, draw.Src)+ draw.Draw(canvas, baseline.Bounds().Sub(baseline.Bounds().Min), baseline, baseline.Bounds().Min, draw.Src)++ for y := 0; y < res.Height; y++ {+ for x := 0; x < res.Width; x++ {+ if !res.mask[y*res.Width+x] {+ continue+ }+ base := canvas.RGBAAt(x, y)+ canvas.SetRGBA(x, y, color.RGBA{+ R: uint8((uint16(base.R) + uint16(highlight.R)) / 2),+ G: uint8(uint16(base.G) / 2),+ B: uint8(uint16(base.B) / 2),+ A: 0xff,+ })+ }+ }++ for _, region := range res.Regions {+ outlineRect(canvas, region)+ }+ return canvas+}++// WriteAnnotatedPNG renders the annotated diff for baseline and encodes it+// as PNG.+func WriteAnnotatedPNG(w io.Writer, baseline image.Image, res Result) error {+ return png.Encode(w, RenderAnnotated(baseline, res))+}++func outlineRect(canvas *image.RGBA, r image.Rectangle) {+ r = r.Intersect(canvas.Bounds())+ for x := r.Min.X; x < r.Max.X; x++ {+ canvas.SetRGBA(x, r.Min.Y, highlight)+ canvas.SetRGBA(x, r.Max.Y-1, highlight)+ }+ for y := r.Min.Y; y < r.Max.Y; y++ {+ canvas.SetRGBA(r.Min.X, y, highlight)+ canvas.SetRGBA(r.Max.X-1, y, highlight)+ }+}diff --git a/internal/audit/visualdiff/diff.go b/internal/audit/visualdiff/diff.gonew file mode 100644index 00000000..cca24e01--- /dev/null+++ b/internal/audit/visualdiff/diff.go@@ -0,0 +1,175 @@+// Package visualdiff compares two screenshots pixel by pixel and renders+// annotated diff images. Pure Go: stdlib image packages only, no CGO.+package visualdiff++import (+ "errors"+ "image"+ "math"+)++// DefaultTolerance is a reasonable per-pixel tolerance for screenshot+// comparison when the caller has no better value.+const DefaultTolerance = 0.1++// aaEdgeLumaDelta is the neighbor luma contrast above which a pixel is+// considered to sit on a color edge for anti-aliasing detection.+const aaEdgeLumaDelta = 0.25++// Options controls how Compare matches pixels.+type Options struct {+ // Tolerance is the normalized color distance in [0,1] at or below which+ // two pixels count as equal. The zero value compares exactly.+ Tolerance float64+ // IgnoreAntiAliasing excuses differing pixels that sit on a color edge+ // in both images, the signature of anti-aliasing artifacts.+ IgnoreAntiAliasing bool+}++// Result is the outcome of comparing two images.+//+// When the input dimensions differ, the comparison area is the union of both+// sizes (anchored at the top-left): pixels present in only one image count as+// changed, and Width/Height report the union.+type Result struct {+ // Width and Height are the dimensions of the compared area.+ Width int+ Height int+ // PixelsChanged is the number of pixels that differ.+ PixelsChanged int+ // DiffPercentage is PixelsChanged over the compared area, in [0,100].+ DiffPercentage float64+ // Regions are the bounding rectangles of 8-connected clusters of+ // changed pixels, in scan order.+ Regions []image.Rectangle++ mask []bool+}++// Compare diffs images a and b pixel by pixel. Differing dimensions are+// handled without error as documented on Result; it never panics on+// mismatched sizes.+func Compare(a, b image.Image, opts Options) (Result, error) {+ if a == nil || b == nil {+ return Result{}, errors.New("visualdiff: both images must be non-nil")+ }+ if opts.Tolerance < 0 || opts.Tolerance > 1 {+ return Result{}, errors.New("visualdiff: tolerance must be in [0,1]")+ }++ aw, ah := a.Bounds().Dx(), a.Bounds().Dy()+ bw, bh := b.Bounds().Dx(), b.Bounds().Dy()+ w, h := max(aw, bw), max(ah, bh)++ res := Result{Width: w, Height: h, mask: make([]bool, w*h)}+ for y := 0; y < h; y++ {+ for x := 0; x < w; x++ {+ inA := x < aw && y < ah+ inB := x < bw && y < bh+ if inA && inB {+ if colorDistance(pixelAt(a, x, y), pixelAt(b, x, y)) <= opts.Tolerance {+ continue+ }+ if opts.IgnoreAntiAliasing && onEdge(a, x, y) && onEdge(b, x, y) {+ continue+ }+ } else if !inA && !inB {+ continue+ }+ res.mask[y*w+x] = true+ res.PixelsChanged+++ }+ }++ if area := w * h; area > 0 {+ res.DiffPercentage = 100 * float64(res.PixelsChanged) / float64(area)+ }+ res.Regions = findRegions(res.mask, w, h)+ return res, nil+}++type pixel struct {+ r, g, b, a float64+}++func pixelAt(img image.Image, x, y int) pixel {+ r, g, b, a := img.At(img.Bounds().Min.X+x, img.Bounds().Min.Y+y).RGBA()+ return pixel{+ r: float64(r) / 0xffff,+ g: float64(g) / 0xffff,+ b: float64(b) / 0xffff,+ a: float64(a) / 0xffff,+ }+}++func colorDistance(p, q pixel) float64 {+ dr, dg, db, da := p.r-q.r, p.g-q.g, p.b-q.b, p.a-q.a+ return math.Sqrt((dr*dr + dg*dg + db*db + da*da) / 4)+}++func luma(p pixel) float64 {+ return 0.299*p.r + 0.587*p.g + 0.114*p.b+}++// onEdge reports whether the pixel at image-local (x, y) has an 8-neighbor+// with strongly contrasting luma, i.e. sits on a color edge.+func onEdge(img image.Image, x, y int) bool {+ w, h := img.Bounds().Dx(), img.Bounds().Dy()+ if x >= w || y >= h {+ return false+ }+ l := luma(pixelAt(img, x, y))+ for dy := -1; dy <= 1; dy++ {+ for dx := -1; dx <= 1; dx++ {+ if dx == 0 && dy == 0 {+ continue+ }+ nx, ny := x+dx, y+dy+ if nx < 0 || ny < 0 || nx >= w || ny >= h {+ continue+ }+ if math.Abs(luma(pixelAt(img, nx, ny))-l) > aaEdgeLumaDelta {+ return true+ }+ }+ }+ return false+}++// findRegions returns the bounding rectangle of every 8-connected cluster of+// set pixels in mask, in scan order.+func findRegions(mask []bool, w, h int) []image.Rectangle {+ var regions []image.Rectangle+ visited := make([]bool, len(mask))+ var stack []int++ for i := range mask {+ if !mask[i] || visited[i] {+ continue+ }+ bounds := image.Rect(i%w, i/w, i%w+1, i/w+1)+ visited[i] = true+ stack = append(stack[:0], i)+ for len(stack) > 0 {+ p := stack[len(stack)-1]+ stack = stack[:len(stack)-1]+ px, py := p%w, p/w+ bounds = bounds.Union(image.Rect(px, py, px+1, py+1))+ for dy := -1; dy <= 1; dy++ {+ for dx := -1; dx <= 1; dx++ {+ nx, ny := px+dx, py+dy+ if nx < 0 || ny < 0 || nx >= w || ny >= h {+ continue+ }+ n := ny*w + nx+ if mask[n] && !visited[n] {+ visited[n] = true+ stack = append(stack, n)+ }+ }+ }+ }+ regions = append(regions, bounds)+ }+ return regions+}diff --git a/internal/audit/visualdiff/testdata/annotated.golden.png b/internal/audit/visualdiff/testdata/annotated.golden.pngnew file mode 100644index 00000000..cc3004f5Binary files /dev/null and b/internal/audit/visualdiff/testdata/annotated.golden.png differdiff --git a/internal/audit/visualdiff/testdata/baseline.png b/internal/audit/visualdiff/testdata/baseline.pngnew file mode 100644index 00000000..dccf76c4Binary files /dev/null and b/internal/audit/visualdiff/testdata/baseline.png differdiff --git a/internal/audit/visualdiff/testdata/changed.png b/internal/audit/visualdiff/testdata/changed.pngnew file mode 100644index 00000000..a81d6658Binary files /dev/null and b/internal/audit/visualdiff/testdata/changed.png differdiff --git a/internal/audit/visualdiff/visualdiff_test.go b/internal/audit/visualdiff/visualdiff_test.gonew file mode 100644index 00000000..98560349--- /dev/null+++ b/internal/audit/visualdiff/visualdiff_test.go@@ -0,0 +1,252 @@+package visualdiff++import (+ "bytes"+ "flag"+ "image"+ "image/color"+ "image/draw"+ "image/png"+ "math"+ "os"+ "path/filepath"+ "testing"+)++var update = flag.Bool("update", false, "regenerate testdata fixtures and golden files")++var (+ white = color.RGBA{0xff, 0xff, 0xff, 0xff}+ blue = color.RGBA{0x20, 0x40, 0xc0, 0xff}+ red = color.RGBA{0xd0, 0x20, 0x20, 0xff}+ black = color.RGBA{0x00, 0x00, 0x00, 0xff}+ gray = color.RGBA{0x80, 0x80, 0x80, 0xff}+)++func fill(img *image.RGBA, r image.Rectangle, c color.RGBA) {+ draw.Draw(img, r, image.NewUniform(c), image.Point{}, draw.Src)+}++// makeBaseline is the source of testdata/baseline.png: white 64x64 with a+// blue square at (8,8)-(20,20).+func makeBaseline() *image.RGBA {+ img := image.NewRGBA(image.Rect(0, 0, 64, 64))+ fill(img, img.Bounds(), white)+ fill(img, image.Rect(8, 8, 20, 20), blue)+ return img+}++// makeChanged is the source of testdata/changed.png: the baseline plus a red+// square at (20,20)-(30,30) — the one known change.+func makeChanged() *image.RGBA {+ img := makeBaseline()+ fill(img, image.Rect(20, 20, 30, 30), red)+ return img+}++func writePNG(t *testing.T, path string, img image.Image) {+ t.Helper()+ var buf bytes.Buffer+ if err := png.Encode(&buf, img); err != nil {+ t.Fatalf("encode %s: %v", path, err)+ }+ if err := os.WriteFile(path, buf.Bytes(), 0o644); err != nil {+ t.Fatalf("write %s: %v", path, err)+ }+}++func loadPNG(t *testing.T, path string) image.Image {+ t.Helper()+ f, err := os.Open(path)+ if err != nil {+ t.Fatalf("open %s: %v (run `go test -update` to generate fixtures)", path, err)+ }+ defer func() { _ = f.Close() }()+ img, err := png.Decode(f)+ if err != nil {+ t.Fatalf("decode %s: %v", path, err)+ }+ return img+}++func TestMain(m *testing.M) {+ flag.Parse()+ if *update {+ regenerateTestdata()+ }+ os.Exit(m.Run())+}++func regenerateTestdata() {+ if err := os.MkdirAll("testdata", 0o755); err != nil {+ panic(err)+ }+ t := &testing.T{}+ baseline := makeBaseline()+ changed := makeChanged()+ writePNG(t, filepath.Join("testdata", "baseline.png"), baseline)+ writePNG(t, filepath.Join("testdata", "changed.png"), changed)++ res, err := Compare(baseline, changed, Options{Tolerance: 0.05})+ if err != nil {+ panic(err)+ }+ var buf bytes.Buffer+ if err := WriteAnnotatedPNG(&buf, baseline, res); err != nil {+ panic(err)+ }+ if err := os.WriteFile(filepath.Join("testdata", "annotated.golden.png"), buf.Bytes(), 0o644); err != nil {+ panic(err)+ }+}++func TestIdenticalImages(t *testing.T) {+ img := makeBaseline()+ res, err := Compare(img, img, Options{})+ if err != nil {+ t.Fatalf("Compare: %v", err)+ }+ if res.PixelsChanged != 0 {+ t.Errorf("PixelsChanged = %d, want 0", res.PixelsChanged)+ }+ if res.DiffPercentage != 0 {+ t.Errorf("DiffPercentage = %v, want 0", res.DiffPercentage)+ }+ if len(res.Regions) != 0 {+ t.Errorf("Regions = %v, want none", res.Regions)+ }+}++func TestKnownChangeGolden(t *testing.T) {+ baseline := loadPNG(t, filepath.Join("testdata", "baseline.png"))+ changed := loadPNG(t, filepath.Join("testdata", "changed.png"))++ res, err := Compare(baseline, changed, Options{Tolerance: 0.05})+ if err != nil {+ t.Fatalf("Compare: %v", err)+ }+ if res.PixelsChanged != 100 {+ t.Errorf("PixelsChanged = %d, want 100", res.PixelsChanged)+ }+ wantPct := 100 * 100.0 / (64 * 64)+ if math.Abs(res.DiffPercentage-wantPct) > 0.01 {+ t.Errorf("DiffPercentage = %v, want %v", res.DiffPercentage, wantPct)+ }+ wantRegion := image.Rect(20, 20, 30, 30)+ if len(res.Regions) != 1 || res.Regions[0] != wantRegion {+ t.Errorf("Regions = %v, want [%v]", res.Regions, wantRegion)+ }+}++func TestDifferentDimensions(t *testing.T) {+ a := image.NewRGBA(image.Rect(0, 0, 4, 4))+ fill(a, a.Bounds(), white)+ b := image.NewRGBA(image.Rect(0, 0, 4, 6))+ fill(b, b.Bounds(), white)++ res, err := Compare(a, b, Options{})+ if err != nil {+ t.Fatalf("Compare: %v", err)+ }+ if res.Width != 4 || res.Height != 6 {+ t.Errorf("compared area = %dx%d, want 4x6", res.Width, res.Height)+ }+ if res.PixelsChanged != 8 {+ t.Errorf("PixelsChanged = %d, want 8 (area present only in b)", res.PixelsChanged)+ }+ wantPct := 100 * 8.0 / 24+ if math.Abs(res.DiffPercentage-wantPct) > 0.01 {+ t.Errorf("DiffPercentage = %v, want %v", res.DiffPercentage, wantPct)+ }+ wantRegion := image.Rect(0, 4, 4, 6)+ if len(res.Regions) != 1 || res.Regions[0] != wantRegion {+ t.Errorf("Regions = %v, want [%v]", res.Regions, wantRegion)+ }+}++func TestNonZeroMinBounds(t *testing.T) {+ big := makeBaseline()+ sub, ok := big.SubImage(image.Rect(8, 8, 40, 40)).(*image.RGBA)+ if !ok {+ t.Fatal("SubImage is not *image.RGBA")+ }+ clone := image.NewRGBA(image.Rect(0, 0, 32, 32))+ draw.Draw(clone, clone.Bounds(), sub, sub.Bounds().Min, draw.Src)++ res, err := Compare(sub, clone, Options{})+ if err != nil {+ t.Fatalf("Compare: %v", err)+ }+ if res.PixelsChanged != 0 {+ t.Errorf("PixelsChanged = %d, want 0 for translated identical content", res.PixelsChanged)+ }+}++func TestNilImage(t *testing.T) {+ if _, err := Compare(nil, makeBaseline(), Options{}); err == nil {+ t.Error("Compare(nil, img) should error")+ }+ if _, err := Compare(makeBaseline(), nil, Options{}); err == nil {+ t.Error("Compare(img, nil) should error")+ }+}++func TestInvalidTolerance(t *testing.T) {+ img := makeBaseline()+ for _, tol := range []float64{-0.1, 1.5} {+ if _, err := Compare(img, img, Options{Tolerance: tol}); err == nil {+ t.Errorf("Compare with tolerance %v should error", tol)+ }+ }+}++func TestIgnoreAntiAliasing(t *testing.T) {+ edge := func() *image.RGBA {+ img := image.NewRGBA(image.Rect(0, 0, 16, 16))+ fill(img, img.Bounds(), white)+ fill(img, image.Rect(5, 0, 6, 16), black)+ return img+ }+ a := edge()+ b := edge()+ fill(b, image.Rect(6, 4, 7, 5), gray)++ strict, err := Compare(a, b, Options{Tolerance: 0.05})+ if err != nil {+ t.Fatalf("Compare: %v", err)+ }+ if strict.PixelsChanged != 1 {+ t.Errorf("strict PixelsChanged = %d, want 1", strict.PixelsChanged)+ }++ lenient, err := Compare(a, b, Options{Tolerance: 0.05, IgnoreAntiAliasing: true})+ if err != nil {+ t.Fatalf("Compare: %v", err)+ }+ if lenient.PixelsChanged != 0 {+ t.Errorf("lenient PixelsChanged = %d, want 0 (edge pixel excused)", lenient.PixelsChanged)+ }+}++func TestAnnotatedGolden(t *testing.T) {+ baseline := loadPNG(t, filepath.Join("testdata", "baseline.png"))+ changed := loadPNG(t, filepath.Join("testdata", "changed.png"))++ res, err := Compare(baseline, changed, Options{Tolerance: 0.05})+ if err != nil {+ t.Fatalf("Compare: %v", err)+ }+ var buf bytes.Buffer+ if err := WriteAnnotatedPNG(&buf, baseline, res); err != nil {+ t.Fatalf("WriteAnnotatedPNG: %v", err)+ }++ goldenPath := filepath.Join("testdata", "annotated.golden.png")+ golden, err := os.ReadFile(goldenPath)+ if err != nil {+ t.Fatalf("read %s: %v (run `go test -update` to generate)", goldenPath, err)+ }+ if !bytes.Equal(buf.Bytes(), golden) {+ t.Errorf("annotated PNG bytes differ from %s (%d vs %d bytes)", goldenPath, buf.Len(), len(golden))+ }+}