Skip to content

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

fix: positional wrappers over a text: selector index semantic rank, so nth:1 can resolve earlier in the document than nth:0 (PIN-044)

Luigi Agostidc97bcdc274f
diff --git a/docs/commands.md b/docs/commands.md
index 9bcb3fa3..2aef13d2 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -107,6 +107,8 @@ Most element commands accept a unified selector:
- label, placeholder, alt, title, or test id selectors such as `label:Email`, `placeholder:Search`, `alt:Logo`, `title:Close`, `testid:submit`
- positional wrappers such as `first:button`, `last:role:button`, or `nth:2:button` (`nth` is zero-based)
+Positional wrappers index the candidates in **document order** for every selector kind, so `nth:0:` is the first match in the page and `nth:1:` always comes after it. A bare `text:` selector is the one form that does not index: it picks the most control-like match among the smallest ones, so `text:Save` prefers a `<button>` over a `<div>` carrying the same label — which means `text:X` and `first:text:X` can resolve to different elements. A wrapper only ever chooses among the matches a bare selector would find; it never changes which matches exist.
+
Selector prefixes are case-insensitive, so `CSS:#login` and `css:#login` mean the same thing. Only the prefix is case-folded; the value after it is passed through unchanged.
Structured forms such as `role:`, `label:`, and `testid:` are matched by the semantic engine against enriched snapshot descriptors. CSS, XPath, refs, the existing `text:` action selector, and bare CSS/text wrappers remain browser-side selector resolution.
diff --git a/docs/reference/mcp-tools.md b/docs/reference/mcp-tools.md
index 7f4fd0d7..3087747a 100644
--- a/docs/reference/mcp-tools.md
+++ b/docs/reference/mcp-tools.md
@@ -17,6 +17,8 @@ Selector forms include:
- `label:Email`, `placeholder:Search`, `alt:Logo`, `title:Close`, `testid:submit`
- `first:button`, `last:button`, `nth:2:button`
+Positional wrappers index the candidates in **document order** for every selector kind, so `nth:0:` is the first match in the page and `nth:1:` always comes after it. A bare `text:` selector is the one form that does not index: it picks the most control-like match among the smallest ones, so `text:Save` prefers a `<button>` over a `<div>` carrying the same label — which means `text:X` and `first:text:X` can resolve to different elements. A wrapper only ever chooses among the matches a bare selector would find; it never changes which matches exist.
+
Structured semantic locators are matched by the semantic engine; CSS, XPath, refs, the existing `text:` action selector, and bare CSS/text wrappers stay browser-side.
## Navigation
diff --git a/internal/bridge/action_resolve.go b/internal/bridge/action_resolve.go
index b0766bee..8f4ee47d 100644
--- a/internal/bridge/action_resolve.go
+++ b/internal/bridge/action_resolve.go
@@ -466,10 +466,10 @@ func ResolveTextToNodeID(ctx context.Context, text string) (int64, error) {
}
func ResolveTextToNodeIDInFrame(ctx context.Context, frameID, text string) (int64, error) {
- return resolveSelectorAtInFrame(ctx, frameID, selector.Selector{Kind: selector.KindText, Value: text}, 0, false)
+ return resolveSelectorAtInFrame(ctx, frameID, selector.Selector{Kind: selector.KindText, Value: text}, 0, false, false)
}
-const resolveSelectorAtFn = `function(kind, value, index, fromEnd) {
+const resolveSelectorAtFn = `function(kind, value, index, fromEnd, positional) {
const root = this;
` + jsNormalizeHelper + `
const needle = normalize(value);
@@ -507,7 +507,9 @@ const resolveSelectorAtFn = `function(kind, value, index, fromEnd) {
// hands back an element no action can operate on.
const nonRendered = new Set(["script", "style", "noscript", "template"]);
// At equal subtree size a control outranks a plain wrapper carrying the same
- // label, so text: lands on the <button> rather than the <div> around it.
+ // label, so a bare text: lands on the <button> rather than the <div> beside it.
+ // This ranking is the BARE text: selector's rule only — a positional wrapper
+ // indexes the document, like css: and xpath:.
const semanticWeight = (el) => {
const tag = (el.tagName || "").toLowerCase();
if (tag === "button" || tag === "a" || tag === "input") return 0.25;
@@ -515,16 +517,32 @@ const resolveSelectorAtFn = `function(kind, value, index, fromEnd) {
if (role === "button" || role === "link" || role === "textbox") return 0.2;
return 0;
};
- // Leaf-most wins: the fewest descendants is the most specific match. The sort
- // is stable, so equally-weighted candidates keep document order and the index
- // first/last/nth asks for stays meaningful.
- const smallestFirst = (matches) => {
+ // Leaf-most wins: the fewest descendants is the most specific match. This
+ // REDUCES the match set, so it is shared by both paths — a wrapper chooses
+ // among matches and must never change which matches exist. What survives stays
+ // in document order, which is the order first:/last:/nth: index.
+ const smallestMatches = (matches) => {
const minSize = Math.min(...matches.map((item) => item.size));
return matches
.filter((item) => item.size === minSize)
- .sort((a, b) => semanticWeight(b.el) - semanticWeight(a.el))
.map((item) => item.el);
};
+ // The bare text: selector's own rule, applied to the document-ordered set. It
+ // has to pick the maximum weight EXPLICITLY: reading element zero of a
+ // weight-sorted list is what made nth:1 resolve earlier in the document than
+ // nth:0. Ties keep the first, so equal weights still mean document order.
+ const bestRanked = (items) => {
+ let best = items[0];
+ let bestWeight = semanticWeight(best);
+ for (const el of items) {
+ const weight = semanticWeight(el);
+ if (weight > bestWeight) {
+ best = el;
+ bestWeight = weight;
+ }
+ }
+ return best;
+ };
const textCandidates = (query) => {
if (!query) return [];
// textContent, not innerText: innerText forces a synchronous layout per
@@ -533,7 +551,7 @@ const resolveSelectorAtFn = `function(kind, value, index, fromEnd) {
.filter((el) => !nonRendered.has((el.tagName || "").toLowerCase()));
const measured = elements.map((el) => ({ el, text: normalize(el.textContent || ""), size: el.getElementsByTagName("*").length }));
const exact = measured.filter((item) => item.text && item.text.includes(query));
- if (exact.length) return smallestFirst(exact);
+ if (exact.length) return smallestMatches(exact);
const tokens = query.split(" ").filter(Boolean);
if (!tokens.length) return [];
const fuzzy = measured.filter((item) => {
@@ -543,7 +561,7 @@ const resolveSelectorAtFn = `function(kind, value, index, fromEnd) {
return hits / tokens.length >= 0.7;
});
if (!fuzzy.length) return [];
- return smallestFirst(fuzzy);
+ return smallestMatches(fuzzy);
};
try {
@@ -560,8 +578,11 @@ const resolveSelectorAtFn = `function(kind, value, index, fromEnd) {
}
return pick(items);
}
- case "text":
- return pick(textCandidates(needle));
+ case "text": {
+ const items = unique(textCandidates(needle));
+ if (!items.length) return null;
+ return positional ? pick(items) : bestRanked(items);
+ }
default:
return null;
}
@@ -578,7 +599,11 @@ const textLookupDeadline = 3 * time.Second
// resolveSelectorAt is the single entry point for every css/xpath/text
// resolution. scopeLabel names the scope in errors; call runs the resolver
// against whichever root the caller resolved.
-func resolveSelectorAt(ctx context.Context, sel selector.Selector, index int, fromEnd bool, scopeLabel string, call func(context.Context, []map[string]any) (int64, error)) (int64, error) {
+// positional says a first:/last:/nth: wrapper asked for this resolution. Plain
+// text: and first:text: arrive with the same index and direction — 0 and forward —
+// so the two cannot be told apart from the pair alone, and they must be: a bare
+// text: ranks by control-likeness while a wrapper indexes the document.
+func resolveSelectorAt(ctx context.Context, sel selector.Selector, index int, fromEnd bool, positional bool, scopeLabel string, call func(context.Context, []map[string]any) (int64, error)) (int64, error) {
switch sel.Kind {
case selector.KindCSS, selector.KindXPath, selector.KindText:
default:
@@ -597,6 +622,7 @@ func resolveSelectorAt(ctx context.Context, sel selector.Selector, index int, fr
{"value": sel.Value},
{"value": index},
{"value": fromEnd},
+ {"value": positional},
})
if err != nil {
if lookupCtx.Err() != nil && ctx.Err() == nil {
@@ -607,8 +633,8 @@ func resolveSelectorAt(ctx context.Context, sel selector.Selector, index int, fr
return nid, nil
}
-func resolveSelectorAtInFrame(ctx context.Context, frameID string, sel selector.Selector, index int, fromEnd bool) (int64, error) {
- return resolveSelectorAt(ctx, sel, index, fromEnd, "", func(ctx context.Context, args []map[string]any) (int64, error) {
+func resolveSelectorAtInFrame(ctx context.Context, frameID string, sel selector.Selector, index int, fromEnd bool, positional bool) (int64, error) {
+ return resolveSelectorAt(ctx, sel, index, fromEnd, positional, "", func(ctx context.Context, args []map[string]any) (int64, error) {
var backendNodeID int64
err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
nid, err := resolveNodeInFrame(ctx, frameID, resolveSelectorAtFn, args)
@@ -622,8 +648,8 @@ func resolveSelectorAtInFrame(ctx context.Context, frameID string, sel selector.
})
}
-func resolveSelectorAtWithinNode(ctx context.Context, scopeBackendNodeID int64, sel selector.Selector, index int, fromEnd bool) (int64, error) {
- return resolveSelectorAt(ctx, sel, index, fromEnd, " inside topmost dialog", func(ctx context.Context, args []map[string]any) (int64, error) {
+func resolveSelectorAtWithinNode(ctx context.Context, scopeBackendNodeID int64, sel selector.Selector, index int, fromEnd bool, positional bool) (int64, error) {
+ return resolveSelectorAt(ctx, sel, index, fromEnd, positional, " inside topmost dialog", func(ctx context.Context, args []map[string]any) (int64, error) {
return resolveNodeWithinBackendNode(ctx, scopeBackendNodeID, resolveSelectorAtFn, args)
})
}
@@ -632,14 +658,14 @@ func resolveSelectorAtWithinNode(ctx context.Context, scopeBackendNodeID int64,
// 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)
+ resolveAt(ctx context.Context, sel selector.Selector, index int, fromEnd bool, positional 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) resolveAt(ctx context.Context, sel selector.Selector, index int, fromEnd bool, positional bool) (int64, error) {
+ return resolveSelectorAtInFrame(ctx, s.frameID, sel, index, fromEnd, positional)
}
func (s frameScope) resolveRef(_ context.Context, sel selector.Selector, refCache *RefCache) (int64, error) {
@@ -653,8 +679,8 @@ func (s frameScope) resolveRef(_ context.Context, sel selector.Selector, refCach
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)
+func (s nodeScope) resolveAt(ctx context.Context, sel selector.Selector, index int, fromEnd bool, positional bool) (int64, error) {
+ return resolveSelectorAtWithinNode(ctx, s.backendNodeID, sel, index, fromEnd, positional)
}
// resolveRef differs from the frame scope only in containment. A cached ref still exists
@@ -700,18 +726,18 @@ func errHandlerLayerKind(kind selector.Kind) error {
// case selector.KindFirst, selector.KindLast, selector.KindNth arm, and those arms
// are still the narrow kind check. Keeping a second switch alive to hold an
// unreachable error would be this duplication wearing a different hat.
-func resolveParsed(ctx context.Context, scope resolveScope, sel selector.Selector, refCache *RefCache, index int, fromEnd bool) (int64, error) {
+func resolveParsed(ctx context.Context, scope resolveScope, sel selector.Selector, refCache *RefCache, index int, fromEnd bool, positional bool) (int64, error) {
switch sel.Kind {
case selector.KindFirst:
- return resolveNested(ctx, scope, sel.Value, refCache, 0, false)
+ return resolveNested(ctx, scope, sel.Value, refCache, 0, false, true)
case selector.KindLast:
- return resolveNested(ctx, scope, sel.Value, refCache, 0, true)
+ return resolveNested(ctx, scope, sel.Value, refCache, 0, true, true)
case selector.KindNth:
nth, nestedRaw, err := selector.ParseNth(sel.Value)
if err != nil {
return 0, err
}
- return resolveNested(ctx, scope, nestedRaw, refCache, nth, false)
+ return resolveNested(ctx, scope, nestedRaw, refCache, nth, false, true)
case selector.KindRef:
if fromEnd || index != 0 {
return 0, fmt.Errorf("ref selector cannot be used with last/nth")
@@ -720,12 +746,12 @@ func resolveParsed(ctx context.Context, scope resolveScope, sel selector.Selecto
case selector.KindSemantic:
return 0, errSemanticAtResolver()
default:
- return scope.resolveAt(ctx, sel, index, fromEnd)
+ return scope.resolveAt(ctx, sel, index, fromEnd, positional)
}
}
-func resolveNested(ctx context.Context, scope resolveScope, raw string, refCache *RefCache, index int, fromEnd bool) (int64, error) {
- return resolveParsed(ctx, scope, selector.Parse(raw), refCache, index, fromEnd)
+func resolveNested(ctx context.Context, scope resolveScope, raw string, refCache *RefCache, index int, fromEnd bool, positional bool) (int64, error) {
+ return resolveParsed(ctx, scope, selector.Parse(raw), refCache, index, fromEnd, positional)
}
func ResolveXPathToNodeID(ctx context.Context, xpath string) (int64, error) {
@@ -742,14 +768,14 @@ func ResolveCSSToNodeIDInFrame(ctx context.Context, frameID, css string) (int64,
// shadow root, not just the light DOM (issue #591). For light-DOM pages this
// returns the same first match as document.querySelector, and it works for both
// the main frame (frameID == "") and sub-frames.
- return resolveSelectorAtInFrame(ctx, frameID, selector.Selector{Kind: selector.KindCSS, Value: css}, 0, false)
+ return resolveSelectorAtInFrame(ctx, frameID, selector.Selector{Kind: selector.KindCSS, Value: css}, 0, false, false)
}
// XPath does not pierce shadow roots: document.evaluate cannot cross a shadow
// boundary. It resolves through the shared walker for consistency and
// isolated-world execution, not for shadow support.
func ResolveXPathToNodeIDInFrame(ctx context.Context, frameID, xpath string) (int64, error) {
- return resolveSelectorAtInFrame(ctx, frameID, selector.Selector{Kind: selector.KindXPath, Value: xpath}, 0, false)
+ return resolveSelectorAtInFrame(ctx, frameID, selector.Selector{Kind: selector.KindXPath, Value: xpath}, 0, false, false)
}
func ResolveFrameElementMetaInFrame(ctx context.Context, sel selector.Selector, frameID string) (FrameElementMeta, error) {
@@ -812,7 +838,7 @@ func ResolveUnifiedSelectorInFrame(ctx context.Context, sel selector.Selector, r
return 0, errHandlerLayerKind(sel.Kind)
case selector.KindFirst, selector.KindLast, selector.KindNth:
- return resolveParsed(ctx, frameScope{frameID}, sel, refCache, 0, false)
+ return resolveParsed(ctx, frameScope{frameID}, sel, refCache, 0, false, false)
default:
return 0, fmt.Errorf("unknown selector kind: %q", sel.Kind)
@@ -833,7 +859,7 @@ func ResolveUnifiedSelectorWithinNode(ctx context.Context, sel selector.Selector
return nodeScope{scopeBackendNodeID}.resolveRef(ctx, sel, refCache)
case selector.KindCSS, selector.KindXPath, selector.KindText:
- return nodeScope{scopeBackendNodeID}.resolveAt(ctx, sel, 0, false)
+ return nodeScope{scopeBackendNodeID}.resolveAt(ctx, sel, 0, false, false)
case selector.KindSemantic:
return 0, errSemanticAtResolver()
@@ -843,7 +869,7 @@ func ResolveUnifiedSelectorWithinNode(ctx context.Context, sel selector.Selector
return 0, errHandlerLayerKind(sel.Kind)
case selector.KindFirst, selector.KindLast, selector.KindNth:
- return resolveParsed(ctx, nodeScope{scopeBackendNodeID}, sel, refCache, 0, false)
+ return resolveParsed(ctx, nodeScope{scopeBackendNodeID}, sel, refCache, 0, false, false)
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.go
index 112b5773..470ea5ab 100644
--- a/internal/bridge/action_resolve_scope_test.go
+++ b/internal/bridge/action_resolve_scope_test.go
@@ -29,14 +29,15 @@ type stubScope struct {
}
type stubAt struct {
- kind selector.Kind
- value string
- index int
- fromEnd bool
+ kind selector.Kind
+ value string
+ index int
+ fromEnd bool
+ positional 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})
+func (s *stubScope) resolveAt(_ context.Context, sel selector.Selector, index int, fromEnd bool, positional bool) (int64, error) {
+ s.atCalls = append(s.atCalls, stubAt{sel.Kind, sel.Value, index, fromEnd, positional})
return s.nodeID, nil
}
@@ -49,25 +50,31 @@ func (s *stubScope) resolveRef(_ context.Context, sel selector.Selector, _ *RefC
}
// Every wrapper form must reach the leaf with the same index/fromEnd it did when
-// each scope had its own copy of this grammar.
+// each scope had its own copy of this grammar — and must mark itself POSITIONAL,
+// which is what tells the resolver to index the document instead of the semantic
+// ranking. A bare selector must not: plain text: and first:text: arrive with the
+// same index and direction, so this flag is the only thing separating them.
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}},
+ {"first:css:#a", stubAt{selector.KindCSS, "#a", 0, false, true}},
+ {"last:css:#a", stubAt{selector.KindCSS, "#a", 0, true, true}},
+ {"nth:2:css:#a", stubAt{selector.KindCSS, "#a", 2, false, true}},
+ {"first:text:Save", stubAt{selector.KindText, "Save", 0, false, true}},
// 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}},
+ {"first:last:css:#a", stubAt{selector.KindCSS, "#a", 0, true, true}},
+ {"nth:3:first:css:#a", stubAt{selector.KindCSS, "#a", 0, false, true}},
+ // Unwrapped: same index and direction as first:, and NOT positional.
+ {"css:#a", stubAt{selector.KindCSS, "#a", 0, false, false}},
+ {"text:Save", stubAt{selector.KindText, "Save", 0, false, false}},
} {
t.Run(tc.raw, func(t *testing.T) {
scope := &stubScope{nodeID: 42}
sel := selector.Parse(tc.raw)
- got, err := resolveParsed(context.Background(), scope, sel, nil, 0, false)
+ got, err := resolveParsed(context.Background(), scope, sel, nil, 0, false, false)
if err != nil {
t.Fatalf("resolveParsed(%q): %v", tc.raw, err)
}
@@ -88,7 +95,7 @@ func TestResolveWrapperRoutesRefsThroughTheScope(t *testing.T) {
outside := errors.New("outside")
scope := &stubScope{nodeID: 7, refErr: outside}
- _, err := resolveParsed(context.Background(), scope, selector.Parse("first:ref:e0"), nil, 0, false)
+ _, err := resolveParsed(context.Background(), scope, selector.Parse("first:ref:e0"), nil, 0, false, false)
if !errors.Is(err, outside) {
t.Fatalf("err = %v, want the scope's own ref error", err)
@@ -115,7 +122,7 @@ func TestResolveWrapperRejectionsUnchanged(t *testing.T) {
t.Run(tc.raw, func(t *testing.T) {
scope := &stubScope{nodeID: 7}
- _, err := resolveParsed(context.Background(), scope, selector.Parse(tc.raw), nil, 0, false)
+ _, err := resolveParsed(context.Background(), scope, selector.Parse(tc.raw), nil, 0, false, false)
if err == nil || !strings.Contains(err.Error(), tc.want) {
t.Fatalf("err = %v, want %q", err, tc.want)
@@ -417,9 +424,12 @@ func newScopedWrapperFixture(t *testing.T) context.Context {
}
// assertWrapperArmStartsFresh checks, through the AST rather than the call's text, that
-// every resolveParsed call inside the named entry point starts its wrapper at index 0
-// with fromEnd false. A wrapper must derive its own index from the grammar; inheriting
-// one from the entry point makes first: behave like last: on every page.
+// every resolveParsed call inside the named entry point starts its wrapper at index 0,
+// fromEnd false, positional false. A wrapper must derive its own index from the grammar;
+// inheriting one from the entry point makes first: behave like last: on every page. The
+// third value is the same shape of defect one step further: an entry point that starts
+// positional=true makes a BARE text: index the document, silently dropping the control
+// ranking that only the bare form carries.
func assertWrapperArmStartsFresh(t *testing.T, src, entrySignature string) {
t.Helper()
@@ -452,13 +462,15 @@ func assertWrapperArmStartsFresh(t *testing.T, src, entrySignature string) {
return true
}
calls++
- if len(call.Args) < 2 {
- t.Errorf("%s calls resolveParsed with %d arguments; the starting index and fromEnd are the last two", name, len(call.Args))
+ if len(call.Args) < 3 {
+ t.Errorf("%s calls resolveParsed with %d arguments; the starting index, fromEnd and positional are the last three", name, len(call.Args))
return true
}
- index, fromEnd := exprText(call.Args[len(call.Args)-2]), exprText(call.Args[len(call.Args)-1])
- if index != "0" || fromEnd != "false" {
- t.Errorf("%s starts its wrapper arm at index %s, fromEnd %s, want 0 and false — a wrapper must derive its own index from the grammar, not inherit one from the entry point", name, index, fromEnd)
+ index := exprText(call.Args[len(call.Args)-3])
+ fromEnd := exprText(call.Args[len(call.Args)-2])
+ positional := exprText(call.Args[len(call.Args)-1])
+ if index != "0" || fromEnd != "false" || positional != "false" {
+ t.Errorf("%s starts its wrapper arm at index %s, fromEnd %s, positional %s, want 0, false and false — a wrapper derives its own index from the grammar, and only a wrapper may claim to be positional", name, index, fromEnd, positional)
}
return true
})
diff --git a/internal/bridge/action_resolve_unified_test.go b/internal/bridge/action_resolve_unified_test.go
index 35e2f2bb..e77b24e2 100644
--- a/internal/bridge/action_resolve_unified_test.go
+++ b/internal/bridge/action_resolve_unified_test.go
@@ -170,12 +170,13 @@ func TestTextSelectorNeverResolvesNonRenderedSourceText(t *testing.T) {
func TestTextSelectorPrefersControlOverPlainElementOfEqualSize(t *testing.T) {
ctx := newSelectorFixture(t)
+ // The first: row is gone on purpose, not adjusted: positional wrappers index
+ // the document now, so first:text: is #decoy. The control preference this test
+ // is named for lives on the BARE text: selector, which is the row that stays.
want := resolve(t, ctx, "css:#inner")
- for _, raw := range []string{"text:Archive record", "first:text:Archive record"} {
- if got := resolve(t, ctx, raw); got != want {
- t.Errorf("%s resolved to %s, want button#inner (%s)",
- raw, describeNode(t, ctx, got), describeNode(t, ctx, want))
- }
+ if got := resolve(t, ctx, "text:Archive record"); got != want {
+ t.Errorf("text:Archive record resolved to %s, want button#inner (%s)",
+ describeNode(t, ctx, got), describeNode(t, ctx, want))
}
// The wrapper is a candidate the size rule must have already discarded.
@@ -199,7 +200,7 @@ func TestResolveSelectorAtBoundsTextLookupsOnly(t *testing.T) {
} {
var deadline time.Time
var hasDeadline bool
- _, err := resolveSelectorAt(context.Background(), selector.Selector{Kind: tc.kind, Value: "x"}, 0, false, "",
+ _, err := resolveSelectorAt(context.Background(), selector.Selector{Kind: tc.kind, Value: "x"}, 0, false, false, "",
func(ctx context.Context, _ []map[string]any) (int64, error) {
deadline, hasDeadline = ctx.Deadline()
return 7, nil
@@ -221,7 +222,7 @@ func TestResolveSelectorAtBoundsTextLookupsOnly(t *testing.T) {
// browser with a kind the resolver's switch does not implement.
func TestResolveSelectorAtRejectsUnwrappableKinds(t *testing.T) {
called := false
- _, err := resolveSelectorAt(context.Background(), selector.Selector{Kind: selector.KindSemantic, Value: "Save"}, 0, false, "",
+ _, err := resolveSelectorAt(context.Background(), selector.Selector{Kind: selector.KindSemantic, Value: "Save"}, 0, false, false, "",
func(context.Context, []map[string]any) (int64, error) {
called = true
return 0, nil
@@ -253,3 +254,73 @@ func TestXPathDoesNotPierceShadowRoots(t *testing.T) {
describeNode(t, ctx, light), describeNode(t, ctx, want))
}
}
+
+// The decided grammar, on the fixture where the two orders disagree: #decoy is a
+// weight-0 div that PRECEDES the weight-0.25 #inner button, and the two tie on
+// subtree size. Before this, nth:1 resolved to an element earlier in the document
+// than nth:0, because pick() indexed a weight-sorted list.
+func TestPositionalWrappersOverTextIndexDocumentOrder(t *testing.T) {
+ ctx := newSelectorFixture(t)
+
+ first := resolve(t, ctx, "css:#decoy")
+ last := resolve(t, ctx, "css:#inner")
+
+ for _, tc := range []struct {
+ raw string
+ want int64
+ what string
+ }{
+ {"first:text:Archive record", first, "div#decoy, the document-first candidate"},
+ {"nth:0:text:Archive record", first, "div#decoy, the document-first candidate"},
+ {"nth:1:text:Archive record", last, "button#inner, the candidate AFTER nth:0"},
+ {"last:text:Archive record", last, "button#inner, the document-last candidate"},
+ } {
+ if got := resolve(t, ctx, tc.raw); got != tc.want {
+ t.Errorf("%s resolved to %s, want %s", tc.raw, describeNode(t, ctx, got), tc.what)
+ }
+ }
+
+ // The defect stated as an ordering property rather than as two node ids: an
+ // index must never walk backwards through the document.
+ if resolve(t, ctx, "nth:0:text:Archive record") == resolve(t, ctx, "nth:1:text:Archive record") {
+ t.Fatal("nth:0 and nth:1 resolved to the same node; the fixture no longer has two candidates")
+ }
+ if resolve(t, ctx, "first:text:Archive record") != resolve(t, ctx, "nth:0:text:Archive record") {
+ t.Error("first:text: and nth:0:text: must be the same candidate")
+ }
+
+ // The decision itself: a bare text: may differ from all three, and here it
+ // does. Leaving this implicit is how option B ships by accident.
+ plain := resolve(t, ctx, "text:Archive record")
+ if plain == first {
+ t.Error("text:Archive record resolved to the document-first div; the control ranking on the bare selector is gone")
+ }
+ if plain != last {
+ t.Errorf("text:Archive record resolved to %s, want button#inner — the bare selector still ranks by control-likeness",
+ describeNode(t, ctx, plain))
+ }
+}
+
+// The change must not read as a general reordering: css: and xpath: indexed
+// document order before and still do, on the same two elements.
+func TestPositionalWrappersOverCSSAndXPathStillIndexDocumentOrder(t *testing.T) {
+ ctx := newSelectorFixture(t)
+
+ decoy := resolve(t, ctx, "css:#decoy")
+ inner := resolve(t, ctx, "css:#inner")
+
+ for _, tc := range []struct {
+ raw string
+ want int64
+ }{
+ {"first:css:#decoy,#inner", decoy},
+ {"last:css:#decoy,#inner", inner},
+ {"nth:1:css:#decoy,#inner", inner},
+ {`first:xpath://*[@id="decoy" or @id="inner"]`, decoy},
+ {`last:xpath://*[@id="decoy" or @id="inner"]`, inner},
+ } {
+ if got := resolve(t, ctx, tc.raw); got != tc.want {
+ t.Errorf("%s resolved to %s, want %s", tc.raw, describeNode(t, ctx, got), describeNode(t, ctx, tc.want))
+ }
+ }
+}
diff --git a/internal/mcp/argcheck_test.go b/internal/mcp/argcheck_test.go
index e2af7b49..2da8ce35 100644
--- a/internal/mcp/argcheck_test.go
+++ b/internal/mcp/argcheck_test.go
@@ -604,3 +604,41 @@ func TestNoActionToolIsSentATypedArgumentItDoesNotDeclare(t *testing.T) {
}
t.Logf("checked %d undeclared (tool, probe) pairs across %d action tools and %d probes", checked, len(actionToolTargets), len(probes))
}
+
+// A wrapper index used to mean document order for css:/xpath: and semantic rank
+// for text:, so nth:1 could resolve earlier in the page than nth:0. The rule is
+// one rule now, and a schema that offers first/last/nth without stating it leaves
+// an agent to infer the grammar from trial and error. Derived over the schemas:
+// any tool that gains a wrapper-accepting selector inherits the requirement.
+func TestSelectorSchemasThatOfferWrappersStateWhatAnIndexMeans(t *testing.T) {
+ checked := 0
+ for _, tool := range allTools() {
+ raw, err := json.Marshal(tool.InputSchema)
+ if err != nil {
+ t.Fatalf("marshal %s schema: %v", tool.Name, err)
+ }
+ var schema struct {
+ Properties map[string]struct {
+ Description string `json:"description"`
+ } `json:"properties"`
+ }
+ if err := json.Unmarshal(raw, &schema); err != nil {
+ t.Fatalf("unmarshal %s schema: %v", tool.Name, err)
+ }
+ for name, property := range schema.Properties {
+ if !strings.Contains(property.Description, "first/last/nth") {
+ continue
+ }
+ checked++
+ if !strings.Contains(property.Description, "document order") {
+ t.Errorf("%s.%s offers first/last/nth without saying an index follows document order: %q", tool.Name, name, property.Description)
+ }
+ if !strings.Contains(property.Description, "text:X and first:text:X can differ") {
+ t.Errorf("%s.%s does not warn that a bare text: selector ranks rather than indexes: %q", tool.Name, name, property.Description)
+ }
+ }
+ }
+ if checked == 0 {
+ t.Fatal("no schema offers first/last/nth, so this guard checked nothing")
+ }
+}
diff --git a/internal/mcp/tools.go b/internal/mcp/tools.go
index 2210c93e..24c3b481 100644
--- a/internal/mcp/tools.go
+++ b/internal/mcp/tools.go
@@ -2,6 +2,13 @@ package mcp
import "github.com/mark3labs/mcp-go/mcp"
+// positionalWrapperGrammar states what an index means, for every tool whose
+// selector accepts first/last/nth. It is one constant because the rule is one
+// rule: a client that reads it in a click description must not learn something
+// different from the snapshot description. Indices used to follow an internal
+// ranking for text:, which made nth:1 resolve earlier in the page than nth:0.
+const positionalWrapperGrammar = " first/last/nth index matches in document order for every kind, so nth:0 is the first match in the page. A bare text: selector instead picks the most control-like smallest match, so text:X and first:text:X can differ."
+
// allTools returns every MCP tool exposed by the PinchTab MCP server.
func allTools() []mcp.Tool {
return []mcp.Tool{
@@ -41,7 +48,7 @@ func allTools() []mcp.Tool {
mcp.WithBoolean("compact", mcp.Description("Compact format (most token-efficient)")),
mcp.WithString("format", mcp.Description("Output format: 'compact' or 'text'")),
mcp.WithBoolean("diff", mcp.Description("Only changes since last snapshot")),
- mcp.WithString("selector", mcp.Description("Unified selector to scope the snapshot (ref, CSS, XPath, text, find, role, label, placeholder, alt, title, testid, first/last/nth). Selectors resolve in the current frame scope; use pinchtab_frame for iframe content.")),
+ mcp.WithString("selector", mcp.Description("Unified selector to scope the snapshot (ref, CSS, XPath, text, find, role, label, placeholder, alt, title, testid, first/last/nth). Selectors resolve in the current frame scope; use pinchtab_frame for iframe content."+positionalWrapperGrammar)),
mcp.WithNumber("maxTokens", mcp.Description("Maximum estimated tokens in response (e.g. 300)")),
mcp.WithNumber("depth", mcp.Description("Maximum tree depth (e.g. 3)")),
mcp.WithBoolean("noAnimations", mcp.Description("Disable animations before capturing the snapshot")),
@@ -96,7 +103,7 @@ func allTools() []mcp.Tool {
mcp.NewTool("pinchtab_click",
mcp.WithDescription("Click an element. Prefer selector from pinchtab_find.best_ref (e.g. 'e5') to avoid extra snapshots."),
- mcp.WithString("selector", mcp.Description("Unified selector: ref (e.g. 'e5'), CSS, XPath, text, find, role, label, placeholder, alt, title, testid, or first/last/nth. Non-ref selectors resolve in the current frame scope.")),
+ mcp.WithString("selector", mcp.Description("Unified selector: ref (e.g. 'e5'), CSS, XPath, text, find, role, label, placeholder, alt, title, testid, or first/last/nth. Non-ref selectors resolve in the current frame scope."+positionalWrapperGrammar)),
mcp.WithString("ref", mcp.Description("(deprecated) Element ref from snapshot — use 'selector' instead")),
mcp.WithString("query", mcp.Description("Alias for semantic targeting when selector is omitted (example: 'login button' -> find:login button)")),
mcp.WithString("dialogAction", mcp.Description("Optional one-shot dialog handling for this click: 'accept' or 'dismiss'")),