: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): render recordings faithfully in the rasterizer (#106498)
Tue Haulundb36b60860e9f
diff --git a/Dockerfile.recording-rasterizer b/Dockerfile.recording-rasterizerindex 6efd902eea3f..53647d2bc9cf 100644--- a/Dockerfile.recording-rasterizer+++ b/Dockerfile.recording-rasterizer@@ -112,6 +112,12 @@ RUN apt-get update && \"libssl3=3.0.*" \# ffmpeg intentionally unpinned: tracks the latest bookworm candidate so security point-updates flow in on rebuild"ffmpeg" \+ # Fonts for recorded pages: without them CJK, Thai, Indic and emoji render as empty boxes, and common UI font+ # stacks (Arial, Helvetica, Roboto) fall back to the wider DejaVu, which changes how text wraps and truncates.+ fonts-liberation \+ fonts-noto-cjk \+ fonts-noto-color-emoji \+ fonts-noto-core \# Shared libraries required by chrome-headless-shelllibasound2 \libatk-bridge2.0-0 \diff --git a/common/replay-headless/src/__tests__/footer-url.test.ts b/common/replay-headless/src/__tests__/footer-url.test.tsnew file mode 100644index 000000000000..3b0c7079de81--- /dev/null+++ b/common/replay-headless/src/__tests__/footer-url.test.ts@@ -0,0 +1,13 @@+import { footerUrl } from '../footer-url'++describe('footerUrl', () => {+ it.each([+ ['https://app.example.com/a/b?utm_source=x&state=abc', 'https://app.example.com/a/b'],+ ['https://app.example.com/a?q=1#panel=access', 'https://app.example.com/a#panel=access'],+ ['https://app.example.com/a#x?not=query', 'https://app.example.com/a#x?not=query'],+ ['https://app.example.com/a', 'https://app.example.com/a'],+ ['not a url?q=1#h', 'not a url#h'],+ ])('drops the query string from %s', (href, expected) => {+ expect(footerUrl(href)).toBe(expected)+ })+})diff --git a/common/replay-headless/src/__tests__/playback-controller.test.ts b/common/replay-headless/src/__tests__/playback-controller.test.tsindex 535132106aba..9d6e53534cab 100644--- a/common/replay-headless/src/__tests__/playback-controller.test.ts+++ b/common/replay-headless/src/__tests__/playback-controller.test.ts@@ -1,7 +1,7 @@import type { RecordingSegment } from '@posthog/replay-shared'import type { HostBridge } from '../host-bridge'-import { PlaybackController } from '../playback-controller'+import { PlaybackController, type PlaybackWindow } from '../playback-controller'function makeSegment(overrides: Partial<RecordingSegment> & Pick<RecordingSegment, 'startTimestamp' | 'endTimestamp'>@@ -37,19 +37,23 @@ function mockReplayer() {}}+function oneWindow(replayer: ReturnType<typeof mockReplayer>, firstTimestamp: number): PlaybackWindow[] {+ return [{ windowId: 1, replayer: replayer as any, firstTimestamp, lastTimestamp: Number.MAX_SAFE_INTEGER }]+}+describe('PlaybackController', () => {describe('lifecycle', () => {it('starts not stopped', () => {const replayer = mockReplayer()const bridge = mockBridge()- const controller = new PlaybackController(replayer as any, [], 0, {}, bridge)+ const controller = new PlaybackController(oneWindow(replayer, 0), [], 0, {}, bridge)expect(controller.isStopped).toBe(false)})it('signals ended on stop()', () => {const replayer = mockReplayer()const bridge = mockBridge()- const controller = new PlaybackController(replayer as any, [], 0, {}, bridge)+ const controller = new PlaybackController(oneWindow(replayer, 0), [], 0, {}, bridge)controller.stop()@@ -60,7 +64,7 @@ describe('PlaybackController', () => {it('stop() is idempotent', () => {const replayer = mockReplayer()const bridge = mockBridge()- const controller = new PlaybackController(replayer as any, [], 0, {}, bridge)+ const controller = new PlaybackController(oneWindow(replayer, 0), [], 0, {}, bridge)controller.stop()controller.stop()@@ -72,7 +76,7 @@ describe('PlaybackController', () => {it('calls replayer.play with startOffset on start()', () => {const replayer = mockReplayer()const bridge = mockBridge()- const controller = new PlaybackController(replayer as any, [], 0, {}, bridge)+ const controller = new PlaybackController(oneWindow(replayer, 0), [], 0, {}, bridge)controller.start(5000)@@ -84,7 +88,7 @@ describe('PlaybackController', () => {it('stops when replayer emits finish', () => {const replayer = mockReplayer()const bridge = mockBridge()- const _controller = new PlaybackController(replayer as any, [], 0, {}, bridge)+ const _controller = new PlaybackController(oneWindow(replayer, 0), [], 0, {}, bridge)replayer._emit('finish')@@ -99,7 +103,7 @@ describe('PlaybackController', () => {const bridge = mockBridge()// firstTimestamp=1000, endOffsetS=4 → absolute cutoff at 1000 + 4*1000 = 5000const _controller = new PlaybackController(- replayer as any,+ oneWindow(replayer, 1000),[],1000,{@@ -121,7 +125,7 @@ describe('PlaybackController', () => {it('does not register event-cast listener when no endOffsetS', () => {const replayer = mockReplayer()const bridge = mockBridge()- new PlaybackController(replayer as any, [], 0, {}, bridge)+ new PlaybackController(oneWindow(replayer, 0), [], 0, {}, bridge)const eventCastCalls = replayer.on.mock.calls.filter((c: any[]) => c[0] === 'event-cast')expect(eventCastCalls).toHaveLength(0)@@ -136,7 +140,7 @@ describe('PlaybackController', () => {const replayer = mockReplayer()const bridge = mockBridge()const segments = [makeSegment({ startTimestamp: 0, endTimestamp: 5000, isActive: false, kind: 'gap' })]- const controller = new PlaybackController(replayer as any, segments, 0, {}, bridge)+ const controller = new PlaybackController(oneWindow(replayer, 0), segments, 0, {}, bridge)controller.start(0)rafSpy.mock.calls[0][0](0)@@ -151,7 +155,7 @@ describe('PlaybackController', () => {const rafSpy = jest.spyOn(window, 'requestAnimationFrame').mockImplementation(() => 0)const replayer = mockReplayer()const bridge = mockBridge()- const controller = new PlaybackController(replayer as any, [], 0, {}, bridge)+ const controller = new PlaybackController(oneWindow(replayer, 0), [], 0, {}, bridge)controller.start(0)rafSpy.mock.calls[0][0](0)@@ -179,7 +183,7 @@ describe('PlaybackController', () => {}),]const controller = new PlaybackController(- replayer as any,+ oneWindow(replayer, 1000),segments,1000,{@@ -225,7 +229,7 @@ describe('PlaybackController', () => {replayer.getCurrentTime.mockReturnValue(6000)const controller = new PlaybackController(- replayer as any,+ oneWindow(replayer, 1000),segments,1000,{@@ -264,7 +268,7 @@ describe('PlaybackController', () => {replayer.getCurrentTime.mockReturnValue(2000)const controller = new PlaybackController(- replayer as any,+ oneWindow(replayer, 1000),segments,1000,{@@ -284,4 +288,113 @@ describe('PlaybackController', () => {jest.restoreAllMocks()})})++ describe('multiple windows', () => {+ function twoWindows(): {+ a: ReturnType<typeof mockReplayer>+ b: ReturnType<typeof mockReplayer>+ windows: PlaybackWindow[]+ segments: RecordingSegment[]+ } {+ const a = mockReplayer()+ const b = mockReplayer()+ return {+ a,+ b,+ windows: [+ { windowId: 1, replayer: a as any, firstTimestamp: 1000, lastTimestamp: 5000 },+ { windowId: 2, replayer: b as any, firstTimestamp: 3000, lastTimestamp: 9000 },+ ],+ segments: [+ makeSegment({ startTimestamp: 1000, endTimestamp: 5000, windowId: 1 }),+ makeSegment({ startTimestamp: 5000, endTimestamp: 9000, windowId: 2 }),+ ],+ }+ }++ it('hands playback to the window that owns the next segment', () => {+ let rafCallback: FrameRequestCallback | null = null+ jest.spyOn(window, 'requestAnimationFrame').mockImplementation((cb) => {+ rafCallback = cb+ return 0+ })+ const { a, b, windows, segments } = twoWindows()+ const controller = new PlaybackController(windows, segments, 1000, {}, mockBridge())+ const shown: number[] = []+ controller.onWindowChange((tab) => shown.push(tab.windowId))++ controller.start(0)+ a.getCurrentTime.mockReturnValue(4500)+ rafCallback!(0)++ expect(a.pause).toHaveBeenCalled()+ expect(b.play).toHaveBeenCalledWith(2500)+ expect(shown).toEqual([1, 2])+ expect(controller.getFrameSessionMs()).toEqual([4500])++ jest.restoreAllMocks()+ })++ it('starts in the window that owns the start offset', () => {+ jest.spyOn(window, 'requestAnimationFrame').mockImplementation(() => 0)+ const { a, b, windows, segments } = twoWindows()+ const controller = new PlaybackController(windows, segments, 1000, {}, mockBridge())++ controller.start(6000)++ expect(controller.activeWindow.windowId).toBe(2)+ expect(b.play).toHaveBeenCalledWith(4000)+ expect(a.play).not.toHaveBeenCalled()++ jest.restoreAllMocks()+ })++ it('switches windows when an inactivity skip lands in another window', () => {+ let rafCallback: FrameRequestCallback | null = null+ jest.spyOn(window, 'requestAnimationFrame').mockImplementation((cb) => {+ rafCallback = cb+ return 0+ })+ const { a, b, windows } = twoWindows()+ const segments = [+ makeSegment({ startTimestamp: 1000, endTimestamp: 3000, windowId: 1 }),+ makeSegment({ startTimestamp: 3000, endTimestamp: 6000, windowId: 1, isActive: false, kind: 'gap' }),+ makeSegment({ startTimestamp: 6000, endTimestamp: 9000, windowId: 2 }),+ ]+ const controller = new PlaybackController(windows, segments, 1000, { skipInactivity: true }, mockBridge())++ controller.start(0)+ a.getCurrentTime.mockReturnValue(2500)+ rafCallback!(0)++ expect(controller.activeWindow.windowId).toBe(2)+ expect(b.play).toHaveBeenCalledWith(3000)++ jest.restoreAllMocks()+ })++ it('does not hand over to a window that has already run out of events', () => {+ const { a, windows, segments } = twoWindows()+ const exhausted = windows.map((tab) => (tab.windowId === 2 ? { ...tab, lastTimestamp: 3500 } : tab))+ const controller = new PlaybackController(exhausted, segments, 1000, {}, mockBridge())++ a.getCurrentTime.mockReturnValue(4000)+ a._emit('finish')++ expect(controller.isStopped).toBe(true)+ })++ it('continues in another window when the one on screen runs out of events', () => {+ const { a, b, windows, segments } = twoWindows()+ const bridge = mockBridge()+ const controller = new PlaybackController(windows, segments, 1000, {}, bridge)++ a.getCurrentTime.mockReturnValue(3000)+ a._emit('finish')++ expect(controller.isStopped).toBe(false)+ expect(controller.activeWindow.windowId).toBe(2)+ expect(b.play).toHaveBeenCalledWith(2000)+ })+ })})diff --git a/common/replay-headless/src/footer-url.ts b/common/replay-headless/src/footer-url.tsnew file mode 100644index 000000000000..4e898cb8a115--- /dev/null+++ b/common/replay-headless/src/footer-url.ts@@ -0,0 +1,15 @@+/** Drop the query string, which often runs to hundreds of characters of tracking and state parameters. */+export function footerUrl(href: string): string {+ try {+ const url = new URL(href)+ url.search = ''+ return url.toString()+ } catch {+ const hashAt = href.indexOf('#')+ const queryAt = href.indexOf('?')+ if (queryAt === -1 || (hashAt !== -1 && hashAt < queryAt)) {+ return href+ }+ return href.slice(0, queryAt) + (hashAt === -1 ? '' : href.slice(hashAt))+ }+}diff --git a/common/replay-headless/src/index.html b/common/replay-headless/src/index.htmlindex 48ef4398aa84..4937bc498d91 100644--- a/common/replay-headless/src/index.html+++ b/common/replay-headless/src/index.html@@ -22,22 +22,27 @@.PlayerFrame__content { position: absolute; top: 0; left: 0; }#metadata-footer {display: none;- height: 32px;background: #000;color: #fff;font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;- font-size: 14px;- padding: 4px 8px 8px 8px;+ font-size: 22px;+ padding: 6px 12px;+ /* Fixed widths in the monospace font keep the first row's fields from moving as their values change. */+ grid-template-columns: 1fr 13ch 16ch 25ch 1fr;+ grid-template-areas: ". rect window status ." "url url url url url";align-items: center;- justify-content: center;- gap: 16px;+ column-gap: 16px;white-space: nowrap;overflow: hidden;}#metadata-footer .label { font-weight: bold; }- #metadata-footer .url { overflow: hidden; text-overflow: ellipsis; }+ #metadata-footer .rect { grid-area: rect; }+ #metadata-footer .window { grid-area: window; }+ #metadata-footer .url { grid-area: url; min-width: 0; overflow: hidden; text-overflow: ellipsis; }+ #metadata-footer .status { grid-area: status; }#metadata-footer .status-ended { font-weight: bold; color: #4ade80; }#metadata-footer .status-idle { font-weight: bold; color: #facc15; }+ #metadata-footer .status-active { font-weight: bold; color: #60a5fa; }.PlayerFrame__content .replayer-wrapper { position: relative; }.PlayerFrame__content iframe { background-color: white; border: 0; }.replayer-mouse { position: absolute; width: 20px; height: 20px; background-size: contain; background-position: center center; background-repeat: no-repeat; background-image: url(data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9JzMwMHB4JyB3aWR0aD0nMzAwcHgnICBmaWxsPSIjMDAwMDAwIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGRhdGEtbmFtZT0iTGF5ZXIgMSIgdmlld0JveD0iMCAwIDUwIDUwIiB4PSIwcHgiIHk9IjBweCI+PHRpdGxlPkRlc2lnbl90bnA8L3RpdGxlPjxwYXRoIGQ9Ik00OC43MSw0Mi45MUwzNC4wOCwyOC4yOSw0NC4zMywxOEExLDEsMCwwLDAsNDQsMTYuMzlMMi4zNSwxLjA2QTEsMSwwLDAsMCwxLjA2LDIuMzVMMTYuMzksNDRhMSwxLDAsMCwwLDEuNjUuMzZMMjguMjksMzQuMDgsNDIuOTEsNDguNzFhMSwxLDAsMCwwLDEuNDEsMGw0LjM4LTQuMzhBMSwxLDAsMCwwLDQ4LjcxLDQyLjkxWm0tNS4wOSwzLjY3TDI5LDMyYTEsMSwwLDAsMC0xLjQxLDBsLTkuODUsOS44NUwzLjY5LDMuNjlsMzguMTIsMTRMMzIsMjcuNThBMSwxLDAsMCwwLDMyLDI5TDQ2LjU5LDQzLjYyWiI+PC9wYXRoPjwvc3ZnPg==); border-color: transparent; transition: left .05s linear, top .05s linear; }@@ -51,9 +56,10 @@<div class="PlayerFrame"><div class="PlayerFrame__content-wrapper"><div class="PlayerFrame__content"></div></div><div id="metadata-footer">+ <span class="rect"><span class="label">REC_T:</span> <span id="meta-rect"></span></span>+ <span class="window"><span class="label">WINDOW:</span> <span id="meta-window"></span></span><span class="url"><span class="label">URL:</span> <span id="meta-url"></span></span>- <span><span class="label">REC_T:</span> <span id="meta-rect"></span></span>- <span id="meta-status"></span>+ <span class="status"><span class="label">STATUS:</span> <span id="meta-status"></span></span></div></div><!-- INLINE_JS -->diff --git a/common/replay-headless/src/metadata-footer.ts b/common/replay-headless/src/metadata-footer.tsindex 4609858ea160..5a70cecc4810 100644--- a/common/replay-headless/src/metadata-footer.ts+++ b/common/replay-headless/src/metadata-footer.ts@@ -1,49 +1,60 @@-import type { Replayer } from 'posthog-js/rrweb'import type { eventWithTime } from 'posthog-js/rrweb-types'-import type { RecordingSegment } from '@posthog/replay-shared'+import { getHrefFromSnapshot, type RecordingSegment } from '@posthog/replay-shared'+import { footerUrl } from './footer-url'import type { PlaybackController } from './playback-controller'-import { getMetaHref } from './replayer-factory'+import { METADATA_FOOTER_HEIGHT_PX } from './protocol'+import type { ReplayerWindow } from './replayer-factory'/**- * Renders an overlay footer showing the current page URL, recording- * time offset, and idle/ended status. Used by the AI summary pipeline- * to correlate video frames with page context.+ * Renders an overlay footer showing the recording time offset, which window is on screen, that window's+ * page URL, and idle/ended status. Used by the AI summary pipeline to correlate video frames with page+ * context.*/export class MetadataFooter {- private currentURL = ''+ private urlByWindow = new Map<number, string>()+ private numberByWindow = new Map<number, number>()private footerEl: HTMLElement | nullprivate metaUrlEl: HTMLElement | nullprivate metaRectEl: HTMLElement | null+ private metaWindowEl: HTMLElement | nullprivate metaStatusEl: HTMLElement | nullconstructor(- private replayer: Replayer,+ private windows: ReplayerWindow[],private segments: RecordingSegment[],private firstTimestamp: number,- private controller: PlaybackController,- initialURL: string+ private controller: PlaybackController) {- this.currentURL = initialURLthis.footerEl = document.getElementById('metadata-footer')this.metaUrlEl = document.getElementById('meta-url')this.metaRectEl = document.getElementById('meta-rect')+ this.metaWindowEl = document.getElementById('meta-window')this.metaStatusEl = document.getElementById('meta-status')- this.replayer.on('event-cast', (event: eventWithTime) => {- const href = getMetaHref(event)- if (href) {- this.currentURL = href- }- })+ windows.forEach((tab, index) => this.numberByWindow.set(tab.windowId, index + 1))+ for (const tab of windows) {+ this.urlByWindow.set(tab.windowId, tab.initialURL)+ // Custom events carry the URL of in-page navigations, which record no Meta event.+ tab.replayer.on('event-cast', (event: eventWithTime) => {+ const href = getHrefFromSnapshot(event)+ if (href) {+ this.urlByWindow.set(tab.windowId, href)+ }+ })+ }+ // The footer's own frame callback runs before the controller's, so without this the frame that switches+ // windows would show the new window's page under the old window's number and URL.+ this.controller.onWindowChange(() => this.update())}start(): void {if (!this.footerEl) {return}- this.footerEl.style.display = 'flex'+ this.footerEl.style.display = 'grid'+ this.footerEl.style.height = `${METADATA_FOOTER_HEIGHT_PX}px`const onFrame = (): void => {this.update()@@ -55,17 +66,20 @@ export class MetadataFooter {}private update(): void {- if (!this.metaUrlEl || !this.metaRectEl || !this.metaStatusEl) {+ if (!this.metaUrlEl || !this.metaRectEl || !this.metaWindowEl || !this.metaStatusEl) {return}- this.metaUrlEl.textContent = this.currentURL- this.metaRectEl.textContent = (Math.max(0, this.replayer.getCurrentTime()) / 1000).toFixed(0)+ const active = this.controller.activeWindow+ const sessionMs = Math.max(0, this.controller.currentSessionMs())+ this.metaRectEl.textContent = (sessionMs / 1000).toFixed(0)+ this.metaWindowEl.textContent = `${this.numberByWindow.get(active.windowId)} of ${this.windows.length}`+ this.metaUrlEl.textContent = footerUrl(this.urlByWindow.get(active.windowId) ?? '')if (this.controller.isStopped) {this.metaStatusEl.className = 'status-ended'this.metaStatusEl.textContent = '[RECORDING ENDED]'} else {- const ts = this.firstTimestamp + Math.max(0, this.replayer.getCurrentTime())+ const ts = this.firstTimestamp + sessionMsconst isIdle = this.segments.some((seg) => !seg.isActive && ts >= seg.startTimestamp && ts <= seg.endTimestamp)@@ -73,8 +87,8 @@ export class MetadataFooter {this.metaStatusEl.className = 'status-idle'this.metaStatusEl.textContent = '[IDLE]'} else {- this.metaStatusEl.className = ''- this.metaStatusEl.textContent = ''+ this.metaStatusEl.className = 'status-active'+ this.metaStatusEl.textContent = '[ACTIVE]'}}}diff --git a/common/replay-headless/src/playback-controller.ts b/common/replay-headless/src/playback-controller.tsindex 75857c7fc2e1..2fc1bde7c4ca 100644--- a/common/replay-headless/src/playback-controller.ts+++ b/common/replay-headless/src/playback-controller.ts@@ -6,32 +6,53 @@ import type { RecordingSegment } from '@posthog/replay-shared'import type { HostBridge } from './host-bridge'import { PLAYER_FRAME_TIMELINE_KEY } from './protocol'+/** One browser tab or window of the recording, replayed on its own timeline. */+export interface PlaybackWindow {+ windowId: number+ replayer: Replayer+ /** Timestamp of the tab's first event, which is the zero of its replayer's clock. */+ firstTimestamp: number+ /** Timestamp of the tab's last event, after which its replayer has nothing left to show. */+ lastTimestamp: number+}+/**- * Controls playback lifecycle: starts the replayer, skips inactive- * segments, and stops when the recording finishes or a configured- * end timestamp is reached.+ * Controls playback lifecycle: starts the replayer of the tab on screen, switches windows as the+ * recording's segments move between tabs, skips inactive segments, and stops when the recording finishes+ * or a configured end timestamp is reached.+ *+ * Each tab has its own replayer, as in the web player: rrweb node ids are only unique within a tab,+ * so one replayer fed every tab's events applies one tab's mutations to another tab's DOM.*/export class PlaybackController {private stopped = falseprivate frameSessionMs: number[] = []+ private active: PlaybackWindow+ private windowsById: Map<number, PlaybackWindow>+ private windowChangeListeners: ((tab: PlaybackWindow) => void)[] = []constructor(- private replayer: Replayer,+ windows: PlaybackWindow[],private segments: RecordingSegment[],private firstTimestamp: number,private options: { skipInactivity?: boolean; endOffsetS?: number },private bridge: HostBridge) {- this.replayer.on('finish', () => this.stop())-- if (this.options.endOffsetS != null) {- const endTs = this.firstTimestamp + this.options.endOffsetS * 1000- this.replayer.on('event-cast', (event: eventWithTime) => {- if (event.timestamp >= endTs) {- this.replayer.pause()- this.stop()- }- })+ this.windowsById = new Map(windows.map((tab) => [tab.windowId, tab]))+ this.active = windows[0]++ for (const tab of windows) {+ tab.replayer.on('finish', () => this.onFinish(tab))++ if (this.options.endOffsetS != null) {+ const endTs = this.firstTimestamp + this.options.endOffsetS * 1000+ tab.replayer.on('event-cast', (event: eventWithTime) => {+ if (tab === this.active && event.timestamp >= endTs) {+ tab.replayer.pause()+ this.stop()+ }+ })+ }}}@@ -39,9 +60,23 @@ export class PlaybackController {return this.stopped}+ get activeWindow(): PlaybackWindow {+ return this.active+ }++ onWindowChange(listener: (tab: PlaybackWindow) => void): void {+ this.windowChangeListeners.push(listener)+ }++ /** Where playback is, in milliseconds since the recording started. */+ currentSessionMs(): number {+ return this.currentTimestamp() - this.firstTimestamp+ }+start(startOffset: number): void {+ const ts = this.firstTimestamp + startOffset+ this.activate(this.windowAt(ts) ?? this.active, ts)this.startFrameLoop()- this.replayer.play(startOffset)}getFrameSessionMs(): number[] {@@ -57,10 +92,63 @@ export class PlaybackController {this.bridge.signalEnded()}+ private currentTimestamp(): number {+ return this.active.firstTimestamp + Math.max(0, this.active.replayer.getCurrentTime())+ }++ /** The tab that owns the recording at `ts`, preferring an active segment where two meet. */+ private windowAt(ts: number): PlaybackWindow | undefined {+ let fallback: PlaybackWindow | undefined+ for (const seg of this.segments) {+ if (ts < seg.startTimestamp || ts > seg.endTimestamp || seg.windowId == null) {+ continue+ }+ const tab = this.windowsById.get(seg.windowId)+ if (!tab) {+ continue+ }+ if (seg.isActive) {+ return tab+ }+ // A merged inactive run keeps its first window's id even after that window has run out of events.+ if (ts <= tab.lastTimestamp) {+ fallback ??= tab+ }+ }+ return fallback+ }++ private activate(tab: PlaybackWindow, ts: number): void {+ this.active.replayer.pause()+ this.active = tab+ tab.replayer.play(Math.max(0, ts - tab.firstTimestamp))+ for (const listener of this.windowChangeListeners) {+ listener(tab)+ }+ }++ /** A tab runs out of events before the session ends whenever the user moved to another tab. */+ private onFinish(tab: PlaybackWindow): void {+ if (this.stopped || tab !== this.active) {+ return+ }+ const ts = this.currentTimestamp()+ for (const seg of this.segments) {+ const next = seg.windowId != null ? this.windowsById.get(seg.windowId) : undefined+ const resumeAt = Math.max(ts, seg.startTimestamp)+ // A window with nothing left after resumeAt would finish at once and hand playback straight back.+ if (next && next !== tab && seg.endTimestamp > ts && next.lastTimestamp > resumeAt) {+ this.activate(next, resumeAt)+ return+ }+ }+ this.stop()+ }+/**- * Record where playback is on every captured frame, and skip inactive segments as they come up.- * Under puppeteer-capture's virtual time, rAF fires once per beginFrame call, so this is- * deterministic and each tick is exactly one frame of the rendered video.+ * Record where playback is on every captured frame, switch to the tab that owns that moment, and+ * skip inactive segments as they come up. Under puppeteer-capture's virtual time, rAF fires once per+ * beginFrame call, so this is deterministic and each tick is exactly one frame of the rendered video.** The sample is taken before the skip: a skip costs the frame it happens on, and recording the* position after the jump would hide that frame from the timeline the same way computing video@@ -75,17 +163,25 @@ export class PlaybackController {if (this.stopped) {return}- const current = this.replayer.getCurrentTime()- this.frameSessionMs.push(Math.round(current))+ const ts = this.currentTimestamp()+ this.frameSessionMs.push(Math.round(ts - this.firstTimestamp))++ let target = tsif (this.options.skipInactivity) {- const ts = this.firstTimestamp + currentconst inactiveSeg = this.segments.find((seg: RecordingSegment) => !seg.isActive && ts >= seg.startTimestamp && ts <= seg.endTimestamp)if (inactiveSeg) {- this.replayer.play(inactiveSeg.endTimestamp - this.firstTimestamp)+ target = inactiveSeg.endTimestamp}}++ const owner = this.windowAt(target)+ if (owner && owner !== this.active) {+ this.activate(owner, target)+ } else if (target !== ts) {+ this.active.replayer.play(target - this.active.firstTimestamp)+ }requestAnimationFrame(onFrame)}requestAnimationFrame(onFrame)diff --git a/common/replay-headless/src/protocol.ts b/common/replay-headless/src/protocol.tsindex d589e19f4544..2b7f574a0be1 100644--- a/common/replay-headless/src/protocol.ts+++ b/common/replay-headless/src/protocol.ts@@ -12,6 +12,11 @@* so both sides are compile-time checked against the same contract.*/+// --- Constants ---++/** Height of the metadata footer. The rasterizer adds it to the capture viewport, so the recording keeps its full size. */+export const METADATA_FOOTER_HEIGHT_PX = 80+// --- Types ---export interface ViewportEvent {diff --git a/common/replay-headless/src/replayer-factory.ts b/common/replay-headless/src/replayer-factory.tsindex b7bdae492626..b71c0b35b89c 100644--- a/common/replay-headless/src/replayer-factory.ts+++ b/common/replay-headless/src/replayer-factory.ts@@ -9,7 +9,9 @@ import {HLSPlayerPlugin,noOpTelemetry,processAllSnapshots,+ speedDependentStyleRules,createSegments,+ getHrefFromSnapshot,mapSnapshotsToWindowId,mergeInactiveSegments,type ProcessingCache,@@ -19,22 +21,49 @@ import {import { loadAllSources } from './data-loader'import type { HostBridge } from './host-bridge'+import type { PlaybackWindow } from './playback-controller'import type { PlayerConfig, ViewportEvent } from './types'-/** Extract the page URL from an rrweb Meta event, if present. */-export function getMetaHref(event: eventWithTime): string | undefined {- if (event.type === EventType.Meta) {- return (event.data as { href?: string })?.href+export interface ReplayerWindow extends PlaybackWindow {+ /** The element the window's replayer renders into, shown only while the window is on screen. */+ root: HTMLElement+ /** The first page URL the window recorded, before any event has played. */+ initialURL: string+}++/** Why no window could be replayed: nothing loaded yet, or snapshots that no window can be drawn from. */+export type ReplayerSetupFailure = 'no_snapshots' | 'no_full_snapshot'++/** Each window keeps its own iframe and DOM alive for the whole render, and window ids come from the recording. */+const MAX_REPLAYED_WINDOWS = 20++/** The windows with the most active time, which are the ones worth their memory when a session opened too many. */+function busiestWindowIds(segments: RecordingSegment[], candidates: Set<number>, limit: number): Set<number> {+ const activeMs = new Map<number, number>()+ for (const seg of segments) {+ if (seg.windowId != null && candidates.has(seg.windowId)) {+ activeMs.set(seg.windowId, (activeMs.get(seg.windowId) ?? 0) + (seg.isActive ? seg.durationMs : 0))+ }}- return undefined+ const ranked = [...activeMs.entries()].sort((a, b) => b[1] - a[1]).slice(0, limit)+ return new Set(ranked.map(([windowId]) => windowId))+}++function firstHref(events: eventWithTime[]): string {+ for (const event of events) {+ const href = getHrefFromSnapshot(event)+ if (href) {+ return href+ }+ }+ return ''}export interface ReplayerSetup {- replayer: Replayer- events: eventWithTime[]+ /** Ordered by when each window first appears in the recording. */+ windows: ReplayerWindow[]segments: RecordingSegment[]firstTimestamp: number- initialURL: string}function buildViewportLookup(events: ViewportEvent[]): (timestamp: number) => ViewportResolution | undefined {@@ -66,15 +95,15 @@ function buildViewportLookup(events: ViewportEvent[]): (timestamp: number) => Vi/*** Load recording data, process snapshots, build segments, and create- * an rrweb Replayer — but don't start playback.+ * one rrweb Replayer per recorded window — but don't start playback.*- * Returns null if no snapshots are available after processing.+ * Returns why not when there are no snapshots, or no window has a full snapshot to build a page from.*/-export async function createReplayer(+export async function createReplayers(config: PlayerConfig,rootEl: HTMLElement,bridge: HostBridge-): Promise<ReplayerSetup | null> {+): Promise<ReplayerSetup | ReplayerSetupFailure> {const { sources, snapshotsBySource } = await loadAllSources(config, (loaded, total) =>bridge.reportLoadingProgress(loaded, total))@@ -92,7 +121,7 @@ export async function createReplayer()if (!snapshots.length) {- return null+ return 'no_snapshots'}const snapshotsByWindowId = mapSnapshotsToWindowId(snapshots)@@ -105,31 +134,52 @@ export async function createReplayer()const segments = mergeInactiveSegments(rawSegments)const firstTimestamp = snapshots[0].timestamp- const events: eventWithTime[] = [...snapshots]-- const replayer = new Replayer(events, {- root: rootEl,- ...COMMON_REPLAYER_CONFIG,- insertStyleRules: [- ...(COMMON_REPLAYER_CONFIG.insertStyleRules || []),- ...(config.playbackSpeed >= 2- ? ['*, *::before, *::after { animation: none !important; transition: none !important; }']- : []),- ],- mouseTail: config.mouseTail,- useVirtualDom: false,- plugins: [CorsPlugin, HLSPlayerPlugin, AudioMuteReplayerPlugin(true), CanvasReplayerPlugin(events)],- speed: config.playbackSpeed,- })-- let initialURL = ''- for (const e of events) {- const href = getMetaHref(e)- if (href) {- initialURL = href- break+ // rrweb cannot build a page without a full snapshot, and its Replayer throws on fewer than two events.+ const replayableIds = new Set(+ Object.entries(snapshotsByWindowId)+ .filter(([, events]) => events.length >= 2 && events.some((event) => event.type === EventType.FullSnapshot))+ .map(([windowId]) => Number(windowId))+ )+ const keptWindowIds =+ replayableIds.size > MAX_REPLAYED_WINDOWS+ ? busiestWindowIds(segments, replayableIds, MAX_REPLAYED_WINDOWS)+ : replayableIds+ const windows: ReplayerWindow[] = []+ for (const [windowId, windowEvents] of Object.entries(snapshotsByWindowId)) {+ if (!keptWindowIds.has(Number(windowId))) {+ continue}+ const root = document.createElement('div')+ // Hidden but still laid out: a display:none iframe drops the scroll positions its fast-forward sets.+ root.style.position = 'absolute'+ root.style.inset = '0'+ root.style.visibility = 'hidden'+ rootEl.appendChild(root)+ const replayer = new Replayer(windowEvents, {+ root,+ ...COMMON_REPLAYER_CONFIG,+ insertStyleRules: [+ ...(COMMON_REPLAYER_CONFIG.insertStyleRules || []),+ ...speedDependentStyleRules(config.playbackSpeed),+ ],+ mouseTail: config.mouseTail,+ useVirtualDom: false,+ plugins: [CorsPlugin, HLSPlayerPlugin, AudioMuteReplayerPlugin(true), CanvasReplayerPlugin(windowEvents)],+ speed: config.playbackSpeed,+ })+ windows.push({+ windowId: Number(windowId),+ replayer,+ root,+ initialURL: firstHref(windowEvents),+ firstTimestamp: windowEvents[0].timestamp,+ lastTimestamp: windowEvents[windowEvents.length - 1].timestamp,+ })+ }+ if (!windows.length) {+ return 'no_full_snapshot'}+ windows.sort((a, b) => a.firstTimestamp - b.firstTimestamp)- return { replayer, events, segments, firstTimestamp, initialURL }+ return { windows, segments, firstTimestamp }}diff --git a/common/replay-headless/src/standalone-player.ts b/common/replay-headless/src/standalone-player.tsindex a19774b55ea6..b076d4fe4453 100644--- a/common/replay-headless/src/standalone-player.ts+++ b/common/replay-headless/src/standalone-player.ts@@ -2,32 +2,35 @@ import { DataLoadError } from './data-loader'import { HostBridge } from './host-bridge'import { MetadataFooter } from './metadata-footer'import { PlaybackController } from './playback-controller'-import { createReplayer } from './replayer-factory'+import { METADATA_FOOTER_HEIGHT_PX } from './protocol'+import { createReplayers } from './replayer-factory'import type { PlayerConfig } from './types'import { ViewportScaler } from './viewport-scaler'async function init(config: PlayerConfig, bridge: HostBridge): Promise<void> {const contentEl = document.querySelector('.PlayerFrame__content') as HTMLElement- const setup = await createReplayer(config, contentEl, bridge)- if (!setup) {+ const setup = await createReplayers(config, contentEl, bridge)+ if (setup === 'no_snapshots' || setup === 'no_full_snapshot') {+ // Blocks can still be landing when nothing loaded, so that stays retryable. Loaded snapshots without a full+ // snapshot never gain one on a retry, and each attempt would render the same blank video.+ const noFullSnapshot = setup === 'no_full_snapshot'bridge.setError({code: 'NO_SNAPSHOTS',- message: 'No snapshots after processing',- retryable: true,+ message: noFullSnapshot ? 'No window has a full snapshot to render' : 'No snapshots after processing',+ retryable: !noFullSnapshot,})bridge.signalEnded()return}- const { replayer, segments, firstTimestamp } = setup+ const { windows, segments, firstTimestamp } = setup- const footerHeight = config.showMetadataFooter ? 32 : 0+ const footerHeight = config.showMetadataFooter ? METADATA_FOOTER_HEIGHT_PX : 0const scaler = new ViewportScaler(contentEl, footerHeight)- scaler.attachToReplayer(replayer)const controller = new PlaybackController(- replayer,+ windows,segments,firstTimestamp,{@@ -36,9 +39,18 @@ async function init(config: PlayerConfig, bridge: HostBridge): Promise<void> {},bridge)+ for (const tab of windows) {+ scaler.attachToReplayer(tab.replayer, () => controller.activeWindow === tab)+ }+ controller.onWindowChange((onScreen) => {+ for (const tab of windows) {+ tab.root.style.visibility = tab === onScreen ? 'visible' : 'hidden'+ }+ scaler.fitReplayer(onScreen.replayer)+ })if (config.showMetadataFooter) {- const footer = new MetadataFooter(replayer, segments, firstTimestamp, controller, setup.initialURL)+ const footer = new MetadataFooter(windows, segments, firstTimestamp, controller)footer.start()}diff --git a/common/replay-headless/src/viewport-scaler.ts b/common/replay-headless/src/viewport-scaler.tsindex 047196c11a49..48a27499661a 100644--- a/common/replay-headless/src/viewport-scaler.ts+++ b/common/replay-headless/src/viewport-scaler.ts@@ -31,15 +31,24 @@ export class ViewportScaler {this.contentEl.style.transform = `translate(${offsetX}px, ${offsetY}px) scale(${scale})`}- attachToReplayer(replayer: Replayer): void {+ /** Follow the replayer's size; with several windows only the one on screen may resize the content. */+ attachToReplayer(replayer: Replayer, isOnScreen: () => boolean = () => true): void {+ if (isOnScreen()) {+ this.fitReplayer(replayer)+ }++ replayer.on('resize', (dimension: { width: number; height: number }) => {+ if (isOnScreen()) {+ this.apply(dimension.width, dimension.height)+ }+ })+ }++ fitReplayer(replayer: Replayer): void {const iframeWidth = Number.parseFloat(replayer.iframe.width)const iframeHeight = Number.parseFloat(replayer.iframe.height)if (iframeWidth > 0 && iframeHeight > 0) {this.apply(iframeWidth, iframeHeight)}-- replayer.on('resize', (dimension: { width: number; height: number }) => {- this.apply(dimension.width, dimension.height)- })}}diff --git a/common/replay-shared/src/index.ts b/common/replay-shared/src/index.tsindex dfccb61fd5e3..1e5ab0c8fedd 100644--- a/common/replay-shared/src/index.ts+++ b/common/replay-shared/src/index.ts@@ -55,6 +55,7 @@ export {AudioMuteReplayerPlugin,CorsPlugin,COMMON_REPLAYER_CONFIG,+ speedDependentStyleRules,HLSPlayerPlugin,createHLSPlayerPlugin,WindowTitlePlugin,diff --git a/common/replay-shared/src/rrweb-plugins/index.ts b/common/replay-shared/src/rrweb-plugins/index.tsindex a740cb4bbc47..06c95b7e9521 100644--- a/common/replay-shared/src/rrweb-plugins/index.ts+++ b/common/replay-shared/src/rrweb-plugins/index.ts@@ -81,6 +81,18 @@ export const COMMON_REPLAYER_CONFIG: Partial<playerConfig> = {UNSAFE_replayCanvas: false,}+/**+ * rrweb does not speed CSS animations and transitions up with playback, so at high speeds they run behind the page.+ * Snap them to their end state instead: removing them outright leaves content a keyframe reveals stuck at opacity 0.+ */+export function speedDependentStyleRules(speed: number): string[] {+ return speed >= 2+ ? [+ '*, *::before, *::after { animation-duration: 1ms !important; animation-delay: 0s !important; animation-iteration-count: 1 !important; animation-fill-mode: forwards !important; transition-duration: 0s !important; transition-delay: 0s !important; }',+ ]+ : []+}+export { AudioMuteReplayerPlugin } from './audio-mute-plugin'export { WindowTitlePlugin } from './window-title-plugin'diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.tsindex adc08e7bdd7b..58e35c0b6f9d 100644--- a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts@@ -26,6 +26,7 @@ import { lemonToast } from '@posthog/lemon-ui'import {AudioMuteReplayerPlugin,COMMON_REPLAYER_CONFIG,+ speedDependentStyleRules,CanvasReplayerPlugin,CorsPlugin,SnapshotStore,@@ -2637,15 +2638,7 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(...COMMON_REPLAYER_CONFIG,insertStyleRules: [...(COMMON_REPLAYER_CONFIG.insertStyleRules || []),- // At high speeds, CSS animations/transitions aren't sped up by rrweb,- // causing visual artifacts. Snap them to their end state instead of suppressing- // them entirely — `animation: none` left content stuck at its pre-animation state- // (e.g. opacity: 0) on sites that use keyframes for content reveal.- ...(values.speed >= 2- ? [- '*, *::before, *::after { animation-duration: 1ms !important; animation-delay: 0s !important; animation-iteration-count: 1 !important; animation-fill-mode: forwards !important; transition-duration: 0s !important; transition-delay: 0s !important; }',- ]- : []),+ ...speedDependentStyleRules(values.speed),],// these two settings are attempts to improve performance of running two Replayers at once// the main player and a preview playerdiff --git a/nodejs/src/session-replay/recording-rasterizer/__tests__/request-interceptor.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/request-interceptor.test.tsindex 14a26e660023..8a5a45214641 100644--- a/nodejs/src/session-replay/recording-rasterizer/__tests__/request-interceptor.test.ts+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/request-interceptor.test.ts@@ -220,6 +220,7 @@ describe('RequestInterceptor', () => {expect(req.respond).toHaveBeenCalledWith({status: 200,contentType: 'text/css',+ headers: { 'access-control-allow-origin': '*' },body: 'body { color: red }',})})diff --git a/nodejs/src/session-replay/recording-rasterizer/capture/recorder.ts b/nodejs/src/session-replay/recording-rasterizer/capture/recorder.tsindex e4f92e0005e1..97c8245cf768 100644--- a/nodejs/src/session-replay/recording-rasterizer/capture/recorder.ts+++ b/nodejs/src/session-replay/recording-rasterizer/capture/recorder.ts@@ -1,4 +1,4 @@-import type { InactivityPeriod } from '@posthog/replay-headless/protocol'+import { type InactivityPeriod, METADATA_FOOTER_HEIGHT_PX } from '@posthog/replay-headless/protocol'import { config as defaultConfig } from '~/session-replay/recording-rasterizer/config'import { RasterizationError } from '~/session-replay/recording-rasterizer/errors'@@ -87,7 +87,7 @@ export async function rasterizeRecording(signal?.throwIfAborted()const viewport = {width: input.viewport_width || 1280,- height: input.viewport_height || 720,+ height: (input.viewport_height || 720) + (input.show_metadata_footer ? METADATA_FOOTER_HEIGHT_PX : 0),}const playerUrl = `${cfg.siteUrl}/player`const capturePage = await CapturePage.prepare(diff --git a/nodejs/src/session-replay/recording-rasterizer/capture/request-interceptor.ts b/nodejs/src/session-replay/recording-rasterizer/capture/request-interceptor.tsindex eeadb42e5a1f..1a524328f87c 100644--- a/nodejs/src/session-replay/recording-rasterizer/capture/request-interceptor.ts+++ b/nodejs/src/session-replay/recording-rasterizer/capture/request-interceptor.ts@@ -169,6 +169,9 @@ export class RequestInterceptor {await request.respond({status: resp.status,contentType: resp.headers['content-type'] || 'text/css',+ // A `<link crossorigin>` makes Chrome CORS-check this response, and without the header it+ // drops the stylesheet and the frame renders unstyled. The fetch above carries no credentials.+ headers: { 'access-control-allow-origin': '*' },body,})} catch (err) {diff --git a/nodejs/src/session-replay/recording-rasterizer/temporal/activities.ts b/nodejs/src/session-replay/recording-rasterizer/temporal/activities.tsindex 76af3846f326..164a3f79dca6 100644--- a/nodejs/src/session-replay/recording-rasterizer/temporal/activities.ts+++ b/nodejs/src/session-replay/recording-rasterizer/temporal/activities.ts@@ -5,6 +5,8 @@ import * as fs from 'fs/promises'import * as os from 'os'import * as path from 'path'+import { METADATA_FOOTER_HEIGHT_PX } from '@posthog/replay-headless/protocol'+import { BrowserPool } from '~/session-replay/recording-rasterizer/capture/browser-pool'import { rasterizeRecording } from '~/session-replay/recording-rasterizer/capture/recorder'import { config } from '~/session-replay/recording-rasterizer/config'@@ -28,8 +30,8 @@ function toActivityError(err: unknown): Error {if (rasterizationError) {// The code travels as the failure type either way, so a caller can tell a recording that can never render// (NO_SNAPSHOTS) from one that merely ran out of retries. Retryability stays the player's call: NO_SNAPSHOTS is- // retryable while a recording is still being ingested, so the code is only conclusive once Temporal has spent- // the attempts.+ // retryable while nothing has loaded, as the recording may still be ingesting, and final when no window has a+ // full snapshot to draw from.return rasterizationError.retryable? ApplicationFailure.retryable(rasterizationError.message, rasterizationError.code, rasterizationError): ApplicationFailure.nonRetryable(rasterizationError.message, rasterizationError.code, rasterizationError)@@ -169,6 +171,7 @@ async function rasterizeRecordingActivity(video_duration_s: result.capture_duration_s,playback_speed: result.playback_speed,show_metadata_footer: !!input.show_metadata_footer,+ footer_height_px: input.show_metadata_footer ? METADATA_FOOTER_HEIGHT_PX : 0,truncated: result.truncated,inactivity_periods: periods,file_size_bytes: stat.size,diff --git a/nodejs/src/session-replay/recording-rasterizer/types.ts b/nodejs/src/session-replay/recording-rasterizer/types.tsindex c21d2dacae34..ed6d40de2a93 100644--- a/nodejs/src/session-replay/recording-rasterizer/types.ts+++ b/nodejs/src/session-replay/recording-rasterizer/types.ts@@ -78,6 +78,8 @@ export interface RasterizeRecordingOutput {video_duration_s: number // actual playback duration of the output videoplayback_speed: numbershow_metadata_footer: boolean+ // Pixels at the bottom of each frame the footer takes, which a consumer crops to get the page alone.+ footer_height_px: numbertruncated: boolean // true when max_virtual_time stopped the recording earlyinactivity_periods: InactivityPeriod[]file_size_bytes: numberdiff --git a/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py b/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.pyindex 6840e972462e..5a073366db60 100644--- a/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py+++ b/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py@@ -191,6 +191,7 @@ def _try_synthesize_cached_output(video_duration_s=float(ctx["video_duration_s"]),playback_speed=float(ctx["playback_speed"]),show_metadata_footer=bool(ctx.get("show_metadata_footer", False)),+ footer_height_px=int(ctx.get("footer_height_px") or 0),truncated=bool(ctx["truncated"]),inactivity_periods=inactivity_periods,file_size_bytes=int(ctx["file_size_bytes"]),@@ -218,6 +219,7 @@ def finalize_rasterization(inputs: FinalizeRasterizationInput) -> None:include={"video_duration_s","playback_speed",+ "footer_height_px","truncated","file_size_bytes","inactivity_periods",diff --git a/posthog/temporal/session_replay/rasterize_recording/types.py b/posthog/temporal/session_replay/rasterize_recording/types.pyindex caf044f31e8a..f4dbeb63763b 100644--- a/posthog/temporal/session_replay/rasterize_recording/types.py+++ b/posthog/temporal/session_replay/rasterize_recording/types.py@@ -87,6 +87,8 @@ class RasterizationActivityOutput(BaseModel, frozen=True):video_duration_s: floatplayback_speed: floatshow_metadata_footer: bool = False+ # Rows at the bottom of each frame the footer takes; renders from before this was reported used 32.+ footer_height_px: int = 0truncated: bool = Falseinactivity_periods: list[InactivityPeriod] = []file_size_bytes: int = 0@@ -117,8 +119,12 @@ class RecordRasterizationFailureInput(BaseModel, frozen=True):_FINGERPRINT_EXCLUDE: set[str] = {"team_id", "session_id", "s3_bucket", "s3_key_prefix", "recording_api_token"}+# Bump when the renderer draws the same inputs differently, so videos cached from the old renderer are not reused.+_RENDERER_VERSION = 2++def compute_params_fingerprint(activity_input: "RasterizationActivityInput") -> str:- payload = activity_input.model_dump_json(exclude=_FINGERPRINT_EXCLUDE)+ payload = f"v{_RENDERER_VERSION}:" + activity_input.model_dump_json(exclude=_FINGERPRINT_EXCLUDE)return hashlib.sha256(payload.encode()).hexdigest()[:16]diff --git a/products/replay_vision/backend/temporal/activities/observation_media.py b/products/replay_vision/backend/temporal/activities/observation_media.pyindex 43418d525baa..7ac47845134a 100644--- a/products/replay_vision/backend/temporal/activities/observation_media.py+++ b/products/replay_vision/backend/temporal/activities/observation_media.py@@ -18,8 +18,8 @@ from products.replay_vision.backend.models.replay_observation import ReplayObserfrom products.replay_vision.backend.models.replay_observation_media import ReplayObservationMediafrom products.replay_vision.backend.temporal.decorators import track_activityfrom products.replay_vision.backend.temporal.media_types import (- ANALYSIS_FOOTER_HEIGHT_PX,FALLBACK_THUMBNAIL_FRACTION,+ LEGACY_ANALYSIS_FOOTER_HEIGHT_PX,THUMBNAIL_WIDTH_PX,ExtractThumbnailActivityInput,FinalizeObservationThumbnailInputs,@@ -35,6 +35,13 @@ _MEDIA_EXPIRY = timedelta(days=90)_EDGE_MARGIN_S = 3.0+def _footer_crop_px(context: dict[str, Any]) -> int:+ """Rows to crop off the analysis video, which carry the metadata footer rather than the page."""+ if not context.get("show_metadata_footer"):+ return 0+ return int(context.get("footer_height_px") or LEGACY_ANALYSIS_FOOTER_HEIGHT_PX)++def _media_key_prefix(team_id: int, observation_id: Any) -> str:# Not under `OBJECT_STORAGE_EXPORTS_FOLDER`: those rules drop an mp4 at 30 days and glacier the rest.return f"replay-vision/media/team-{team_id}/{observation_id}"@@ -135,7 +142,7 @@ async def prepare_observation_thumbnail_activity(inputs: ObservationMediaInputs)activity_input=ExtractThumbnailActivityInput(source_s3_uri=f"s3://{settings.OBJECT_STORAGE_BUCKET}/{asset.content_location}",video_time_s=video_time_s,- footer_crop_px=ANALYSIS_FOOTER_HEIGHT_PX if context.get("show_metadata_footer") else 0,+ footer_crop_px=_footer_crop_px(context),width=THUMBNAIL_WIDTH_PX,s3_bucket=settings.OBJECT_STORAGE_BUCKET,s3_key_prefix=_media_key_prefix(media_inputs.team_id, media_inputs.observation_id),diff --git a/products/replay_vision/backend/temporal/media_types.py b/products/replay_vision/backend/temporal/media_types.pyindex d01ba81d6f92..e359cf1737f3 100644--- a/products/replay_vision/backend/temporal/media_types.py+++ b/products/replay_vision/backend/temporal/media_types.py@@ -5,8 +5,8 @@ from uuid import UUIDfrom pydantic import BaseModel, Field-# Matches `footerHeight` in common/replay-headless/src/standalone-player.ts.-ANALYSIS_FOOTER_HEIGHT_PX = 32+# The footer height of analysis videos rendered before the rasterizer reported it as `footer_height_px`.+LEGACY_ANALYSIS_FOOTER_HEIGHT_PX = 32THUMBNAIL_WIDTH_PX = 1280@@ -44,7 +44,7 @@ class ExtractThumbnailActivityInput(BaseModel, frozen=True):source_s3_uri: strvideo_time_s: float- footer_crop_px: int = ANALYSIS_FOOTER_HEIGHT_PX+ footer_crop_px: int = LEGACY_ANALYSIS_FOOTER_HEIGHT_PXwidth: int = THUMBNAIL_WIDTH_PXs3_bucket: strs3_key_prefix: strdiff --git a/products/replay_vision/backend/temporal/scanners/base.py b/products/replay_vision/backend/temporal/scanners/base.pyindex 525cee8f29ac..a148a9cf5df2 100644--- a/products/replay_vision/backend/temporal/scanners/base.py+++ b/products/replay_vision/backend/temporal/scanners/base.py@@ -77,7 +77,11 @@ class SignalFinding(BaseModel, frozen=True):ge=0, description="When the issue ends, in whole seconds of video time — the same scale as `start_time`.")url: str = Field(- description="The page the issue happened on — copy the `URL:` value shown in the video footer at that moment."+ description=(+ "The page the issue happened on: the navigation timeline's URL for that window at that moment, or the "+ "`URL:` in the video footer when the timeline has none (the footer drops the query string and cuts long "+ "URLs short)."+ ))description: str = Field(description=(diff --git a/products/replay_vision/backend/temporal/scanners/prompts/preamble.jinja b/products/replay_vision/backend/temporal/scanners/prompts/preamble.jinjaindex 5c0a3f945c2d..91a2dd3da547 100644--- a/products/replay_vision/backend/temporal/scanners/prompts/preamble.jinja+++ b/products/replay_vision/backend/temporal/scanners/prompts/preamble.jinja@@ -6,7 +6,7 @@ Background on what {{ team_name }}'s product does, sourced from their PostHog wo</customer_product_context>{% endif %}<video>-The video plays at normal speed but at a low frame rate (about 3 frames per second), so motion looks choppy and brief states can flash by or be skipped between frames — don't mistake low-framerate choppiness (a cursor jumping, a tooltip appearing in different spots, a half-drawn frame) for a rendering glitch. Inactive periods are cut, so the recording clock jumps forward across them. A footer at the bottom of every frame shows the current page `URL:` and `REC_T:` — the whole number of seconds since the recording started. Use `REC_T` to judge how long something lasted, never to say where it happened: positions are always in video time, counted from the start of the video file.+The video plays at normal speed but at a low frame rate (about 3 frames per second), so motion looks choppy and brief states can flash by or be skipped between frames — don't mistake low-framerate choppiness (a cursor jumping, a tooltip appearing in different spots, a half-drawn frame) for a rendering glitch. Inactive periods are cut, so the recording clock jumps forward across them. A footer at the bottom of every frame shows `REC_T:`, the whole number of seconds since the recording started; `WINDOW: X of Y`, which of the recording's browser tabs or windows is on screen, counted in the order they first appear; the `URL:` of the page in that window, without its query string and cut short when long; and `STATUS:`, which is `[ACTIVE]` during normal playback, `[IDLE]` on the frame where an inactive stretch is cut, and `[RECORDING ENDED]` after the last event. When the window number changes, the user switched tabs rather than navigated. Use `REC_T` to judge how long something lasted, never to say where it happened: positions are always in video time, counted from the start of the video file.</video><masking>diff --git a/products/replay_vision/backend/temporal/workflow.py b/products/replay_vision/backend/temporal/workflow.pyindex bcdd8cc02da5..6fef406e09cd 100644--- a/products/replay_vision/backend/temporal/workflow.py+++ b/products/replay_vision/backend/temporal/workflow.py@@ -179,8 +179,9 @@ _PROVIDER_TIMEOUT_ACTIVITY_TYPES = frozenset()# The rasterizer sends its own `RasterizationError.code` as the ApplicationError type. This one means the recording-# holds no renderable snapshots. It stays retryable over there (blocks can still be landing), so by the time it-# surfaces here the render attempts are spent and the emptiness is a property of the recording, not of one attempt.+# holds no renderable snapshots. It is retryable over there while nothing has loaded (blocks can still be landing) and+# final when snapshots loaded but no window has a full snapshot, so either way the emptiness surfaces here as a property+# of the recording, not of one attempt._RASTERIZER_NO_SNAPSHOTS_TYPE = "NO_SNAPSHOTS"# The rasterizer refuses a recording whose snapshot blocks exceed its size cap, to keep an oversized render fromdiff --git a/products/replay_vision/backend/tests/test_observation_media.py b/products/replay_vision/backend/tests/test_observation_media.pyindex 88d20a7bd4f1..4380ea6361fd 100644--- a/products/replay_vision/backend/tests/test_observation_media.py+++ b/products/replay_vision/backend/tests/test_observation_media.py@@ -24,6 +24,7 @@ from products.replay_vision.backend.models.replay_observation import (from products.replay_vision.backend.models.replay_observation_media import ReplayObservationMediafrom products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerTypefrom products.replay_vision.backend.temporal.activities.observation_media import (+ _footer_crop_px,_pick_video_time_s,finalize_observation_thumbnail_activity,prepare_observation_thumbnail_activity,@@ -302,3 +303,15 @@ def test_the_thumbnail_moment_stays_off_the_unstyled_edges_of_the_video(team_id=1, observation_id=uuid7(), session_id="s", analysis_asset_id=1, thumbnail_video_s=thumbnail_video_s)assert _pick_video_time_s(inputs, model_output, None, duration_s) == expected_s+++ "context,expected_px",+ [+ ({"show_metadata_footer": True, "footer_height_px": 48}, 48),+ ({"show_metadata_footer": True}, 32),+ ({"show_metadata_footer": False, "footer_height_px": 48}, 0),+ ],+)+def test_the_thumbnail_crops_the_footer_its_video_was_rendered_with(context: dict[str, Any], expected_px: int) -> None:+ assert _footer_crop_px(context) == expected_px