Skip to content

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

fix(toolbar): report heatmap widths that fail to capture (#99825)

posthog[bot]a4448060f524
diff --git a/docs/internal/toolbar-entitlements.md b/docs/internal/toolbar-entitlements.md
index 6fcf7b29591b..1cc03e7f046d 100644
--- a/docs/internal/toolbar-entitlements.md
+++ b/docs/internal/toolbar-entitlements.md
@@ -28,3 +28,6 @@ Capture requests without a data URL keep using the exact page URL.
A heatmap editor with resource-level access can change the data URL of a toolbar capture in the page settings without replacing its screenshot.
Changing the captured page or its rendering settings still requires a new capture from the toolbar.
Object-level editor access alone does not allow changing either URL.
+
+Saving again retries all configured page widths and creates a new heatmap.
+It does not add missing widths to an existing heatmap.
diff --git a/frontend/src/lib/lemon-ui/LemonToast/LemonToast.test.tsx b/frontend/src/lib/lemon-ui/LemonToast/LemonToast.test.tsx
index 4b2f77b6a6bd..53a18cc8302f 100644
--- a/frontend/src/lib/lemon-ui/LemonToast/LemonToast.test.tsx
+++ b/frontend/src/lib/lemon-ui/LemonToast/LemonToast.test.tsx
@@ -1,9 +1,12 @@
import '@testing-library/jest-dom'
import { act, fireEvent, render, within } from '@testing-library/react'
+import posthog from 'posthog-js'
import { resetGetHelpAction, setGetHelpAction } from './getHelp'
-import { GET_HELP_BUTTON, ToastContent, withClickableUrls } from './LemonToast'
+import { GET_HELP_BUTTON, ToastContent, lemonToast, withClickableUrls } from './LemonToast'
+
+const mockPosthog = posthog as unknown as { __loaded: boolean; capture: jest.Mock }
describe('LemonToast', () => {
const writeText = jest.fn((_text: string) => Promise.resolve())
@@ -98,4 +101,19 @@ describe('LemonToast', () => {
it('returns a message without URLs unchanged', () => {
expect(withClickableUrls('Load experiment failed')).toBe('Load experiment failed')
})
+
+ // The toolbar bundle imports this default instance but initializes a named one, so the guard has
+ // to read __loaded. `capture` is a class method, so checking for it lets the call through.
+ it.each([
+ { name: 'reports a warning toast on an initialized instance', type: 'warning', event: 'toast warning' },
+ { name: 'reports an error toast on an initialized instance', type: 'error', event: 'toast error' },
+ { name: 'stays quiet for a warning toast on an uninitialized instance', type: 'warning', event: null },
+ { name: 'stays quiet for an error toast on an uninitialized instance', type: 'error', event: null },
+ ] as const)('$name', ({ type, event }) => {
+ mockPosthog.__loaded = event !== null
+
+ lemonToast[type]('Load experiment failed')
+
+ expect(mockPosthog.capture.mock.calls.map(([name]) => name)).toEqual(event ? [event] : [])
+ })
})
diff --git a/frontend/src/lib/lemon-ui/LemonToast/LemonToast.tsx b/frontend/src/lib/lemon-ui/LemonToast/LemonToast.tsx
index 9e8c11d9f3bb..73a8fbcf8be5 100644
--- a/frontend/src/lib/lemon-ui/LemonToast/LemonToast.tsx
+++ b/frontend/src/lib/lemon-ui/LemonToast/LemonToast.tsx
@@ -242,11 +242,15 @@ export const lemonToast = {
return id
},
warning(message: string | JSX.Element, { button, ...toastOptions }: ToastOptionsWithButton = {}) {
- posthog.capture('toast warning', {
- message: String(message),
- button: button?.label,
- toastId: toastOptions.toastId,
- })
+ // The toolbar bundle initializes a named instance, so the default instance imported here stays
+ // uninitialized there and posthog-js discards the event. `capture` is defined either way.
+ if (posthog.__loaded) {
+ posthog.capture('toast warning', {
+ message: String(message),
+ button: button?.label,
+ toastId: toastOptions.toastId,
+ })
+ }
const options = ensureToastId(toastOptions, 'warning', message)
const id = options.toastId!
queueMicrotask(() => {
@@ -261,9 +265,9 @@ export const lemonToast = {
return id
},
error(message: string | JSX.Element, { button, hideButton, ...toastOptions }: ToastOptionsWithButton = {}) {
- // when used inside the posthog toolbar, `posthog.capture` isn't loaded
- // check if the function is available before calling it.
- if (posthog.capture) {
+ // The toolbar bundle initializes a named instance, so the default instance imported here stays
+ // uninitialized there and posthog-js discards the event. `capture` is defined either way.
+ if (posthog.__loaded) {
posthog.capture('toast error', {
message: String(message),
button: button?.label,
diff --git a/frontend/src/toolbar/stats/heatmapCaptureLogic.test.ts b/frontend/src/toolbar/stats/heatmapCaptureLogic.test.ts
index a15a0e77bb1e..8eede44365cf 100644
--- a/frontend/src/toolbar/stats/heatmapCaptureLogic.test.ts
+++ b/frontend/src/toolbar/stats/heatmapCaptureLogic.test.ts
@@ -12,12 +12,16 @@ jest.mock('~/toolbar/toolbarLogger', () => ({
jest.mock('~/toolbar/utils/screenshot', () => ({
captureElementScreenshot: jest.fn(() => Promise.resolve(new Blob(['fake-image'], { type: 'image/jpeg' }))),
}))
+jest.mock('lib/lemon-ui/LemonToast', () => ({
+ lemonToast: { success: jest.fn(), warning: jest.fn(), error: jest.fn() },
+}))
jest.mock('~/toolbar/utils/responsiveScreenshot', () => ({
RESPONSIVE_CAPTURE_WIDTHS: [320, 768, 1440],
captureResponsiveScreenshots: jest.fn(),
}))
const { captureResponsiveScreenshots } = jest.requireMock('~/toolbar/utils/responsiveScreenshot')
+const { lemonToast } = jest.requireMock('lib/lemon-ui/LemonToast')
const jpeg = (): Blob => new Blob(['fake-image'], { type: 'image/jpeg' })
@@ -41,6 +45,8 @@ describe('heatmapCaptureLogic', () => {
initKeaTests()
window.innerWidth = 1440
;(captureResponsiveScreenshots as jest.Mock).mockReset()
+ ;(lemonToast.success as jest.Mock).mockClear()
+ ;(lemonToast.warning as jest.Mock).mockClear()
toolbarConfigLogic
.build({
apiURL: 'http://localhost',
@@ -98,4 +104,47 @@ describe('heatmapCaptureLogic', () => {
expect(body.get('image') instanceof File).toBe(expectedSingleWidth !== null)
})
})
+
+ it.each([
+ {
+ name: 'confirms a full capture with a plain success toast',
+ captures: [
+ { width: 320, blob: jpeg() },
+ { width: 768, blob: jpeg() },
+ { width: 1440, blob: jpeg() },
+ ],
+ expectedToast: 'success' as const,
+ expectedMessage: 'Heatmap saved',
+ },
+ {
+ name: 'warns that a partial capture only saved some widths',
+ captures: [{ width: 320, blob: jpeg() }],
+ expectedToast: 'warning' as const,
+ expectedMessage:
+ 'Heatmap saved with 1 of 3 page widths. Saving again creates a new heatmap and retries all page widths.',
+ },
+ {
+ name: 'warns that the fallback only saved the current window width',
+ captures: [] as { width: number; blob: Blob }[],
+ expectedToast: 'warning' as const,
+ expectedMessage:
+ 'Heatmap saved at your current window width only. Saving again creates a new heatmap and retries all page widths.',
+ },
+ ])('$name', async ({ captures, expectedToast, expectedMessage }) => {
+ ;(captureResponsiveScreenshots as jest.Mock).mockResolvedValue(captures)
+ mockCaptureResponse()
+
+ await expectLogic(logic, () => {
+ logic.actions.saveToPostHog()
+ })
+ .delay(0)
+ .toDispatchActions(['saveToPostHog', 'saveToPostHogSuccess'])
+
+ const quiet = expectedToast === 'success' ? lemonToast.warning : lemonToast.success
+ expect(quiet).not.toHaveBeenCalled()
+ expect(lemonToast[expectedToast]).toHaveBeenCalledWith(
+ expectedMessage,
+ expect.objectContaining({ toastId: 'heatmap-saved-hm123' })
+ )
+ })
})
diff --git a/frontend/src/toolbar/stats/heatmapCaptureLogic.ts b/frontend/src/toolbar/stats/heatmapCaptureLogic.ts
index 239c97e4bff0..697337edb604 100644
--- a/frontend/src/toolbar/stats/heatmapCaptureLogic.ts
+++ b/frontend/src/toolbar/stats/heatmapCaptureLogic.ts
@@ -27,6 +27,11 @@ interface CaptureProgress {
total: number
}
+interface CaptureSummary {
+ savedWidths: number
+ totalWidths: number
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface heatmapCaptureLogicValues {
href: string // currentPageLogic
@@ -37,6 +42,7 @@ export interface heatmapCaptureLogicValues {
captureProgress: CaptureProgress | null
captureResult: HeatmapCaptureResult | null
captureResultLoading: boolean
+ captureSummary: CaptureSummary | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -65,6 +71,9 @@ export interface heatmapCaptureLogicActions {
setCaptureProgress: (progress: CaptureProgress | null) => {
progress: CaptureProgress | null
}
+ setCaptureSummary: (summary: CaptureSummary | null) => {
+ summary: CaptureSummary | null
+ }
}
export type heatmapCaptureLogicType = MakeLogicType<heatmapCaptureLogicValues, heatmapCaptureLogicActions>
@@ -108,6 +117,7 @@ export const heatmapCaptureLogic = kea<heatmapCaptureLogicType>([
})),
actions({
setCaptureProgress: (progress: CaptureProgress | null) => ({ progress }),
+ setCaptureSummary: (summary: CaptureSummary | null) => ({ summary }),
}),
reducers({
captureProgress: [
@@ -116,6 +126,12 @@ export const heatmapCaptureLogic = kea<heatmapCaptureLogicType>([
setCaptureProgress: (_, { progress }) => progress,
},
],
+ captureSummary: [
+ null as CaptureSummary | null,
+ {
+ setCaptureSummary: (_, { summary }) => summary,
+ },
+ ],
}),
loaders(({ values, actions }) => ({
captureResult: [
@@ -127,6 +143,11 @@ export const heatmapCaptureLogic = kea<heatmapCaptureLogicType>([
const captures = await captureResponsiveScreenshots(RESPONSIVE_CAPTURE_WIDTHS, (done, total) =>
actions.setCaptureProgress({ done, total })
)
+ actions.setCaptureSummary({
+ savedWidths: captures.length,
+ totalWidths: RESPONSIVE_CAPTURE_WIDTHS.length,
+ })
+
const formData =
captures.length > 0
? buildMultiWidthFormData(values.href, values.wildcardHref, captures)
@@ -150,13 +171,29 @@ export const heatmapCaptureLogic = kea<heatmapCaptureLogicType>([
if (!captureResult) {
return
}
- lemonToast.success('Heatmap saved', {
- button: {
- label: 'Open in PostHog',
- action: () =>
- window.open(joinWithUiHost(values.uiHost, urls.heatmap(captureResult.short_id)), '_blank'),
- },
- })
+ const button = {
+ label: 'Open in PostHog',
+ action: () =>
+ window.open(joinWithUiHost(values.uiHost, urls.heatmap(captureResult.short_id)), '_blank'),
+ }
+ // Without an explicit id, the toast id is a hash of the message, so two saves that produce
+ // the same message share one id and react-toastify drops the second toast while the first
+ // one is still on screen.
+ const toastOptions = { button, toastId: `heatmap-saved-${captureResult.short_id}` }
+ const summary = values.captureSummary
+ if (!summary || summary.savedWidths === summary.totalWidths) {
+ lemonToast.success('Heatmap saved', toastOptions)
+ } else if (summary.savedWidths === 0) {
+ lemonToast.warning(
+ 'Heatmap saved at your current window width only. Saving again creates a new heatmap and retries all page widths.',
+ toastOptions
+ )
+ } else {
+ lemonToast.warning(
+ `Heatmap saved with ${summary.savedWidths} of ${summary.totalWidths} page widths. Saving again creates a new heatmap and retries all page widths.`,
+ toastOptions
+ )
+ }
},
saveToPostHogFailure: ({ error }) => {
actions.setCaptureProgress(null)
diff --git a/frontend/src/toolbar/utils/responsiveScreenshot.test.ts b/frontend/src/toolbar/utils/responsiveScreenshot.test.ts
index 8b3c27703f8a..b965dda62972 100644
--- a/frontend/src/toolbar/utils/responsiveScreenshot.test.ts
+++ b/frontend/src/toolbar/utils/responsiveScreenshot.test.ts
@@ -3,9 +3,22 @@ import { captureResponsiveScreenshots } from '~/toolbar/utils/responsiveScreensh
jest.mock('~/toolbar/utils/screenshot', () => ({
captureElementScreenshot: jest.fn(() => Promise.reject(new Error('capture failed'))),
}))
+jest.mock('~/toolbar/toolbarPosthogJS', () => ({
+ captureToolbarException: jest.fn(),
+}))
+jest.mock('~/toolbar/toolbarLogger', () => ({
+ toolbarLogger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() },
+}))
+
+const { captureToolbarException } = jest.requireMock('~/toolbar/toolbarPosthogJS')
+const { toolbarLogger } = jest.requireMock('~/toolbar/toolbarLogger')
describe('captureResponsiveScreenshots', () => {
- beforeEach(() => jest.useFakeTimers())
+ beforeEach(() => {
+ jest.useFakeTimers()
+ ;(captureToolbarException as jest.Mock).mockClear()
+ ;(toolbarLogger.warn as jest.Mock).mockClear()
+ })
afterEach(() => jest.useRealTimers())
it('skips every failed width and resolves to an empty array instead of throwing', async () => {
@@ -17,4 +30,18 @@ describe('captureResponsiveScreenshots', () => {
expect(onProgress).toHaveBeenCalledTimes(3)
expect(onProgress).toHaveBeenLastCalledWith(3, 3)
})
+
+ it('reports the failed widths once per run instead of swallowing them', async () => {
+ const promise = captureResponsiveScreenshots([320, 768, 1440])
+ await jest.runAllTimersAsync()
+ await promise
+
+ expect(toolbarLogger.warn).toHaveBeenCalledTimes(3)
+ expect(captureToolbarException).toHaveBeenCalledTimes(1)
+ expect(captureToolbarException).toHaveBeenCalledWith(expect.any(Error), 'responsive_screenshot', {
+ failed_widths: [320, 768, 1440],
+ captured_count: 0,
+ requested_count: 3,
+ })
+ })
})
diff --git a/frontend/src/toolbar/utils/responsiveScreenshot.ts b/frontend/src/toolbar/utils/responsiveScreenshot.ts
index 4f6a03ad0c60..5f8a8cc3a5c3 100644
--- a/frontend/src/toolbar/utils/responsiveScreenshot.ts
+++ b/frontend/src/toolbar/utils/responsiveScreenshot.ts
@@ -1,6 +1,8 @@
import { delay } from 'lib/utils/async'
-import { TOOLBAR_ID } from '~/toolbar/utils'
+import { toolbarLogger } from '~/toolbar/toolbarLogger'
+import { captureToolbarException } from '~/toolbar/toolbarPosthogJS'
+import { TOOLBAR_ID, toError } from '~/toolbar/utils'
import { captureElementScreenshot } from '~/toolbar/utils/screenshot'
export const RESPONSIVE_CAPTURE_WIDTHS = [320, 375, 425, 768, 1024, 1440, 1920]
@@ -120,14 +122,33 @@ export async function captureResponsiveScreenshots(
onProgress?: (done: number, total: number) => void
): Promise<WidthCapture[]> {
const captures: WidthCapture[] = []
+ const failures: { width: number; error: Error }[] = []
let attempted = 0
for (const width of widths) {
try {
const blob = await captureWidth(width)
captures.push({ width, blob })
- } catch {}
+ } catch (e) {
+ const error = toError(e, `Responsive heatmap capture failed at ${width}px`)
+ failures.push({ width, error })
+ toolbarLogger.warn('responsive_screenshot', 'Width capture failed', {
+ width,
+ error: error.message,
+ })
+ }
attempted++
onProgress?.(attempted, widths.length)
}
+
+ // One exception per run, not one per width, so the occurrence count equals the number of
+ // partly-failed captures rather than the number of widths a page happens to fail at.
+ if (failures.length > 0) {
+ captureToolbarException(failures[0].error, 'responsive_screenshot', {
+ failed_widths: failures.map((failure) => failure.width),
+ captured_count: captures.length,
+ requested_count: widths.length,
+ })
+ }
+
return captures
}