: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(replay): lead the player frame error with retry and record focus diagnostics (#122193)
posthog[bot]1530113cbbc2
diff --git a/frontend/src/scenes/session-recordings/player/PlayerFrame.test.tsx b/frontend/src/scenes/session-recordings/player/PlayerFrame.test.tsxindex 15a376395568..e6b39154edae 100644--- a/frontend/src/scenes/session-recordings/player/PlayerFrame.test.tsx+++ b/frontend/src/scenes/session-recordings/player/PlayerFrame.test.tsx@@ -41,6 +41,7 @@ describe('PlayerFrame', () => {}it('mounts the player on the frame document once the frame loads', () => {+ const captureSpy = jest.spyOn(posthog, 'capture')const iframe = renderPlayerFrame()const frameDocument = iframe.contentDocument!frameDocument.open()@@ -54,6 +55,7 @@ describe('PlayerFrame', () => {)// The frame is same-origin, so any script permission added here runs as the app.expect(iframe).toHaveAttribute('sandbox', 'allow-same-origin')+ expect(captureSpy).not.toHaveBeenCalledWith('replay player frame load recovered', expect.anything())})// A load event that never arrives used to leave rrweb with nowhere to mount, so the player@@ -74,7 +76,13 @@ describe('PlayerFrame', () => {})expect(captureSpy).toHaveBeenCalledWith('replay player frame load retried',- expect.objectContaining({ attempt: 1, restarts: 0 })+ // The focus and activation that may decide the load are read when the frame mounted, not 10s later.+ expect.objectContaining({+ attempt: 1,+ restarts: 0,+ frameMountHasFocus: expect.any(Boolean),+ msSinceFrameMount: 10000,+ }))// The retry replaces the frame, because a frame stuck on about:blank can ignore a new src.@@ -218,6 +226,32 @@ describe('PlayerFrame', () => {}})+ // Comparing the frames that loaded after a failure with the ones that did not tests why a retry recovers.+ it('reports a frame that loads after a failed load', () => {+ jest.useFakeTimers()+ try {+ const captureSpy = jest.spyOn(posthog, 'capture')+ const container = renderPlayerFrame().parentElement!++ fireEvent.load(currentFrame(container))+ act(() => {+ jest.advanceTimersByTime(1000)+ })+ const frameDocument = currentFrame(container).contentDocument!+ frameDocument.open()+ frameDocument.write('<div id="player-frame-content"></div>')+ frameDocument.close()+ fireEvent.load(currentFrame(container))++ expect(captureSpy).toHaveBeenCalledWith(+ 'replay player frame load recovered',+ expect.objectContaining({ attempt: 1, restarts: 0, frameMountHasFocus: expect.any(Boolean) })+ )+ } finally {+ jest.useRealTimers()+ }+ })+// A retry from the error card must load a new frame. A page reload repeats the same failed load.it('loads a new frame and mounts the player when the viewer retries from the error state', () => {const onLine = jest.spyOn(navigator, 'onLine', 'get').mockReturnValue(false)diff --git a/frontend/src/scenes/session-recordings/player/PlayerFrame.tsx b/frontend/src/scenes/session-recordings/player/PlayerFrame.tsxindex 0d1964b9b800..dea7e395aa0c 100644--- a/frontend/src/scenes/session-recordings/player/PlayerFrame.tsx+++ b/frontend/src/scenes/session-recordings/player/PlayerFrame.tsx@@ -6,6 +6,7 @@ import { useActions, useValues } from 'kea'import { Handler, viewportResizeDimension } from 'posthog-js/rrweb-types'import { useCallback, useEffect, useRef } from 'react'+import { recordPlayerFrameMount } from 'scenes/session-recordings/player/playerFrameLoadDiagnostics'import { getPlayerFrameScale, isIOS } from 'scenes/session-recordings/player/playerFrameScaling'import { sessionRecordingPlayerLogic } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'@@ -25,7 +26,8 @@ export const PlayerFrame = (): JSX.Element => {const replayDimensionRef = useRef<viewportResizeDimension>()const { player, sessionRecordingId, maskingWindow, speed, resolution, playerFrameLoadRetries } =useValues(sessionRecordingPlayerLogic)- const { setScale, setRootFrame, playerFrameDocumentLoadFailed } = useActions(sessionRecordingPlayerLogic)+ const { setScale, setRootFrame, playerFrameDocumentLoaded, playerFrameDocumentLoadFailed } =+ useActions(sessionRecordingPlayerLogic)// Each retry adds a query string the server ignores, so the browser fetches the shell again.const frameSrc = playerFrameLoadRetries ? `${PLAYER_FRAME_SRC}?retry=${playerFrameLoadRetries}` : PLAYER_FRAME_SRC@@ -101,12 +103,14 @@ export const PlayerFrame = (): JSX.Element => {// The frame usually loads after speed and maskingWindow settle, so the effect below has// already run against a document that did not exist yet.applyFrameStyles()+ playerFrameDocumentLoaded(iframeRef.current)setRootFrame(frameRef.current)- }, [setRootFrame, applyFrameStyles, playerFrameDocumentLoadFailed])+ }, [setRootFrame, applyFrameStyles, playerFrameDocumentLoaded, playerFrameDocumentLoadFailed])// frameSrc is a dependency so each retry, which swaps the frame's document, arms its own// timeout instead of reusing the one armed for the previous document.useEffect(() => {+ recordPlayerFrameMount(iframeRef.current)const timer = setTimeout(() => {if (!frameRef.current) {playerFrameDocumentLoadFailed(iframeRef.current)diff --git a/frontend/src/scenes/session-recordings/player/PlayerFrameOverlay.tsx b/frontend/src/scenes/session-recordings/player/PlayerFrameOverlay.tsxindex a265d4f41b95..2a7e1e033afa 100644--- a/frontend/src/scenes/session-recordings/player/PlayerFrameOverlay.tsx+++ b/frontend/src/scenes/session-recordings/player/PlayerFrameOverlay.tsx@@ -80,6 +80,19 @@ const RECOVERABLE_SNAPSHOT_ERRORS = ['snapshotSourceLoadExhausted',]+// The frame failure reports show an online browser and a frame that never started to load, and a retry+// from this card almost always fixes it. So the message leads with the retry, and it mentions extensions+// only after a retry from this card also failed.+function playerFrameFailureMessage(restarts: number): string {+ if (!navigator.onLine) {+ return "Your browser is offline, so the player couldn't load. Reconnect to the internet and retry."+ }+ if (restarts === 0) {+ return "The player didn't start in your browser. Retry usually fixes this."+ }+ return "The player still didn't start. A browser extension or security setting may be blocking it. Turn off extensions for PostHog, or try another browser."+}+const PlayerFrameOverlayContent = (): JSX.Element | null => {const {currentPlayerState,@@ -87,6 +100,7 @@ const PlayerFrameOverlayContent = (): JSX.Element | null => {logicProps,playerError,playerFrameDocumentFailed,+ playerFrameLoadRestarts,isWaitingForIngestion,sessionPlayerMetaData,matchingEventSkipTarget,@@ -149,7 +163,7 @@ const PlayerFrameOverlayContent = (): JSX.Element | null => {</div><div className="text-secondary text-sm text-center">{playerFrameDocumentFailed- ? "Your browser couldn't load the player. Check your internet connection and retry. If it keeps happening, a browser extension or security setting may be blocking it. Try turning off extensions for PostHog or using another browser."+ ? playerFrameFailureMessage(playerFrameLoadRestarts): isMissingFullSnapshot? 'This part of the recording is missing the snapshot data needed to render it. The data never reached PostHog, usually because the browser was closed or went offline before the recording finished uploading.': isUnauthorizeddiff --git a/frontend/src/scenes/session-recordings/player/playerFrameLoadDiagnostics.ts b/frontend/src/scenes/session-recordings/player/playerFrameLoadDiagnostics.tsindex 5e64f8fe294a..947dcddb5b50 100644--- a/frontend/src/scenes/session-recordings/player/playerFrameLoadDiagnostics.ts+++ b/frontend/src/scenes/session-recordings/player/playerFrameLoadDiagnostics.ts@@ -7,11 +7,40 @@ export interface PlayerFrameLoadDiagnostics {frameResponseStatus: number | nullbrowserOnline: booleanpageVisibility: DocumentVisibilityState+ documentHasFocus: boolean+ frameMountHasFocus: boolean | null+ frameMountUserActivationActive: boolean | null+ msSinceFrameMount: number | nullmsSincePageLoad: number}+interface PlayerFrameMount {+ hasFocus: boolean+ userActivationActive: boolean | null+ at: number+}+const MAX_TITLE_LENGTH = 100+// A failure is reported up to 10s after its frame mounted, and a click's user activation expires sooner, so+// the state that may decide whether the frame loads is read when the frame mounts.+const frameMounts = new WeakMap<HTMLIFrameElement, PlayerFrameMount>()++export function recordPlayerFrameMount(iframe: HTMLIFrameElement | null): void {+ if (!iframe) {+ return+ }+ try {+ frameMounts.set(iframe, {+ hasFocus: document.hasFocus(),+ userActivationActive: navigator.userActivation?.isActive ?? null,+ at: performance.now(),+ })+ } catch {+ // A diagnostic must never stop the frame from loading.+ }+}+// Resource Timing records the frame's navigation in the embedding document. A navigation that never finished has// no entry, and some browsers leave out `responseStatus`. jsdom has no `getEntriesByName`, and the retry runs after// this, so a missing API must not throw here.@@ -25,6 +54,7 @@ function responseStatus(src: string): number | null {export function getPlayerFrameLoadDiagnostics(iframe: HTMLIFrameElement | null): Partial<PlayerFrameLoadDiagnostics> {// A browser error page or a redirect to another origin makes the frame cross-origin, which hides its document.const frameDocument = iframe?.contentDocument ?? null+ const mount = iframe ? frameMounts.get(iframe) : undefinedtry {return {frameDocumentReadable: frameDocument !== null,@@ -37,6 +67,12 @@ export function getPlayerFrameLoadDiagnostics(iframe: HTMLIFrameElement | null):frameResponseStatus: iframe ? responseStatus(iframe.src) : null,browserOnline: navigator.onLine,pageVisibility: document.visibilityState,+ documentHasFocus: document.hasFocus(),+ // A retry from the error card almost always loads, and the automatic retries almost never do.+ // The click gives the page focus and user activation, so the report records both to test that.+ frameMountHasFocus: mount?.hasFocus ?? null,+ frameMountUserActivationActive: mount?.userActivationActive ?? null,+ msSinceFrameMount: mount ? Math.round(performance.now() - mount.at) : null,msSincePageLoad: Math.round(performance.now()),}} catch {diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.tsindex de891c84f6f1..20ec571ecbf9 100644--- a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts@@ -1135,6 +1135,9 @@ export interface sessionRecordingPlayerLogicActions {playerFrameDocumentLoadFailed: (iframe: HTMLIFrameElement | null) => {iframe: HTMLIFrameElement | null}+ playerFrameDocumentLoaded: (iframe: HTMLIFrameElement | null) => {+ iframe: HTMLIFrameElement | null+ }restartIframePlayback: () => {value: true}@@ -1639,6 +1642,7 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(// the error is emitted from code we don't control in rrweb, so we can't guarantee it's really an ErrorplayerErrorSeen: (error: any) => ({ error }),playerFrameDocumentLoadFailed: (iframe: HTMLIFrameElement | null) => ({ iframe }),+ playerFrameDocumentLoaded: (iframe: HTMLIFrameElement | null) => ({ iframe }),retryPlayerFrameLoad: true,stopRetryingPlayerFrameLoad: true,restartPlayerFrameLoad: true,@@ -2689,6 +2693,8 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(sessionRecordingId: props.sessionRecordingId,attempt: values.playerFrameLoadFailures,restarts: values.playerFrameLoadRestarts,+ // The playback loop keeps running without a frame, so this tells whether it ran during the failure.+ playingState: values.playingState,...getPlayerFrameLoadDiagnostics(iframe),}// A load retried while offline fails again, and a connection can stay away for the rest of the@@ -2715,6 +2721,19 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>({ pauseOnPageHidden: false })},+ playerFrameDocumentLoaded: ({ iframe }) => {+ // Only a frame that loaded after a failure, so its report can be compared with the failures.+ if (!values.playerFrameLoadRetries) {+ return+ }+ posthog.capture('replay player frame load recovered', {+ sessionRecordingId: props.sessionRecordingId,+ attempt: values.playerFrameLoadFailures,+ restarts: values.playerFrameLoadRestarts,+ playingState: values.playingState,+ ...getPlayerFrameLoadDiagnostics(iframe),+ })+ },restartPlayerFrameLoad: () => {posthog.capture('replay player frame load restarted', {sessionRecordingId: props.sessionRecordingId,