High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
refactor: one owner for the selector prefix vocabulary, and settle the case question while doing it PIN-047
Luigi Agosti869c05b2579d
diff --git a/docs/commands.md b/docs/commands.mdindex 2b7b79a5..6a3daad1 100644--- a/docs/commands.md+++ b/docs/commands.md@@ -69,6 +69,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)+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.Selector lookup is explicit by frame. Unscoped selectors search only the current frame scope, which defaults to `main`. Use `pinchtab frame ...` before selector-based iframe work. Same-origin iframe scopes are supported; cross-origin iframe descendants are not currently exposed.diff --git a/internal/mcp/handlers_helpers.go b/internal/mcp/handlers_helpers.goindex 2554098e..9863d672 100644--- a/internal/mcp/handlers_helpers.go+++ b/internal/mcp/handlers_helpers.go@@ -39,9 +39,20 @@ func optInt(r mcp.CallToolRequest, key string) (int, bool) {return int(v), ok}+// Booleans get the same tolerance as numbers, and for the same reason. The one+// opt-out argument makes it matter more than the opt-in flags: dropping+// withBounds="false" leaves bounds switched on, so the response looks like the+// default rather than like the request.func optBool(r mcp.CallToolRequest, key string) (bool, bool) {- v, ok := r.GetArguments()[key].(bool)- return v, ok+ if v, ok := r.GetArguments()[key].(bool); ok {+ return v, true+ }+ if raw := optTrimmedString(r, key); raw != "" {+ if v, err := strconv.ParseBool(raw); err == nil {+ return v, true+ }+ }+ return false, false}func firstNonEmptyString(r mcp.CallToolRequest, keys ...string) string {@@ -53,25 +64,6 @@ func firstNonEmptyString(r mcp.CallToolRequest, keys ...string) string {return ""}-func hasKnownSelectorPrefix(v string) bool {- lower := strings.ToLower(strings.TrimSpace(v))- return strings.HasPrefix(lower, "css:") ||- strings.HasPrefix(lower, "xpath:") ||- strings.HasPrefix(lower, "text:") ||- strings.HasPrefix(lower, "find:") ||- strings.HasPrefix(lower, "semantic:") ||- strings.HasPrefix(lower, "role:") ||- strings.HasPrefix(lower, "label:") ||- strings.HasPrefix(lower, "placeholder:") ||- strings.HasPrefix(lower, "alt:") ||- strings.HasPrefix(lower, "title:") ||- strings.HasPrefix(lower, "testid:") ||- strings.HasPrefix(lower, "first:") ||- strings.HasPrefix(lower, "last:") ||- strings.HasPrefix(lower, "nth:") ||- strings.HasPrefix(lower, "ref:")-}-func looksLikeStructuredSelector(v string) bool {v = strings.TrimSpace(v)if v == "" {@@ -135,7 +127,7 @@ func actionSelectorArg(r mcp.CallToolRequest) string {if query == "" {return ""}- if hasKnownSelectorPrefix(query) || selector.IsRef(query) || looksLikeStructuredSelector(query) {+ if selector.HasKnownPrefix(query) || selector.IsRef(query) || looksLikeStructuredSelector(query) {return query}return "find:" + querydiff --git a/internal/mcp/handlers_helpers_test.go b/internal/mcp/handlers_helpers_test.goindex 114b1c3b..924f2979 100644--- a/internal/mcp/handlers_helpers_test.go+++ b/internal/mcp/handlers_helpers_test.go@@ -1,6 +1,7 @@package mcpimport (+ "strings""testing""github.com/mark3labs/mcp-go/mcp"@@ -47,19 +48,29 @@ func TestLooksLikeStructuredSelector(t *testing.T) {}}-func TestHasKnownSelectorPrefixIsCaseInsensitive(t *testing.T) {- for _, in := range []string{"css:#a", "CSS:#a", "Find:submit", "NTH:2:div", " text:hello"} {- if !hasKnownSelectorPrefix(in) {- t.Errorf("hasKnownSelectorPrefix(%q) = false, want true", in)+func TestActionSelectorArgUsesTheGrammarsPrefixVocabulary(t *testing.T) {+ // "find: login button" and "Role: Save" are the discriminating cases: the+ // space after the colon keeps looksLikeStructuredSelector from claiming+ // them, so only the grammar's prefix vocabulary passes them through.+ for _, in := range []string{"css:#a", "CSS:#a", "Find:submit", "NTH:2:div", " text:hello", "find: login button", "Role: Save"} {+ want := strings.TrimSpace(in)+ if got := actionSelectorArg(queryRequest(in)); got != want {+ t.Errorf("actionSelectorArg(%q) = %q, want %q passed through as a selector", in, got, want)}}- for _, in := range []string{"submit", "unknownprefix:value"} {- if hasKnownSelectorPrefix(in) {- t.Errorf("hasKnownSelectorPrefix(%q) = true, want false", in)+ for _, in := range []string{"submit", "unknownprefix value"} {+ if got := actionSelectorArg(queryRequest(in)); got != "find:"+in {+ t.Errorf("actionSelectorArg(%q) = %q, want it wrapped as find:", in, got)}}}+func queryRequest(query string) mcp.CallToolRequest {+ req := mcp.CallToolRequest{}+ req.Params.Arguments = map[string]any{"query": query}+ return req+}+func TestActionSelectorArgRoutesSpaceSeparatedProseToFind(t *testing.T) {tests := []struct {name stringdiff --git a/internal/selector/selector.go b/internal/selector/selector.goindex 3ab0c85a..82e34ca8 100644--- a/internal/selector/selector.go+++ b/internal/selector/selector.go@@ -15,6 +15,9 @@// "testid:submit" → Test id locator// "last:button" → Positional selector wrapper//+// Prefixes match case-insensitively, so "CSS:#login" and "css:#login" are the+// same selector. Values are never case-folded.+//// Bare strings that look like CSS selectors (start with ., #, [,// or contain tag-like patterns) are treated as CSS. Everything else// without a prefix is treated as a ref if it matches the eN pattern,@@ -97,7 +100,7 @@ func (s Selector) IsEmpty() bool {// Parse interprets a selector string and returns a typed Selector.//-// Explicit prefixes take priority:+// Explicit prefixes take priority and match case-insensitively://// "css:..." → CSS// "xpath:..." → XPath@@ -130,50 +133,8 @@ func Parse(s string) Selector {return Selector{}}- if after, ok := cutPrefix(s, "css:"); ok {- return Selector{Kind: KindCSS, Value: after}- }- if after, ok := cutPrefix(s, "xpath:"); ok {- return Selector{Kind: KindXPath, Value: after}- }- if after, ok := cutPrefix(s, "text:"); ok {- return Selector{Kind: KindText, Value: after}- }- if after, ok := cutPrefix(s, "find:"); ok {- return Selector{Kind: KindSemantic, Value: after}- }- if after, ok := cutPrefix(s, "semantic:"); ok {- return Selector{Kind: KindSemantic, Value: after}- }- if after, ok := cutPrefix(s, "role:"); ok {- return Selector{Kind: KindRole, Value: after}- }- if after, ok := cutPrefix(s, "label:"); ok {- return Selector{Kind: KindLabel, Value: after}- }- if after, ok := cutPrefix(s, "placeholder:"); ok {- return Selector{Kind: KindPlaceholder, Value: after}- }- if after, ok := cutPrefix(s, "alt:"); ok {- return Selector{Kind: KindAlt, Value: after}- }- if after, ok := cutPrefix(s, "title:"); ok {- return Selector{Kind: KindTitle, Value: after}- }- if after, ok := cutPrefix(s, "testid:"); ok {- return Selector{Kind: KindTestID, Value: after}- }- if after, ok := cutPrefix(s, "first:"); ok {- return Selector{Kind: KindFirst, Value: after}- }- if after, ok := cutPrefix(s, "last:"); ok {- return Selector{Kind: KindLast, Value: after}- }- if after, ok := cutPrefix(s, "nth:"); ok {- return Selector{Kind: KindNth, Value: after}- }- if after, ok := cutPrefix(s, "ref:"); ok {- return Selector{Kind: KindRef, Value: after}+ if kind, value, ok := cutKnownPrefix(s); ok {+ return Selector{Kind: kind, Value: value}}if strings.HasPrefix(s, "//") || strings.HasPrefix(s, "(//") {@@ -310,9 +271,51 @@ func ParseNth(value string) (index int, nested string, err error) {return index, rawSelector, nil}-func cutPrefix(s, prefix string) (string, bool) {- if strings.HasPrefix(s, prefix) {- return s[len(prefix):], true+// prefixKind binds one explicit prefix to the Kind it produces.+type prefixKind struct {+ Prefix string+ Kind Kind+}++// prefixKinds is the one vocabulary of explicit selector prefixes. Parse and+// HasKnownPrefix both read it, so a new kind is a single edit that cannot be+// half-applied. Several prefixes may share a Kind: "find:" and "semantic:"+// both produce KindSemantic.+//+// The unprefixed forms Parse also accepts — "//div" and "(//div)" as XPath, a+// bare "e5" as a ref — are pattern matches rather than prefixes and stay out,+// so HasKnownPrefix keeps meaning what its name says.+var prefixKinds = []prefixKind{+ {"css:", KindCSS},+ {"xpath:", KindXPath},+ {"text:", KindText},+ {"find:", KindSemantic},+ {"semantic:", KindSemantic},+ {"role:", KindRole},+ {"label:", KindLabel},+ {"placeholder:", KindPlaceholder},+ {"alt:", KindAlt},+ {"title:", KindTitle},+ {"testid:", KindTestID},+ {"first:", KindFirst},+ {"last:", KindLast},+ {"nth:", KindNth},+ {"ref:", KindRef},+}++// HasKnownPrefix reports whether s starts with an explicit selector prefix+// Parse recognises. It answers false for the unprefixed forms Parse+// auto-detects, such as "//div" and "e5".+func HasKnownPrefix(s string) bool {+ _, _, ok := cutKnownPrefix(strings.TrimSpace(s))+ return ok+}++func cutKnownPrefix(s string) (Kind, string, bool) {+ for _, pk := range prefixKinds {+ if len(s) >= len(pk.Prefix) && strings.EqualFold(s[:len(pk.Prefix)], pk.Prefix) {+ return pk.Kind, s[len(pk.Prefix):], true+ }}- return s, false+ return KindNone, s, false}diff --git a/internal/selector/selector_test.go b/internal/selector/selector_test.goindex 7502d24e..51f3c067 100644--- a/internal/selector/selector_test.go+++ b/internal/selector/selector_test.go@@ -1,6 +1,7 @@package selectorimport (+ "strings""testing")@@ -508,3 +509,100 @@ func TestParseNth(t *testing.T) {t.Error("expected blank nested selector to fail")}}++// TestPrefixTableDrivesBothParseAndHasKnownPrefix is the guard that keeps the+// two readers of prefixKinds from drifting: every table entry must parse to its+// own Kind and be recognised by the predicate, in lower, upper and mixed case.+func TestPrefixTableDrivesBothParseAndHasKnownPrefix(t *testing.T) {+ if len(prefixKinds) == 0 {+ t.Fatal("prefixKinds is empty; the guard would pass vacuously")+ }++ for _, pk := range prefixKinds {+ for _, spelling := range []string{+ pk.Prefix,+ strings.ToUpper(pk.Prefix),+ strings.ToUpper(pk.Prefix[:1]) + pk.Prefix[1:],+ } {+ input := spelling + "value"+ t.Run(input, func(t *testing.T) {+ if !HasKnownPrefix(input) {+ t.Errorf("HasKnownPrefix(%q) = false, want true", input)+ }+ got := Parse(input)+ if got.Kind != pk.Kind {+ t.Errorf("Parse(%q).Kind = %q, want %q", input, got.Kind, pk.Kind)+ }+ if got.Value != "value" {+ t.Errorf("Parse(%q).Value = %q, want %q", input, got.Value, "value")+ }+ })+ }+ }+}++func TestPrefixTableCoversEveryKindWithAPrefix(t *testing.T) {+ tabled := map[Kind]bool{}+ for _, pk := range prefixKinds {+ tabled[pk.Kind] = true+ }+ for _, kind := range []Kind{+ KindRef, KindCSS, KindXPath, KindText, KindSemantic, KindRole, KindLabel,+ KindPlaceholder, KindAlt, KindTitle, KindTestID, KindFirst, KindLast, KindNth,+ } {+ if !tabled[kind] {+ t.Errorf("kind %q has no prefix in prefixKinds", kind)+ }+ }+ if got := Parse("semantic:login button"); got.Kind != KindSemantic {+ t.Errorf(`Parse("semantic:...").Kind = %q, want %q`, got.Kind, KindSemantic)+ }+ if got := Parse("find:login button"); got.Kind != KindSemantic {+ t.Errorf(`Parse("find:...").Kind = %q, want %q`, got.Kind, KindSemantic)+ }+}++func TestHasKnownPrefixExcludesTheAutoDetectedForms(t *testing.T) {+ for _, in := range []string{"//div", "(//div)", "e5", "#id", ".class", "submit", "unknownprefix:value", ""} {+ if HasKnownPrefix(in) {+ t.Errorf("HasKnownPrefix(%q) = true, want false", in)+ }+ }++ if got := Parse("//div"); got.Kind != KindXPath || got.Value != "//div" {+ t.Errorf(`Parse("//div") = %+v, want xpath //div`, got)+ }+ if got := Parse("(//div)"); got.Kind != KindXPath || got.Value != "(//div)" {+ t.Errorf(`Parse("(//div)") = %+v, want xpath (//div)`, got)+ }+ if got := Parse("e5"); got.Kind != KindRef || got.Value != "e5" {+ t.Errorf(`Parse("e5") = %+v, want ref e5`, got)+ }++ if !HasKnownPrefix(" text:hello") {+ t.Error(`HasKnownPrefix(" text:hello") = false; leading space must be trimmed as Parse trims it`)+ }+}++func TestParseMixedCasePrefixesMatchTheirLowercaseForm(t *testing.T) {+ pairs := [][2]string{+ {"CSS:#id", "css:#id"},+ {"Text:hello", "text:hello"},+ {"XPath://div", "xpath://div"},+ {"Find:login button", "find:login button"},+ {"Role:button Save", "role:button Save"},+ {"TestID:submit", "testid:submit"},+ {"NTH:2:div", "nth:2:div"},+ {"Ref:e5", "ref:e5"},+ }+ for _, pair := range pairs {+ mixed, lower := Parse(pair[0]), Parse(pair[1])+ if mixed != lower {+ t.Errorf("Parse(%q) = %+v, want it identical to Parse(%q) = %+v", pair[0], mixed, pair[1], lower)+ }+ }++ if got := Parse("CSS:#id"); got.Kind != KindCSS || got.Value != "#id" {+ t.Errorf(`Parse("CSS:#id") = %+v, want css #id`, got)+ }+}