Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

fix: compare --fail-on-diff passes a staging deploy that introduced an uncaught JS error, while failing one that only logged console.error (PIN-126)

Luigi Agosti00d9e9938130
diff --git a/cmd/pinchtab/cmd_compare.go b/cmd/pinchtab/cmd_compare.go
index 4be239a0..f920c4dc 100644
--- a/cmd/pinchtab/cmd_compare.go
+++ b/cmd/pinchtab/cmd_compare.go
@@ -10,7 +10,13 @@ var compareCmd = &cobra.Command{
Short: "Compare two site versions visually and by audit data",
Long: `Audit the same pages on a live and a staging base URL, then compare
each pair: pixel-level visual diff on the screenshots plus data drift
-(console errors, broken assets, accessibility score, load time).
+(uncaught JS errors, console errors, broken assets, accessibility score,
+load time).
+
+Uncaught JS errors drift on identity, not just count: an exception present
+on one side only, or swapped for a different one, is a difference. The same
+exception on both sides is not — this is a comparison gate, not an absolute
+health check.
Pages default to the two base URLs; pass --pages with comma-separated
relative paths to compare more. With --output-dir the comparison report is
diff --git a/cmd/pinchtab/cmd_compare_test.go b/cmd/pinchtab/cmd_compare_test.go
new file mode 100644
index 00000000..863a3e66
--- /dev/null
+++ b/cmd/pinchtab/cmd_compare_test.go
@@ -0,0 +1,35 @@
+package main
+
+import (
+ "bytes"
+ "strings"
+ "testing"
+)
+
+// The gate rejection suppresses usage at its return site, not at declaration,
+// so a genuine misuse must still get the usage block.
+func TestCompareWrongArgumentCountStillPrintsUsage(t *testing.T) {
+ var out bytes.Buffer
+ t.Cleanup(func() {
+ rootCmd.SetArgs(nil)
+ rootCmd.SetOut(nil)
+ rootCmd.SetErr(nil)
+ compareCmd.SilenceUsage = false
+ })
+ rootCmd.SetOut(&out)
+ rootCmd.SetErr(&out)
+ rootCmd.SetArgs([]string{"compare", "http://only-one-url"})
+
+ if err := rootCmd.Execute(); err == nil {
+ t.Fatal("compare with one argument should be rejected")
+ }
+ if !strings.Contains(out.String(), "Usage:") {
+ t.Fatalf("argument error lost its usage block: %q", out.String())
+ }
+}
+
+func TestCompareHelpNamesUncaughtJSErrors(t *testing.T) {
+ if !strings.Contains(compareCmd.Long, "Uncaught JS errors") {
+ t.Fatalf("compare help does not name uncaught JS errors: %q", compareCmd.Long)
+ }
+}
diff --git a/docs/audit.md b/docs/audit.md
index 74deeab8..fbf40973 100644
--- a/docs/audit.md
+++ b/docs/audit.md
@@ -121,9 +121,17 @@ pinchtab compare <live-url> <staging-url> [flags]
```
Audits the same pages on both base URLs, pairs them by path, pixel-diffs the
-screenshot pairs, and diffs the data (console error count, broken assets,
-accessibility score, load time with a noise threshold). Pages present on only
-one side are reported as `added`/`removed`.
+screenshot pairs, and diffs the data (uncaught JS errors, console error count,
+broken assets, accessibility score, load time with a noise threshold). Pages
+present on only one side are reported as `added`/`removed`.
+
+Uncaught JS errors (`jsErrors`) are compared by identity rather than by count:
+each exception's first message line, with the page's own `scheme://host`
+masked, so the same failure on two base URLs matches. An exception on one side
+only — or one swapped for another — is drift; the same exception on both sides
+is not, since this gate compares two deploys and does not judge absolute page
+health. The other fields, `consoleErrors` included, compare counts, so
+substituting one console message for another stays invisible.
| Flag | Default | Meaning |
|---|---|---|
diff --git a/internal/audit/compare.go b/internal/audit/compare.go
index 8d90c02d..d0382e93 100644
--- a/internal/audit/compare.go
+++ b/internal/audit/compare.go
@@ -7,6 +7,9 @@ import (
"image"
"image/png"
"math"
+ "net/url"
+ "slices"
+ "sort"
"strings"
"time"
@@ -30,7 +33,7 @@ const timingDriftThresholdMs = 1000.0
// DataDrift is one field-level difference between paired pages.
type DataDrift struct {
- // Field identifies what drifted (consoleErrors, brokenAssets,
+ // Field identifies what drifted (consoleErrors, jsErrors, brokenAssets,
// accessibilityScore, loadMs).
Field string `json:"field"`
// Live and Staging are the two observed values, stringified.
@@ -240,6 +243,9 @@ func diffPageData(live, staging PageResult) []DataDrift {
if liveErrs != stagingErrs {
record("consoleErrors", liveErrs, stagingErrs)
}
+ if liveJS, stagingJS := jsErrorIdentities(live), jsErrorIdentities(staging); !slices.Equal(liveJS, stagingJS) {
+ record("jsErrors", jsErrorDriftValue(liveJS), jsErrorDriftValue(stagingJS))
+ }
if lb, sb := len(live.Browser.BrokenAssets), len(staging.Browser.BrokenAssets); lb != sb {
record("brokenAssets", lb, sb)
}
@@ -252,6 +258,51 @@ func diffPageData(live, staging PageResult) []DataDrift {
return drift
}
+// jsErrorOriginPlaceholder stands in for a page's own scheme://host inside an
+// exception message, so the same failure on two base URLs reads as one identity.
+const jsErrorOriginPlaceholder = "<origin>"
+
+// jsErrorIdentities is the sorted multiset of uncaught exceptions on a page.
+// Unlike the count-based fields, uncaught errors are compared by identity: a
+// staging deploy that fixes one exception and introduces another is a drift,
+// not a wash. The identity is the message's first line — the exception text —
+// with the page's own origin masked, which drops the stack frames and the
+// host, the two parts that differ between live and staging for one same bug.
+func jsErrorIdentities(p PageResult) []string {
+ origin := urlOrigin(p.URL)
+ identities := make([]string, 0, len(p.Browser.JSErrors))
+ for _, e := range p.Browser.JSErrors {
+ identities = append(identities, jsErrorIdentity(e.Message, origin))
+ }
+ sort.Strings(identities)
+ return identities
+}
+
+func jsErrorIdentity(message, origin string) string {
+ first, _, _ := strings.Cut(message, "\n")
+ if origin != "" {
+ first = strings.ReplaceAll(first, origin, jsErrorOriginPlaceholder)
+ }
+ return strings.TrimSpace(first)
+}
+
+func urlOrigin(raw string) string {
+ u, err := url.Parse(raw)
+ if err != nil || u.Scheme == "" || u.Host == "" {
+ return ""
+ }
+ return u.Scheme + "://" + u.Host
+}
+
+// jsErrorDriftValue names the exceptions behind the count, so a reader can tell
+// a substitution (1 vs 1) from an unchanged page.
+func jsErrorDriftValue(identities []string) string {
+ if len(identities) == 0 {
+ return "0"
+ }
+ return fmt.Sprintf("%d: %s", len(identities), strings.Join(identities, " | "))
+}
+
func consoleErrorCount(p PageResult) int {
n := 0
for _, l := range p.Browser.ConsoleLogs {
diff --git a/internal/audit/compare_test.go b/internal/audit/compare_test.go
index 5e4bcf80..76be4504 100644
--- a/internal/audit/compare_test.go
+++ b/internal/audit/compare_test.go
@@ -3,10 +3,12 @@ package audit
import (
"bytes"
"encoding/base64"
+ "fmt"
"image"
"image/color"
"image/draw"
"image/png"
+ "strings"
"testing"
)
@@ -102,6 +104,120 @@ func TestDiffPageDataFields(t *testing.T) {
}
}
+func jsError(message string) func(*PageResult) {
+ return func(p *PageResult) {
+ p.Browser.JSErrors = append(p.Browser.JSErrors, JSError{Message: message})
+ }
+}
+
+const referenceError = "Uncaught: ReferenceError: brokenFunctionThatDoesNotExist is not defined\n at %s/index.html:3:9"
+
+func TestDiffPageDataUncaughtJSErrors(t *testing.T) {
+ live := "http://localhost:18601"
+ staging := "http://localhost:18602"
+
+ tests := []struct {
+ name string
+ live []func(*PageResult)
+ staging []func(*PageResult)
+ wantDrift bool
+ }{
+ {
+ name: "introduced on staging",
+ staging: []func(*PageResult){jsError(fmt.Sprintf(referenceError, staging))},
+ wantDrift: true,
+ },
+ {
+ name: "fixed on staging",
+ live: []func(*PageResult){jsError(fmt.Sprintf(referenceError, live))},
+ wantDrift: true,
+ },
+ {
+ name: "same error on both sides is not a regression",
+ live: []func(*PageResult){jsError(fmt.Sprintf(referenceError, live))},
+ staging: []func(*PageResult){jsError(fmt.Sprintf(referenceError, staging))},
+ wantDrift: false,
+ },
+ {
+ name: "one error swapped for another at the same count",
+ live: []func(*PageResult){jsError("Uncaught: TypeError: a is not a function")},
+ staging: []func(*PageResult){jsError("Uncaught: TypeError: b is not a function")},
+ wantDrift: true,
+ },
+ {
+ name: "same two errors in a different order",
+ live: []func(*PageResult){
+ jsError("Uncaught: TypeError: a is not a function"),
+ jsError("Uncaught: RangeError: out of range"),
+ },
+ staging: []func(*PageResult){
+ jsError("Uncaught: RangeError: out of range"),
+ jsError("Uncaught: TypeError: a is not a function"),
+ },
+ wantDrift: false,
+ },
+ {
+ name: "the same error twice is not one error",
+ live: []func(*PageResult){jsError("Uncaught: TypeError: a is not a function")},
+ staging: []func(*PageResult){jsError("Uncaught: TypeError: a is not a function"), jsError("Uncaught: TypeError: a is not a function")},
+ wantDrift: true,
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ drift := diffPageData(page(live+"/index.html", tc.live...), page(staging+"/index.html", tc.staging...))
+ var got *DataDrift
+ for i := range drift {
+ if drift[i].Field == "jsErrors" {
+ got = &drift[i]
+ }
+ }
+ if tc.wantDrift && got == nil {
+ t.Fatalf("no jsErrors drift in %+v", drift)
+ }
+ if !tc.wantDrift && got != nil {
+ t.Fatalf("unexpected jsErrors drift: %+v", *got)
+ }
+ if len(drift) != len(diffPageData(page(live), page(staging)))+boolToInt(tc.wantDrift) {
+ t.Fatalf("jsErrors changed the other drift fields: %+v", drift)
+ }
+ })
+ }
+}
+
+func boolToInt(b bool) int {
+ if b {
+ return 1
+ }
+ return 0
+}
+
+func TestJSErrorDriftValueNamesTheExceptions(t *testing.T) {
+ staging := page("http://localhost:18602/index.html", jsError("Uncaught: TypeError: b is not a function"))
+ value := jsErrorDriftValue(jsErrorIdentities(staging))
+ if !strings.Contains(value, "TypeError: b is not a function") || !strings.HasPrefix(value, "1:") {
+ t.Fatalf("drift value = %q, want the count and the exception text", value)
+ }
+ if jsErrorDriftValue(jsErrorIdentities(page("http://localhost:18601/index.html"))) != "0" {
+ t.Fatalf("a page without exceptions should read as 0")
+ }
+}
+
+func TestUncaughtJSErrorMakesTheGateFail(t *testing.T) {
+ live := AuditReport{Pages: []PageResult{page("http://localhost:18601/index.html")}}
+ staging := AuditReport{Pages: []PageResult{page("http://localhost:18602/index.html",
+ jsError(fmt.Sprintf(referenceError, "http://localhost:18602")))}}
+
+ outcome, err := ComparePages("http://localhost:18601", "http://localhost:18602", live, staging)
+ if err != nil {
+ t.Fatalf("ComparePages: %v", err)
+ }
+ if !outcome.Report.HasDiffs {
+ t.Fatalf("an uncaught exception on staging must count as a diff: %+v", outcome.Report.Pages)
+ }
+}
+
func encodeShot(t *testing.T, c color.RGBA, w, h int) string {
t.Helper()
img := image.NewRGBA(image.Rect(0, 0, w, h))
diff --git a/internal/cli/actions/actions_compare.go b/internal/cli/actions/actions_compare.go
index 9e1a0f7f..11c286e6 100644
--- a/internal/cli/actions/actions_compare.go
+++ b/internal/cli/actions/actions_compare.go
@@ -114,6 +114,10 @@ func Compare(client *http.Client, base, token string, cmd *cobra.Command, liveBa
}
if mustBool(cmd, "fail-on-diff") && outcome.Report.HasDiffs {
+ // The gate did exactly what it promises, so this is not a misuse:
+ // suppress usage here rather than at declaration, which would also
+ // swallow it for the argument-count error.
+ cmd.SilenceUsage = true
return fmt.Errorf("differences found (--fail-on-diff)")
}
return nil
@@ -190,9 +194,22 @@ func printCompareSummary(report audit.ComparisonReport) {
case p.Status != audit.CompareStatusCompared:
fmt.Printf(" %s · %s\n", label, p.Status)
case p.DiffPercentage != nil:
- fmt.Printf(" %s · visual %.2f%% · drift %d\n", label, *p.DiffPercentage, len(p.Drift))
+ fmt.Printf(" %s · visual %.2f%% · %s\n", label, *p.DiffPercentage, driftLabel(p.Drift))
default:
- fmt.Printf(" %s · drift %d\n", label, len(p.Drift))
+ fmt.Printf(" %s · %s\n", label, driftLabel(p.Drift))
}
}
}
+
+// driftLabel names the drifted fields beside the count, so a new uncaught
+// exception is not read as a stray console line.
+func driftLabel(drift []audit.DataDrift) string {
+ if len(drift) == 0 {
+ return "drift 0"
+ }
+ fields := make([]string, 0, len(drift))
+ for _, d := range drift {
+ fields = append(fields, d.Field)
+ }
+ return fmt.Sprintf("drift %d (%s)", len(drift), strings.Join(fields, ", "))
+}
diff --git a/internal/cli/actions/actions_compare_test.go b/internal/cli/actions/actions_compare_test.go
new file mode 100644
index 00000000..e755ab69
--- /dev/null
+++ b/internal/cli/actions/actions_compare_test.go
@@ -0,0 +1,124 @@
+package actions
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/audit"
+ "github.com/spf13/cobra"
+)
+
+const (
+ compareLiveBase = "http://localhost:18601"
+ compareStagingBase = "http://localhost:18602"
+)
+
+// compareStub answers /audit with one page per requested URL, carrying the
+// browser data of whichever side the URL belongs to.
+func compareStub(t *testing.T, live, staging audit.BrowserPageData) *httptest.Server {
+ t.Helper()
+ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/audit" {
+ http.NotFound(w, r)
+ return
+ }
+ var body struct {
+ URLs []string `json:"urls"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Errorf("decode audit body: %v", err)
+ return
+ }
+ report := audit.AuditReport{}
+ for _, u := range body.URLs {
+ data := live
+ if strings.HasPrefix(u, compareStagingBase) {
+ data = staging
+ }
+ report.Pages = append(report.Pages, audit.PageResult{URL: u, Browser: data})
+ }
+ _ = json.NewEncoder(w).Encode(report)
+ }))
+}
+
+func uncaughtOn(base string) audit.BrowserPageData {
+ return audit.BrowserPageData{JSErrors: []audit.JSError{{
+ Message: "Uncaught: ReferenceError: brokenFunctionThatDoesNotExist is not defined\n at " + base + "/index.html:3:9",
+ }}}
+}
+
+func consoleErrorPage() audit.BrowserPageData {
+ return audit.BrowserPageData{ConsoleLogs: []audit.ConsoleLogEntry{{Level: "error", Message: "staging regression"}}}
+}
+
+func runCompareGate(t *testing.T, live, staging audit.BrowserPageData) (*cobra.Command, error) {
+ t.Helper()
+ srv := compareStub(t, live, staging)
+ defer srv.Close()
+ cmd := newCompareTestCmd("--fail-on-diff")
+ return cmd, Compare(http.DefaultClient, srv.URL, "", cmd, compareLiveBase, compareStagingBase)
+}
+
+func TestCompareGateFailsOnEitherErrorChannel(t *testing.T) {
+ tests := []struct {
+ name string
+ live audit.BrowserPageData
+ staging audit.BrowserPageData
+ wantFail bool
+ }{
+ {
+ name: "uncaught exception introduced on staging",
+ staging: uncaughtOn(compareStagingBase),
+ wantFail: true,
+ },
+ {
+ name: "console error introduced on staging",
+ staging: consoleErrorPage(),
+ wantFail: true,
+ },
+ {
+ name: "identical pages",
+ wantFail: false,
+ },
+ {
+ name: "the same uncaught exception on both sides",
+ live: uncaughtOn(compareLiveBase),
+ staging: uncaughtOn(compareStagingBase),
+ wantFail: false,
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ cmd, err := runCompareGate(t, tc.live, tc.staging)
+ if tc.wantFail {
+ if err == nil || !strings.Contains(err.Error(), "--fail-on-diff") {
+ t.Fatalf("Compare() error = %v, want the differences-found refusal", err)
+ }
+ if !cmd.SilenceUsage {
+ t.Error("a gate rejection must not print the usage block")
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("Compare() error = %v, want the gate to pass", err)
+ }
+ if cmd.SilenceUsage {
+ t.Error("usage suppression leaked onto a passing run")
+ }
+ })
+ }
+}
+
+func TestCompareSummaryNamesTheDriftedFields(t *testing.T) {
+ pc := audit.PageComparison{Drift: []audit.DataDrift{{Field: "jsErrors"}}}
+ if got := driftLabel(pc.Drift); got != "drift 1 (jsErrors)" {
+ t.Fatalf("driftLabel = %q, want the field named", got)
+ }
+ if got := driftLabel(nil); got != "drift 0" {
+ t.Fatalf("driftLabel(nil) = %q", got)
+ }
+}