Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(toolbar): stop mangling escaped chars in generated element selectors (#68800)

Paul D'Ambra5741e31bc9e0
diff --git a/frontend/src/toolbar/utils.test.ts b/frontend/src/toolbar/utils.test.ts
index 7706dfcad9b7..53907fb42c6d 100644
--- a/frontend/src/toolbar/utils.test.ts
+++ b/frontend/src/toolbar/utils.test.ts
@@ -1,4 +1,11 @@
-import { asNonEmptyString, joinWithUiHost, safeFetch, slashDotDataAttrUnescape } from './utils'
+import {
+ asNonEmptyString,
+ containsUnstableGeneratedId,
+ elementToQuery,
+ joinWithUiHost,
+ safeFetch,
+ unescapeCssSelector,
+} from './utils'
describe('utils', () => {
describe('asNonEmptyString', () => {
@@ -66,7 +73,7 @@ describe('utils', () => {
})
})
- describe('slashDotDataAttrUnescape', () => {
+ describe('unescapeCssSelector', () => {
const testCases = [
{
input: 'div[data-attr="test"]',
@@ -88,15 +95,74 @@ describe('utils', () => {
input: '\\.tomato div[data-something="test\\.test\\.test"]',
expected: '.tomato div[data-something="test.test.test"]',
},
+ {
+ // escaped characters other than dots must round-trip, not be mangled into dots
+ input: '[data-id="base-ui-\\:rg\\:-viewport"] > [data-has-overflow-y=""]',
+ expected: '[data-id="base-ui-:rg:-viewport"] > [data-has-overflow-y=""]',
+ },
+ {
+ // CSS.escape emits hex code-point escapes for leading digits, e.g. CSS.escape('123-foo')
+ input: '[data-id="\\31 23-foo"]',
+ expected: '[data-id="123-foo"]',
+ },
+ {
+ // code point 0 is invalid per the CSS spec — fall back to U+FFFD
+ input: '[data-id="\\0 foo"]',
+ expected: '[data-id="�foo"]',
+ },
+ {
+ // code point above U+10FFFF is invalid — fall back to U+FFFD
+ input: '[data-id="\\ffffff foo"]',
+ expected: '[data-id="�foo"]',
+ },
]
testCases.forEach(({ input, expected }) => {
it(`should unescape "${input}" to "${expected}"`, () => {
- const result = slashDotDataAttrUnescape(input)
+ const result = unescapeCssSelector(input)
expect(result).toBe(expected)
})
})
})
+ describe('containsUnstableGeneratedId', () => {
+ const testCases: Array<{ value: string; expected: boolean }> = [
+ { value: 'base-ui-:rg:-viewport', expected: true },
+ { value: ':r5:', expected: true },
+ { value: 'radix-:R1d6:', expected: true },
+ { value: 'base-ui-«r5»-viewport', expected: true },
+ { value: 'sidebar-viewport', expected: false },
+ { value: 'session.recording.preview', expected: false },
+ ]
+ it.each(testCases)('$value -> $expected', ({ value, expected }) => {
+ expect(containsUnstableGeneratedId(value)).toBe(expected)
+ })
+ })
+
+ describe('elementToQuery', () => {
+ it('does not build selectors from useId-derived data attributes', () => {
+ document.body.innerHTML = `
+ <div data-id="base-ui-:rg:-viewport">
+ <div data-has-overflow-y=""><button>hi</button></div>
+ </div>
+ `
+ const element = document.querySelector('[data-has-overflow-y]') as HTMLElement
+ const selector = elementToQuery(element, [])
+ expect(selector).toBeTruthy()
+ expect(selector).not.toContain('base-ui-')
+ })
+
+ it('uses stable data attributes via finder', () => {
+ document.body.innerHTML = `
+ <div data-id="sidebar-viewport">
+ <div data-has-overflow-y=""><button>hi</button></div>
+ </div>
+ `
+ const element = document.querySelector('[data-id="sidebar-viewport"]') as HTMLElement
+ const selector = elementToQuery(element, [])
+ expect(selector).toContain('[data-id="sidebar-viewport"]')
+ })
+ })
+
describe('safeFetch', () => {
const originalFetch = global.fetch
diff --git a/frontend/src/toolbar/utils.ts b/frontend/src/toolbar/utils.ts
index 15845be78f7e..72afde7c5197 100644
--- a/frontend/src/toolbar/utils.ts
+++ b/frontend/src/toolbar/utils.ts
@@ -174,10 +174,10 @@ function computeElementQuery(element: HTMLElement, dataAttributes: string[]): st
tagName: (name) => !TAGS_TO_IGNORE.includes(name),
// include several selectors e.g. prefer .project-homepage > .project-header > .project-title over .project-title
seedMinLength: 5,
- attr: (name) => {
+ attr: (name, value) => {
// preference to data attributes if they exist
// that aren't in the PostHog preferred list - they were returned early above
- return name.startsWith('data-')
+ return name.startsWith('data-') && value.length < 100 && !containsUnstableGeneratedId(value)
},
// the combination guard tripped and cut the candidate search short -
// the selector may degrade to a brittle positional path - record host
@@ -188,7 +188,7 @@ function computeElementQuery(element: HTMLElement, dataAttributes: string[]): st
levels,
}),
})
- return slashDotDataAttrUnescape(foundSelector)
+ return unescapeCssSelector(foundSelector)
} catch (error) {
toolbarLogger.warn('element_selector', 'Error while trying to find a selector for element')
captureToolbarException(error, 'element_selector_computation')
@@ -655,14 +655,34 @@ export function getHeatMapHue(count: number, maxCount: number): number {
}
/*
- * KLUDGE: e.g. [data-attr="session\.recording\.preview"] is valid CSS
- * but our action matching doesn't support it
- * in order to avoid trying to write a general purpose CSS unescaper
- * we just remove the backslash in this specific pattern
- * if it matches data-attr="bla\.blah\.blah"
+ * KLUDGE: finder() builds selectors with CSS.escape, e.g. [data-attr="session\.recording\.preview"]
+ * or [data-id="base-ui-\:rg\:-viewport"]. That's valid CSS, but our action/element matching compares
+ * raw attribute values, so the escapes must be removed. This handles single-character escapes
+ * (\. -> ., \: -> :) and hex code-point escapes (\31 -> 1) without being a fully general CSS unescaper.
+ *
+ * Safety: this only works correctly because finder's wordLike gate rejects id/class tokens that
+ * contain ':', so unescaping outside quoted attribute values never produces pseudo-class collisions.
+ * If that gate is ever relaxed, this function will need to become attribute-value-aware.
*/
-export function slashDotDataAttrUnescape(foundSelector: string): string | undefined {
- return foundSelector.replace(/\\./g, '.')
+export function unescapeCssSelector(foundSelector: string): string {
+ return foundSelector.replace(/\\([0-9a-fA-F]{1,6} ?|.)/g, (_, escaped: string) => {
+ if (/^[0-9a-fA-F]/.test(escaped)) {
+ // hex code-point escape: \31 23-foo → "123-foo", \: would not reach here
+ const codePoint = parseInt(escaped, 16)
+ // guard invalid code points (> U+10FFFF or 0) per CSS spec — fall back to U+FFFD
+ return codePoint === 0 || codePoint > 0x10ffff ? '�' : String.fromCodePoint(codePoint)
+ }
+ return escaped
+ })
+}
+
+// React's useId() emits per-render identifiers like ":r5:" (React <= 18) or "«r5»" (React 19),
+// which component libraries embed in DOM attributes (e.g. data-id="base-ui-:rg:-viewport").
+// They change between renders and deploys, so a selector built on one never matches recorded events.
+const UNSTABLE_GENERATED_ID_REGEX = /:r[0-9a-z]*:|«r[0-9a-z]*»/i
+
+export function containsUnstableGeneratedId(value: string): boolean {
+ return UNSTABLE_GENERATED_ID_REGEX.test(value)
}
export function makeNavigateWrapper(onNavigate: () => void, patchKey: string): () => () => void {