Skip to content

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

feat: GET /visible and the capture snapshot's visible field answer… (PIN-188)

Luigi Agosti75fdb27f1eeb
diff --git a/cmd/pinchtab/cmd_cli_browser_inspect.go b/cmd/pinchtab/cmd_cli_browser_inspect.go
index 14b978d0..c6420497 100644
--- a/cmd/pinchtab/cmd_cli_browser_inspect.go
+++ b/cmd/pinchtab/cmd_cli_browser_inspect.go
@@ -172,8 +172,12 @@ var boxCmd = &cobra.Command{
var visibleCmd = &cobra.Command{
Use: "visible <ref>",
- Short: "Check if an element is visible by ref",
- Args: cobra.ExactArgs(1),
+ Short: "Check if an element is rendered (display/visibility/opacity/size) by ref",
+ Long: `Check if an element is rendered by ref: display, visibility, opacity and a
+non-zero box. Scroll position is not an input, so an element far below the fold
+is still rendered. Use --json to also read onScreen, the viewport-intersection
+answer that the capture snapshot's per-node visible field publishes.`,
+ Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
runCLI(func(rt cliRuntime) {
browseractions.Visible(rt.client, rt.base, rt.token, cmd, args)
diff --git a/docs/reference/capture.md b/docs/reference/capture.md
index eb3eb378..026b00df 100644
--- a/docs/reference/capture.md
+++ b/docs/reference/capture.md
@@ -118,6 +118,21 @@ taken: `withBounds=false`, a node with no backend node id, or a node whose
box query failed. Treat a missing `visible` as unknown and a present
`false` as off-screen; they are different answers.
+### `visible` here is not `GET /visible`
+
+`GET /visible` (and `pinchtab visible <ref>`) answers a different question
+under the same word: **CSS rendered-ness** — `display`, `visibility`,
+`opacity`, and a laid-out or positioned box with non-zero size. **Scroll
+position is not an input**, so an element far below the fold is `"visible":
+true` there while this snapshot reports `"visible": false` for the same node
+at the same moment. Both answers are correct and both are wanted: one says
+the element is rendered at all, the other says it is on screen right now.
+
+`GET /visible` also returns `onScreen`, which is this snapshot's predicate
+computed for that one element, so a single call answers both questions.
+`onScreen` follows the same absent-means-not-measured rule as `visible`
+above.
+
## Useful flags
### API Query Parameters
diff --git a/internal/bridge/observe/bounds.go b/internal/bridge/observe/bounds.go
index af89de4b..ce72dec4 100644
--- a/internal/bridge/observe/bounds.go
+++ b/internal/bridge/observe/bounds.go
@@ -82,7 +82,7 @@ func AnnotateBounds(ctx context.Context, nodes []A11yNode, pageCoords bool, vp V
if !ok {
continue
}
- visible := isVisible(box, vp)
+ visible := IsOnScreen(box, vp)
if pageCoords {
box.X += vp.ScrollX
box.Y += vp.ScrollY
@@ -149,9 +149,12 @@ func ElementBorderBox(ctx context.Context, backendNodeID int64) (BoundingBox, bo
return BoundingBox{X: minX, Y: minY, W: maxX - minX, H: maxY - minY}, true
}
-// isVisible takes b in viewport coordinates, the space DOM.getBoxModel reports
-// and the space AnnotateBounds measures in before any document transform.
-func isVisible(b BoundingBox, vp ViewportInfo) bool {
+// IsOnScreen is the one owner of the on-screen question: positive area AND
+// intersection with the viewport. b is in viewport coordinates, the space
+// DOM.getBoxModel reports and the space AnnotateBounds measures in before any
+// document transform. It is deliberately NOT the rendered-ness question that
+// GET /visible answers — that predicate ignores scroll position.
+func IsOnScreen(b BoundingBox, vp ViewportInfo) bool {
if b.W <= 0 || b.H <= 0 {
return false
}
diff --git a/internal/bridge/observe/bounds_test.go b/internal/bridge/observe/bounds_test.go
index 8148f548..3b933501 100644
--- a/internal/bridge/observe/bounds_test.go
+++ b/internal/bridge/observe/bounds_test.go
@@ -11,19 +11,19 @@ import (
"github.com/pinchtab/pinchtab/internal/testbrowser"
)
-// The scroll offset must not enter the test: boxes reach isVisible in viewport
+// The scroll offset must not enter the test: boxes reach IsOnScreen in viewport
// coordinates, so a page scrolled to y=1000 sees the same numbers as an
// unscrolled one.
func TestIsVisibleUsesViewportCoordinates(t *testing.T) {
vp := ViewportInfo{Width: 800, Height: 600, ScrollX: 0, ScrollY: 1000}
- if !isVisible(BoundingBox{X: 20, Y: 50, W: 100, H: 40}, vp) {
+ if !IsOnScreen(BoundingBox{X: 20, Y: 50, W: 100, H: 40}, vp) {
t.Fatal("box inside the viewport should be visible")
}
- if isVisible(BoundingBox{X: 20, Y: -200, W: 100, H: 40}, vp) {
+ if IsOnScreen(BoundingBox{X: 20, Y: -200, W: 100, H: 40}, vp) {
t.Fatal("box scrolled above the viewport should not be visible")
}
- if isVisible(BoundingBox{X: 20, Y: 700, W: 100, H: 40}, vp) {
+ if IsOnScreen(BoundingBox{X: 20, Y: 700, W: 100, H: 40}, vp) {
t.Fatal("box below the viewport should not be visible")
}
}
diff --git a/internal/bridge/observe_facade.go b/internal/bridge/observe_facade.go
index 72e68cbe..6685a9ba 100644
--- a/internal/bridge/observe_facade.go
+++ b/internal/bridge/observe_facade.go
@@ -76,6 +76,10 @@ func ElementBorderBox(ctx context.Context, backendNodeID int64) (BoundingBox, bo
return bridgeobserve.ElementBorderBox(ctx, backendNodeID)
}
+func IsOnScreen(box BoundingBox, vp ViewportInfo) bool {
+ return bridgeobserve.IsOnScreen(box, vp)
+}
+
func FetchAXTree(ctx context.Context) ([]RawAXNode, error) {
return bridgeobserve.FetchAXTree(ctx)
}
diff --git a/internal/handlers/box_frame_test.go b/internal/handlers/box_frame_test.go
index e1a6e0e6..173c9547 100644
--- a/internal/handlers/box_frame_test.go
+++ b/internal/handlers/box_frame_test.go
@@ -202,12 +202,9 @@ func TestVisibleIsFrameLocalForInFrameRef(t *testing.T) {
f := newFrameFixture(t)
nodeID := f.nodeIDByName(t, "button", "frame button")
- f.handlers.Bridge.SetRefCache("tab-frame", &bridge.RefCache{Targets: map[string]bridge.RefTarget{
- "e0": {BackendNodeID: nodeID},
- }})
- visible, err := f.handlers.getElementVisible(f.ctx, "tab-frame", "ref:e0")
+ visible, err := f.handlers.elementRendered(f.ctx, nodeID)
if err != nil {
- t.Fatalf("getElementVisible: %v", err)
+ t.Fatalf("elementRendered: %v", err)
}
if !visible {
t.Fatal("an in-frame button that is on screen reported not visible")
diff --git a/internal/handlers/capture_test.go b/internal/handlers/capture_test.go
index df92b5e9..9ec18fe8 100644
--- a/internal/handlers/capture_test.go
+++ b/internal/handlers/capture_test.go
@@ -296,3 +296,73 @@ func TestCaptureEnvelopeEmbedsSnapshotNodesVerbatim(t *testing.T) {
t.Fatal("the capture envelope no longer embeds result.Nodes directly; re-mapping nodes into a literal drops whatever field the map forgets")
}
}
+
+// visible drives GET /visible for a ref the capture just published, on the same
+// tab and at the same scroll position.
+func (f captureFixture) visible(t *testing.T, ref string) map[string]any {
+ t.Helper()
+ rec := httptest.NewRecorder()
+ f.handlers.HandleGetVisible(rec, httptest.NewRequest(http.MethodGet, "/visible?ref="+ref+"&tabId="+capturePairTabID, nil))
+ if rec.Code != http.StatusOK {
+ t.Fatalf("/visible?ref=%s status %d: %s", ref, rec.Code, rec.Body.String())
+ }
+ var body map[string]any
+ if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
+ t.Fatalf("decode /visible response: %v (body %s)", err, rec.Body.String())
+ }
+ return body
+}
+
+// Two surfaces publish a boolean called visible for the same node and they
+// answer different questions: GET /visible is CSS rendered-ness with scroll
+// position as no input, the capture snapshot's field is viewport intersection.
+// Both answers are wanted, so this fixture holds them apart — a later change
+// that quietly aligns the two predicates reds here. The endpoint's own onScreen
+// field is the bridge between them and must agree with capture node for node.
+func TestTheVisibleEndpointAndCaptureAnswerDifferentQuestions(t *testing.T) {
+ f := newCaptureFixture(t)
+ nodes := f.capture(t, "&"+captureBoundsParam+"=true")
+
+ for _, tc := range []struct {
+ name string
+ wantCapture bool
+ wantRendered bool
+ wantOnScreen bool
+ whyTheyDisagree string
+ }{
+ {
+ name: "TopBtn", wantCapture: false, wantRendered: true, wantOnScreen: false,
+ whyTheyDisagree: "scrolled past above: rendered by CSS, not intersecting the viewport",
+ },
+ {
+ name: "BotBtn", wantCapture: true, wantRendered: true, wantOnScreen: true,
+ whyTheyDisagree: "on screen: both questions answer true, so the divergence above is not a blanket disagreement",
+ },
+ } {
+ node := nodeByName(t, nodes, tc.name)
+ if node["visible"] != tc.wantCapture {
+ t.Fatalf("%s: capture visible = %v, want %v (%s)", tc.name, node["visible"], tc.wantCapture, tc.whyTheyDisagree)
+ }
+
+ ref, _ := node["ref"].(string)
+ if ref == "" {
+ t.Fatalf("%s: capture node published no ref: %v", tc.name, node)
+ }
+ body := f.visible(t, ref)
+
+ if body["visible"] != tc.wantRendered {
+ t.Errorf("%s: /visible visible = %v, want %v — the endpoint answers CSS rendered-ness and scroll position is not an input (%s)",
+ tc.name, body["visible"], tc.wantRendered, tc.whyTheyDisagree)
+ }
+ onScreen, ok := body["onScreen"]
+ if !ok {
+ t.Fatalf("%s: /visible published no onScreen for a node capture measured: %v", tc.name, body)
+ }
+ if onScreen != tc.wantOnScreen {
+ t.Errorf("%s: /visible onScreen = %v, want %v", tc.name, onScreen, tc.wantOnScreen)
+ }
+ if onScreen != node["visible"] {
+ t.Errorf("%s: /visible onScreen = %v but capture visible = %v; they must be the same predicate", tc.name, onScreen, node["visible"])
+ }
+ }
+}
diff --git a/internal/handlers/visible.go b/internal/handlers/visible.go
index 4280b3ba..f8cc2396 100644
--- a/internal/handlers/visible.go
+++ b/internal/handlers/visible.go
@@ -3,24 +3,38 @@ package handlers
import (
"context"
"net/http"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
)
+// visibleResponse answers two different questions about one element. Visible is
+// CSS rendered-ness — display, visibility, opacity, a positioned or laid-out box
+// with non-zero size — and scroll position is not an input, so an element far
+// below the fold is still visible:true. OnScreen is viewport intersection, the
+// same predicate the capture snapshot's per-node visible field publishes.
+// OnScreen is absent when the element could not be measured, matching the
+// capture rule that a missing answer means "not measured", never "no".
type visibleResponse struct {
- Ref string `json:"ref"`
- Visible bool `json:"visible"`
+ Ref string `json:"ref"`
+ Visible bool `json:"visible"`
+ OnScreen *bool `json:"onScreen,omitempty"`
}
-// HandleGetVisible returns whether an element identified by a unified selector
-// (ref/css/xpath/text/semantic) is visible on the page.
+// HandleGetVisible reports whether an element identified by a unified selector
+// (ref/css/xpath/text/semantic) is rendered, plus whether it is on screen.
//
// @Endpoint GET /visible
func (h *Handlers) HandleGetVisible(w http.ResponseWriter, r *http.Request) {
h.serveElementInspection(w, r, "inspect.visible", func(ctx context.Context, tabID, sel string) (any, error) {
- visible, err := h.getElementVisible(ctx, tabID, sel)
+ nodeID, err := h.resolveElementNodeID(ctx, tabID, sel)
+ if err != nil {
+ return nil, err
+ }
+ rendered, err := h.elementRendered(ctx, nodeID)
if err != nil {
return nil, err
}
- return visibleResponse{Ref: sel, Visible: visible}, nil
+ return visibleResponse{Ref: sel, Visible: rendered, OnScreen: elementOnScreen(ctx, nodeID)}, nil
})
}
@@ -40,6 +54,25 @@ const elementVisibleJS = `function() {
return rect.width > 0 && rect.height > 0;
}`
-func (h *Handlers) getElementVisible(ctx context.Context, tabID, sel string) (bool, error) {
- return callOnResolvedElement[bool](h, ctx, tabID, sel, elementVisibleJS, nil)
+func (h *Handlers) elementRendered(ctx context.Context, nodeID int64) (bool, error) {
+ var rendered bool
+ err := h.Bridge.CallFunctionOnNode(ctx, nodeID, elementVisibleJS, nil, &rendered)
+ return rendered, err
+}
+
+// elementOnScreen measures through the same border-box and viewport pair the
+// capture path uses and asks bridge.IsOnScreen, so this endpoint and the capture
+// snapshot cannot drift apart on the on-screen question. nil when the element
+// has no box model or the layout read fails: unknown, not false.
+func elementOnScreen(ctx context.Context, nodeID int64) *bool {
+ box, ok := bridge.ElementBorderBox(ctx, nodeID)
+ if !ok {
+ return nil
+ }
+ vp, err := bridge.FetchLayout(ctx)
+ if err != nil {
+ return nil
+ }
+ onScreen := bridge.IsOnScreen(box, vp)
+ return &onScreen
}
diff --git a/internal/handlers/visible_test.go b/internal/handlers/visible_test.go
index b33ac069..b29178dc 100644
--- a/internal/handlers/visible_test.go
+++ b/internal/handlers/visible_test.go
@@ -6,6 +6,8 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
+ "os"
+ "strconv"
"strings"
"testing"
"time"
@@ -149,6 +151,11 @@ func TestVisibleRoutesRegistered(t *testing.T) {
type visibleMockBridge struct {
mockBridge
refCache *bridge.RefCache
+ rendered bool
+}
+
+func (m *visibleMockBridge) CallFunctionOnNode(ctx context.Context, backendNodeID int64, functionDecl string, args []map[string]any, result any) error {
+ return json.Unmarshal([]byte(strconv.FormatBool(m.rendered)), result)
}
func (m *visibleMockBridge) GetRefCache(tabID string) *bridge.RefCache {
@@ -262,3 +269,90 @@ func TestTheVisiblePredicateNeverReadsTheInlineStyleAttribute(t *testing.T) {
t.Errorf("style.position is read before getComputedStyle assigns it:\n%s", elementVisibleJS)
}
}
+
+// The browser-backed divergence test lives in capture_test.go and skips where no
+// browser is installed, so the property it protects is also stated here, where a
+// browser is never needed: the endpoint predicate must not learn about scroll.
+func TestTheVisiblePredicateNeverConsultsScrollOrViewport(t *testing.T) {
+ for _, banned := range []string{"innerHeight", "innerWidth", "scrollY", "scrollX", "pageYOffset", "pageXOffset", "IntersectionObserver"} {
+ if strings.Contains(elementVisibleJS, banned) {
+ t.Errorf("the visible predicate reads %s, so it has become an on-screen check; that answer belongs to onScreen via bridge.IsOnScreen:\n%s", banned, elementVisibleJS)
+ }
+ }
+}
+
+// onScreen must stay the capture path's own predicate rather than a second
+// implementation that can drift from it — this card exists because two spellings
+// of one question disagreed.
+func TestTheOnScreenAnswerDelegatesToTheCapturePredicate(t *testing.T) {
+ src, err := os.ReadFile("visible.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(string(src), "bridge.IsOnScreen(") {
+ t.Fatal("visible.go no longer asks bridge.IsOnScreen; the endpoint would answer on-screen-ness with its own predicate and could disagree with the capture snapshot")
+ }
+ if !strings.Contains(string(src), "bridge.ElementBorderBox(") || !strings.Contains(string(src), "bridge.FetchLayout(") {
+ t.Fatal("visible.go no longer measures through the border box and layout the capture path uses")
+ }
+}
+
+func TestVisibleResponseOmitsOnScreenWhenUnmeasured(t *testing.T) {
+ measured := false
+ for _, tc := range []struct {
+ name string
+ response visibleResponse
+ wantKey bool
+ wantVal any
+ }{
+ {name: "unmeasured", response: visibleResponse{Ref: "e1", Visible: true}, wantKey: false},
+ {name: "measured false", response: visibleResponse{Ref: "e1", Visible: true, OnScreen: &measured}, wantKey: true, wantVal: false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ encoded, err := json.Marshal(tc.response)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var decoded map[string]any
+ if err := json.Unmarshal(encoded, &decoded); err != nil {
+ t.Fatal(err)
+ }
+ value, ok := decoded["onScreen"]
+ if ok != tc.wantKey {
+ t.Fatalf("onScreen present = %v, want %v: absent means not measured, and a real false must stay visible (%s)", ok, tc.wantKey, encoded)
+ }
+ if tc.wantKey && value != tc.wantVal {
+ t.Fatalf("onScreen = %v, want %v", value, tc.wantVal)
+ }
+ })
+ }
+}
+
+// An element the endpoint can evaluate but cannot measure still gets its
+// rendered-ness answer; the missing on-screen answer never turns into a false.
+func TestHandleGetVisible_AnswersRenderedWhenNothingCanBeMeasured(t *testing.T) {
+ mb := &visibleMockBridge{
+ rendered: true,
+ refCache: &bridge.RefCache{
+ Refs: map[string]int64{"e1": 100},
+ Targets: map[string]bridge.RefTarget{"e1": {BackendNodeID: 100}},
+ },
+ }
+ h := New(mb, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("GET", "/visible?ref=e1", nil)
+ w := httptest.NewRecorder()
+ h.HandleGetVisible(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var body map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
+ t.Fatal(err)
+ }
+ if body["visible"] != true {
+ t.Fatalf("visible = %v, want true: %s", body["visible"], w.Body.String())
+ }
+ if _, ok := body["onScreen"]; ok {
+ t.Fatalf("onScreen answered without a measurement: %s", w.Body.String())
+ }
+}