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.

feat(ml/replay): More features for sampling model - nodejs (#57944)

Nicholas Waltz875ed7a587a6
diff --git a/nodejs/src/session-recording/sessions/session-feature-recorder.test.ts b/nodejs/src/session-recording/sessions/session-feature-recorder.test.ts
index 51e3a323d8b8..b9a508ec20ce 100644
--- a/nodejs/src/session-recording/sessions/session-feature-recorder.test.ts
+++ b/nodejs/src/session-recording/sessions/session-feature-recorder.test.ts
@@ -1154,6 +1154,352 @@ describe('SessionFeatureRecorder', () => {
expect(result.clickTargetIds).toEqual([])
expect(result.visitedUrls).toEqual([])
expect(result.textSelectionCount).toBe(0)
+ expect(result.scrollToTopCount).toBe(0)
+ expect(result.backspaceCount).toBe(0)
+ expect(result.longIdleGapCount).toBe(0)
+ expect(result.consoleWarnCount).toBe(0)
+ expect(result.network4xxCount).toBe(0)
+ expect(result.network5xxCount).toBe(0)
+ expect(result.mutationCount).toBe(0)
+ expect(result.viewportResizeCount).toBe(0)
+ expect(result.touchEventCount).toBe(0)
+ expect(result.formFieldIds).toEqual([])
+ expect(result.selectionCopyCount).toBe(0)
+ for (const value of Object.values(result.pathTokenCounts)) {
+ expect(value).toBe(0)
+ }
+ })
+ })
+
+ describe('Mutation density', () => {
+ const makeMutationEvent = (timestamp: number): SnapshotEvent =>
+ ({
+ type: RRWebEventType.IncrementalSnapshot,
+ timestamp,
+ data: { source: RRWebEventSource.Mutation },
+ }) as unknown as SnapshotEvent
+
+ it('should count mutation events from IncrementalSnapshot.Mutation source', () => {
+ const events = [makeMutationEvent(1000), makeMutationEvent(2000), makeMutationEvent(3000)]
+ recorder.recordMessage(createMessage(events))
+ const result = recorder.end()!
+
+ expect(result.mutationCount).toBe(3)
+ })
+
+ it('should not count non-mutation incremental events as mutations', () => {
+ const events = [makeScrollEvent(1000, 0), makeClickEvent(2000), makeKeypressEvent(3000)]
+ recorder.recordMessage(createMessage(events))
+ const result = recorder.end()!
+
+ expect(result.mutationCount).toBe(0)
+ })
+ })
+
+ describe('Touch events', () => {
+ const makeTouchMoveEvent = (timestamp: number): SnapshotEvent =>
+ ({
+ type: RRWebEventType.IncrementalSnapshot,
+ timestamp,
+ data: { source: RRWebEventSource.TouchMove },
+ }) as unknown as SnapshotEvent
+
+ const makeTouchInteraction = (timestamp: number, type: MouseInteractions): SnapshotEvent =>
+ ({
+ type: RRWebEventType.IncrementalSnapshot,
+ timestamp,
+ data: { source: RRWebEventSource.MouseInteraction, type },
+ }) as unknown as SnapshotEvent
+
+ it('should count TouchMove source events', () => {
+ recorder.recordMessage(createMessage([makeTouchMoveEvent(1000), makeTouchMoveEvent(2000)]))
+ const result = recorder.end()!
+
+ expect(result.touchEventCount).toBe(2)
+ })
+
+ it('should count TouchStart and TouchEnd interactions', () => {
+ const events = [
+ makeTouchInteraction(1000, MouseInteractions.TouchStart),
+ makeTouchInteraction(2000, MouseInteractions.TouchEnd),
+ ]
+ recorder.recordMessage(createMessage(events))
+ const result = recorder.end()!
+
+ expect(result.touchEventCount).toBe(2)
+ })
+
+ it('should not count regular mouse activity as touch events', () => {
+ recorder.recordMessage(createMessage([makeMouseMoveEvent(1000, [{ x: 1, y: 1 }]), makeClickEvent(2000)]))
+ const result = recorder.end()!
+
+ expect(result.touchEventCount).toBe(0)
+ })
+ })
+
+ describe('Network status class split', () => {
+ const makeRRWebNetworkEvent = (
+ timestamp: number,
+ requests: Array<{ duration?: number; status?: number; responseStatus?: number }>
+ ): SnapshotEvent =>
+ ({
+ type: RRWebEventType.Plugin,
+ timestamp,
+ data: { plugin: 'rrweb/network@1', payload: { requests } },
+ }) as unknown as SnapshotEvent
+
+ it('should split 4xx vs 5xx vs 2xx', () => {
+ const events = [
+ makeRRWebNetworkEvent(1000, [
+ { status: 200 },
+ { status: 301 },
+ { status: 401 },
+ { status: 404 },
+ { status: 500 },
+ { status: 503 },
+ ]),
+ ]
+ recorder.recordMessage(createMessage(events))
+ const result = recorder.end()!
+
+ expect(result.network4xxCount).toBe(2)
+ expect(result.network5xxCount).toBe(2)
+ expect(result.networkFailedRequestCount).toBe(4)
+ })
+ })
+
+ describe('Long idle gap count', () => {
+ it('should count gaps over 30s', () => {
+ // gaps: 5s, 35s, 10s, 60s — two long
+ const events = [
+ makeClickEvent(0),
+ makeClickEvent(5_000),
+ makeClickEvent(40_000),
+ makeClickEvent(50_000),
+ makeClickEvent(110_000),
+ ]
+ recorder.recordMessage(createMessage(events))
+ const result = recorder.end()!
+
+ expect(result.longIdleGapCount).toBe(2)
+ })
+
+ it('should not count gaps that are exactly 30s (boundary is strict greater-than)', () => {
+ const events = [makeClickEvent(0), makeClickEvent(30_000)]
+ recorder.recordMessage(createMessage(events))
+ const result = recorder.end()!
+
+ expect(result.longIdleGapCount).toBe(0)
+ })
+ })
+
+ describe('Scroll-to-top events', () => {
+ it('should count transitions from scrollY > 0 back to scrollY === 0', () => {
+ const events = [
+ makeScrollEvent(1000, 0),
+ makeScrollEvent(2000, 200),
+ makeScrollEvent(3000, 0), // scroll-to-top
+ makeScrollEvent(4000, 100),
+ makeScrollEvent(5000, 0), // scroll-to-top
+ ]
+ recorder.recordMessage(createMessage(events))
+ const result = recorder.end()!
+
+ expect(result.scrollToTopCount).toBe(2)
+ })
+
+ it('should not count transitions that already start at 0', () => {
+ const events = [makeScrollEvent(1000, 0), makeScrollEvent(2000, 0)]
+ recorder.recordMessage(createMessage(events))
+ const result = recorder.end()!
+
+ expect(result.scrollToTopCount).toBe(0)
+ })
+
+ it('should reset between distinct scroll element ids', () => {
+ const events = [
+ makeScrollEvent(1000, 100, 1),
+ makeScrollEvent(2000, 0, 2), // first event for element 2 — establishes baseline, no transition
+ ]
+ recorder.recordMessage(createMessage(events))
+ const result = recorder.end()!
+
+ expect(result.scrollToTopCount).toBe(0)
+ })
+ })
+
+ describe('Console warn tracking', () => {
+ it('should count console warn plugin events', () => {
+ const event = {
+ type: RRWebEventType.Plugin,
+ timestamp: 1000,
+ data: { plugin: 'rrweb/console@1', payload: { level: 'warn' } },
+ } as unknown as SnapshotEvent
+ recorder.recordMessage(createMessage([event, event]))
+ const result = recorder.end()!
+
+ expect(result.consoleWarnCount).toBe(2)
+ expect(result.consoleErrorCount).toBe(0)
+ })
+
+ it('should not double-count error events as warns', () => {
+ recorder.recordMessage(createMessage([makeConsoleErrorEvent(1000)]))
+ const result = recorder.end()!
+
+ expect(result.consoleWarnCount).toBe(0)
+ expect(result.consoleErrorCount).toBe(1)
+ })
+ })
+
+ describe('Backspace heuristic', () => {
+ const makeInputEvent = (timestamp: number, id: number, text: string): SnapshotEvent =>
+ ({
+ type: RRWebEventType.IncrementalSnapshot,
+ timestamp,
+ data: { source: RRWebEventSource.Input, id, text },
+ }) as unknown as SnapshotEvent
+
+ it('should count text length decrease as backspaces', () => {
+ const events = [
+ makeInputEvent(1000, 1, 'hello'),
+ makeInputEvent(2000, 1, 'hell'), // -1
+ makeInputEvent(3000, 1, 'hel'), // -1
+ makeInputEvent(4000, 1, 'hello world'), // grows, no backspace
+ makeInputEvent(5000, 1, 'hello'), // -6
+ ]
+ recorder.recordMessage(createMessage(events))
+ const result = recorder.end()!
+
+ expect(result.backspaceCount).toBe(8)
+ })
+
+ it('should track shrinkage independently per element id', () => {
+ const events = [
+ makeInputEvent(1000, 1, 'abc'),
+ makeInputEvent(1100, 2, 'xyz'),
+ makeInputEvent(1200, 1, 'a'), // -2 on field 1
+ makeInputEvent(1300, 2, ''), // -3 on field 2
+ ]
+ recorder.recordMessage(createMessage(events))
+ const result = recorder.end()!
+
+ expect(result.backspaceCount).toBe(5)
+ })
+ })
+
+ describe('Distinct form field interactions', () => {
+ const makeInputEvent = (timestamp: number, id: number): SnapshotEvent =>
+ ({
+ type: RRWebEventType.IncrementalSnapshot,
+ timestamp,
+ data: { source: RRWebEventSource.Input, id, text: '' },
+ }) as unknown as SnapshotEvent
+
+ it('should collect unique form field ids', () => {
+ const events = [makeInputEvent(1000, 5), makeInputEvent(2000, 7), makeInputEvent(3000, 5)]
+ recorder.recordMessage(createMessage(events))
+ const result = recorder.end()!
+
+ expect(result.formFieldIds).toEqual(expect.arrayContaining([5, 7]))
+ expect(result.formFieldIds).toHaveLength(2)
+ })
+ })
+
+ describe('Viewport resize tracking', () => {
+ it('should count viewport resize events', () => {
+ const event = {
+ type: RRWebEventType.IncrementalSnapshot,
+ timestamp: 1000,
+ data: { source: RRWebEventSource.ViewportResize },
+ } as unknown as SnapshotEvent
+ recorder.recordMessage(createMessage([event, event, event]))
+ const result = recorder.end()!
+
+ expect(result.viewportResizeCount).toBe(3)
+ })
+ })
+
+ describe('Selection-copy heuristic', () => {
+ const makeSelectionEvent = (timestamp: number): SnapshotEvent =>
+ ({
+ type: RRWebEventType.IncrementalSnapshot,
+ timestamp,
+ data: { source: RRWebEventSource.Selection },
+ }) as unknown as SnapshotEvent
+
+ it('should count selection followed by keypress within 2s', () => {
+ const events = [makeSelectionEvent(1000), makeKeypressEvent(2500)]
+ recorder.recordMessage(createMessage(events))
+ const result = recorder.end()!
+
+ expect(result.selectionCopyCount).toBe(1)
+ })
+
+ it('should not count keypress further than 2s after selection', () => {
+ const events = [makeSelectionEvent(1000), makeKeypressEvent(3500)]
+ recorder.recordMessage(createMessage(events))
+ const result = recorder.end()!
+
+ expect(result.selectionCopyCount).toBe(0)
+ })
+
+ it('should not double-count multiple keypresses for one selection', () => {
+ // The selection state is consumed by the first qualifying keypress.
+ const events = [makeSelectionEvent(1000), makeKeypressEvent(1500), makeKeypressEvent(2500)]
+ recorder.recordMessage(createMessage(events))
+ const result = recorder.end()!
+
+ expect(result.selectionCopyCount).toBe(1)
+ })
+ })
+
+ describe('URL path-token counts', () => {
+ it('should count tokens that match an allowlist segment', () => {
+ const events = [
+ makeNavigationEvent(1000, 'https://example.com/login'),
+ makeNavigationEvent(2000, 'https://example.com/checkout/step1'),
+ makeNavigationEvent(3000, 'https://example.com/account/settings'),
+ makeNavigationEvent(4000, 'https://example.com/billing/invoices'),
+ ]
+ recorder.recordMessage(createMessage(events))
+ const result = recorder.end()!
+
+ expect(result.pathTokenCounts.login).toBe(1)
+ expect(result.pathTokenCounts.checkout).toBe(1)
+ expect(result.pathTokenCounts.account).toBe(1)
+ expect(result.pathTokenCounts.settings).toBe(1)
+ expect(result.pathTokenCounts.billing).toBe(1)
+ })
+
+ it('should match case-insensitively', () => {
+ recorder.recordMessage(createMessage([makeNavigationEvent(1000, 'https://example.com/Login')]))
+ const result = recorder.end()!
+
+ expect(result.pathTokenCounts.login).toBe(1)
+ })
+
+ it('should not count non-allowlisted segments', () => {
+ recorder.recordMessage(createMessage([makeNavigationEvent(1000, 'https://example.com/foo/bar/baz')]))
+ const result = recorder.end()!
+
+ for (const value of Object.values(result.pathTokenCounts)) {
+ expect(value).toBe(0)
+ }
+ })
+
+ it('should count 404 token for not_found', () => {
+ recorder.recordMessage(createMessage([makeNavigationEvent(1000, 'https://example.com/error/404')]))
+ const result = recorder.end()!
+
+ expect(result.pathTokenCounts.error).toBe(1)
+ expect(result.pathTokenCounts['404']).toBe(1)
+ })
+
+ it('should only count each token once per URL even if it appears multiple times', () => {
+ recorder.recordMessage(createMessage([makeNavigationEvent(1000, 'https://example.com/login/login/login')]))
+ const result = recorder.end()!
+
+ expect(result.pathTokenCounts.login).toBe(1)
})
})
diff --git a/nodejs/src/session-recording/sessions/session-feature-recorder.ts b/nodejs/src/session-recording/sessions/session-feature-recorder.ts
index 1785fb394be4..d2f254a5bcd9 100644
--- a/nodejs/src/session-recording/sessions/session-feature-recorder.ts
+++ b/nodejs/src/session-recording/sessions/session-feature-recorder.ts
@@ -3,7 +3,15 @@ import { DateTime } from 'luxon'
import { defaultConfig } from '../../config/config'
import { ParsedMessageData, SnapshotEvent } from '../kafka/types'
-import { RRWebEventSource, RRWebEventType, hrefFrom, isClick, isKeypress, isMouseActivity } from '../rrweb-types'
+import {
+ MouseInteractions,
+ RRWebEventSource,
+ RRWebEventType,
+ hrefFrom,
+ isClick,
+ isKeypress,
+ isMouseActivity,
+} from '../rrweb-types'
const POSTHOG_NETWORK_PLUGIN = 'posthog/network@1'
const RRWEB_NETWORK_PLUGIN = 'rrweb/network@1'
@@ -13,6 +21,34 @@ const POSTHOG_NETWORK_STATUS_KEY = 21
export const MAX_UNIQUE_VALUES = 1000
+export const LONG_IDLE_GAP_MS = 30_000
+
+export const SELECTION_COPY_WINDOW_MS = 2_000
+
+/**
+ * Allowlist of path tokens we count when they appear in a navigation URL's path.
+ * Order is part of the public contract — it maps 1:1 to {@link FeatureEndResult.pathTokenCounts}
+ * and the corresponding ClickHouse columns. Only append; do not reorder.
+ */
+export const PATH_TOKEN_ALLOWLIST = [
+ 'login',
+ 'signup',
+ 'checkout',
+ 'cart',
+ 'billing',
+ 'settings',
+ 'account',
+ 'error',
+ '404',
+ 'admin',
+ 'dashboard',
+ 'onboarding',
+ 'cancel',
+ 'refund',
+] as const
+
+export type PathToken = (typeof PATH_TOKEN_ALLOWLIST)[number]
+
export const md5Hex = (s: string): string => crypto.createHash('md5').update(s).digest('hex')
interface RRWebEventData {
@@ -24,6 +60,7 @@ interface RRWebEventData {
x?: number
y?: number
id?: number
+ text?: string
positions?: Array<{ x: number; y: number; id: number; timeOffset: number }>
plugin?: string
payload?: {
@@ -52,14 +89,25 @@ interface RRWebEventData {
* - mouse_activity_count
* - rage_click_count
* - dead_click_count
+ * - backspace_count
* - scroll_event_count
+ * - scroll_to_top_count
* - quick_back_count
* - page_visit_count
+ * - long_idle_gap_count
* - console_error_count
* - console_error_after_click_count
+ * - console_warn_count
* - network_request_count
* - network_failed_request_count
+ * - network_4xx_count
+ * - network_5xx_count
+ * - mutation_count
+ * - viewport_resize_count
+ * - touch_event_count
* - text_selection_count
+ * - selection_copy_count
+ * - {token}_path_visit_count
*
* Max aggregates:
* - max_idle_gap_ms
@@ -78,9 +126,10 @@ interface RRWebEventData {
* - Mouse direction change rate: mouse_direction_change_count / mouse_distance_traveled
*
* Set-based metrics:
- * - Unique click targets: uniqExactMerge(unique_click_target_count)
- * - Unique URLs visited: uniqExactMerge(unique_url_count) — visited_urls are md5-hashed at the source
- * - Page revisit count: page_visit_count - uniqExactMerge(unique_url_count)
+ * - Unique click targets: uniqExactMerge(unique_click_target_count)
+ * - Unique form fields: uniqExactMerge(unique_form_field_count) — distinct Input source target ids
+ * - Unique URLs visited: uniqExactMerge(unique_url_count) — visited_urls are md5-hashed at the source
+ * - Page revisit count: page_visit_count - uniqExactMerge(unique_url_count)
*
* All sets are capped at MAX_UNIQUE_VALUES per batch to bound payload size < 50 KB.
*/
@@ -110,6 +159,7 @@ export interface FeatureEndResult {
totalScrollMagnitude: number
scrollDirectionReversalCount: number
rapidScrollReversalCount: number
+ scrollToTopCount: number
// Click frustration features
clickCount: number
@@ -117,39 +167,58 @@ export interface FeatureEndResult {
mouseActivityCount: number
rageClickCount: number
deadClickCount: number
+ backspaceCount: number
// Inter-action timing sufficient statistics
interActionGapCount: number
interActionGapSumMs: number
interActionGapSumOfSquaresMs: number
maxIdleGapMs: number
+ longIdleGapCount: number
// Navigation features
quickBackCount: number
pageVisitCount: number
visitedUrls: string[]
+ pathTokenCounts: Record<PathToken, number>
// Error features
consoleErrorCount: number
consoleErrorAfterClickCount: number
+ consoleWarnCount: number
// Network features
networkRequestCount: number
networkFailedRequestCount: number
+ network4xxCount: number
+ network5xxCount: number
networkRequestDurationSum: number
networkRequestDurationSumOfSquares: number
networkRequestDurationCount: number
+ // DOM/viewport
+ mutationCount: number
+ viewportResizeCount: number
+
+ // Touch
+ touchEventCount: number
+
// Scroll depth
maxScrollY: number
// Click target diversity
clickTargetIds: number[]
+ // Form interaction diversity
+ formFieldIds: number[]
+
// Text selection
textSelectionCount: number
+ selectionCopyCount: number
}
+const TOUCH_INTERACTION_TYPES: number[] = [MouseInteractions.TouchStart, MouseInteractions.TouchEnd]
+
/**
* Extracts aggregate features from session recording events for ML scoring.
*/
@@ -187,6 +256,7 @@ export class SessionFeatureRecorder {
private totalScrollMagnitude = 0
private scrollDirectionReversalCount = 0
private rapidScrollReversalCount = 0
+ private scrollToTopCount = 0
private lastScrollDirection: 'up' | 'down' | null = null
private lastScrollTimestamp: number | null = null
private lastScrollY: number | null = null
@@ -195,6 +265,7 @@ export class SessionFeatureRecorder {
// Click frustration features
private rageClickCount = 0
private deadClickCount = 0
+ private backspaceCount = 0
private lastClickTimestamp: number | null = null
private lastClickX: number | null = null
private lastClickY: number | null = null
@@ -207,6 +278,7 @@ export class SessionFeatureRecorder {
private interActionGapSumMs = 0
private interActionGapSumOfSquaresMs = 0
private maxIdleGapMs = 0
+ private longIdleGapCount = 0
// Navigation features
private quickBackCount = 0
@@ -214,27 +286,47 @@ export class SessionFeatureRecorder {
private visitedUrls: Set<string> = new Set()
private lastNavigationTimestamp: number | null = null
private lastNavigationUrl: string | null = null
+ private pathTokenCounts: Record<PathToken, number> = SessionFeatureRecorder.emptyPathTokenCounts()
// Error features
private consoleErrorCount = 0
private consoleErrorAfterClickCount = 0
+ private consoleWarnCount = 0
private lastUserActionTimestamp: number | null = null
// Network features
private networkRequestCount = 0
private networkFailedRequestCount = 0
+ private network4xxCount = 0
+ private network5xxCount = 0
private networkRequestDurationSum = 0
private networkRequestDurationSumOfSquares = 0
private networkRequestDurationCount = 0
+ // DOM/viewport
+ private mutationCount = 0
+ private viewportResizeCount = 0
+
+ // Touch
+ private touchEventCount = 0
+
// Scroll depth
private maxScrollY = 0
// Click target diversity
private clickTargetIds: Set<number> = new Set()
+ // Form interaction diversity
+ private formFieldIds: Set<number> = new Set()
+
+ // Per-element last input length for backspace heuristic.
+ // Bounded by MAX_UNIQUE_VALUES to keep memory cost predictable.
+ private inputTextLengths: Map<number, number> = new Map()
+
// Text selection
private textSelectionCount = 0
+ private selectionCopyCount = 0
+ private lastSelectionTimestamp: number | null = null
constructor(
public readonly sessionId: string,
@@ -244,6 +336,14 @@ export class SessionFeatureRecorder {
this._run = this.shouldRun(sessionId)
}
+ private static emptyPathTokenCounts(): Record<PathToken, number> {
+ const counts = {} as Record<PathToken, number>
+ for (const token of PATH_TOKEN_ALLOWLIST) {
+ counts[token] = 0
+ }
+ return counts
+ }
+
public recordMessage(message: ParsedMessageData): void {
if (!this._run) {
return
@@ -292,12 +392,15 @@ export class SessionFeatureRecorder {
this.trackMousePosition(e)
this.trackScroll(e)
this.trackClicks(event, e)
- this.trackKeypress(event, e.timestamp)
+ this.trackKeypress(event, e)
this.trackInterActionTiming(event, e.timestamp)
this.trackNavigation(event, e.timestamp)
- this.trackConsoleErrors(e)
+ this.trackConsoleLogs(e)
this.trackNetworkRequests(e)
this.trackTextSelection(e)
+ this.trackMutation(e)
+ this.trackViewportResize(e)
+ this.trackTouchEvent(e)
if (isMouseActivity(event)) {
this.mouseActivityCount++
@@ -386,6 +489,10 @@ export class SessionFeatureRecorder {
const deltaY = scrollY - this.lastScrollY
this.totalScrollMagnitude += Math.abs(deltaY)
+ if (this.lastScrollY > 0 && scrollY === 0) {
+ this.scrollToTopCount++
+ }
+
if (deltaY !== 0) {
const direction: 'up' | 'down' = deltaY < 0 ? 'up' : 'down'
if (this.lastScrollDirection !== null && direction !== this.lastScrollDirection) {
@@ -456,12 +563,38 @@ export class SessionFeatureRecorder {
this.lastClickY = clickY ?? null
}
- private trackKeypress(event: SnapshotEvent, timestamp: number): void {
+ private trackKeypress(event: SnapshotEvent, e: RRWebEventData): void {
if (!isKeypress(event)) {
return
}
this.keypressCount++
- this.lastUserActionTimestamp = timestamp
+ this.lastUserActionTimestamp = e.timestamp
+
+ const targetId = e.data?.id
+ if (targetId !== undefined) {
+ if (this.formFieldIds.size < MAX_UNIQUE_VALUES) {
+ this.formFieldIds.add(targetId)
+ }
+
+ const text = e.data?.text
+ if (typeof text === 'string') {
+ const previousLength = this.inputTextLengths.get(targetId)
+ if (previousLength !== undefined && text.length < previousLength) {
+ this.backspaceCount += previousLength - text.length
+ }
+ if (this.inputTextLengths.size < MAX_UNIQUE_VALUES || this.inputTextLengths.has(targetId)) {
+ this.inputTextLengths.set(targetId, text.length)
+ }
+ }
+ }
+
+ if (
+ this.lastSelectionTimestamp !== null &&
+ e.timestamp - this.lastSelectionTimestamp <= SELECTION_COPY_WINDOW_MS
+ ) {
+ this.selectionCopyCount++
+ this.lastSelectionTimestamp = null
+ }
}
private trackInterActionTiming(event: SnapshotEvent, timestamp: number): void {
@@ -478,6 +611,9 @@ export class SessionFeatureRecorder {
if (gap > this.maxIdleGapMs) {
this.maxIdleGapMs = gap
}
+ if (gap > LONG_IDLE_GAP_MS) {
+ this.longIdleGapCount++
+ }
}
}
this.lastActionTimestamp = timestamp
@@ -494,6 +630,7 @@ export class SessionFeatureRecorder {
this.visitedUrls.add(md5Hex(eventUrl))
}
this.urlChangedSinceLastClick = true
+ this.recordPathTokens(eventUrl)
if (
this.lastNavigationUrl !== null &&
@@ -507,22 +644,45 @@ export class SessionFeatureRecorder {
this.lastNavigationTimestamp = timestamp
}
- private trackConsoleErrors(e: RRWebEventData): void {
- if (e.type !== RRWebEventType.Plugin) {
+ private recordPathTokens(url: string): void {
+ const path = pathFromUrl(url)
+ if (path === null) {
return
}
- if (e.data?.plugin !== 'rrweb/console@1' || e.data?.payload?.level !== 'error') {
+ const segments = path
+ .toLowerCase()
+ .split('/')
+ .filter((s) => s.length > 0)
+ if (segments.length === 0) {
return
}
+ const seen = new Set<PathToken>()
+ for (const segment of segments) {
+ for (const token of PATH_TOKEN_ALLOWLIST) {
+ if (segment === token && !seen.has(token)) {
+ this.pathTokenCounts[token]++
+ seen.add(token)
+ }
+ }
+ }
+ }
- this.consoleErrorCount++
- if (this.lastUserActionTimestamp === null) {
+ private trackConsoleLogs(e: RRWebEventData): void {
+ if (e.type !== RRWebEventType.Plugin || e.data?.plugin !== 'rrweb/console@1') {
return
}
-
- const timeSinceAction = e.timestamp - this.lastUserActionTimestamp
- if (timeSinceAction >= 0 && timeSinceAction < 5000) {
- this.consoleErrorAfterClickCount++
+ const level = e.data?.payload?.level
+ if (level === 'error') {
+ this.consoleErrorCount++
+ if (this.lastUserActionTimestamp === null) {
+ return
+ }
+ const timeSinceAction = e.timestamp - this.lastUserActionTimestamp
+ if (timeSinceAction >= 0 && timeSinceAction < 5000) {
+ this.consoleErrorAfterClickCount++
+ }
+ } else if (level === 'warn') {
+ this.consoleWarnCount++
}
}
@@ -555,8 +715,16 @@ export class SessionFeatureRecorder {
private processNetworkRequest(duration: unknown, status: unknown): void {
this.networkRequestCount++
- if (typeof status === 'number' && status >= 400) {
- this.networkFailedRequestCount++
+ if (typeof status === 'number') {
+ if (status >= 400 && status < 500) {
+ this.network4xxCount++
+ this.networkFailedRequestCount++
+ } else if (status >= 500 && status < 600) {
+ this.network5xxCount++
+ this.networkFailedRequestCount++
+ } else if (status >= 600) {
+ this.networkFailedRequestCount++
+ }
}
if (typeof duration === 'number' && duration > 0) {
@@ -571,6 +739,37 @@ export class SessionFeatureRecorder {
return
}
this.textSelectionCount++
+ this.lastSelectionTimestamp = e.timestamp
+ }
+
+ private trackMutation(e: RRWebEventData): void {
+ if (e.type !== RRWebEventType.IncrementalSnapshot || e.data?.source !== RRWebEventSource.Mutation) {
+ return
+ }
+ this.mutationCount++
+ }
+
+ private trackViewportResize(e: RRWebEventData): void {
+ if (e.type !== RRWebEventType.IncrementalSnapshot || e.data?.source !== RRWebEventSource.ViewportResize) {
+ return
+ }
+ this.viewportResizeCount++
+ }
+
+ private trackTouchEvent(e: RRWebEventData): void {
+ if (e.type !== RRWebEventType.IncrementalSnapshot) {
+ return
+ }
+ if (e.data?.source === RRWebEventSource.TouchMove) {
+ this.touchEventCount++
+ return
+ }
+ if (
+ e.data?.source === RRWebEventSource.MouseInteraction &&
+ TOUCH_INTERACTION_TYPES.includes(e.data?.type ?? -1)
+ ) {
+ this.touchEventCount++
+ }
}
public get distinctId(): string {
@@ -612,36 +811,64 @@ export class SessionFeatureRecorder {
totalScrollMagnitude: this.totalScrollMagnitude,
scrollDirectionReversalCount: this.scrollDirectionReversalCount,
rapidScrollReversalCount: this.rapidScrollReversalCount,
+ scrollToTopCount: this.scrollToTopCount,
clickCount: this.clickCount,
keypressCount: this.keypressCount,
mouseActivityCount: this.mouseActivityCount,
rageClickCount: this.rageClickCount,
deadClickCount: this.deadClickCount,
+ backspaceCount: this.backspaceCount,
interActionGapCount: this.interActionGapCount,
interActionGapSumMs: this.interActionGapSumMs,
interActionGapSumOfSquaresMs: this.interActionGapSumOfSquaresMs,
maxIdleGapMs: this.maxIdleGapMs,
+ longIdleGapCount: this.longIdleGapCount,
quickBackCount: this.quickBackCount,
pageVisitCount: this.pageVisitCount,
visitedUrls: Array.from(this.visitedUrls),
+ pathTokenCounts: this.pathTokenCounts,
consoleErrorCount: this.consoleErrorCount,
consoleErrorAfterClickCount: this.consoleErrorAfterClickCount,
+ consoleWarnCount: this.consoleWarnCount,
networkRequestCount: this.networkRequestCount,
networkFailedRequestCount: this.networkFailedRequestCount,
+ network4xxCount: this.network4xxCount,
+ network5xxCount: this.network5xxCount,
networkRequestDurationSum: this.networkRequestDurationSum,
networkRequestDurationSumOfSquares: this.networkRequestDurationSumOfSquares,
networkRequestDurationCount: this.networkRequestDurationCount,
+ mutationCount: this.mutationCount,
+ viewportResizeCount: this.viewportResizeCount,
+ touchEventCount: this.touchEventCount,
+
maxScrollY: this.maxScrollY,
clickTargetIds: Array.from(this.clickTargetIds),
+ formFieldIds: Array.from(this.formFieldIds),
textSelectionCount: this.textSelectionCount,
+ selectionCopyCount: this.selectionCopyCount,
}
}
}
+
+const pathFromUrl = (url: string): string | null => {
+ try {
+ return new URL(url).pathname
+ } catch {
+ const trimmed = url.trim()
+ if (trimmed.startsWith('/')) {
+ const queryIdx = trimmed.indexOf('?')
+ const hashIdx = trimmed.indexOf('#')
+ const end = [queryIdx, hashIdx].filter((i) => i >= 0).reduce((a, b) => Math.min(a, b), trimmed.length)
+ return trimmed.slice(0, end)
+ }
+ return null
+ }
+}
diff --git a/nodejs/src/session-replay/shared/features/session-feature-store.ts b/nodejs/src/session-replay/shared/features/session-feature-store.ts
index 38e066bd5021..2fa0ca9a6f07 100644
--- a/nodejs/src/session-replay/shared/features/session-feature-store.ts
+++ b/nodejs/src/session-replay/shared/features/session-feature-store.ts
@@ -82,28 +82,53 @@ export class SessionFeatureStore {
total_scroll_magnitude: block.features.totalScrollMagnitude,
scroll_direction_reversal_count: block.features.scrollDirectionReversalCount,
rapid_scroll_reversal_count: block.features.rapidScrollReversalCount,
+ scroll_to_top_count: block.features.scrollToTopCount,
click_count: block.features.clickCount,
keypress_count: block.features.keypressCount,
mouse_activity_count: block.features.mouseActivityCount,
rage_click_count: block.features.rageClickCount,
dead_click_count: block.features.deadClickCount,
+ backspace_count: block.features.backspaceCount,
inter_action_gap_count: block.features.interActionGapCount,
inter_action_gap_sum_ms: block.features.interActionGapSumMs,
inter_action_gap_sum_of_squares_ms: block.features.interActionGapSumOfSquaresMs,
max_idle_gap_ms: block.features.maxIdleGapMs,
+ long_idle_gap_count: block.features.longIdleGapCount,
quick_back_count: block.features.quickBackCount,
page_visit_count: block.features.pageVisitCount,
visited_urls: block.features.visitedUrls,
+ login_path_visit_count: block.features.pathTokenCounts.login,
+ signup_path_visit_count: block.features.pathTokenCounts.signup,
+ checkout_path_visit_count: block.features.pathTokenCounts.checkout,
+ cart_path_visit_count: block.features.pathTokenCounts.cart,
+ billing_path_visit_count: block.features.pathTokenCounts.billing,
+ settings_path_visit_count: block.features.pathTokenCounts.settings,
+ account_path_visit_count: block.features.pathTokenCounts.account,
+ error_path_visit_count: block.features.pathTokenCounts.error,
+ not_found_path_visit_count: block.features.pathTokenCounts['404'],
+ admin_path_visit_count: block.features.pathTokenCounts.admin,
+ dashboard_path_visit_count: block.features.pathTokenCounts.dashboard,
+ onboarding_path_visit_count: block.features.pathTokenCounts.onboarding,
+ cancel_path_visit_count: block.features.pathTokenCounts.cancel,
+ refund_path_visit_count: block.features.pathTokenCounts.refund,
console_error_count: block.features.consoleErrorCount,
console_error_after_click_count: block.features.consoleErrorAfterClickCount,
+ console_warn_count: block.features.consoleWarnCount,
network_request_count: block.features.networkRequestCount,
network_failed_request_count: block.features.networkFailedRequestCount,
+ network_4xx_count: block.features.network4xxCount,
+ network_5xx_count: block.features.network5xxCount,
network_request_duration_sum: block.features.networkRequestDurationSum,
network_request_duration_sum_of_squares: block.features.networkRequestDurationSumOfSquares,
network_request_duration_count: block.features.networkRequestDurationCount,
+ mutation_count: block.features.mutationCount,
+ viewport_resize_count: block.features.viewportResizeCount,
+ touch_event_count: block.features.touchEventCount,
max_scroll_y: block.features.maxScrollY,
click_target_ids: block.features.clickTargetIds,
+ form_field_ids: block.features.formFieldIds,
text_selection_count: block.features.textSelectionCount,
+ selection_copy_count: block.features.selectionCopyCount,
is_deleted: block.isDeleted ? 1 : 0,
}))