High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: a renderer that refuses the read-the-view capture fails the whole screenshot instead of falling back to a fresh composite (PIN-140)
Luigi Agostid06551952575
diff --git a/internal/bridge/screenshot.go b/internal/bridge/screenshot.goindex 59844d3c..79bc5eb9 100644--- a/internal/bridge/screenshot.go+++ b/internal/bridge/screenshot.go@@ -185,23 +185,25 @@ func CaptureScreenshot(ctx context.Context, opts ScreenshotOpts) ([]byte, error)fromSurface := cdptk.CaptureFromSurface(opts.BeyondViewport, clip)- var buf []byte- err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {- shot := page.CaptureScreenshot().WithFormat(opts.Format).WithFromSurface(fromSurface)- if clip != nil {- shot = shot.WithClip(clip)- }- if opts.BeyondViewport && clip == nil {- shot = shot.WithCaptureBeyondViewport(true)- }- if opts.Format == page.CaptureScreenshotFormatJpeg {- shot = shot.WithQuality(int64(opts.Quality))- }- var inner error- buf, inner = captureScreenshotWithoutActivation(ctx, shot, opts.DisableActivation)- return inner- }))- return buf, err+ return cdptk.CaptureWithSurfaceFallback(fromSurface, func(fromSurface bool) ([]byte, error) {+ var buf []byte+ err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {+ shot := page.CaptureScreenshot().WithFormat(opts.Format).WithFromSurface(fromSurface)+ if clip != nil {+ shot = shot.WithClip(clip)+ }+ if opts.BeyondViewport && clip == nil {+ shot = shot.WithCaptureBeyondViewport(true)+ }+ if opts.Format == page.CaptureScreenshotFormatJpeg {+ shot = shot.WithQuality(int64(opts.Quality))+ }+ var inner error+ buf, inner = captureScreenshotWithoutActivation(ctx, shot, opts.DisableActivation)+ return inner+ }))+ return buf, err+ })}// ScreenshotClipForNode returns a page-coordinate clip for a backend node ID.diff --git a/internal/browsers/chrome/instance.go b/internal/browsers/chrome/instance.goindex 422cc857..5e7c4a0e 100644--- a/internal/browsers/chrome/instance.go+++ b/internal/browsers/chrome/instance.go@@ -33,37 +33,41 @@ func NewInstance(browserCtx context.Context, headless bool) *Instance {var _ browsers.RuntimeInstance = (*Instance)(nil)func (i *Instance) CaptureScreenshot(ctx context.Context, format string, quality int, clip *cdptk.ScreenshotClip) ([]byte, error) {- var buf []byte- err := chromedp.Run(ctx, chromedp.ActionFunc(func(c context.Context) error {- // Wake the target's renderer before capturing. Background / non-- // foreground tabs throttle their compositor and stop painting, so- // captureScreenshot blocks until the action deadline (~30s). A- // best-effort BringToFront resumes painting for the target we are- // about to capture; the error is ignored so providers whose CDP proxy- // does not implement it still capture normally.- _ = page.BringToFront().Do(c)-- var cdpFormat page.CaptureScreenshotFormat- switch format {- case "png":- cdpFormat = page.CaptureScreenshotFormatPng- default:- cdpFormat = page.CaptureScreenshotFormatJpeg- }+ const beyondViewport = false+ vp := cdptk.ClipViewport(clip)++ buf, err := cdptk.CaptureWithSurfaceFallback(cdptk.CaptureFromSurface(beyondViewport, vp), func(fromSurface bool) ([]byte, error) {+ var buf []byte+ err := chromedp.Run(ctx, chromedp.ActionFunc(func(c context.Context) error {+ // Wake the target's renderer before capturing. Background / non-+ // foreground tabs throttle their compositor and stop painting, so+ // captureScreenshot blocks until the action deadline (~30s). A+ // best-effort BringToFront resumes painting for the target we are+ // about to capture; the error is ignored so providers whose CDP proxy+ // does not implement it still capture normally.+ _ = page.BringToFront().Do(c)++ var cdpFormat page.CaptureScreenshotFormat+ switch format {+ case "png":+ cdpFormat = page.CaptureScreenshotFormatPng+ default:+ cdpFormat = page.CaptureScreenshotFormatJpeg+ }- const beyondViewport = false- vp := cdptk.ClipViewport(clip)- shot := page.CaptureScreenshot().WithFormat(cdpFormat).WithFromSurface(cdptk.CaptureFromSurface(beyondViewport, vp))- if vp != nil {- shot = shot.WithClip(vp)- }- if cdpFormat == page.CaptureScreenshotFormatJpeg && quality > 0 {- shot = shot.WithQuality(int64(quality))- }- var err error- buf, err = shot.Do(c)- return err- }))+ shot := page.CaptureScreenshot().WithFormat(cdpFormat).WithFromSurface(fromSurface)+ if vp != nil {+ shot = shot.WithClip(vp)+ }+ if cdpFormat == page.CaptureScreenshotFormatJpeg && quality > 0 {+ shot = shot.WithQuality(int64(quality))+ }+ var err error+ buf, err = shot.Do(c)+ return err+ }))+ return buf, err+ })if err != nil {return nil, fmt.Errorf("screenshot: %w", err)}diff --git a/internal/cdptk/screenshot.go b/internal/cdptk/screenshot.goindex 44f6b01c..9919c967 100644--- a/internal/cdptk/screenshot.go+++ b/internal/cdptk/screenshot.go@@ -4,6 +4,8 @@ import ("context""encoding/json""fmt"+ "log/slog"+ "strings""github.com/chromedp/cdproto/page""github.com/chromedp/chromedp"@@ -141,6 +143,36 @@ func CaptureFromSurface(beyondViewport bool, clip *page.Viewport) bool {return beyondViewport || clip != nil}+// captureRefusal is the CDP error a renderer returns when it will not serve the+// read-the-view fast path. It carries no code the client can match on, so the message is+// the only discriminator available.+const captureRefusal = "Unable to capture screenshot"++// CaptureWithSurfaceFallback runs a capture and, when the renderer REFUSES the fast path,+// retries once forcing a fresh composite.+//+// fromSurface=false reads the renderer's current view rather than waiting for a surface+// frame, which is why CaptureFromSurface prefers it — but that view is a resource that can+// be unavailable (no screen-recording permission, another client holding the surface), and+// when it is, CDP answers -32000 instead of a frame. Failing the whole capture there throws+// away a picture the browser can still produce the slower way.+//+// Retried ONLY on that refusal, and only when the fast path was actually taken: any other+// error is a real failure and must surface, and a fromSurface=true capture that fails has+// no faster path left to fall back from. The retry costs one extra round trip in the case+// that was going to fail outright, and nothing at all on a healthy browser.+//+// The fallback is deliberate about what it does NOT change: it re-runs the SAME params, so+// a clip still travels and a clipped capture cannot silently widen to the whole viewport.+func CaptureWithSurfaceFallback(fromSurface bool, capture func(fromSurface bool) ([]byte, error)) ([]byte, error) {+ buf, err := capture(fromSurface)+ if err == nil || fromSurface || !strings.Contains(err.Error(), captureRefusal) {+ return buf, err+ }+ slog.Warn("screenshot: renderer refused the read-the-view capture, retrying from surface", "err", err)+ return capture(true)+}+// NormalizedViewport owns the non-zero-scale rule for a clip already in CDP's own type.// Scale 0 means native. CDP does not agree: it discards a scale-0 clip and returns the// whole viewport, no error, exactly as it discards a clip passed with fromSurface=false.diff --git a/internal/cdptk/screenshot_fallback_test.go b/internal/cdptk/screenshot_fallback_test.gonew file mode 100644index 00000000..f0258490--- /dev/null+++ b/internal/cdptk/screenshot_fallback_test.go@@ -0,0 +1,157 @@+package cdptk++import (+ "errors"+ "strings"+ "testing"++ "github.com/pinchtab/pinchtab/internal/srccensus"+)++// The property is that a REFUSAL of the read-the-view fast path is handled, whatever the+// clip — not that an unclipped capture works. A browser fixture cannot pin this: the+// refusal depends on whether the renderer's view is available, which no test can withhold+// on demand, and when it is available both flags return a frame. So the capture is+// injected and the flag it was called with is the assertion.+func TestCaptureRetriesFromSurfaceOnlyWhenTheFastPathWasRefused(t *testing.T) {+ refusal := errors.New("Unable to capture screenshot (-32000)")++ for _, tc := range []struct {+ name string+ fromSurface bool+ errs []error+ wantCalls []bool+ wantErr error+ }{+ {+ name: "the fast path is refused, so the surface path answers",+ errs: []error{refusal, nil},+ wantCalls: []bool{false, true},+ },+ {+ name: "a healthy fast path costs no second call",+ errs: []error{nil},+ wantCalls: []bool{false},+ },+ {+ name: "any other error is a real failure and surfaces",+ errs: []error{errors.New("target closed")},+ wantCalls: []bool{false},+ wantErr: errors.New("target closed"),+ },+ {+ name: "a refused surface capture has no faster path to fall back from",+ fromSurface: true,+ errs: []error{refusal},+ wantCalls: []bool{true},+ wantErr: refusal,+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ var calls []bool+ buf, err := CaptureWithSurfaceFallback(tc.fromSurface, func(fromSurface bool) ([]byte, error) {+ calls = append(calls, fromSurface)+ return []byte("frame"), tc.errs[len(calls)-1]+ })++ if len(calls) != len(tc.wantCalls) {+ t.Fatalf("capture called with %v, want %v", calls, tc.wantCalls)+ }+ for i, want := range tc.wantCalls {+ if calls[i] != want {+ t.Errorf("call %d used fromSurface=%v, want %v", i+1, calls[i], want)+ }+ }+ if tc.wantErr == nil {+ if err != nil {+ t.Fatalf("err = %v, want the capture to succeed", err)+ }+ if string(buf) != "frame" {+ t.Errorf("buf = %q, want the captured frame", buf)+ }+ return+ }+ if err == nil || err.Error() != tc.wantErr.Error() {+ t.Errorf("err = %v, want %v", err, tc.wantErr)+ }+ })+ }+}++// The refusal is matched on the message because CDP sends no code the client can read, so+// the string is load-bearing rather than cosmetic. This pins it against the error the+// browser actually produces, which is what the capture sites saw on a real host.+func TestTheRefusalIsRecognisedInTheErrorTheBrowserSends(t *testing.T) {+ if !strings.Contains("screenshot: Unable to capture screenshot (-32000)", captureRefusal) {+ t.Errorf("the refusal constant %q does not appear in the error CDP sends, so the fallback never fires", captureRefusal)+ }+}++// The wiring, which nothing else can pin. The refusal depends on whether the renderer's+// view is available, and no test can withhold it — so a capture site that stops calling the+// fallback keeps every browser-backed test green and only fails on the host that was+// already failing. A source census is the only guard available, and without it this fix is+// unwired the first time someone rewrites a capture site.+func TestEveryCaptureSiteRoutesThroughTheSurfaceFallback(t *testing.T) {+ // Screencast polls frames continuously rather than answering one request, so a retry+ // there belongs to that loop's own cadence rather than to a per-call fallback. Exempt+ // with the reason, not silently skipped.+ exempt := map[string]string{+ "internal/cdptk/screencast.go": "a polling frame loop, not a one-shot capture",+ }++ sites := 0+ for _, file := range srccensus.Tree(t, "../..", moduleFileFloor) {+ if !strings.Contains(file.Text, "page.CaptureScreenshot()") {+ continue+ }+ sites+++ if reason, ok := exempt[file.Name]; ok {+ if reason == "" {+ t.Errorf("%s is exempt with no reason recorded", file.Name)+ }+ continue+ }+ if !strings.Contains(file.Text, "CaptureWithSurfaceFallback") {+ t.Errorf("%s captures a screenshot without routing through CaptureWithSurfaceFallback, so a renderer that refuses the read-the-view path fails the whole capture there", file.Name)+ }+ }++ if sites <= len(exempt) {+ t.Fatalf("found %d capture sites against %d exemptions; the census matched almost nothing and would pass vacuously", sites, len(exempt))+ }+ for name := range exempt {+ found := false+ for _, file := range srccensus.Tree(t, "../..", moduleFileFloor) {+ if file.Name == name {+ found = true+ }+ }+ if !found {+ t.Errorf("%s is exempt but the walk never found it, so the exemption is stale", name)+ }+ }+}++const moduleFileFloor = 200++// A clip must survive the retry: the fallback re-runs the same params, and re-running+// without the clip would answer the whole viewport while reporting success — the silent+// widening the clip-forces-surface rule exists to prevent.+func TestTheRetryDoesNotChangeWhatWasAskedForBesidesTheFlag(t *testing.T) {+ var seen []bool+ if _, err := CaptureWithSurfaceFallback(false, func(fromSurface bool) ([]byte, error) {+ seen = append(seen, fromSurface)+ if len(seen) == 1 {+ return nil, errors.New("Unable to capture screenshot (-32000)")+ }+ return []byte("frame"), nil+ }); err != nil {+ t.Fatalf("err = %v", err)+ }+ // The callback receives only the flag, so nothing else CAN differ between the two+ // attempts — that is the point of the seam, and this asserts the shape stays that way.+ if len(seen) != 2 || seen[0] || !seen[1] {+ t.Errorf("attempts = %v, want the fast path then the surface path", seen)+ }+}