High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
refactor: one selector-unwrapping recursion behind a scope abstraction, not one per scope kind (PIN-038)
Luigi Agostice3370ced058
diff --git a/internal/bridge/action_resolve.go b/internal/bridge/action_resolve.goindex 341a1c1d..ffc7fb45 100644--- a/internal/bridge/action_resolve.go+++ b/internal/bridge/action_resolve.go@@ -628,53 +628,107 @@ func resolveSelectorAtWithinNode(ctx context.Context, scopeBackendNodeID int64,})}-func resolveNestedSelectorAtInFrame(ctx context.Context, frameID string, raw string, refCache *RefCache, index int, fromEnd bool) (int64, error) {+// resolveScope is where a search is rooted. Selector grammar — unwrapping+// first:/last:/nth: — does not depend on it, so the recursion below is written+// once against this interface rather than once per scope kind.+type resolveScope interface {+ resolveAt(ctx context.Context, sel selector.Selector, index int, fromEnd bool) (int64, error)+ resolveRef(ctx context.Context, sel selector.Selector, refCache *RefCache) (int64, error)+}++type frameScope struct{ frameID string }++func (s frameScope) resolveAt(ctx context.Context, sel selector.Selector, index int, fromEnd bool) (int64, error) {+ return resolveSelectorAtInFrame(ctx, s.frameID, sel, index, fromEnd)+}++func (s frameScope) resolveRef(_ context.Context, sel selector.Selector, refCache *RefCache) (int64, error) {+ if refCache != nil {+ if target, ok := refCache.Lookup(sel.Value); ok {+ return target.BackendNodeID, nil+ }+ }+ return 0, fmt.Errorf("ref %s not in snapshot cache: %w", sel.Value, ErrSelectorNoMatch)+}++type nodeScope struct{ backendNodeID int64 }++func (s nodeScope) resolveAt(ctx context.Context, sel selector.Selector, index int, fromEnd bool) (int64, error) {+ return resolveSelectorAtWithinNode(ctx, s.backendNodeID, sel, index, fromEnd)+}++// resolveRef is where the two scopes genuinely differ. A cached ref still exists+// while the dialog owns the interaction surface, so it must be proven to lie+// inside the scope subtree — otherwise a dialog-scoped action silently reaches+// an element behind the dialog. The outside-scope sentinel is distinct from+// not-found: callers must not treat it as a stale ref.+func (s nodeScope) resolveRef(ctx context.Context, sel selector.Selector, refCache *RefCache) (int64, error) {+ if refCache == nil {+ return 0, fmt.Errorf("ref %s not in snapshot cache: %w", sel.Value, ErrSelectorNoMatch)+ }+ target, ok := refCache.Lookup(sel.Value)+ if !ok || target.BackendNodeID == 0 {+ return 0, fmt.Errorf("ref %s not in snapshot cache: %w", sel.Value, ErrSelectorNoMatch)+ }+ inside, err := BackendNodeWithinScope(ctx, s.backendNodeID, target.BackendNodeID)+ if err != nil {+ return 0, fmt.Errorf("validate ref %s against topmost dialog: %w", sel.Value, err)+ }+ if !inside {+ return 0, fmt.Errorf("ref %s is outside the topmost dialog: %w", sel.Value, ErrSelectorOutsideScope)+ }+ return target.BackendNodeID, nil+}++func errSemanticAtResolver() error {+ return fmt.Errorf("semantic selectors must be resolved at the handler layer via /find")+}++func errHandlerLayerKind(kind selector.Kind) error {+ return fmt.Errorf("%s selectors must be resolved at the handler layer via semantic", kind)+}++func resolveNested(ctx context.Context, scope resolveScope, raw string, refCache *RefCache, index int, fromEnd bool) (int64, error) {inner := selector.Parse(raw)switch inner.Kind {case selector.KindFirst:- return resolveNestedSelectorAtInFrame(ctx, frameID, inner.Value, refCache, 0, false)+ return resolveNested(ctx, scope, inner.Value, refCache, 0, false)case selector.KindLast:- return resolveNestedSelectorAtInFrame(ctx, frameID, inner.Value, refCache, 0, true)+ return resolveNested(ctx, scope, inner.Value, refCache, 0, true)case selector.KindNth:nth, nestedRaw, err := selector.ParseNth(inner.Value)if err != nil {return 0, err}- return resolveNestedSelectorAtInFrame(ctx, frameID, nestedRaw, refCache, nth, false)+ return resolveNested(ctx, scope, nestedRaw, refCache, nth, false)case selector.KindRef:if fromEnd || index != 0 {return 0, fmt.Errorf("ref selector cannot be used with last/nth")}- return ResolveUnifiedSelectorInFrame(ctx, inner, refCache, frameID)+ return scope.resolveRef(ctx, inner, refCache)case selector.KindSemantic:- return 0, fmt.Errorf("semantic selectors must be resolved at the handler layer via /find")+ return 0, errSemanticAtResolver()default:- return resolveSelectorAtInFrame(ctx, frameID, inner, index, fromEnd)+ return scope.resolveAt(ctx, inner, index, fromEnd)}}-func resolveNestedSelectorWithinNode(ctx context.Context, scopeBackendNodeID int64, raw string, refCache *RefCache, index int, fromEnd bool) (int64, error) {- inner := selector.Parse(raw)- switch inner.Kind {+// resolveWrapper turns a first:/last:/nth: wrapper into the index the shared+// recursion carries. Both entry points dispatch their wrapper kinds here.+func resolveWrapper(ctx context.Context, scope resolveScope, sel selector.Selector, refCache *RefCache) (int64, error) {+ switch sel.Kind {case selector.KindFirst:- return resolveNestedSelectorWithinNode(ctx, scopeBackendNodeID, inner.Value, refCache, 0, false)+ return resolveNested(ctx, scope, sel.Value, refCache, 0, false)case selector.KindLast:- return resolveNestedSelectorWithinNode(ctx, scopeBackendNodeID, inner.Value, refCache, 0, true)+ return resolveNested(ctx, scope, sel.Value, refCache, 0, true)case selector.KindNth:- nth, nestedRaw, err := selector.ParseNth(inner.Value)+ index, rawSelector, err := selector.ParseNth(sel.Value)if err != nil {return 0, err}- return resolveNestedSelectorWithinNode(ctx, scopeBackendNodeID, nestedRaw, refCache, nth, false)- case selector.KindRef:- if fromEnd || index != 0 {- return 0, fmt.Errorf("ref selector cannot be used with last/nth")- }- return ResolveUnifiedSelectorWithinNode(ctx, inner, refCache, scopeBackendNodeID)- case selector.KindSemantic:- return 0, fmt.Errorf("semantic selectors must be resolved at the handler layer via /find")+ return resolveNested(ctx, scope, rawSelector, refCache, index, false)default:- return resolveSelectorAtWithinNode(ctx, scopeBackendNodeID, inner, index, fromEnd)+ return 0, fmt.Errorf("unknown selector kind: %q", sel.Kind)}}@@ -743,12 +797,7 @@ func ResolveFrameElementMetaInFrame(ctx context.Context, sel selector.Selector,func ResolveUnifiedSelectorInFrame(ctx context.Context, sel selector.Selector, refCache *RefCache, frameID string) (int64, error) {switch sel.Kind {case selector.KindRef:- if refCache != nil {- if target, ok := refCache.Lookup(sel.Value); ok {- return target.BackendNodeID, nil- }- }- return 0, fmt.Errorf("ref %s not in snapshot cache: %w", sel.Value, ErrSelectorNoMatch)+ return frameScope{frameID}.resolveRef(ctx, sel, refCache)case selector.KindCSS:return ResolveCSSToNodeIDInFrame(ctx, frameID, sel.Value)@@ -760,24 +809,14 @@ func ResolveUnifiedSelectorInFrame(ctx context.Context, sel selector.Selector, rreturn ResolveTextToNodeIDInFrame(ctx, frameID, sel.Value)case selector.KindSemantic:- return 0, fmt.Errorf("semantic selectors must be resolved at the handler layer via /find")+ return 0, errSemanticAtResolver()case selector.KindRole, selector.KindLabel, selector.KindPlaceholder,selector.KindAlt, selector.KindTitle, selector.KindTestID:- return 0, fmt.Errorf("%s selectors must be resolved at the handler layer via semantic", sel.Kind)+ return 0, errHandlerLayerKind(sel.Kind)- case selector.KindFirst:- return resolveNestedSelectorAtInFrame(ctx, frameID, sel.Value, refCache, 0, false)-- case selector.KindLast:- return resolveNestedSelectorAtInFrame(ctx, frameID, sel.Value, refCache, 0, true)-- case selector.KindNth:- index, rawSelector, err := selector.ParseNth(sel.Value)- if err != nil {- return 0, err- }- return resolveNestedSelectorAtInFrame(ctx, frameID, rawSelector, refCache, index, false)+ case selector.KindFirst, selector.KindLast, selector.KindNth:+ return resolveWrapper(ctx, frameScope{frameID}, sel, refCache)default:return 0, fmt.Errorf("unknown selector kind: %q", sel.Kind)@@ -795,44 +834,20 @@ func ResolveUnifiedSelectorWithinNode(ctx context.Context, sel selector.Selectorswitch sel.Kind {case selector.KindRef:- if refCache == nil {- return 0, fmt.Errorf("ref %s not in snapshot cache: %w", sel.Value, ErrSelectorNoMatch)- }- target, ok := refCache.Lookup(sel.Value)- if !ok || target.BackendNodeID == 0 {- return 0, fmt.Errorf("ref %s not in snapshot cache: %w", sel.Value, ErrSelectorNoMatch)- }- inside, err := BackendNodeWithinScope(ctx, scopeBackendNodeID, target.BackendNodeID)- if err != nil {- return 0, fmt.Errorf("validate ref %s against topmost dialog: %w", sel.Value, err)- }- if !inside {- return 0, fmt.Errorf("ref %s is outside the topmost dialog: %w", sel.Value, ErrSelectorOutsideScope)- }- return target.BackendNodeID, nil+ return nodeScope{scopeBackendNodeID}.resolveRef(ctx, sel, refCache)case selector.KindCSS, selector.KindXPath, selector.KindText:- return resolveSelectorAtWithinNode(ctx, scopeBackendNodeID, sel, 0, false)+ return nodeScope{scopeBackendNodeID}.resolveAt(ctx, sel, 0, false)case selector.KindSemantic:- return 0, fmt.Errorf("semantic selectors must be resolved at the handler layer via /find")+ return 0, errSemanticAtResolver()case selector.KindRole, selector.KindLabel, selector.KindPlaceholder,selector.KindAlt, selector.KindTitle, selector.KindTestID:- return 0, fmt.Errorf("%s selectors must be resolved at the handler layer via semantic", sel.Kind)-- case selector.KindFirst:- return resolveNestedSelectorWithinNode(ctx, scopeBackendNodeID, sel.Value, refCache, 0, false)+ return 0, errHandlerLayerKind(sel.Kind)- case selector.KindLast:- return resolveNestedSelectorWithinNode(ctx, scopeBackendNodeID, sel.Value, refCache, 0, true)-- case selector.KindNth:- index, rawSelector, err := selector.ParseNth(sel.Value)- if err != nil {- return 0, err- }- return resolveNestedSelectorWithinNode(ctx, scopeBackendNodeID, rawSelector, refCache, index, false)+ case selector.KindFirst, selector.KindLast, selector.KindNth:+ return resolveWrapper(ctx, nodeScope{scopeBackendNodeID}, sel, refCache)default:return 0, fmt.Errorf("unknown selector kind: %q", sel.Kind)diff --git a/internal/bridge/action_resolve_scope_test.go b/internal/bridge/action_resolve_scope_test.gonew file mode 100644index 00000000..2ca7ed36--- /dev/null+++ b/internal/bridge/action_resolve_scope_test.go@@ -0,0 +1,151 @@+package bridge++import (+ "context"+ "errors"+ "strings"+ "testing"++ "github.com/pinchtab/pinchtab/internal/selector"+)++// stubScope records what the shared recursion asks of a scope, so the grammar+// can be exercised without a browser. The real scopes differ only in these two+// answers, which is the premise the shared recursion rests on.+type stubScope struct {+ atCalls []stubAt+ refCalls []string+ nodeID int64+ refErr error+}++type stubAt struct {+ kind selector.Kind+ value string+ index int+ fromEnd bool+}++func (s *stubScope) resolveAt(_ context.Context, sel selector.Selector, index int, fromEnd bool) (int64, error) {+ s.atCalls = append(s.atCalls, stubAt{sel.Kind, sel.Value, index, fromEnd})+ return s.nodeID, nil+}++func (s *stubScope) resolveRef(_ context.Context, sel selector.Selector, _ *RefCache) (int64, error) {+ s.refCalls = append(s.refCalls, sel.Value)+ if s.refErr != nil {+ return 0, s.refErr+ }+ return s.nodeID, nil+}++// Every wrapper form must reach the leaf with the same index/fromEnd it did when+// each scope had its own copy of this grammar.+func TestResolveWrapperUnwrapsToTheSameLeafForEveryForm(t *testing.T) {+ for _, tc := range []struct {+ raw string+ want stubAt+ }{+ {"first:css:#a", stubAt{selector.KindCSS, "#a", 0, false}},+ {"last:css:#a", stubAt{selector.KindCSS, "#a", 0, true}},+ {"nth:2:css:#a", stubAt{selector.KindCSS, "#a", 2, false}},+ {"first:text:Save", stubAt{selector.KindText, "Save", 0, false}},+ // Nesting collapses: the innermost wrapper decides.+ {"first:last:css:#a", stubAt{selector.KindCSS, "#a", 0, true}},+ {"nth:3:first:css:#a", stubAt{selector.KindCSS, "#a", 0, false}},+ } {+ t.Run(tc.raw, func(t *testing.T) {+ scope := &stubScope{nodeID: 42}+ sel := selector.Parse(tc.raw)++ got, err := resolveWrapper(context.Background(), scope, sel, nil)+ if err != nil {+ t.Fatalf("resolveWrapper(%q): %v", tc.raw, err)+ }+ if got != 42 {+ t.Errorf("node id = %d, want 42", got)+ }+ if len(scope.atCalls) != 1 || scope.atCalls[0] != tc.want {+ t.Errorf("leaf calls = %+v, want exactly one %+v", scope.atCalls, tc.want)+ }+ })+ }+}++// A wrapped ref must go through the scope's own resolveRef — that is where the+// dialog containment check lives, so routing it anywhere else would let a+// dialog-scoped action reach outside the dialog.+func TestResolveWrapperRoutesRefsThroughTheScope(t *testing.T) {+ outside := errors.New("outside")+ scope := &stubScope{nodeID: 7, refErr: outside}++ _, err := resolveWrapper(context.Background(), scope, selector.Parse("first:ref:e0"), nil)++ if !errors.Is(err, outside) {+ t.Fatalf("err = %v, want the scope's own ref error", err)+ }+ if len(scope.refCalls) != 1 || scope.refCalls[0] != "e0" {+ t.Errorf("ref calls = %v, want exactly [e0]", scope.refCalls)+ }+ if len(scope.atCalls) != 0 {+ t.Errorf("a ref reached the leaf resolver: %+v", scope.atCalls)+ }+}++// last:/nth: cannot select among a single cached ref, and semantic selectors+// belong to the handler layer. Both rejections predate the shared recursion.+func TestResolveWrapperRejectionsUnchanged(t *testing.T) {+ for _, tc := range []struct {+ raw string+ want string+ }{+ {"last:ref:e0", "ref selector cannot be used with last/nth"},+ {"nth:1:ref:e0", "ref selector cannot be used with last/nth"},+ {"first:find:Save", "semantic selectors must be resolved at the handler layer via /find"},+ } {+ t.Run(tc.raw, func(t *testing.T) {+ scope := &stubScope{nodeID: 7}++ _, err := resolveWrapper(context.Background(), scope, selector.Parse(tc.raw), nil)++ if err == nil || !strings.Contains(err.Error(), tc.want) {+ t.Fatalf("err = %v, want %q", err, tc.want)+ }+ if len(scope.atCalls) != 0 || len(scope.refCalls) != 0 {+ t.Errorf("rejected selector still reached the scope: at=%+v ref=%v", scope.atCalls, scope.refCalls)+ }+ })+ }+}++// The two scopes are deliberately NOT interchangeable on refs. frameScope hands+// back whatever the cache holds; nodeScope proves containment first. This pins+// the half that needs no browser — the containment half is pinned against a real+// dialog in the modal test.+func TestScopeRefBehaviourDiffersByDesign(t *testing.T) {+ cache := &RefCache{Targets: map[string]RefTarget{"e0": {BackendNodeID: 99}}}+ sel := selector.Parse("ref:e0")++ got, err := (frameScope{}).resolveRef(context.Background(), sel, cache)+ if err != nil || got != 99 {+ t.Fatalf("frame scope ref = (%d, %v), want (99, nil)", got, err)+ }++ if _, err := (frameScope{}).resolveRef(context.Background(), sel, nil); !errors.Is(err, ErrSelectorNoMatch) {+ t.Errorf("frame scope with no cache = %v, want ErrSelectorNoMatch", err)+ }+ if _, err := (nodeScope{backendNodeID: 1}).resolveRef(context.Background(), sel, nil); !errors.Is(err, ErrSelectorNoMatch) {+ t.Errorf("node scope with no cache = %v, want ErrSelectorNoMatch", err)+ }++ // Divergence between the former copies, preserved rather than reconciled:+ // a cached ref carrying a zero backend node id is a successful resolution to+ // 0 in the frame scope and a not-in-cache error in the node scope.+ zero := &RefCache{Targets: map[string]RefTarget{"e0": {BackendNodeID: 0}}}+ if got, err := (frameScope{}).resolveRef(context.Background(), sel, zero); err != nil || got != 0 {+ t.Errorf("frame scope zero-id ref = (%d, %v), want (0, nil) as before", got, err)+ }+ if _, err := (nodeScope{backendNodeID: 1}).resolveRef(context.Background(), sel, zero); !errors.Is(err, ErrSelectorNoMatch) {+ t.Errorf("node scope zero-id ref = %v, want ErrSelectorNoMatch as before", err)+ }+}