Skip to content

feat(extension): add role and text matching engine - #3188

Open
supremeboxlogos wants to merge 5 commits into
amel/role-text-locators-upstreamfrom
amel/role-text-locators-matching
Open

supremeboxlogos wants to merge 5 commits into
amel/role-text-locators-upstreamfrom
amel/role-text-locators-matching

Conversation

@supremeboxlogos

Copy link
Copy Markdown
Member

why

Add accessible-role and text matching as an isolated extension layer. Stacked on #3187; this PR does not expose SDK builders or add wait/snapshot integration.

what changed

  • Adapt the pinned accessibility/text helpers to a typed query plan: role, name, description, ARIA states, text/regex, descendant scope, and ordered index selection.
  • Reuse existing selector resolution, actions, deadlines, and handle cleanup. Preserve existing CSS/XPath/text roots and iframe hops; keep literal >> inside selector strings intact.
  • Keep query validation on the host and browser imports type-only. Package upstream notices, validate classic content scripts, and regenerate the deterministic embedded extension ZIP.
  • Keep the query contract private until the shared-protocol follow-up. No public SDK methods in this layer.

test plan

  • 921 extension/discovery tests passed; 10 existing todos.
  • 56 real-Chrome tests passed, including 48 ordered-result comparisons against the pinned upstream implementation.
  • Rechecked 37 codec/build tests after aligning the private schema with the later canonical contract.
  • Extension typecheck, extension/SDK builds, scoped lint/format checks, and embedded archive checks passed.
  • Strict structural and standalone-boundary review passed; no new smoke-test infrastructure.

@changeset-bot

changeset-bot Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 2bf8ee3

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 24 packages
Name Type
@browserbasehq/stagehand-extension Patch
@browserbasehq/stagehand Patch
@browserbasehq/stagehand-python Patch
@browserbasehq/stagehand-go Patch
browse Patch
@browserbasehq/stagehand-examples Patch
@browserbasehq/stagehand-integrations-claude-cua-sdk Patch
@browserbasehq/stagehand-integrations Patch
@browserbasehq/eve Patch
@browserbasehq/stagehand-integrations-gemini-cua-sdk Patch
@browserbasehq/stagehand-integrations-example-pi-facade Patch
@browserbasehq/stagehand-integrations-claude-agent-sdk Patch
@browserbasehq/stagehand-integrations-example-claude-code-facade Patch
@browserbasehq/stagehand-integrations-codex-sdk Patch
@browserbasehq/stagehand-integrations-example-codex-facade Patch
@browserbasehq/stagehand-integrations-cursor-sdk Patch
@browserbasehq/stagehand-integrations-example-cursor-facade Patch
@browserbasehq/stagehand-integrations-deepagents-sdk Patch
@browserbasehq/stagehand-integrations-eve-sdk Patch
@browserbasehq/stagehand-integrations-fx-sdk Patch
@browserbasehq/stagehand-integrations-mastra-sdk Patch
@browserbasehq/stagehand-integrations-example-mastra-facade Patch
@browserbasehq/stagehand-integrations-pi-sdk Patch
@browserbasehq/stagehand-integrations-example-vercel-ai-facade Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

4 issues found and verified against the latest diff

Confidence score: 3/5

  • semanticSelectors.ts misses matches inside closed shadow roots, so semantic role, text, and scoped CSS queries can fail on those elements. Use getOpenOrClosedShadowRoot for the scope host and descendant hosts.
  • semanticLocator.test.ts reads mock.instances[0] even though the method spy is called without new, so the assertion fails. Use mock.contexts[0] to inspect the receiver.
  • selectorParser.ts treats >> inside a CSS comment as a frame-hop separator, so valid selectors such as button/* >> */ are misparsed. Skip CSS comments while scanning for separators.
  • semanticLocator.ts lets role/state mismatches through host validation, so invalid combinations fail only after Runtime.evaluate runs roleQuery in the page. Add role-aware refinement to the query schema.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="packages/extension/understudy/selectorParser.ts">

<violation number="1" location="packages/extension/understudy/selectorParser.ts:25">
P2: This treats `>>` inside a CSS comment as a frame-hop separator, so `deepLocator('button/* >> */')` tries to resolve `button/*` as a frame selector instead of matching the valid CSS selector. Skip CSS comments while scanning.</violation>
</file>

<file name="packages/extension/types/private/semanticLocator.ts">

<violation number="1" location="packages/extension/types/private/semanticLocator.ts:147">
P2: Role/state mismatches pass host validation and fail only after `Runtime.evaluate` runs `roleQuery` in the page. Add a role-aware refinement to the query schema so invalid combinations are rejected on the host.</violation>
</file>

<file name="packages/extension/understudy/semanticLocator.test.ts">

<violation number="1" location="packages/extension/understudy/semanticLocator.test.ts:166">
P2: This method spy is called without `new`, so `mock.instances[0]` is undefined and this assertion fails; use `mock.contexts[0]` to inspect the receiver.</violation>
</file>

<file name="packages/extension/dom/locatorScripts/semanticSelectors.ts">

<violation number="1" location="packages/extension/dom/locatorScripts/semanticSelectors.ts:196">
P2: Semantic role, text, and scoped CSS queries miss elements inside closed shadow roots because this traversal reads only `.shadowRoot`. Use `getOpenOrClosedShadowRoot` for the scope host and descendant hosts, matching the existing selector resolver.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread .changeset/role-text-locator-engine.md Resolved
.strictObject({
kind: z.literal("role"),
role: AriaRoleSchema,
options: GetByRoleOptionsSchema.optional(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Role/state mismatches pass host validation and fail only after Runtime.evaluate runs roleQuery in the page. Add a role-aware refinement to the query schema so invalid combinations are rejected on the host.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/extension/types/private/semanticLocator.ts, line 147:

<comment>Role/state mismatches pass host validation and fail only after `Runtime.evaluate` runs `roleQuery` in the page. Add a role-aware refinement to the query schema so invalid combinations are rejected on the host.</comment>

<file context>
@@ -0,0 +1,205 @@
+      .strictObject({
+        kind: z.literal("role"),
+        role: AriaRoleSchema,
+        options: GetByRoleOptionsSchema.optional(),
+      })
+      .meta({ id: "RoleQueryStep" }),
</file context>

const shadows: ShadowRoot[] = [];
if (scope instanceof Element && scope.shadowRoot) shadows.push(scope.shadowRoot);
for (const element of scope.querySelectorAll("*")) {
if (element.shadowRoot) shadows.push(element.shadowRoot);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Semantic role, text, and scoped CSS queries miss elements inside closed shadow roots because this traversal reads only .shadowRoot. Use getOpenOrClosedShadowRoot for the scope host and descendant hosts, matching the existing selector resolver.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/extension/dom/locatorScripts/semanticSelectors.ts, line 196:

<comment>Semantic role, text, and scoped CSS queries miss elements inside closed shadow roots because this traversal reads only `.shadowRoot`. Use `getOpenOrClosedShadowRoot` for the scope host and descendant hosts, matching the existing selector resolver.</comment>

<file context>
@@ -0,0 +1,242 @@
+  const shadows: ShadowRoot[] = [];
+  if (scope instanceof Element && scope.shadowRoot) shadows.push(scope.shadowRoot);
+  for (const element of scope.querySelectorAll("*")) {
+    if (element.shadowRoot) shadows.push(element.shadowRoot);
+  }
+  for (const shadow of shadows) result.push(...queryElements(shadow, selector, true));
</file context>

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 existing issue remains and 1 new issue found across 18 files

Confidence score: 3/5

  • Chained XPath selectors in semanticSelectors.ts can miss descendants inside shadow roots even when pierceShadow is enabled. Use a scoped composed XPath resolver for nested steps.
  • QueryStepSchema in semanticLocator.ts accepts checked for roles that roleQuery rejects, so invalid plans can pass validation and fail in the browser. Cross-validate role and option pairs here.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="packages/extension/dom/locatorScripts/semanticSelectors.ts">

<violation number="1" location="packages/extension/dom/locatorScripts/semanticSelectors.ts:235">
P2: Nested XPath steps use native `evaluate`, which cannot reach descendants inside shadow roots even when `pierceShadow` is true. Use a scoped composed XPath resolver so chained XPath selectors honor shadow piercing.</violation>
</file>
Architecture diagram
sequenceDiagram
    participant Client as SDK Client
    participant Protocol as Protocol Layer
    participant Extension as Stagehand Extension
    participant Resolver as FrameSelectorResolver
    participant Parser as SelectorParser
    participant Codec as SemanticLocator Codec
    participant DeepLocator as DeepLocator
    participant CDP as CDP/Browser Context
    participant DOM as DOM/ARIA Engine
    
    Note over Client,DOM: Semantic Locator Runtime Flow
    
    Client->>Protocol: Send semantic locator request
    Protocol->>Extension: Encode locator query (internal:locator= prefix)
    Extension->>Codec: encodeLocatorQuery(steps)
    Codec->>Codec: Validate steps (ARIA roles, states, regex)
    Codec-->>Extension: Encoded selector string
    
    Extension->>Resolver: parseSelector(encodedSelector)
    Resolver->>Codec: decodeLocatorQuery(selector)
    alt Valid semantic query
        Codec-->>Resolver: QueryStep[] (kind: semantic)
        Resolver->>DeepLocator: resolveLocatorTarget()
    else Malformed query
        Codec-->>Resolver: Throw error (Invalid semantic locator query)
        Resolver-->>Extension: Reject request
    end
    
    DeepLocator->>Parser: splitSelectorHops(initialSelector)
    alt Has iframe hop
        Parser-->>DeepLocator: Frame chain segments
        DeepLocator->>CDP: Resolve iframe target frame
        CDP-->>DeepLocator: Target frame context
        DeepLocator->>Codec: Re-encode with resolved frame
        Codec-->>DeepLocator: Updated selector with frame context
    else No iframe hop
        DeepLocator-->>Resolver: Same frame, original selector
    end
    
    DeepLocator-->>Resolver: Resolved target (frame + selector)
    
    Resolver->>CDP: Runtime.evaluate (resolveSemanticSelector)
    CDP->>DOM: Execute querySemanticSelector(steps)
    
    DOM->>DOM: Process step sequence
    loop Each QueryStep
        alt Role step
            DOM->>DOM: roleQuery() with ARIA state validation
        else Text step
            DOM->>DOM: textQuery() with regex/literal matching
        else Selector step
            DOM->>DOM: selectorQuery() (CSS/XPath/text=)
        else Nth step
            DOM->>DOM: Filter to specific index
        end
        DOM->>DOM: Apply shadow DOM piercing
    end
    
    DOM-->>CDP: Matching Element[] results
    CDP-->>Resolver: Remote object references
    
    alt Count operation
        Resolver->>CDP: Runtime.evaluate (countSemanticMatches)
        CDP->>DOM: Execute count query
        DOM-->>CDP: Match count
        CDP-->>Resolver: Numeric result
    end
    
    Resolver-->>Extension: Resolved nodes or count
    Extension-->>Protocol: Response with results
    Protocol-->>Client: Final locator result
    
    Note over Resolver,DOM: Error handling
    alt Semantic query error (invalid ARIA state, bad regex)
        DOM-->>CDP: Throw exception with details
        CDP-->>Resolver: Exception details
        Resolver-->>Extension: Reject with cause details
    end
Loading

Requires human review: Auto-approval blocked because this review re-detected 4 unresolved issues already reported by Cubic.

View guided diff | Turn on auto-fix | Re-trigger cubic

let expression = selector.replace(/^xpath=/i, "");
if (scope instanceof Element && expression.startsWith("/")) expression = "." + expression;
const owner = scope instanceof Document ? scope : scope.ownerDocument;
const iterator = owner.evaluate(expression, scope, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Nested XPath steps use native evaluate, which cannot reach descendants inside shadow roots even when pierceShadow is true. Use a scoped composed XPath resolver so chained XPath selectors honor shadow piercing.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/extension/dom/locatorScripts/semanticSelectors.ts, line 235:

<comment>Nested XPath steps use native `evaluate`, which cannot reach descendants inside shadow roots even when `pierceShadow` is true. Use a scoped composed XPath resolver so chained XPath selectors honor shadow piercing.</comment>

<file context>
@@ -0,0 +1,242 @@
+  let expression = selector.replace(/^xpath=/i, "");
+  if (scope instanceof Element && expression.startsWith("/")) expression = "." + expression;
+  const owner = scope instanceof Document ? scope : scope.ownerDocument;
+  const iterator = owner.evaluate(expression, scope, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE);
+  const result: Element[] = [];
+  let node: Node | null;
</file context>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant