High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: snapshots omit checkbox and radio checked state, so an agent cannot see which options are selected (PIN-102)
Luigi Agosti445686df2d49
diff --git a/docs/reference/snapshot.md b/docs/reference/snapshot.mdindex 70ff92e1..4e2e4a81 100644--- a/docs/reference/snapshot.md+++ b/docs/reference/snapshot.md@@ -53,6 +53,43 @@ pinchtab snap --max-tokens 2000 # Limit output size| `maxTokens` | Token budget limit || `depth` | Tree depth limit |+## Control state on a node++A snapshot reports the state of a control, not just its identity, so an agent can+verify its own action and read a page it did not set up:++- `value` — the current text of an input or the selection of a `select`+- `focused`, `disabled`, `hidden` — booleans, present only when true+- `checked` — `"true"`, `"false"` or `"mixed"` for a checkbox, radio,+ `menuitemcheckbox`, `menuitemradio`, or any element carrying `aria-checked`++`checked` is a three-value string rather than a boolean because `"mixed"` is a real+state: both a native indeterminate checkbox and `aria-checked="mixed"` report it.++**An absent `checked` means the node has no checkedness — never that it is off.**+Ordinary nodes do not carry the key at all, so a missing value must not be read as+unchecked. A control that is off says so explicitly with `"false"`.++The rendered formats carry all three states, so an unchecked option never looks+like a node the field does not apply to:++| State | `format=text` | `format=compact` |+|-------|---------------|------------------|+| checked | `[checked]` | `[x]` |+| unchecked | `[unchecked]` | `[ ]` |+| mixed | `[mixed]` | `[/]` |++A radio group is therefore readable from a single snapshot:++```+e4 radio "Standard shipping" [checked]+e5 radio "Express shipping" [unchecked]+e6 radio "Pickup" [unchecked]+```++Diff mode treats a change of `checked` as a change, so `pinchtab snap -d` after a+`check` shows the node as `[~]`.+## Related Pages- [Click](./click.md)diff --git a/internal/bridge/observe/snapshot.go b/internal/bridge/observe/snapshot.goindex 63216c62..b51a7571 100644--- a/internal/bridge/observe/snapshot.go+++ b/internal/bridge/observe/snapshot.go@@ -28,10 +28,39 @@ func IsSensitiveAutocomplete(value string) bool {return false}+// CheckedState is the tri-state checkedness of a checkable control, taken+// verbatim from the accessibility tree's own "checked" property. It is a+// three-value string rather than a bool because "mixed" is a real state — a+// native indeterminate checkbox and aria-checked="mixed" both report it — and+// because ABSENT must never read as unchecked: the empty value means this node+// has no checkedness, not that it is off. A bool could not say all three things.+type CheckedState string++const (+ CheckedTrue CheckedState = "true"+ CheckedFalse CheckedState = "false"+ CheckedMixed CheckedState = "mixed"+)++// checkedStateFromAX accepts only the three states the accessibility tree+// defines. Anything else — including an empty value — leaves the field absent,+// so an unrecognised reading is reported as "no answer" rather than as "off".+func checkedStateFromAX(value string) (CheckedState, bool) {+ switch CheckedState(value) {+ case CheckedTrue, CheckedFalse, CheckedMixed:+ return CheckedState(value), true+ }+ return "", false+}+// A11yNode is one snapshot node. Visible is a pointer because nil (absent on// the wire) means the bounds pass never measured this node, which is a// different statement from a measured false: it is set exactly when// BoundingBox is.+//+// Checked is empty for every node that has no checkedness. Only a checkable+// control gets it, because only such a control carries the accessibility+// property it is read from.type A11yNode struct {Ref string `json:"ref"`Role string `json:"role"`@@ -47,6 +76,7 @@ type A11yNode struct {Tag string `json:"tag,omitempty"`Disabled bool `json:"disabled,omitempty"`Focused bool `json:"focused,omitempty"`+ Checked CheckedState `json:"checked,omitempty"`Hidden bool `json:"hidden,omitempty"`NodeID int64 `json:"nodeId,omitempty"`FrameID string `json:"frameId,omitempty"`@@ -471,6 +501,19 @@ func BuildSnapshot(nodes []RawAXNode, filter string, maxDepth int) ([]A11yNode,if prop.Name == "focused" && prop.Value.String() == "true" {entry.Focused = true}+ // The accessibility tree already answers this for checkboxes, radios,+ // menuitemcheckbox/radio and any custom role carrying aria-checked, and+ // it answers "mixed" for a native indeterminate box too. Reading it here+ // costs nothing: no DOM access and no extra round trip. The other route+ // — evaluating aria-checked in the page, as /checked and the check action+ // do — would add a page call to every snapshot and would have to run in+ // the best-effort DOM pass, where a failure produces an absent field that+ // every consumer reads as unchecked.+ if prop.Name == "checked" {+ if state, ok := checkedStateFromAX(prop.Value.String()); ok {+ entry.Checked = state+ }+ }// Unconditional by design: this pass has no DOM access, and the DOM// enrichment that knows whether the field is empty is best-effort. If// it never runs, this mask is what keeps a password out of the@@ -617,7 +660,7 @@ func DiffSnapshot(prev, curr []A11yNode) (added, changed, removed []A11yNode) {old, existed := prevMap[key]if !existed {added = append(added, n)- } else if old.Value != n.Value || old.Focused != n.Focused || old.Disabled != n.Disabled {+ } else if old.Value != n.Value || old.Focused != n.Focused || old.Disabled != n.Disabled || old.Checked != n.Checked {changed = append(changed, n)}}diff --git a/internal/bridge/observe/snapshot_checked_test.go b/internal/bridge/observe/snapshot_checked_test.gonew file mode 100644index 00000000..c02aab9d--- /dev/null+++ b/internal/bridge/observe/snapshot_checked_test.go@@ -0,0 +1,285 @@+package observe++import (+ "context"+ "encoding/base64"+ "encoding/json"+ "strings"+ "testing"+ "time"++ "github.com/chromedp/chromedp"+ "github.com/pinchtab/pinchtab/internal/testbrowser"+)++// checkedFixtureHTML covers every case the field has to answer for: a checked and+// an unchecked native box, a native INDETERMINATE box (which reports mixed with no+// aria attribute at all), a radio group where one option is on, a custom+// role=checkbox and a menuitemcheckbox, and two controls — a textbox and a button+// — that must not gain the field.+const checkedFixtureHTML = `<body>+<input id="name" type="text" value="Alice">+<input id="on" type="checkbox" checked>+<input id="off" type="checkbox">+<input id="ind" type="checkbox">+<input id="r1" type="radio" name="group" checked>+<input id="r2" type="radio" name="group">+<div id="custom" role="checkbox" aria-checked="mixed" tabindex="0">Custom</div>+<div id="menu" role="menuitemcheckbox" aria-checked="true" tabindex="0">Menu item</div>+<button id="go">Go</button>+<script>document.getElementById('ind').indeterminate = true;</script>+</body>`++func newCheckedFixture(t *testing.T) context.Context {+ t.Helper()+ chromePath := testbrowser.Path(t)++ alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(+ chromedp.DefaultExecAllocatorOptions[:],+ chromedp.ExecPath(chromePath),+ chromedp.UserDataDir(t.TempDir()),+ chromedp.Flag("headless", true),+ chromedp.Flag("no-sandbox", true),+ )...)+ ctx, cancelBrowser := chromedp.NewContext(alloc)+ ctx, cancelTimeout := context.WithTimeout(ctx, 30*time.Second)+ t.Cleanup(func() {+ cancelTimeout()+ cancelBrowser()+ cancelAlloc()+ })++ dataURL := "data:text/html;base64," + base64.StdEncoding.EncodeToString([]byte(checkedFixtureHTML))+ if err := chromedp.Run(ctx,+ chromedp.Navigate(dataURL),+ chromedp.WaitVisible("#go", chromedp.ByID),+ ); err != nil {+ t.Fatal(err)+ }+ return ctx+}++func snapshotNodes(t *testing.T, ctx context.Context) []A11yNode {+ t.Helper()+ raw, err := FetchAXTree(ctx)+ if err != nil {+ t.Fatal(err)+ }+ nodes, _ := BuildSnapshot(raw, "", -1)+ if len(nodes) == 0 {+ t.Fatal("snapshot produced no nodes")+ }+ return nodes+}++func nodesByRole(nodes []A11yNode, role string) []A11yNode {+ var out []A11yNode+ for _, n := range nodes {+ if n.Role == role {+ out = append(out, n)+ }+ }+ return out+}++// The reported defect: a checked and an unchecked control were byte-identical in+// the snapshot apart from their identity, so an agent could not read a radio group+// or verify its own check without one extra call per element.+func TestSnapshotReportsCheckedStateForCheckableControls(t *testing.T) {+ nodes := snapshotNodes(t, newCheckedFixture(t))++ checkboxes := nodesByRole(nodes, "checkbox")+ if len(checkboxes) != 4 {+ t.Fatalf("found %d checkbox nodes, want 4 (on, off, indeterminate, custom)", len(checkboxes))+ }+ states := map[CheckedState]int{}+ for _, n := range checkboxes {+ states[n.Checked]+++ }+ if states[CheckedTrue] != 1 || states[CheckedFalse] != 1 || states[CheckedMixed] != 2 {+ t.Errorf("checkbox states = %v, want one true, one false and two mixed (native indeterminate + aria-checked=mixed)", states)+ }++ radios := nodesByRole(nodes, "radio")+ if len(radios) != 2 {+ t.Fatalf("found %d radio nodes, want 2", len(radios))+ }+ // The whole point of the card: which option is selected is readable from ONE+ // snapshot, with no follow-up call per option.+ selected := 0+ for _, n := range radios {+ switch n.Checked {+ case CheckedTrue:+ selected+++ case CheckedFalse:+ default:+ t.Errorf("radio %s reports checked=%q; a radio always has a checkedness", n.Ref, n.Checked)+ }+ }+ if selected != 1 {+ t.Errorf("%d radios report checked=true, want exactly 1", selected)+ }++ menu := nodesByRole(nodes, "menuitemcheckbox")+ if len(menu) != 1 || menu[0].Checked != CheckedTrue {+ t.Errorf("menuitemcheckbox nodes = %+v, want one reporting checked=true", menu)+ }+}++// Absent must mean "this node has no checkedness", never "unchecked". A node that+// gained checked=false here would be a positive false statement about the page.+func TestNodesWithoutCheckednessDoNotGainTheField(t *testing.T) {+ nodes := snapshotNodes(t, newCheckedFixture(t))++ checkableRoles := map[string]bool{"checkbox": true, "radio": true, "menuitemcheckbox": true, "menuitemradio": true}+ for _, n := range nodes {+ if checkableRoles[n.Role] {+ continue+ }+ if n.Checked != "" {+ t.Errorf("%s node %s reports checked=%q; checkedness is meaningless for it", n.Role, n.Ref, n.Checked)+ }+ }++ // Named explicitly, because these two are the controls a wrong role list would+ // most likely sweep in.+ for _, role := range []string{"textbox", "button"} {+ found := nodesByRole(nodes, role)+ if len(found) == 0 {+ t.Fatalf("fixture produced no %s node, so this guard checks nothing", role)+ }+ for _, n := range found {+ if n.Checked != "" {+ t.Errorf("%s reports checked=%q, want the field absent", role, n.Checked)+ }+ }+ }+}++// The round trip the card asked for: the observation surface must change when the+// state does, in both directions, for the same ref.+func TestSnapshotFollowsCheckAndUncheckOnTheSameRef(t *testing.T) {+ ctx := newCheckedFixture(t)++ // Re-read the SAME ref each time: the card asks for the observation surface to+ // follow the state, not for two readings of two different nodes.+ stateOf := func(t *testing.T, ref string) CheckedState {+ t.Helper()+ for _, n := range nodesByRole(snapshotNodes(t, ctx), "checkbox") {+ if n.Ref == ref {+ return n.Checked+ }+ }+ t.Fatalf("checkbox %s is no longer in the snapshot", ref)+ return ""+ }++ // Find the ref of the initially-unchecked native box.+ var ref string+ for _, n := range nodesByRole(snapshotNodes(t, ctx), "checkbox") {+ if n.Checked == CheckedFalse {+ ref = n.Ref+ break+ }+ }+ if ref == "" {+ t.Fatal("fixture has no unchecked checkbox to toggle")+ }++ if err := chromedp.Run(ctx, chromedp.Click("#off", chromedp.ByID)); err != nil {+ t.Fatal(err)+ }+ if state := stateOf(t, ref); state != CheckedTrue {+ t.Fatalf("after check, %s reports checked=%q, want true", ref, state)+ }++ if err := chromedp.Run(ctx, chromedp.Click("#off", chromedp.ByID)); err != nil {+ t.Fatal(err)+ }+ if state := stateOf(t, ref); state != CheckedFalse {+ t.Fatalf("after uncheck, %s reports checked=%q, want false", ref, state)+ }+}++// A snapshot diff drives the change markers, so a check that does not register as+// a CHANGE leaves an agent watching diffs blind to exactly the event it acted on.+func TestSnapshotDiffTreatsACheckedChangeAsAChange(t *testing.T) {+ before := []A11yNode{{Ref: "e1", Role: "checkbox", NodeID: 7, Checked: CheckedFalse}}+ after := []A11yNode{{Ref: "e1", Role: "checkbox", NodeID: 7, Checked: CheckedTrue}}++ added, changed, removed := DiffSnapshot(before, after)+ if len(added) != 0 || len(removed) != 0 {+ t.Fatalf("added %v removed %v, want neither for the same node", added, removed)+ }+ if len(changed) != 1 || changed[0].Ref != "e1" {+ t.Fatalf("changed = %v, want the checkbox whose state moved", changed)+ }+}++// The three states must be distinguishable in the rendered forms too, and a node+// WITHOUT checkedness must not look like an unchecked one.+func TestRenderedFormatsDistinguishAllThreeCheckedStates(t *testing.T) {+ nodes := []A11yNode{+ {Ref: "e1", Role: "checkbox", Checked: CheckedTrue},+ {Ref: "e2", Role: "checkbox", Checked: CheckedFalse},+ {Ref: "e3", Role: "checkbox", Checked: CheckedMixed},+ {Ref: "e4", Role: "button", Name: "Go"},+ }++ text := FormatSnapshotText(nodes)+ for _, want := range []string{"e1 checkbox [checked]", "e2 checkbox [unchecked]", "e3 checkbox [mixed]"} {+ if !strings.Contains(text, want) {+ t.Errorf("text output missing %q:\n%s", want, text)+ }+ }+ for _, line := range strings.Split(text, "\n") {+ if strings.HasPrefix(strings.TrimSpace(line), "e4 ") && strings.Contains(line, "check") {+ t.Errorf("a node without checkedness carries a checked annotation: %q", line)+ }+ }++ compact := FormatSnapshotCompact(nodes)+ for _, want := range []string{"e1:checkbox [x]", "e2:checkbox [ ]", "e3:checkbox [/]"} {+ if !strings.Contains(compact, want) {+ t.Errorf("compact output missing %q:\n%s", want, compact)+ }+ }++ // [~] is the compact diff's "changed" marker, so mixed must not reuse it: one+ // token meaning two things on the same line cannot be read.+ if strings.Contains(compact, "[~]") {+ t.Errorf("compact checked annotation collides with the diff's changed marker:\n%s", compact)+ }+}++// Absent is not a state, so an unrecognised or empty accessibility reading must+// leave the field off rather than defaulting to unchecked.+func TestUnrecognisedCheckedReadingIsNotReportedAsUnchecked(t *testing.T) {+ for _, raw := range []string{"", "undefined", "TRUE", "yes", "0"} {+ if state, ok := checkedStateFromAX(raw); ok {+ t.Errorf("checkedStateFromAX(%q) = %q, accepted; only true/false/mixed are answers", raw, state)+ }+ }+ for raw, want := range map[string]CheckedState{"true": CheckedTrue, "false": CheckedFalse, "mixed": CheckedMixed} {+ state, ok := checkedStateFromAX(raw)+ if !ok || state != want {+ t.Errorf("checkedStateFromAX(%q) = %q,%v want %q,true", raw, state, ok, want)+ }+ }++ // On the wire, absent means absent: the key must not appear at all.+ encoded, err := json.Marshal(A11yNode{Ref: "e1", Role: "button"})+ if err != nil {+ t.Fatal(err)+ }+ if strings.Contains(string(encoded), "checked") {+ t.Errorf("a node with no checkedness serialises a checked key: %s", encoded)+ }+ encoded, err = json.Marshal(A11yNode{Ref: "e2", Role: "checkbox", Checked: CheckedFalse})+ if err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(string(encoded), `"checked":"false"`) {+ t.Errorf("a measured false must reach the wire: %s", encoded)+ }+}diff --git a/internal/bridge/observe/snapshot_format.go b/internal/bridge/observe/snapshot_format.goindex 21f5e71b..8151674e 100644--- a/internal/bridge/observe/snapshot_format.go+++ b/internal/bridge/observe/snapshot_format.go@@ -2,6 +2,25 @@ package observeimport "strings"+// checkedAnnotations render all THREE states, not just the checked one. A bare+// node and an unchecked one must not look alike: absent means the control has no+// checkedness, false means it is off, and an agent reading a radio group needs to+// tell those apart at a glance. The compact forms stay three characters so a+// five-option group costs fifteen.+var checkedAnnotations = map[CheckedState]string{+ CheckedTrue: " [checked]",+ CheckedFalse: " [unchecked]",+ CheckedMixed: " [mixed]",+}++// [~] is NOT available here: the compact diff renderer already uses it for+// "changed", and the same token meaning two things on one line is unreadable.+var checkedCompactAnnotations = map[CheckedState]string{+ CheckedTrue: " [x]",+ CheckedFalse: " [ ]",+ CheckedMixed: " [/]",+}+func FormatSnapshotText(nodes []A11yNode) string {var b strings.Builderfor _, n := range nodes {@@ -24,6 +43,9 @@ func FormatSnapshotText(nodes []A11yNode) string {if n.Focused {b.WriteString(" [focused]")}+ if annotation, ok := checkedAnnotations[n.Checked]; ok {+ b.WriteString(annotation)+ }if n.Disabled {b.WriteString(" [disabled]")}@@ -54,6 +76,9 @@ func FormatSnapshotCompact(nodes []A11yNode) string {if n.Focused {b.WriteString(" *")}+ if annotation, ok := checkedCompactAnnotations[n.Checked]; ok {+ b.WriteString(annotation)+ }if n.Disabled {b.WriteString(" -")}@@ -96,6 +121,9 @@ func FormatSnapshotCompactDiff(nodes []A11yNode, added, changed, removed []A11yNif n.Focused {b.WriteString(" *")}+ if annotation, ok := checkedCompactAnnotations[n.Checked]; ok {+ b.WriteString(annotation)+ }if n.Disabled {b.WriteString(" -")}@@ -128,10 +156,10 @@ func TruncateToTokens(nodes []A11yNode, maxTokens int, format string) ([]A11yNodvar nodeTokens intswitch format {case "compact":- size := len(n.Ref) + 1 + len(n.Role) + len(n.Name) + len(n.Value) + 8+ size := len(n.Ref) + 1 + len(n.Role) + len(n.Name) + len(n.Value) + 8 + len(checkedCompactAnnotations[n.Checked])nodeTokens = size / 4case "text":- size := n.Depth*2 + len(n.Ref) + 1 + len(n.Role) + len(n.Name) + len(n.Value) + 8+ size := n.Depth*2 + len(n.Ref) + 1 + len(n.Role) + len(n.Name) + len(n.Value) + 8 + len(checkedAnnotations[n.Checked])nodeTokens = size / 4default:size := len(n.Ref) + len(n.Role) + len(n.Name) + len(n.Value) + 60