High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
chore: improve find and selector semantics with structured locator support
Luigi Agostidd01312ee7ce
diff --git a/docs/architecture/find.md b/docs/architecture/find.mdindex a99bb95e..62775699 100644--- a/docs/architecture/find.md+++ b/docs/architecture/find.md@@ -17,6 +17,7 @@ The implementation is designed to stay:```textaccessibility snapshot+ -> DOM metadata enrichment-> element descriptors-> lexical matcher-> embedding matcher@@ -33,8 +34,22 @@ Each accessibility node is converted into a descriptor with:- `role`- `name`- `value`--Those fields are also combined into a composite string used for matching.+- `label`+- `placeholder`+- `alt`+- `title`+- `testid`+- `text`+- `tag`+- `interactive`+- `parent`+- `section`+- `documentIdx`+- positional hints: `depth`, `siblingIndex`, `siblingCount`, `labelledBy`++PinchTab owns extraction of DOM-only metadata from backend node ids. The `semantic` package owns structured locator parsing and matching for `role:`, `text:`, `label:`, `placeholder:`, `alt:`, `title:`, `testid:`, `first:`, `last:`, and `nth:` forms.++CSS, XPath, refs, frame scoping, converting a matched ref back to a backend node, and the existing DOM-backed action `text:` selector remain PinchTab responsibilities.## Matchersdiff --git a/docs/commands.md b/docs/commands.mdindex 43697cf2..d3c32f3d 100644--- a/docs/commands.md+++ b/docs/commands.md@@ -65,6 +65,11 @@ Most element commands accept a unified selector:- XPath such as `xpath://button`- text selector such as `text:Submit`- semantic selector such as `find:login button`+- role/name selector such as `role:button Save`+- 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)++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/docs/reference/find.md b/docs/reference/find.mdindex 509468a8..69e158fb 100644--- a/docs/reference/find.md+++ b/docs/reference/find.md@@ -73,7 +73,19 @@ When `explain` is enabled, each match may also include lexical and embedding sco## Query Syntax-Beyond plain natural-language descriptions, the matcher understands two query modifiers:+Beyond plain natural-language descriptions, the matcher understands three query modifiers:++### Ordinal Queries++Use ordinal words to pick a position from otherwise similar matches:++```bash+pinchtab find "first button"+pinchtab find "second search result"+pinchtab find "last link"+```++Ordinal matching is applied after semantic scoring. When the snapshot has no coordinates, document order is used as the stable order.### Negative Queries@@ -146,6 +158,8 @@ curl -X POST http://localhost:9867/tabs/<tabId>/action \## Operational Notes- `/find` uses the tab's accessibility snapshot, not raw DOM selectors.+- Structured `/find` queries such as `role:button Save`, `text:Submit`, `label:Email`, `placeholder:Search`, `alt:Logo`, `title:Close`, `testid:submit`, `first:role:button`, `last:text:Submit`, and `nth:2:label:Email` are matched by the semantic engine against enriched descriptors.+- In action commands, `role:`, `label:`, `placeholder:`, `alt:`, `title:`, `testid:`, and wrappers around those forms use semantic matching. CSS, XPath, refs, the existing `text:` action selector, and bare CSS/text wrappers such as `first:button` remain browser-side selector resolution.- If there is no cached snapshot, PinchTab tries to refresh it automatically before matching.- Successful matches are useful inputs to `/action`, `/actions`, and higher-level recovery logic.- A `200` response can still return an empty `best_ref` if nothing met the threshold.diff --git a/docs/reference/mcp-tools.md b/docs/reference/mcp-tools.mdindex 0c0b07d9..d1b9d82f 100644--- a/docs/reference/mcp-tools.md+++ b/docs/reference/mcp-tools.md@@ -13,6 +13,11 @@ Selector forms include:- `xpath://button`- `text:Submit`- `find:login button`+- `role:button Save`+- `label:Email`, `placeholder:Search`, `alt:Logo`, `title:Close`, `testid:submit`+- `first:button`, `last:button`, `nth:2:button`++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.## Navigationdiff --git a/go.mod b/go.modindex a0235ebb..9f8f120a 100644--- a/go.mod+++ b/go.mod@@ -9,7 +9,7 @@ require (github.com/gost-dom/browser v0.11.0github.com/mark3labs/mcp-go v0.49.0github.com/pinchtab/idpishield v0.1.4- github.com/pinchtab/semantic v0.1.2+ github.com/pinchtab/semantic v0.1.3github.com/shirou/gopsutil/v4 v4.26.3github.com/spf13/cobra v1.10.2golang.org/x/net v0.53.0diff --git a/go.sum b/go.sumindex ee13a770..486db32f 100644--- a/go.sum+++ b/go.sum@@ -52,8 +52,8 @@ github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde h1:x0TT0RDC7UhAgithub.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde/go.mod h1:nZgzbfBr3hhjoZnS66nKrHmduYNpc34ny7RK4z5/HM0=github.com/pinchtab/idpishield v0.1.4 h1:zuIofkQ6c9tzdrYsaNWA10w78OuMcgiBlsCOz4Zk34E=github.com/pinchtab/idpishield v0.1.4/go.mod h1:i6MNCo1Y03KvpqblGAsGviox1WKpsn11gwOSeIlzYm0=-github.com/pinchtab/semantic v0.1.2 h1:aSSwNwFb+laEBW1/x44dhnGmqUn5xdWJsweLgbqu8WM=-github.com/pinchtab/semantic v0.1.2/go.mod h1:SPKIra6m26faxTxn4dxa1ex1TbGkZDKbJ2r5rCngWoQ=+github.com/pinchtab/semantic v0.1.3 h1:4nzJby6CZlqag5tfmeZux8mjB2xKgS4uWUi9GMtSqSM=+github.com/pinchtab/semantic v0.1.3/go.mod h1:SPKIra6m26faxTxn4dxa1ex1TbGkZDKbJ2r5rCngWoQ=github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=diff --git a/internal/bridge/action_request.go b/internal/bridge/action_request.goindex 55933709..fb0bac93 100644--- a/internal/bridge/action_request.go+++ b/internal/bridge/action_request.go@@ -21,6 +21,10 @@ type ActionFunc func(ctx context.Context, req ActionRequest) (map[string]any, er// "xpath://div" → XPath expression// "text:Submit" → text content match// "find:login btn" → semantic / natural-language query+// "role:button Save" → role/name locator+// "label:Email" → form control by label+// "testid:submit" → test id locator+// "last:button" → positional selector wrapper//// For backward compatibility, the legacy Ref and Selector (CSS) fields// are still accepted. Call NormalizeSelector() to merge them into thediff --git a/internal/bridge/action_resolve.go b/internal/bridge/action_resolve.goindex b67dcc04..faf79af1 100644--- a/internal/bridge/action_resolve.go+++ b/internal/bridge/action_resolve.go@@ -4,6 +4,7 @@ import ("context""encoding/json""fmt"+ "strconv""strings""time"@@ -398,6 +399,146 @@ func ResolveTextToNodeIDInFrame(ctx context.Context, frameID, text string) (int6return backendNodeID, err}+const resolveSelectorAtFn = `function(kind, value, index, fromEnd) {+ const root = this;+ const normalize = (input) => String(input || "")+ .toLowerCase()+ .replace(/\s+/g, " ")+ .trim();+ const needle = normalize(value);+ const unique = (items) => {+ const seen = new Set();+ const out = [];+ for (const item of items) {+ if (!item || seen.has(item)) continue;+ seen.add(item);+ out.push(item);+ }+ return out;+ };+ const pick = (items) => {+ items = unique(items);+ if (!items.length) return null;+ const idx = fromEnd ? items.length - 1 : index;+ if (idx < 0 || idx >= items.length) return null;+ return items[idx];+ };+ const textCandidates = (query) => {+ const elements = Array.from((root.body || root.documentElement || root).querySelectorAll("*"));+ const exact = [];+ for (const el of elements) {+ const text = normalize(el.textContent || "");+ if (!query || !text || !(text === query || text.includes(query))) continue;+ exact.push({ el, size: el.getElementsByTagName("*").length });+ }+ if (exact.length) {+ const minSize = Math.min(...exact.map((item) => item.size));+ return exact.filter((item) => item.size === minSize).map((item) => item.el);+ }+ const tokens = query.split(" ").filter(Boolean);+ if (!tokens.length) return [];+ const fuzzy = [];+ for (const el of elements) {+ const text = normalize(el.textContent || "");+ if (!text) continue;+ let hits = 0;+ for (const token of tokens) if (text.includes(token)) hits++;+ if (hits / tokens.length >= 0.7) {+ fuzzy.push({ el, size: el.getElementsByTagName("*").length });+ }+ }+ if (!fuzzy.length) return [];+ const minSize = Math.min(...fuzzy.map((item) => item.size));+ return fuzzy.filter((item) => item.size === minSize).map((item) => item.el);+ };++ try {+ switch (kind) {+ case "css":+ return pick(Array.from(root.querySelectorAll(value)));+ case "xpath": {+ const result = root.evaluate(value, root, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);+ const items = [];+ for (let i = 0; i < result.snapshotLength; i++) items.push(result.snapshotItem(i));+ return pick(items);+ }+ case "text":+ return pick(textCandidates(needle));+ default:+ return null;+ }+ } catch (e) {+ return null;+ }+}`++func resolveSelectorAtInFrame(ctx context.Context, frameID string, sel selector.Selector, index int, fromEnd bool) (int64, error) {+ kind := string(sel.Kind)+ switch sel.Kind {+ case selector.KindCSS, selector.KindXPath, selector.KindText:+ default:+ return 0, fmt.Errorf("%s selector cannot be used with first/last/nth", sel.Kind)+ }++ var backendNodeID int64+ err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {+ nid, err := resolveNodeInFrame(ctx, frameID, resolveSelectorAtFn, []map[string]any{+ {"value": kind},+ {"value": sel.Value},+ {"value": index},+ {"value": fromEnd},+ })+ if err != nil {+ return fmt.Errorf("%s %q: no element found", sel.Kind, sel.Value)+ }+ backendNodeID = nid+ return nil+ }))+ return backendNodeID, err+}++func parseNthSelectorValue(value string) (int, string, error) {+ rawIndex, rawSelector, ok := strings.Cut(value, ":")+ if !ok {+ return 0, "", fmt.Errorf("nth selector requires nth:<index>:<selector>")+ }+ rawIndex = strings.TrimSpace(rawIndex)+ rawSelector = strings.TrimSpace(rawSelector)+ if rawSelector == "" {+ return 0, "", fmt.Errorf("nth selector requires a nested selector")+ }+ index, err := strconv.Atoi(rawIndex)+ if err != nil || index < 0 {+ return 0, "", fmt.Errorf("nth selector index must be a zero-based non-negative integer")+ }+ return index, rawSelector, nil+}++func resolveNestedSelectorAtInFrame(ctx context.Context, frameID string, 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)+ case selector.KindLast:+ return resolveNestedSelectorAtInFrame(ctx, frameID, inner.Value, refCache, 0, true)+ case selector.KindNth:+ nth, nestedRaw, err := parseNthSelectorValue(inner.Value)+ if err != nil {+ return 0, err+ }+ return resolveNestedSelectorAtInFrame(ctx, frameID, 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)+ case selector.KindSemantic:+ return 0, fmt.Errorf("semantic selectors must be resolved at the handler layer via /find")+ default:+ return resolveSelectorAtInFrame(ctx, frameID, inner, index, fromEnd)+ }+}+// ResolveCSSToNodeID resolves a CSS selector to a backend node ID.func ResolveCSSToNodeID(ctx context.Context, css string) (int64, error) {return ResolveCSSToNodeIDInFrame(ctx, "", css)@@ -548,6 +689,23 @@ func ResolveUnifiedSelectorInFrame(ctx context.Context, sel selector.Selector, rcase selector.KindSemantic:return 0, fmt.Errorf("semantic selectors must be resolved at the handler layer via /find")+ 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 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 := parseNthSelectorValue(sel.Value)+ if err != nil {+ return 0, err+ }+ return resolveNestedSelectorAtInFrame(ctx, frameID, rawSelector, refCache, index, false)+default:return 0, fmt.Errorf("unknown selector kind: %q", sel.Kind)}@@ -555,8 +713,8 @@ func ResolveUnifiedSelectorInFrame(ctx context.Context, sel selector.Selector, r// ResolveUnifiedSelector resolves a parsed selector to a backend node ID.// For ref selectors, the refCache is consulted. For CSS, XPath, and text-// selectors, CDP is used directly. Semantic selectors are not resolved here-// (they require the semantic matcher at a higher layer).+// selectors, CDP is used directly. Semantic and structured semantic locators+// are not resolved here; they require the semantic matcher at a higher layer.func ResolveUnifiedSelector(ctx context.Context, sel selector.Selector, refCache *RefCache) (int64, error) {return ResolveUnifiedSelectorInFrame(ctx, sel, refCache, "")}diff --git a/internal/bridge/action_resolve_test.go b/internal/bridge/action_resolve_test.gonew file mode 100644index 00000000..e1a2d15a--- /dev/null+++ b/internal/bridge/action_resolve_test.go@@ -0,0 +1,45 @@+package bridge++import (+ "context"+ "testing"++ "github.com/pinchtab/pinchtab/internal/selector"+)++func TestParseNthSelectorValue(t *testing.T) {+ index, raw, err := parseNthSelectorValue("2:role:button Save")+ if err != nil {+ t.Fatalf("parseNthSelectorValue returned error: %v", err)+ }+ if index != 2 || raw != "role:button Save" {+ t.Fatalf("got index=%d raw=%q, want 2 role selector", index, raw)+ }+}++func TestParseNthSelectorValueRejectsInvalidIndex(t *testing.T) {+ if _, _, err := parseNthSelectorValue("-1:button"); err == nil {+ t.Fatal("expected negative index to fail")+ }+ if _, _, err := parseNthSelectorValue("button"); err == nil {+ t.Fatal("expected missing nested selector to fail")+ }+}++func TestResolveUnifiedSelector_FirstRef(t *testing.T) {+ cache := &RefCache{Refs: map[string]int64{"e5": 42}}+ got, err := ResolveUnifiedSelectorInFrame(context.Background(), selector.Parse("first:e5"), cache, "")+ if err != nil {+ t.Fatalf("ResolveUnifiedSelectorInFrame returned error: %v", err)+ }+ if got != 42 {+ t.Fatalf("node id = %d, want 42", got)+ }+}++func TestResolveUnifiedSelector_LastRefRejected(t *testing.T) {+ cache := &RefCache{Refs: map[string]int64{"e5": 42}}+ if _, err := ResolveUnifiedSelectorInFrame(context.Background(), selector.Parse("last:e5"), cache, ""); err == nil {+ t.Fatal("expected last:ref to fail")+ }+}diff --git a/internal/bridge/observe/snapshot.go b/internal/bridge/observe/snapshot.goindex 32c3ea57..0faa42a7 100644--- a/internal/bridge/observe/snapshot.go+++ b/internal/bridge/observe/snapshot.go@@ -17,6 +17,13 @@ type A11yNode struct {Name string `json:"name"`Depth int `json:"depth"`Value string `json:"value,omitempty"`+ Label string `json:"label,omitempty"`+ Placeholder string `json:"placeholder,omitempty"`+ Alt string `json:"alt,omitempty"`+ Title string `json:"title,omitempty"`+ TestID string `json:"testid,omitempty"`+ Text string `json:"text,omitempty"`+ Tag string `json:"tag,omitempty"`Disabled bool `json:"disabled,omitempty"`Focused bool `json:"focused,omitempty"`Hidden bool `json:"hidden,omitempty"`diff --git a/internal/bridge/semantic_metadata.go b/internal/bridge/semantic_metadata.gonew file mode 100644index 00000000..2e1cb51b--- /dev/null+++ b/internal/bridge/semantic_metadata.go@@ -0,0 +1,171 @@+package bridge++import (+ "context"+ "encoding/json"+ "strings"++ "github.com/chromedp/chromedp"+)++type nodeDOMMetadata struct {+ Tag string `json:"tag"`+ Label string `json:"label"`+ Placeholder string `json:"placeholder"`+ Alt string `json:"alt"`+ Title string `json:"title"`+ TestID string `json:"testid"`+ Text string `json:"text"`+}++// EnrichA11yNodesWithDOMMetadata adds DOM-backed descriptor fields used by the+// semantic structured locator matcher. It is best-effort: per-node CDP failures+// are skipped so snapshots still work on pages with detached or remote nodes.+func EnrichA11yNodesWithDOMMetadata(ctx context.Context, nodes []A11yNode) error {+ if len(nodes) == 0 {+ return nil+ }+ return chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {+ c := chromedp.FromContext(ctx)+ if c == nil || c.Target == nil {+ return nil+ }+ for i := range nodes {+ if nodes[i].NodeID == 0 || hasNodeDOMMetadata(nodes[i]) {+ continue+ }+ meta, ok := resolveNodeDOMMetadata(ctx, nodes[i].NodeID)+ if !ok {+ continue+ }+ applyNodeDOMMetadata(&nodes[i], meta)+ }+ return nil+ }))+}++func hasNodeDOMMetadata(node A11yNode) bool {+ return node.Tag != "" ||+ node.Label != "" ||+ node.Placeholder != "" ||+ node.Alt != "" ||+ node.Title != "" ||+ node.TestID != "" ||+ node.Text != ""+}++func resolveNodeDOMMetadata(ctx context.Context, backendNodeID int64) (nodeDOMMetadata, bool) {+ var resolveResult json.RawMessage+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{+ "backendNodeId": backendNodeID,+ }, &resolveResult); err != nil {+ return nodeDOMMetadata{}, false+ }++ var resolved struct {+ Object struct {+ ObjectID string `json:"objectId"`+ } `json:"object"`+ }+ if err := json.Unmarshal(resolveResult, &resolved); err != nil || resolved.Object.ObjectID == "" {+ return nodeDOMMetadata{}, false+ }+ defer func() {+ _ = chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.releaseObject", map[string]any{+ "objectId": resolved.Object.ObjectID,+ }, nil)+ }()++ var callResult json.RawMessage+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{+ "functionDeclaration": domMetadataFn,+ "objectId": resolved.Object.ObjectID,+ "returnByValue": true,+ }, &callResult); err != nil {+ return nodeDOMMetadata{}, false+ }++ var call struct {+ Result struct {+ Value json.RawMessage `json:"value"`+ } `json:"result"`+ ExceptionDetails json.RawMessage `json:"exceptionDetails"`+ }+ if err := json.Unmarshal(callResult, &call); err != nil || len(call.ExceptionDetails) > 0 || len(call.Result.Value) == 0 {+ return nodeDOMMetadata{}, false+ }++ var meta nodeDOMMetadata+ if err := json.Unmarshal(call.Result.Value, &meta); err != nil {+ return nodeDOMMetadata{}, false+ }+ return meta, true+}++func applyNodeDOMMetadata(node *A11yNode, meta nodeDOMMetadata) {+ node.Tag = strings.TrimSpace(meta.Tag)+ node.Label = strings.TrimSpace(meta.Label)+ node.Placeholder = strings.TrimSpace(meta.Placeholder)+ node.Alt = strings.TrimSpace(meta.Alt)+ node.Title = strings.TrimSpace(meta.Title)+ node.TestID = strings.TrimSpace(meta.TestID)+ node.Text = strings.TrimSpace(meta.Text)+}++const domMetadataFn = `function() {+ const el = this;+ if (!el || el.nodeType !== 1) return {};+ const doc = el.ownerDocument || document;+ const normalize = (value) => String(value || "").replace(/\s+/g, " ").trim();+ const attr = (name) => el.getAttribute ? el.getAttribute(name) || "" : "";+ const unique = (items) => {+ const seen = new Set();+ const out = [];+ for (const item of items) {+ const value = normalize(item);+ if (!value || seen.has(value.toLowerCase())) continue;+ seen.add(value.toLowerCase());+ out.push(value);+ }+ return out;+ };+ const labelledByText = () => {+ const labelledBy = attr("aria-labelledby");+ if (!labelledBy) return "";+ return labelledBy.split(/\s+/)+ .map((id) => doc.getElementById && doc.getElementById(id))+ .filter(Boolean)+ .map((node) => node.textContent || "")+ .join(" ");+ };+ const labelText = () => {+ const parts = [];+ if (el.labels) {+ for (const label of el.labels) parts.push(label.textContent || "");+ }+ const id = el.id;+ if (id && doc.querySelectorAll) {+ for (const label of doc.querySelectorAll("label")) {+ if (label.getAttribute("for") === id) parts.push(label.textContent || "");+ }+ }+ return parts.join(" ");+ };+ const testID = () => {+ for (const name of ["data-testid", "data-test-id", "data-test", "data-qa", "testid"]) {+ const value = attr(name);+ if (normalize(value)) return value;+ }+ return "";+ };+ const text = normalize(typeof el.innerText === "string" ? el.innerText : el.textContent || "");+ return {+ tag: String(el.tagName || "").toLowerCase(),+ label: unique([labelledByText(), labelText(), attr("aria-label")]).join(" "),+ placeholder: attr("placeholder"),+ alt: attr("alt"),+ title: attr("title"),+ testid: testID(),+ text: text.length > 500 ? text.slice(0, 500) : text+ };+}`diff --git a/internal/handlers/actions.go b/internal/handlers/actions.goindex 85b50b82..7e3dbb82 100644--- a/internal/handlers/actions.go+++ b/internal/handlers/actions.go@@ -209,93 +209,70 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {refMissing := falseif !useLiteAction && req.NodeID == 0 && req.Selector != "" {sel := selector.Parse(req.Selector)- switch sel.Kind {- case selector.KindRef:- // Ensure Ref is set for downstream recovery/intent caching.- req.Ref = sel.Value- // Clear Selector so the bridge doesn't try to use the ref- // string as a CSS selector (it checks Selector before NodeID).- req.Selector = ""- cache := h.Bridge.GetRefCache(resolvedTabID)- if cache != nil {- if target, ok := cache.Lookup(sel.Value); ok {- req.NodeID = target.BackendNodeID- }- }- if req.NodeID == 0 {- refMissing = true- }- case selector.KindCSS:- req.Ref = ""- nid, err := bridge.ResolveCSSToNodeIDInFrame(tCtx, h.selectorFrameID(resolvedTabID), sel.Value)- if err != nil {- httpx.Error(w, 400, frameScopedSelectorError("css selector", err))- return- }- req.NodeID = nid- req.Selector = ""- case selector.KindXPath:- nid, err := bridge.ResolveXPathToNodeIDInFrame(tCtx, h.selectorFrameID(resolvedTabID), sel.Value)+ if handled, err := h.applySemanticActionSelector(tCtx, resolvedTabID, sel, &req); handled {if err != nil {- httpx.Error(w, 400, frameScopedSelectorError("xpath selector", err))+ httpx.Error(w, semanticSelectorHTTPStatus(err), err)return}- req.NodeID = nid- req.Selector = ""- req.Ref = ""- case selector.KindText:- nid, err := bridge.ResolveTextToNodeIDInFrame(tCtx, h.selectorFrameID(resolvedTabID), sel.Value)- if err != nil {- httpx.Error(w, 400, frameScopedSelectorError("text selector", err))- return- }- req.NodeID = nid- req.Selector = ""- req.Ref = ""- case selector.KindSemantic:- // Semantic selectors require the matcher — resolve via find logic.- if h.Matcher != nil {- nodes := h.resolveSnapshotNodes(resolvedTabID)- if len(nodes) == 0 {- h.refreshRefCache(tCtx, resolvedTabID)- nodes = h.resolveSnapshotNodes(resolvedTabID)- }- if len(nodes) > 0 {- descs := make([]semantic.ElementDescriptor, len(nodes))- for i, n := range nodes {- descs[i] = semantic.ElementDescriptor{- Ref: n.Ref, Role: n.Role, Name: n.Name, Value: n.Value,- }- }- result, err := h.Matcher.Find(tCtx, sel.Value, descs, semantic.FindOptions{- Threshold: 0.3, TopK: 1,- })- if err != nil {- httpx.Error(w, 500, fmt.Errorf("semantic selector: %w", err))- return- }- if result.BestRef != "" {- req.Ref = result.BestRef- cache := h.Bridge.GetRefCache(resolvedTabID)- if cache != nil {- if target, ok := cache.Lookup(result.BestRef); ok {- req.NodeID = target.BackendNodeID- }- }- }- if req.NodeID == 0 {- httpx.Error(w, 404, fmt.Errorf("semantic selector %q: no matching element found", sel.Value))- return+ } else {+ switch sel.Kind {+ case selector.KindRef:+ // Ensure Ref is set for downstream recovery/intent caching.+ req.Ref = sel.Value+ // Clear Selector so the bridge doesn't try to use the ref+ // string as a CSS selector (it checks Selector before NodeID).+ req.Selector = ""+ cache := h.Bridge.GetRefCache(resolvedTabID)+ if cache != nil {+ if target, ok := cache.Lookup(sel.Value); ok {+ req.NodeID = target.BackendNodeID}- } else {- httpx.Error(w, 500, fmt.Errorf("semantic selector: no snapshot available — navigate first"))+ }+ if req.NodeID == 0 {+ refMissing = true+ }+ case selector.KindCSS:+ req.Ref = ""+ nid, err := bridge.ResolveCSSToNodeIDInFrame(tCtx, h.selectorFrameID(resolvedTabID), sel.Value)+ if err != nil {+ httpx.Error(w, 400, frameScopedSelectorError("css selector", err))return}- } else {- httpx.Error(w, 501, fmt.Errorf("semantic selectors require a matcher (not configured)"))+ req.NodeID = nid+ req.Selector = ""+ case selector.KindXPath:+ nid, err := bridge.ResolveXPathToNodeIDInFrame(tCtx, h.selectorFrameID(resolvedTabID), sel.Value)+ if err != nil {+ httpx.Error(w, 400, frameScopedSelectorError("xpath selector", err))+ return+ }+ req.NodeID = nid+ req.Selector = ""+ req.Ref = ""+ case selector.KindText:+ nid, err := bridge.ResolveTextToNodeIDInFrame(tCtx, h.selectorFrameID(resolvedTabID), sel.Value)+ if err != nil {+ httpx.Error(w, 400, frameScopedSelectorError("text selector", err))+ return+ }+ req.NodeID = nid+ req.Selector = ""+ req.Ref = ""+ case selector.KindRole, selector.KindLabel, selector.KindPlaceholder,+ selector.KindAlt, selector.KindTitle, selector.KindTestID,+ selector.KindFirst, selector.KindLast, selector.KindNth:+ nid, err := bridge.ResolveUnifiedSelectorInFrame(tCtx, sel, h.Bridge.GetRefCache(resolvedTabID), h.selectorFrameID(resolvedTabID))+ if err != nil {+ httpx.Error(w, 400, frameScopedSelectorError("selector", err))+ return+ }+ req.NodeID = nid+ req.Selector = ""+ req.Ref = ""+ case selector.KindSemantic:+ httpx.Error(w, 400, fmt.Errorf("semantic selector requires a non-empty query"))return}- req.Selector = ""}}@@ -604,117 +581,109 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, rerefMissing := falseif !useLiteAction && action.NodeID == 0 && action.Selector != "" {sel := selector.Parse(action.Selector)- switch sel.Kind {- case selector.KindRef:- action.Ref = sel.Value- action.Selector = ""- cache := h.Bridge.GetRefCache(resolvedTabID)- if cache != nil {- if target, ok := cache.Lookup(sel.Value); ok {- action.NodeID = target.BackendNodeID- }- }- if action.NodeID == 0 {- refMissing = true- }- case selector.KindCSS:- action.Ref = ""- nid, resolveErr := bridge.ResolveCSSToNodeIDInFrame(tCtx, h.selectorFrameID(resolvedTabID), sel.Value)+ if handled, resolveErr := h.applySemanticActionSelector(tCtx, resolvedTabID, sel, &action); handled {if resolveErr != nil {tCancel()results = append(results, actionResult{Index: i, Success: false,- Error: frameScopedSelectorError("css selector", resolveErr).Error(),+ Error: resolveErr.Error(),})if req.StopOnError {break}continue}- action.NodeID = nid- action.Selector = ""- case selector.KindXPath:- nid, resolveErr := bridge.ResolveXPathToNodeIDInFrame(tCtx, h.selectorFrameID(resolvedTabID), sel.Value)- if resolveErr != nil {- tCancel()- results = append(results, actionResult{- Index: i, Success: false,- Error: frameScopedSelectorError("xpath selector", resolveErr).Error(),- })- if req.StopOnError {- break+ } else {+ switch sel.Kind {+ case selector.KindRef:+ action.Ref = sel.Value+ action.Selector = ""+ cache := h.Bridge.GetRefCache(resolvedTabID)+ if cache != nil {+ if target, ok := cache.Lookup(sel.Value); ok {+ action.NodeID = target.BackendNodeID+ }}- continue- }- action.NodeID = nid- action.Selector = ""- action.Ref = ""- case selector.KindText:- nid, resolveErr := bridge.ResolveTextToNodeIDInFrame(tCtx, h.selectorFrameID(resolvedTabID), sel.Value)- if resolveErr != nil {- tCancel()- results = append(results, actionResult{- Index: i, Success: false,- Error: frameScopedSelectorError("text selector", resolveErr).Error(),- })- if req.StopOnError {- break+ if action.NodeID == 0 {+ refMissing = true}- continue- }- action.NodeID = nid- action.Selector = ""- action.Ref = ""- case selector.KindSemantic:- if h.Matcher != nil {- nodes := h.resolveSnapshotNodes(resolvedTabID)- if len(nodes) == 0 {- h.refreshRefCache(tCtx, resolvedTabID)- nodes = h.resolveSnapshotNodes(resolvedTabID)+ case selector.KindCSS:+ action.Ref = ""+ nid, resolveErr := bridge.ResolveCSSToNodeIDInFrame(tCtx, h.selectorFrameID(resolvedTabID), sel.Value)+ if resolveErr != nil {+ tCancel()+ results = append(results, actionResult{+ Index: i, Success: false,+ Error: frameScopedSelectorError("css selector", resolveErr).Error(),+ })+ if req.StopOnError {+ break+ }+ continue}- if len(nodes) > 0 {- descs := make([]semantic.ElementDescriptor, len(nodes))- for j, n := range nodes {- descs[j] = semantic.ElementDescriptor{- Ref: n.Ref, Role: n.Role, Name: n.Name, Value: n.Value,- }+ action.NodeID = nid+ action.Selector = ""+ case selector.KindXPath:+ nid, resolveErr := bridge.ResolveXPathToNodeIDInFrame(tCtx, h.selectorFrameID(resolvedTabID), sel.Value)+ if resolveErr != nil {+ tCancel()+ results = append(results, actionResult{+ Index: i, Success: false,+ Error: frameScopedSelectorError("xpath selector", resolveErr).Error(),+ })+ if req.StopOnError {+ break}- findResult, findErr := h.Matcher.Find(tCtx, sel.Value, descs, semantic.FindOptions{- Threshold: 0.3, TopK: 1,+ continue+ }+ action.NodeID = nid+ action.Selector = ""+ action.Ref = ""+ case selector.KindText:+ nid, resolveErr := bridge.ResolveTextToNodeIDInFrame(tCtx, h.selectorFrameID(resolvedTabID), sel.Value)+ if resolveErr != nil {+ tCancel()+ results = append(results, actionResult{+ Index: i, Success: false,+ Error: frameScopedSelectorError("text selector", resolveErr).Error(),})- if findErr == nil && findResult.BestRef != "" {- action.Ref = findResult.BestRef- cache := h.Bridge.GetRefCache(resolvedTabID)- if cache != nil {- if target, ok := cache.Lookup(findResult.BestRef); ok {- action.NodeID = target.BackendNodeID- }- }+ if req.StopOnError {+ break}+ continue}- if action.NodeID == 0 {+ action.NodeID = nid+ action.Selector = ""+ action.Ref = ""+ case selector.KindRole, selector.KindLabel, selector.KindPlaceholder,+ selector.KindAlt, selector.KindTitle, selector.KindTestID,+ selector.KindFirst, selector.KindLast, selector.KindNth:+ nid, resolveErr := bridge.ResolveUnifiedSelectorInFrame(tCtx, sel, h.Bridge.GetRefCache(resolvedTabID), h.selectorFrameID(resolvedTabID))+ if resolveErr != nil {tCancel()results = append(results, actionResult{Index: i, Success: false,- Error: fmt.Sprintf("semantic selector %q: no matching element found", sel.Value),+ Error: frameScopedSelectorError("selector", resolveErr).Error(),})if req.StopOnError {break}continue}- } else {+ action.NodeID = nid+ action.Selector = ""+ action.Ref = ""+ case selector.KindSemantic:tCancel()results = append(results, actionResult{Index: i, Success: false,- Error: "semantic selectors require a matcher (not configured)",+ Error: "semantic selector requires a non-empty query",})if req.StopOnError {break}continue}- action.Selector = ""}} else if !useLiteAction && action.Ref != "" && action.NodeID == 0 {// Legacy path: Ref set but NormalizeSelector didn't promote it@@ -927,120 +896,114 @@ func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {stepRefMissing := falseif !useLiteAction && step.NodeID == 0 && step.Selector != "" {sel := selector.Parse(step.Selector)- switch sel.Kind {- case selector.KindRef:- step.Ref = sel.Value- step.Selector = ""- cache := h.Bridge.GetRefCache(resolvedTabID)- if cache != nil {- if target, ok := cache.Lookup(sel.Value); ok {- step.NodeID = target.BackendNodeID- }- }- if step.NodeID == 0 {- stepRefMissing = true- }- case selector.KindCSS:- step.Ref = ""- tCtx, cancel := context.WithTimeout(ctx, stepTimeout)- nid, resolveErr := bridge.ResolveCSSToNodeIDInFrame(tCtx, h.selectorFrameID(resolvedTabID), sel.Value)- cancel()+ semanticCtx, semanticCancel := context.WithTimeout(ctx, stepTimeout)+ handled, resolveErr := h.applySemanticActionSelector(semanticCtx, resolvedTabID, sel, &step)+ semanticCancel()+ if handled {if resolveErr != nil {results = append(results, actionResult{Index: i, Success: false,- Error: frameScopedSelectorError("css selector", resolveErr).Error(),+ Error: resolveErr.Error(),})if req.StopOnError {break}continue}- step.NodeID = nid- step.Selector = ""- case selector.KindXPath:- tCtx, cancel := context.WithTimeout(ctx, stepTimeout)- nid, resolveErr := bridge.ResolveXPathToNodeIDInFrame(tCtx, h.selectorFrameID(resolvedTabID), sel.Value)- cancel()- if resolveErr != nil {- results = append(results, actionResult{- Index: i, Success: false,- Error: frameScopedSelectorError("xpath selector", resolveErr).Error(),- })- if req.StopOnError {- break+ } else {+ switch sel.Kind {+ case selector.KindRef:+ step.Ref = sel.Value+ step.Selector = ""+ cache := h.Bridge.GetRefCache(resolvedTabID)+ if cache != nil {+ if target, ok := cache.Lookup(sel.Value); ok {+ step.NodeID = target.BackendNodeID+ }}- continue- }- step.NodeID = nid- step.Selector = ""- step.Ref = ""- case selector.KindText:- tCtx, cancel := context.WithTimeout(ctx, stepTimeout)- nid, resolveErr := bridge.ResolveTextToNodeIDInFrame(tCtx, h.selectorFrameID(resolvedTabID), sel.Value)- cancel()- if resolveErr != nil {- results = append(results, actionResult{- Index: i, Success: false,- Error: frameScopedSelectorError("text selector", resolveErr).Error(),- })- if req.StopOnError {- break+ if step.NodeID == 0 {+ stepRefMissing = true}- continue- }- step.NodeID = nid- step.Selector = ""- step.Ref = ""- case selector.KindSemantic:- if h.Matcher != nil {+ case selector.KindCSS:+ step.Ref = ""tCtx, cancel := context.WithTimeout(ctx, stepTimeout)- nodes := h.resolveSnapshotNodes(resolvedTabID)- if len(nodes) == 0 {- h.refreshRefCache(tCtx, resolvedTabID)- nodes = h.resolveSnapshotNodes(resolvedTabID)+ nid, resolveErr := bridge.ResolveCSSToNodeIDInFrame(tCtx, h.selectorFrameID(resolvedTabID), sel.Value)+ cancel()+ if resolveErr != nil {+ results = append(results, actionResult{+ Index: i, Success: false,+ Error: frameScopedSelectorError("css selector", resolveErr).Error(),+ })+ if req.StopOnError {+ break+ }+ continue}- if len(nodes) > 0 {- descs := make([]semantic.ElementDescriptor, len(nodes))- for j, n := range nodes {- descs[j] = semantic.ElementDescriptor{- Ref: n.Ref, Role: n.Role, Name: n.Name, Value: n.Value,- }+ step.NodeID = nid+ step.Selector = ""+ case selector.KindXPath:+ tCtx, cancel := context.WithTimeout(ctx, stepTimeout)+ nid, resolveErr := bridge.ResolveXPathToNodeIDInFrame(tCtx, h.selectorFrameID(resolvedTabID), sel.Value)+ cancel()+ if resolveErr != nil {+ results = append(results, actionResult{+ Index: i, Success: false,+ Error: frameScopedSelectorError("xpath selector", resolveErr).Error(),+ })+ if req.StopOnError {+ break}- findResult, findErr := h.Matcher.Find(tCtx, sel.Value, descs, semantic.FindOptions{- Threshold: 0.3, TopK: 1,+ continue+ }+ step.NodeID = nid+ step.Selector = ""+ step.Ref = ""+ case selector.KindText:+ tCtx, cancel := context.WithTimeout(ctx, stepTimeout)+ nid, resolveErr := bridge.ResolveTextToNodeIDInFrame(tCtx, h.selectorFrameID(resolvedTabID), sel.Value)+ cancel()+ if resolveErr != nil {+ results = append(results, actionResult{+ Index: i, Success: false,+ Error: frameScopedSelectorError("text selector", resolveErr).Error(),})- if findErr == nil && findResult.BestRef != "" {- step.Ref = findResult.BestRef- cache := h.Bridge.GetRefCache(resolvedTabID)- if cache != nil {- if target, ok := cache.Lookup(findResult.BestRef); ok {- step.NodeID = target.BackendNodeID- }- }+ if req.StopOnError {+ break}+ continue}+ step.NodeID = nid+ step.Selector = ""+ step.Ref = ""+ case selector.KindRole, selector.KindLabel, selector.KindPlaceholder,+ selector.KindAlt, selector.KindTitle, selector.KindTestID,+ selector.KindFirst, selector.KindLast, selector.KindNth:+ tCtx, cancel := context.WithTimeout(ctx, stepTimeout)+ nid, resolveErr := bridge.ResolveUnifiedSelectorInFrame(tCtx, sel, h.Bridge.GetRefCache(resolvedTabID), h.selectorFrameID(resolvedTabID))cancel()- if step.NodeID == 0 {+ if resolveErr != nil {results = append(results, actionResult{Index: i, Success: false,- Error: fmt.Sprintf("semantic selector %q: no matching element found", sel.Value),+ Error: frameScopedSelectorError("selector", resolveErr).Error(),})if req.StopOnError {break}continue}- } else {+ step.NodeID = nid+ step.Selector = ""+ step.Ref = ""+ case selector.KindSemantic:results = append(results, actionResult{Index: i, Success: false,- Error: "semantic selectors require a matcher (not configured)",+ Error: "semantic selector requires a non-empty query",})if req.StopOnError {break}continue}- step.Selector = ""}}@@ -1177,11 +1140,9 @@ func (h *Handlers) cacheActionIntent(tabID string, req bridge.ActionRequest) {desc := semantic.ElementDescriptor{Ref: req.Ref}// Try to enrich from the current snapshot cache.if cache := h.Bridge.GetRefCache(tabID); cache != nil {- for _, n := range cache.Nodes {- if n.Ref == req.Ref {- desc.Role = n.Role- desc.Name = n.Name- desc.Value = n.Value+ for _, enriched := range semanticDescriptorsFromNodes(cache.Nodes) {+ if enriched.Ref == req.Ref {+ desc = enrichedbreak}}@@ -1326,6 +1287,7 @@ func (h *Handlers) refreshRefCache(ctx context.Context, tabID string) {return}flat, refs := bridge.BuildSnapshot(nodes, bridge.FilterInteractive, -1)+ _ = bridge.EnrichA11yNodesWithDOMMetadata(ctx, flat)h.Bridge.SetRefCache(tabID, &bridge.RefCache{Refs: refs,Targets: bridge.RefTargetsFromNodes(flat),diff --git a/internal/handlers/find.go b/internal/handlers/find.goindex b5827018..dea04fe6 100644--- a/internal/handlers/find.go+++ b/internal/handlers/find.go@@ -109,17 +109,10 @@ func (h *Handlers) HandleFind(w http.ResponseWriter, r *http.Request) {httpx.Error(w, 500, fmt.Errorf("no elements found in snapshot for tab %s — navigate first", resolvedTabID))return}+ _ = bridge.EnrichA11yNodesWithDOMMetadata(ctxTab, nodes)// Build descriptors from A11yNodes.- descs := make([]semantic.ElementDescriptor, len(nodes))- for i, n := range nodes {- descs[i] = semantic.ElementDescriptor{- Ref: n.Ref,- Role: n.Role,- Name: n.Name,- Value: n.Value,- }- }+ descs := semanticDescriptorsFromNodes(nodes)// IDPI: scan AX-node text corpus and full page body text for injection// patterns before semantic matching. The interactive AX filter omitsdiff --git a/internal/handlers/find_test.go b/internal/handlers/find_test.goindex 82ab981f..bb6234e8 100644--- a/internal/handlers/find_test.go+++ b/internal/handlers/find_test.go@@ -14,6 +14,7 @@ import ("github.com/chromedp/cdproto/target""github.com/pinchtab/pinchtab/internal/bridge""github.com/pinchtab/pinchtab/internal/config"+ "github.com/pinchtab/pinchtab/internal/selector""github.com/pinchtab/semantic")@@ -347,6 +348,102 @@ func TestHandleFind_VisualQuery_BottomButton(t *testing.T) {}}+func TestHandleFind_OrdinalQuery_LastButton(t *testing.T) {+ cache := &bridge.RefCache{+ Nodes: []bridge.A11yNode{+ {Ref: "e0", Role: "button", Name: "Action"},+ {Ref: "e1", Role: "button", Name: "Action"},+ {Ref: "e2", Role: "button", Name: "Action"},+ },+ Refs: map[string]int64{"e0": 1, "e1": 2, "e2": 3},+ }++ mb := &findMockBridge{refCache: cache}+ h := New(mb, &config.RuntimeConfig{ActionTimeout: 10 * time.Second}, nil, nil, nil)+ h.Matcher = semantic.NewCombinedMatcher(semantic.NewHashingEmbedder(128))++ body := `{"query": "last button", "threshold": 0.0, "topK": 3}`+ req := httptest.NewRequest("POST", "/find", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleFind(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }++ var resp findResponse+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }++ if resp.BestRef != "e2" {+ t.Errorf("expected best_ref=e2 for 'last button', got %s", resp.BestRef)+ }+}++func TestSemanticDescriptorsFromNodes_EnrichesContext(t *testing.T) {+ nodes := []bridge.A11yNode{+ {Ref: "e0", Role: "form", Name: "Login", Depth: 0},+ {Ref: "e1", Role: "textbox", Name: "Email", Depth: 1, Label: "Work Email", Placeholder: "Email address", TestID: "email-input", Text: "Email", Tag: "input"},+ {Ref: "e2", Role: "button", Name: "Submit", Depth: 1},+ }++ descs := semanticDescriptorsFromNodes(nodes)+ if len(descs) != 3 {+ t.Fatalf("expected 3 descriptors, got %d", len(descs))+ }+ if !descs[1].Interactive {+ t.Error("expected textbox descriptor to be interactive")+ }+ if descs[1].DocumentIdx != 1 {+ t.Errorf("DocumentIdx = %d, want 1", descs[1].DocumentIdx)+ }+ if descs[1].Parent != "form: Login" {+ t.Errorf("Parent = %q, want form context", descs[1].Parent)+ }+ if descs[1].Section != "form: Login" {+ t.Errorf("Section = %q, want form context", descs[1].Section)+ }+ if descs[1].Positional.Depth != 1 {+ t.Errorf("Positional.Depth = %d, want 1", descs[1].Positional.Depth)+ }+ if descs[1].Positional.SiblingIndex != 0 || descs[1].Positional.SiblingCount != 2 {+ t.Errorf("sibling metadata = %d/%d, want 0/2", descs[1].Positional.SiblingIndex, descs[1].Positional.SiblingCount)+ }+ if descs[1].Positional.LabelledBy != "Login" {+ t.Errorf("LabelledBy = %q, want Login", descs[1].Positional.LabelledBy)+ }+ if descs[1].Label != "Work Email" || descs[1].Placeholder != "Email address" || descs[1].TestID != "email-input" || descs[1].Text != "Email" || descs[1].Tag != "input" {+ t.Errorf("DOM-backed fields were not copied into semantic descriptor: %+v", descs[1])+ }+}++func TestApplySemanticActionSelector_UsesStructuredLocator(t *testing.T) {+ cache := &bridge.RefCache{+ Nodes: []bridge.A11yNode{+ {Ref: "e0", Role: "textbox", Name: "Input", Label: "Work Email", NodeID: 42},+ },+ Targets: map[string]bridge.RefTarget{+ "e0": {BackendNodeID: 42},+ },+ }+ mb := &findMockBridge{refCache: cache}+ h := New(mb, &config.RuntimeConfig{ActionTimeout: 10 * time.Second}, nil, nil, nil)+ h.Matcher = semantic.NewCombinedMatcher(semantic.NewHashingEmbedder(128))++ req := bridge.ActionRequest{Selector: "label:Work Email"}+ handled, err := h.applySemanticActionSelector(context.Background(), "tab1", selector.Parse(req.Selector), &req)+ if err != nil {+ t.Fatalf("applySemanticActionSelector returned error: %v", err)+ }+ if !handled {+ t.Fatal("expected structured locator to be handled by semantic")+ }+ if req.Ref != "e0" || req.NodeID != 42 || req.Selector != "" {+ t.Fatalf("resolved request = %+v, want ref e0 node 42 and cleared selector", req)+ }+}+func TestHandleFind_EmbeddingMatcher(t *testing.T) {cache := &bridge.RefCache{Nodes: []bridge.A11yNode{diff --git a/internal/handlers/frame.go b/internal/handlers/frame.goindex 7dfaa683..71ec7ad5 100644--- a/internal/handlers/frame.go+++ b/internal/handlers/frame.go@@ -67,6 +67,10 @@ func (h *Handlers) resolveSelectorNodeIDInFrame(ctx context.Context, tabID, raw,if frameID == "" {frameID = h.selectorFrameID(tabID)}+ req := bridge.ActionRequest{}+ if handled, err := h.applySemanticActionSelectorInFrame(ctx, tabID, frameID, sel, &req); handled {+ return req.NodeID, err+ }return bridge.ResolveUnifiedSelectorInFrame(ctx, sel, cache, frameID)}@@ -290,7 +294,10 @@ func (h *Handlers) resolveFrameScope(ctx context.Context, tabID, target string)}switch sel.Kind {- case selector.KindCSS, selector.KindXPath, selector.KindText:+ case selector.KindCSS, selector.KindXPath, selector.KindText,+ selector.KindRole, selector.KindLabel, selector.KindPlaceholder,+ selector.KindAlt, selector.KindTitle, selector.KindTestID,+ selector.KindFirst, selector.KindLast, selector.KindNth:nodeID, err := h.resolveSelectorNodeID(ctx, tabID, target)if err != nil {return bridge.FrameScope{}, false, errdiff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.goindex b6f870f3..3a397ce7 100644--- a/internal/handlers/handlers.go+++ b/internal/handlers/handlers.go@@ -81,16 +81,7 @@ func New(b bridge.BridgeAPI, cfg *config.RuntimeConfig, p bridge.ProfileService,// DescriptorBuilderfunc(tabID string) []semantic.ElementDescriptor {nodes := h.resolveSnapshotNodes(tabID)- descs := make([]semantic.ElementDescriptor, len(nodes))- for i, n := range nodes {- descs[i] = semantic.ElementDescriptor{- Ref: n.Ref,- Role: n.Role,- Name: n.Name,- Value: n.Value,- }- }- return descs+ return semanticDescriptorsFromNodes(nodes)},)diff --git a/internal/handlers/semantic_descriptors.go b/internal/handlers/semantic_descriptors.gonew file mode 100644index 00000000..a39742d6--- /dev/null+++ b/internal/handlers/semantic_descriptors.go@@ -0,0 +1,130 @@+package handlers++import (+ "strings"++ "github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/semantic"+)++func semanticDescriptorsFromNodes(nodes []bridge.A11yNode) []semantic.ElementDescriptor {+ descs := make([]semantic.ElementDescriptor, len(nodes))+ if len(nodes) == 0 {+ return descs+ }++ parentIdx := make([]int, len(nodes))+ for i := range parentIdx {+ parentIdx[i] = -1+ }++ stackByDepth := make(map[int]int)+ for i, node := range nodes {+ depth := node.Depth+ if depth < 0 {+ depth = 0+ }+ if depth > 0 {+ if parent, ok := stackByDepth[depth-1]; ok {+ parentIdx[i] = parent+ }+ }+ stackByDepth[depth] = i+ for knownDepth := range stackByDepth {+ if knownDepth > depth {+ delete(stackByDepth, knownDepth)+ }+ }+ }++ type siblingKey struct {+ parent int+ depth int+ }+ siblingIndex := make([]int, len(nodes))+ siblingCounts := make(map[siblingKey]int)+ keys := make([]siblingKey, len(nodes))+ for i, node := range nodes {+ key := siblingKey{parent: parentIdx[i], depth: node.Depth}+ keys[i] = key+ siblingIndex[i] = siblingCounts[key]+ siblingCounts[key]+++ }++ for i, node := range nodes {+ desc := semantic.ElementDescriptor{+ Ref: node.Ref,+ Role: node.Role,+ Name: node.Name,+ Value: node.Value,+ Label: node.Label,+ Placeholder: node.Placeholder,+ Alt: node.Alt,+ Title: node.Title,+ TestID: node.TestID,+ Text: node.Text,+ Tag: node.Tag,+ Interactive: bridge.InteractiveRoles[node.Role],+ DocumentIdx: i,+ Positional: semantic.PositionalHints{+ Depth: node.Depth,+ SiblingIndex: siblingIndex[i],+ SiblingCount: siblingCounts[keys[i]],+ },+ }++ if parent := parentIdx[i]; parent >= 0 {+ desc.Parent = semanticContextLabel(nodes[parent])+ if isLabelledContainer(nodes[parent].Role) {+ desc.Positional.LabelledBy = nodes[parent].Name+ }+ }+ if section := nearestSemanticSection(nodes, parentIdx, i); section != "" {+ desc.Section = section+ }++ descs[i] = desc+ }++ return descs+}++func semanticContextLabel(node bridge.A11yNode) string {+ role := strings.TrimSpace(node.Role)+ name := strings.TrimSpace(node.Name)+ switch {+ case role != "" && name != "":+ return role + ": " + name+ case name != "":+ return name+ default:+ return role+ }+}++func nearestSemanticSection(nodes []bridge.A11yNode, parentIdx []int, idx int) string {+ for parent := parentIdx[idx]; parent >= 0; parent = parentIdx[parent] {+ if isSectionRole(nodes[parent].Role) {+ return semanticContextLabel(nodes[parent])+ }+ }+ return ""+}++func isLabelledContainer(role string) bool {+ switch strings.ToLower(strings.TrimSpace(role)) {+ case "form", "group", "region", "dialog", "tabpanel":+ return true+ default:+ return false+ }+}++func isSectionRole(role string) bool {+ switch strings.ToLower(strings.TrimSpace(role)) {+ case "form", "region", "dialog", "navigation", "main", "banner", "contentinfo", "group", "tabpanel":+ return true+ default:+ return false+ }+}diff --git a/internal/handlers/semantic_selectors.go b/internal/handlers/semantic_selectors.gonew file mode 100644index 00000000..a3919d19--- /dev/null+++ b/internal/handlers/semantic_selectors.go@@ -0,0 +1,108 @@+package handlers++import (+ "context"+ "fmt"+ "net/http"+ "strings"++ "github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/selector"+ "github.com/pinchtab/semantic"+)++func (h *Handlers) applySemanticActionSelector(ctx context.Context, tabID string, sel selector.Selector, req *bridge.ActionRequest) (bool, error) {+ return h.applySemanticActionSelectorInFrame(ctx, tabID, h.selectorFrameID(tabID), sel, req)+}++func (h *Handlers) applySemanticActionSelectorInFrame(ctx context.Context, tabID, frameID string, sel selector.Selector, req *bridge.ActionRequest) (bool, error) {+ query, ok := sel.SemanticQuery()+ if !ok {+ return false, nil+ }+ if h.Matcher == nil {+ return true, fmt.Errorf("semantic selectors require a matcher (not configured)")+ }++ descs, err := h.semanticDescriptorsForTabInFrame(ctx, tabID, frameID)+ if err != nil {+ return true, err+ }+ result, err := h.Matcher.Find(ctx, query, descs, semantic.FindOptions{+ Threshold: 0.3,+ TopK: 1,+ })+ if err != nil {+ return true, fmt.Errorf("semantic selector: %w", err)+ }+ if result.BestRef == "" {+ return true, fmt.Errorf("semantic selector %q: no matching element found", query)+ }++ cache := h.Bridge.GetRefCache(tabID)+ if cache == nil {+ return true, fmt.Errorf("semantic selector %q: no snapshot cache available", query)+ }+ target, ok := cache.Lookup(result.BestRef)+ if !ok || target.BackendNodeID == 0 {+ return true, fmt.Errorf("semantic selector %q matched ref %s but no node is available", query, result.BestRef)+ }++ req.Ref = result.BestRef+ req.NodeID = target.BackendNodeID+ req.Selector = ""+ return true, nil+}++func (h *Handlers) semanticDescriptorsForTabInFrame(ctx context.Context, tabID, frameID string) ([]semantic.ElementDescriptor, error) {+ nodes := h.resolveSnapshotNodes(tabID)+ if len(nodes) == 0 {+ h.refreshRefCache(ctx, tabID)+ nodes = h.resolveSnapshotNodes(tabID)+ }+ if len(nodes) == 0 {+ return nil, fmt.Errorf("semantic selector: no snapshot available; navigate or snapshot first")+ }++ if cache := h.Bridge.GetRefCache(tabID); cache != nil && len(cache.Nodes) > 0 {+ _ = bridge.EnrichA11yNodesWithDOMMetadata(ctx, cache.Nodes)+ nodes = cache.Nodes+ }+ nodes = scopeSemanticNodesByFrame(nodes, frameID)+ if len(nodes) == 0 {+ return nil, fmt.Errorf("semantic selector: no elements found in current frame")+ }+ return semanticDescriptorsFromNodes(nodes), nil+}++func scopeSemanticNodesByFrame(nodes []bridge.A11yNode, frameID string) []bridge.A11yNode {+ if frameID == "" {+ return nodes+ }+ filtered := make([]bridge.A11yNode, 0, len(nodes))+ for _, node := range nodes {+ if node.FrameID == frameID {+ filtered = append(filtered, node)+ }+ }+ return filtered+}++func semanticSelectorHTTPStatus(err error) int {+ if err == nil {+ return http.StatusOK+ }+ msg := strings.ToLower(err.Error())+ switch {+ case strings.Contains(msg, "not configured"):+ return http.StatusNotImplemented+ case strings.Contains(msg, "no matching element found"),+ strings.Contains(msg, "no node is available"):+ return http.StatusNotFound+ case strings.Contains(msg, "no snapshot available"),+ strings.Contains(msg, "no elements found"):+ return http.StatusInternalServerError+ default:+ return http.StatusInternalServerError+ }+}diff --git a/internal/handlers/snapshot.go b/internal/handlers/snapshot.goindex 1466d3ca..cab5cfcd 100644--- a/internal/handlers/snapshot.go+++ b/internal/handlers/snapshot.go@@ -162,6 +162,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {}flat, refs := bridge.BuildSnapshot(treeResp.Nodes, filter, maxDepth)+ _ = bridge.EnrichA11yNodesWithDOMMetadata(tCtx, flat)// Check if scoped snapshot returned 0 nodes but element exists in DOMvar scopedEmptyHint stringdiff --git a/internal/mcp/handlers_helpers.go b/internal/mcp/handlers_helpers.goindex 6d580f41..c847cfc4 100644--- a/internal/mcp/handlers_helpers.go+++ b/internal/mcp/handlers_helpers.go@@ -65,6 +65,16 @@ func hasKnownSelectorPrefix(v string) bool {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:")}diff --git a/internal/mcp/handlers_interaction_test.go b/internal/mcp/handlers_interaction_test.goindex bd30e4f1..0dbae3b8 100644--- a/internal/mcp/handlers_interaction_test.go+++ b/internal/mcp/handlers_interaction_test.go@@ -96,6 +96,21 @@ func TestHandleClickQueryAliasNumericTextUsesSemanticSelector(t *testing.T) {}}+func TestHandleClickQueryAliasPreservesStructuredLocator(t *testing.T) {+ srv := mockPinchTab()+ defer srv.Close()++ r := callTool(t, "pinchtab_click", map[string]any{+ "query": "label:Email",+ }, srv)++ resp := resultJSON(t, r)+ body, _ := resp["body"].(map[string]any)+ if got, _ := body["selector"].(string); got != "label:Email" {+ t.Fatalf("selector = %q, want label:Email", got)+ }+}+func TestHandleClickDialogActionPassThrough(t *testing.T) {srv := mockPinchTab()defer srv.Close()diff --git a/internal/mcp/tools.go b/internal/mcp/tools.goindex ed7f0b06..8854f254 100644--- a/internal/mcp/tools.go+++ b/internal/mcp/tools.go@@ -19,7 +19,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 (CSS, XPath, text, or ref). 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.")),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")),@@ -32,7 +32,7 @@ func allTools() []mcp.Tool {mcp.NewTool("pinchtab_screenshot",mcp.WithDescription("Take a screenshot of the current page"),mcp.WithString("tabId", mcp.Description("Target tab ID")),- mcp.WithString("selector", mcp.Description("Unified selector to capture a specific element (CSS, XPath, text, or ref). Selectors resolve in the current frame scope.")),+ mcp.WithString("selector", mcp.Description("Unified selector to capture a specific element (ref, CSS, XPath, text, find, role, label, placeholder, alt, title, testid, first/last/nth). Selectors resolve in the current frame scope.")),mcp.WithString("format", mcp.Description("Image format: 'jpeg' (default) or 'png'")),mcp.WithNumber("quality", mcp.Description("JPEG quality 0-100 (only for JPEG format)")),mcp.WithBoolean("css1x", mcp.Description("When selector is set, return element screenshot at CSS pixel size (1x) instead of device pixels")),@@ -48,7 +48,7 @@ func allTools() []mcp.Tool {// ── Interaction ─────────────────────────────────────────────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 ('css:#btn' or '#btn'), XPath ('xpath://button'), text ('text:Submit'), or semantic ('find:login button'). 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.")),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'")),diff --git a/internal/selector/selector.go b/internal/selector/selector.goindex 5da2cfeb..f0a8cb90 100644--- a/internal/selector/selector.go+++ b/internal/selector/selector.go@@ -10,6 +10,10 @@// "xpath://div" → XPath// "text:Submit" → Text (match by visible text)// "find:login btn" → Semantic (natural-language query)+// "role:button Save" → Role/name locator+// "label:Email" → Form control by label text+// "testid:submit" → Test id locator+// "last:button" → Positional selector wrapper//// Bare strings that look like CSS selectors (start with ., #, [,// or contain tag-like patterns) are treated as CSS. Everything else@@ -19,6 +23,7 @@ package selectorimport ("fmt"+ "strconv""strings")@@ -26,12 +31,21 @@ import (type Kind stringconst (- KindNone Kind = ""- KindRef Kind = "ref"- KindCSS Kind = "css"- KindXPath Kind = "xpath"- KindText Kind = "text"- KindSemantic Kind = "semantic"+ KindNone Kind = ""+ KindRef Kind = "ref"+ KindCSS Kind = "css"+ KindXPath Kind = "xpath"+ KindText Kind = "text"+ KindSemantic Kind = "semantic"+ KindRole Kind = "role"+ KindLabel Kind = "label"+ KindPlaceholder Kind = "placeholder"+ KindAlt Kind = "alt"+ KindTitle Kind = "title"+ KindTestID Kind = "testid"+ KindFirst Kind = "first"+ KindLast Kind = "last"+ KindNth Kind = "nth")// Selector is a parsed, unified element selector.@@ -53,6 +67,24 @@ func (s Selector) String() string {return "text:" + s.Valuecase KindSemantic:return "find:" + s.Value+ case KindRole:+ return "role:" + s.Value+ case KindLabel:+ return "label:" + s.Value+ case KindPlaceholder:+ return "placeholder:" + s.Value+ case KindAlt:+ return "alt:" + s.Value+ case KindTitle:+ return "title:" + s.Value+ case KindTestID:+ return "testid:" + s.Value+ case KindFirst:+ return "first:" + s.Value+ case KindLast:+ return "last:" + s.Value+ case KindNth:+ return "nth:" + s.Valuedefault:return s.Value}@@ -71,6 +103,16 @@ func (s Selector) IsEmpty() bool {// "xpath:..." → XPath// "text:..." → Text// "find:..." → Semantic+// "semantic:..." → Semantic+// "role:..." → Role/name locator+// "label:..." → Label locator+// "placeholder:..." → Placeholder locator+// "alt:..." → Alt-text locator+// "title:..." → Title attribute locator+// "testid:..." → Test id locator+// "first:..." → First match of nested selector+// "last:..." → Last match of nested selector+// "nth:N:..." → Nth match of nested selector// "ref:..." → Ref (optional explicit prefix)//// Without a prefix, auto-detection applies:@@ -101,6 +143,36 @@ func Parse(s string) Selector {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}}@@ -178,13 +250,66 @@ func (s Selector) Validate() error {return fmt.Errorf("empty selector")}switch s.Kind {- case KindRef, KindCSS, KindXPath, KindText, KindSemantic:+ case KindRef, KindCSS, KindXPath, KindText, KindSemantic,+ KindRole, KindLabel, KindPlaceholder, KindAlt, KindTitle, KindTestID,+ KindFirst, KindLast, KindNth:return nildefault:return fmt.Errorf("unknown selector kind: %q", s.Kind)}}+// SemanticQuery returns the query string to send to the semantic matcher for+// selector-resolution paths. The existing text selector intentionally stays+// browser-side for backward-compatible action targeting.+func (s Selector) SemanticQuery() (string, bool) {+ if s.IsEmpty() {+ return "", false+ }+ switch s.Kind {+ case KindSemantic:+ return s.Value, strings.TrimSpace(s.Value) != ""+ case KindRole, KindLabel, KindPlaceholder, KindAlt, KindTitle, KindTestID:+ return s.String(), strings.TrimSpace(s.Value) != ""+ case KindFirst, KindLast:+ if rawSelectorCanUseSemantic(s.Value) {+ return s.String(), true+ }+ case KindNth:+ _, raw, ok := splitNthSelectorValue(s.Value)+ if ok && rawSelectorCanUseSemantic(raw) {+ return s.String(), true+ }+ }+ return "", false+}++func rawSelectorCanUseSemantic(raw string) bool {+ sel := Parse(raw)+ switch sel.Kind {+ case KindRole, KindLabel, KindPlaceholder, KindAlt, KindTitle, KindTestID:+ return strings.TrimSpace(sel.Value) != ""+ default:+ return false+ }+}++func splitNthSelectorValue(value string) (int, string, bool) {+ rawIndex, rawSelector, ok := strings.Cut(value, ":")+ if !ok {+ return 0, "", false+ }+ rawSelector = strings.TrimSpace(rawSelector)+ if rawSelector == "" {+ return 0, "", false+ }+ index, err := strconv.Atoi(strings.TrimSpace(rawIndex))+ if err != nil || index < 0 {+ return 0, "", false+ }+ return index, rawSelector, true+}+// cutPrefix is a helper for strings.CutPrefix (available in Go 1.20+).func cutPrefix(s, prefix string) (string, bool) {if strings.HasPrefix(s, prefix) {diff --git a/internal/selector/selector_test.go b/internal/selector/selector_test.goindex 8a02f5c3..5dc257c9 100644--- a/internal/selector/selector_test.go+++ b/internal/selector/selector_test.go@@ -34,9 +34,21 @@ func TestParse_ExplicitPrefixes(t *testing.T) {// Semantic / find{"find:login button", KindSemantic, "login button"},+ {"semantic:login button", KindSemantic, "login button"},{"find:the search input field", KindSemantic, "the search input field"},{"find:", KindSemantic, ""},+ // Locator prefixes+ {"role:button Save", KindRole, "button Save"},+ {"label:Email", KindLabel, "Email"},+ {"placeholder:Search", KindPlaceholder, "Search"},+ {"alt:Product photo", KindAlt, "Product photo"},+ {"title:Close", KindTitle, "Close"},+ {"testid:submit-button", KindTestID, "submit-button"},+ {"first:button", KindFirst, "button"},+ {"last:text:Submit", KindLast, "text:Submit"},+ {"nth:2:role:button Save", KindNth, "2:role:button Save"},+// Ref (explicit prefix){"ref:e5", KindRef, "e5"},{"ref:e0", KindRef, "e0"},@@ -309,6 +321,15 @@ func TestSelector_String(t *testing.T) {{Selector{KindText, "Submit"}, "text:Submit"},{Selector{KindText, "with:colon"}, "text:with:colon"},{Selector{KindSemantic, "login button"}, "find:login button"},+ {Selector{KindRole, "button Save"}, "role:button Save"},+ {Selector{KindLabel, "Email"}, "label:Email"},+ {Selector{KindPlaceholder, "Search"}, "placeholder:Search"},+ {Selector{KindAlt, "Logo"}, "alt:Logo"},+ {Selector{KindTitle, "Close"}, "title:Close"},+ {Selector{KindTestID, "submit"}, "testid:submit"},+ {Selector{KindFirst, "button"}, "first:button"},+ {Selector{KindLast, "text:Submit"}, "last:text:Submit"},+ {Selector{KindNth, "1:button"}, "nth:1:button"},{Selector{KindNone, ""}, ""},{Selector{KindNone, "something"}, "something"},}@@ -346,6 +367,15 @@ func TestSelector_Validate(t *testing.T) {{KindXPath, "//div"},{KindText, "Submit"},{KindSemantic, "login button"},+ {KindRole, "button Save"},+ {KindLabel, "Email"},+ {KindPlaceholder, "Search"},+ {KindAlt, "Logo"},+ {KindTitle, "Close"},+ {KindTestID, "submit"},+ {KindFirst, "button"},+ {KindLast, "button"},+ {KindNth, "1:button"},}for _, s := range valid {if err := s.Validate(); err != nil {@@ -370,6 +400,41 @@ func TestSelector_Validate(t *testing.T) {}}+func TestSelector_SemanticQuery(t *testing.T) {+ tests := []struct {+ input string+ want string+ ok bool+ }{+ {"find:login button", "login button", true},+ {"semantic:login button", "login button", true},+ {"text:Submit", "", false},+ {"role:button Save", "role:button Save", true},+ {"label:Email", "label:Email", true},+ {"placeholder:Search", "placeholder:Search", true},+ {"alt:Logo", "alt:Logo", true},+ {"title:Close", "title:Close", true},+ {"testid:submit", "testid:submit", true},+ {"first:text:Submit", "", false},+ {"last:role:button Save", "last:role:button Save", true},+ {"nth:2:label:Email", "nth:2:label:Email", true},+ {"first:button", "", false},+ {"last:css:button", "", false},+ {"nth:2:button", "", false},+ {"nth:-1:text:Submit", "", false},+ {"css:button", "", false},+ {"e1", "", false},+ }+ for _, tt := range tests {+ t.Run(tt.input, func(t *testing.T) {+ got, ok := Parse(tt.input).SemanticQuery()+ if ok != tt.ok || got != tt.want {+ t.Fatalf("SemanticQuery() = %q, %v; want %q, %v", got, ok, tt.want, tt.ok)+ }+ })+ }+}+// ---------------------------------------------------------------------------// From* constructors// ---------------------------------------------------------------------------@@ -427,6 +492,16 @@ func TestParse_Roundtrip(t *testing.T) {"text:Submit Order","text:with:colon:in:value","find:the big red button",+ "semantic:the big red button",+ "role:button Save",+ "label:Email",+ "placeholder:Search",+ "alt:Logo",+ "title:Close",+ "testid:submit",+ "first:button",+ "last:text:Submit",+ "nth:1:role:button Save",}for _, input := range inputs {s := Parse(input)diff --git a/tests/e2e/scenarios/api/browser-basic.sh b/tests/e2e/scenarios/api/browser-basic.shindex 893d8c88..b476cb25 100644--- a/tests/e2e/scenarios/api/browser-basic.sh+++ b/tests/e2e/scenarios/api/browser-basic.sh@@ -360,6 +360,38 @@ assert_json_length_gte "$RESULT" ".matches" 1 "has matches"end_test+# ─────────────────────────────────────────────────────────────────+start_test "pinchtab find (structured semantic locators)"++pt_post /find -d '{"query":"role:button Log In"}'+assert_ok "find role locator"+assert_json_contains "$RESULT" '.strategy' 'structured' "role locator uses structured matcher"+assert_json_eq "$RESULT" '.matches[0].name' 'Log In' "role locator matched login button"++pt_post /find -d '{"query":"placeholder:Email address"}'+assert_ok "find placeholder locator"+assert_json_contains "$RESULT" '.strategy' 'structured' "placeholder locator uses structured matcher"+assert_json_eq "$RESULT" '.matches[0].role' 'textbox' "placeholder locator matched textbox"++pt_post /find -d '{"query":"first:role:button"}'+assert_ok "find first role locator"+assert_json_contains "$RESULT" '.strategy' 'structured' "wrapper locator uses structured matcher"+assert_json_eq "$RESULT" '.matches[0].name' 'Log In' "first role locator uses document order"++end_test++# ─────────────────────────────────────────────────────────────────+start_test "pinchtab action (semantic label selector)"++pt_post /action -d '{"kind":"type","selector":"label:Email","text":"[email protected]","fast":true}'+assert_ok "type by semantic label selector"++pt_post /evaluate -d '{"expression":"document.querySelector(\"input[type=email]\").value"}'+assert_ok "evaluate email value"+assert_json_eq "$RESULT" '.result' '[email protected]' "semantic label selector typed into email input"++end_test+# ─────────────────────────────────────────────────────────────────start_test "pinchtab find --tab <id>"