Skip to content

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

fix: address review feedback on captureAllowActivation defaults and add real-browser regression test

Luigi Agostidfdd2a6ca02f
diff --git a/internal/bridge/capture_background_tab_test.go b/internal/bridge/capture_background_tab_test.go
new file mode 100644
index 00000000..eab66cea
--- /dev/null
+++ b/internal/bridge/capture_background_tab_test.go
@@ -0,0 +1,152 @@
+package bridge
+
+import (
+ "context"
+ "encoding/base64"
+ "os"
+ "os/exec"
+ "testing"
+ "time"
+
+ "github.com/chromedp/cdproto/page"
+ "github.com/chromedp/cdproto/target"
+ "github.com/chromedp/chromedp"
+)
+
+// TestCaptureScreenshotOfBackgroundTabCompletesQuickly is a real-Chromium
+// regression test for the bug fixed by always calling Page.bringToFront in
+// captureScreenshotWithoutActivation: a genuinely backgrounded tab's
+// compositor never resumes painting from Emulation.setFocusEmulationEnabled
+// alone, so Page.captureScreenshot previously hung until the caller's
+// deadline. A mocked-CDP test can't catch this — the mock "succeeds" at
+// focus emulation and returns from captureScreenshot immediately regardless
+// of whether a real tab is actually painting.
+func TestCaptureScreenshotOfBackgroundTabCompletesQuickly(t *testing.T) {
+ chromePath, err := exec.LookPath("chromium")
+ if err != nil {
+ t.Skip("chromium not installed")
+ }
+ profile, err := os.MkdirTemp("", "pinchtab-bg-capture-")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = os.RemoveAll(profile) })
+
+ alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
+ chromedp.DefaultExecAllocatorOptions[:],
+ chromedp.ExecPath(chromePath),
+ chromedp.UserDataDir(profile),
+ chromedp.Flag("headless", true),
+ chromedp.Flag("no-sandbox", true),
+ )...)
+ defer cancelAlloc()
+
+ browserCtx, cancelBrowser := chromedp.NewContext(alloc)
+ defer cancelBrowser()
+ if err := chromedp.Run(browserCtx); err != nil {
+ t.Fatalf("start browser: %v", err)
+ }
+
+ html := `<h1>background tab</h1>`
+ dataURL := "data:text/html;base64," + base64.StdEncoding.EncodeToString([]byte(html))
+
+ // Target.createTarget(background=true) is CDP's own mechanism for
+ // opening a tab that never becomes the foreground/active one — the same
+ // mechanism this codebase's tab manager uses, and exactly the situation
+ // (capture on a tab that was never activated) that hung in production.
+ var bgTarget target.ID
+ if err := chromedp.Run(browserCtx, chromedp.ActionFunc(func(ctx context.Context) error {
+ id, err := target.CreateTarget(dataURL).WithBackground(true).Do(ctx)
+ bgTarget = id
+ return err
+ })); err != nil {
+ t.Fatalf("create background target: %v", err)
+ }
+
+ bgCtx, cancelBg := chromedp.NewContext(browserCtx, chromedp.WithTargetID(bgTarget))
+ defer cancelBg()
+
+ // Tight but fair: production uses a 30s ActionTimeout, and a tab that
+ // never resumes painting hangs for the whole window. 10s is generous for
+ // a real capture to complete, but a regression (activation skipped)
+ // fails this test loudly instead of quietly eating a 30s timeout.
+ captureCtx, cancelCapture := context.WithTimeout(bgCtx, 10*time.Second)
+ defer cancelCapture()
+
+ if err := chromedp.Run(captureCtx); err != nil {
+ t.Fatalf("attach to background target: %v", err)
+ }
+
+ buf, err := CaptureScreenshot(captureCtx, ScreenshotOpts{Format: page.CaptureScreenshotFormatPng})
+ if err != nil {
+ t.Fatalf("capture background tab: %v", err)
+ }
+ if len(buf) == 0 {
+ t.Fatal("capture returned no image bytes")
+ }
+}
+
+// TestCaptureScreenshotOfBackgroundTabBlocksWhenActivationDisabled documents
+// the accepted trade-off of DisableActivation: without Page.bringToFront, a
+// genuinely backgrounded tab's compositor never resumes, so the capture
+// blocks until the context deadline instead of completing. This is the same
+// hang TestCaptureScreenshotOfBackgroundTabCompletesQuickly proves is fixed
+// by default — this test guards that the opt-out still reproduces it
+// deliberately, rather than the fix accidentally covering both cases.
+func TestCaptureScreenshotOfBackgroundTabBlocksWhenActivationDisabled(t *testing.T) {
+ chromePath, err := exec.LookPath("chromium")
+ if err != nil {
+ t.Skip("chromium not installed")
+ }
+ profile, err := os.MkdirTemp("", "pinchtab-bg-capture-noactivate-")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = os.RemoveAll(profile) })
+
+ alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
+ chromedp.DefaultExecAllocatorOptions[:],
+ chromedp.ExecPath(chromePath),
+ chromedp.UserDataDir(profile),
+ chromedp.Flag("headless", true),
+ chromedp.Flag("no-sandbox", true),
+ )...)
+ defer cancelAlloc()
+
+ browserCtx, cancelBrowser := chromedp.NewContext(alloc)
+ defer cancelBrowser()
+ if err := chromedp.Run(browserCtx); err != nil {
+ t.Fatalf("start browser: %v", err)
+ }
+
+ html := `<h1>background tab</h1>`
+ dataURL := "data:text/html;base64," + base64.StdEncoding.EncodeToString([]byte(html))
+
+ var bgTarget target.ID
+ if err := chromedp.Run(browserCtx, chromedp.ActionFunc(func(ctx context.Context) error {
+ id, err := target.CreateTarget(dataURL).WithBackground(true).Do(ctx)
+ bgTarget = id
+ return err
+ })); err != nil {
+ t.Fatalf("create background target: %v", err)
+ }
+
+ bgCtx, cancelBg := chromedp.NewContext(browserCtx, chromedp.WithTargetID(bgTarget))
+ defer cancelBg()
+
+ // Short deadline: we expect this to time out, not succeed.
+ captureCtx, cancelCapture := context.WithTimeout(bgCtx, 3*time.Second)
+ defer cancelCapture()
+
+ if err := chromedp.Run(captureCtx); err != nil {
+ t.Fatalf("attach to background target: %v", err)
+ }
+
+ _, err = CaptureScreenshot(captureCtx, ScreenshotOpts{
+ Format: page.CaptureScreenshotFormatPng,
+ DisableActivation: true,
+ })
+ if err == nil {
+ t.Fatal("capture with activation disabled succeeded on a background tab, want it to block until the deadline")
+ }
+}
diff --git a/internal/bridge/screenshot.go b/internal/bridge/screenshot.go
index c04a4985..73ff9e70 100644
--- a/internal/bridge/screenshot.go
+++ b/internal/bridge/screenshot.go
@@ -123,12 +123,14 @@ type ScreenshotOpts struct {
ViewportWidth float64
ViewportHeight float64
- // AllowActivation permits Page.bringToFront to wake a backgrounded tab's
- // compositor before capturing (security.instanceDefaults.captureAllowActivation,
- // default true). When false, capture relies solely on focus emulation and
- // never raises the tab in the operator's browser, accepting that a
- // background tab's capture may then block until the caller's deadline.
- AllowActivation bool
+ // DisableActivation suppresses the Page.bringToFront call that wakes a
+ // backgrounded tab's compositor before capturing (the inverse of
+ // instanceDefaults.captureAllowActivation, default true — so the zero
+ // value here is the safe/reliable default even if a caller forgets to
+ // set it). When true, capture relies solely on focus emulation and never
+ // raises the tab in the operator's browser, accepting that a background
+ // tab's capture may then block until the caller's deadline.
+ DisableActivation bool
}
func scaledScreenshotClip(opts ScreenshotOpts, viewportWidth, viewportHeight, documentWidth, documentHeight float64) *page.Viewport {
@@ -179,14 +181,14 @@ func captureFromSurface(beyondViewport bool, clip *page.Viewport) bool {
// captureScreenshotWithoutActivation wakes a background renderer before
// capturing it. Focus emulation alone does not resume a backgrounded tab's
-// compositor — that requires Page.bringToFront — so when allowActivation is
-// true (the default) it always runs as well; focus emulation is layered on
-// top only so document.hasFocus()/`:focus` reflect the capture as
-// best-effort. When allowActivation is false, the tab is never raised in the
-// operator's browser, accepting that its capture may then block until the
-// caller's deadline (Chromium never resumes a backgrounded compositor
-// without either activation or being brought into view).
-func captureScreenshotWithoutActivation(ctx context.Context, shot *page.CaptureScreenshotParams, allowActivation bool) ([]byte, error) {
+// compositor — that requires Page.bringToFront — so unless disableActivation
+// is set, it always runs as well; focus emulation is layered on top only so
+// document.hasFocus()/`:focus` reflect the capture as best-effort. When
+// disableActivation is true, the tab is never raised in the operator's
+// browser, accepting that its capture may then block until the caller's
+// deadline (Chromium never resumes a backgrounded compositor without either
+// activation or being brought into view).
+func captureScreenshotWithoutActivation(ctx context.Context, shot *page.CaptureScreenshotParams, disableActivation bool) ([]byte, error) {
executor := cdp.ExecutorFromContext(ctx)
focusEmulated := emulation.SetFocusEmulationEnabled(true).Do(ctx) == nil
if focusEmulated {
@@ -197,7 +199,7 @@ func captureScreenshotWithoutActivation(ctx context.Context, shot *page.CaptureS
_ = emulation.SetFocusEmulationEnabled(false).Do(restoreCtx)
}()
}
- if allowActivation {
+ if !disableActivation {
_ = page.BringToFront().Do(ctx)
}
return shot.Do(ctx)
@@ -245,7 +247,7 @@ func CaptureScreenshot(ctx context.Context, opts ScreenshotOpts) ([]byte, error)
shot = shot.WithQuality(int64(opts.Quality))
}
var inner error
- buf, inner = captureScreenshotWithoutActivation(ctx, shot, opts.AllowActivation)
+ buf, inner = captureScreenshotWithoutActivation(ctx, shot, opts.DisableActivation)
return inner
}))
return buf, err
@@ -366,12 +368,12 @@ func (b *Bridge) CaptureScreenshot(ctx context.Context, format string, quality i
Scale: clip.Scale,
}
}
- allowActivation := b.Config == nil || b.Config.CaptureAllowActivation
+ disableActivation := b.Config != nil && !b.Config.CaptureAllowActivation
buf, err := CaptureScreenshot(ctx, ScreenshotOpts{
- Format: cdpFormat,
- Quality: quality,
- Clip: vp,
- AllowActivation: allowActivation,
+ Format: cdpFormat,
+ Quality: quality,
+ Clip: vp,
+ DisableActivation: disableActivation,
})
if err != nil {
return nil, fmt.Errorf("screenshot: %w", err)
diff --git a/internal/bridge/screenshot_test.go b/internal/bridge/screenshot_test.go
index 00d5e7b3..79feeb1b 100644
--- a/internal/bridge/screenshot_test.go
+++ b/internal/bridge/screenshot_test.go
@@ -35,7 +35,7 @@ func (e *screenshotExecutor) Execute(_ context.Context, method string, params, r
func TestCaptureScreenshotWithoutActivationRestoresFocusEmulation(t *testing.T) {
exec := &screenshotExecutor{}
ctx := cdp.WithExecutor(context.Background(), exec)
- got, err := captureScreenshotWithoutActivation(ctx, page.CaptureScreenshot(), true)
+ got, err := captureScreenshotWithoutActivation(ctx, page.CaptureScreenshot(), false)
if err != nil {
t.Fatalf("capture: %v", err)
}
@@ -59,7 +59,7 @@ func TestCaptureScreenshotWithoutActivationRestoresFocusEmulation(t *testing.T)
func TestCaptureScreenshotWithoutActivationRestoresAfterCaptureError(t *testing.T) {
exec := &screenshotExecutor{captureErr: errors.New("capture failed")}
ctx := cdp.WithExecutor(context.Background(), exec)
- if _, err := captureScreenshotWithoutActivation(ctx, page.CaptureScreenshot(), true); err == nil {
+ if _, err := captureScreenshotWithoutActivation(ctx, page.CaptureScreenshot(), false); err == nil {
t.Fatal("expected capture error")
}
if !reflect.DeepEqual(exec.focusFlags, []bool{true, false}) {
@@ -70,7 +70,7 @@ func TestCaptureScreenshotWithoutActivationRestoresAfterCaptureError(t *testing.
func TestCaptureScreenshotWithoutActivationSkipsBringToFrontWhenDisallowed(t *testing.T) {
exec := &screenshotExecutor{}
ctx := cdp.WithExecutor(context.Background(), exec)
- if _, err := captureScreenshotWithoutActivation(ctx, page.CaptureScreenshot(), false); err != nil {
+ if _, err := captureScreenshotWithoutActivation(ctx, page.CaptureScreenshot(), true); err != nil {
t.Fatalf("capture: %v", err)
}
for _, m := range exec.methods {
diff --git a/internal/config/config_file.go b/internal/config/config_file.go
index b6f124f9..f0abe1e8 100644
--- a/internal/config/config_file.go
+++ b/internal/config/config_file.go
@@ -117,6 +117,7 @@ func DefaultFileConfig() FileConfig {
restartMaxBackoffSec := 60
restartStableAfterSec := 300
maxTabs := 20
+ captureAllowActivation := true
allowEvaluate := false
allowMacro := false
allowScreencast := false
@@ -177,10 +178,11 @@ func DefaultFileConfig() FileConfig {
Default: DefaultBrowserForSystem(),
},
InstanceDefaults: InstanceDefaultsConfig{
- Mode: "headless",
- MaxTabs: &maxTabs,
- StealthLevel: "light",
- TabEvictionPolicy: "close_lru",
+ Mode: "headless",
+ MaxTabs: &maxTabs,
+ CaptureAllowActivation: &captureAllowActivation,
+ StealthLevel: "light",
+ TabEvictionPolicy: "close_lru",
},
Security: SecurityConfig{
AllowEvaluate: &allowEvaluate,
diff --git a/internal/handlers/capture.go b/internal/handlers/capture.go
index bf6ef83f..a6abd23a 100644
--- a/internal/handlers/capture.go
+++ b/internal/handlers/capture.go
@@ -118,11 +118,11 @@ func (h *Handlers) HandleCapture(w http.ResponseWriter, r *http.Request) {
opts := bridge.CaptureOpts{
Image: bridge.ScreenshotOpts{
- Format: format,
- Quality: quality,
- BeyondViewport: beyondViewport,
- Scale: scale,
- AllowActivation: h.Config.CaptureAllowActivation,
+ Format: format,
+ Quality: quality,
+ BeyondViewport: beyondViewport,
+ Scale: scale,
+ DisableActivation: !h.Config.CaptureAllowActivation,
},
Filter: filter,
MaxDepth: depth,
diff --git a/internal/handlers/screenshot.go b/internal/handlers/screenshot.go
index 5392332c..83c5f7cd 100644
--- a/internal/handlers/screenshot.go
+++ b/internal/handlers/screenshot.go
@@ -104,12 +104,12 @@ func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {
cdpFormat = bridge.ScreenshotFormatPng
}
buf, captureErr := bridge.CaptureScreenshot(tCtx, bridge.ScreenshotOpts{
- Format: cdpFormat,
- Quality: req.quality,
- Clip: clip,
- BeyondViewport: req.beyondViewport,
- Scale: req.scale,
- AllowActivation: h.Config.CaptureAllowActivation,
+ Format: cdpFormat,
+ Quality: req.quality,
+ Clip: clip,
+ BeyondViewport: req.beyondViewport,
+ Scale: req.scale,
+ DisableActivation: !h.Config.CaptureAllowActivation,
})
if captureErr != nil {
httpx.Error(w, 500, fmt.Errorf("screenshot: %w", captureErr))