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(heatmaps): capture page history on demand (#117202)

Jordan Mryyan497a80e22b5d
diff --git a/products/web_analytics/frontend/heatmaps/history/PageHistoryStrip.tsx b/products/web_analytics/frontend/heatmaps/history/PageHistoryStrip.tsx
index 159a3733792e..45a6aad7a4cf 100644
--- a/products/web_analytics/frontend/heatmaps/history/PageHistoryStrip.tsx
+++ b/products/web_analytics/frontend/heatmaps/history/PageHistoryStrip.tsx
@@ -2,14 +2,15 @@ import { useActions, useValues } from 'kea'
import { useCallback, useLayoutEffect, useRef, useState } from 'react'
import useResizeObserver from 'use-resize-observer'
-import { IconChevronLeft, IconChevronRight, IconEllipsis, IconRefresh } from '@posthog/icons'
-import { LemonBanner, LemonButton, LemonCard, LemonMenu, Tooltip } from '@posthog/lemon-ui'
+import { IconCamera, IconChevronLeft, IconChevronRight, IconEllipsis, IconRefresh } from '@posthog/icons'
+import { LemonBanner, LemonButton, LemonCard, LemonMenu, Spinner, Tooltip } from '@posthog/lemon-ui'
import { heatmapDataLogic } from 'lib/components/heatmaps/heatmapDataLogic'
import { dayjs } from 'lib/dayjs'
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
import { dateFilterToText } from 'lib/utils/dateFilters'
+import { pageHistoryCaptureLogic } from './pageHistoryCaptureLogic'
import { pageHistoryLogic } from './pageHistoryLogic'
import { PageHistoryRangeEditor } from './PageHistoryRangeEditor'
import { PageHistoryTile } from './PageHistoryTile'
@@ -44,6 +45,10 @@ export function PageHistoryStrip({ id }: { id: string }): JSX.Element {
setHistoryExpanded,
setMissingCaptureDate,
} = useActions(logic)
+ const captureLogic = pageHistoryCaptureLogic({ id })
+ const { capturing, captureError, captureStatusUnknown, completedCapture, captureNowDisabledReason, todaysCapture } =
+ useValues(captureLogic)
+ const { requestCapture, setCompletedRequestId } = useActions(captureLogic)
const { effectiveCommonFilters } = useValues(heatmapDataLogic({ context: 'in-app' }))
const contextRef = useRef<HTMLElement | null>(null)
const [browserMaxHeight, setBrowserMaxHeight] = useState(640)
@@ -77,6 +82,7 @@ export function PageHistoryStrip({ id }: { id: string }): JSX.Element {
setHistoryExpanded(false)
browseRef.current?.focus({ preventScroll: true })
}
+ const captureLabel = todaysCapture ? "Update today's screenshot" : "Capture today's screenshot"
return (
<section
@@ -157,6 +163,13 @@ export function PageHistoryStrip({ id }: { id: string }): JSX.Element {
{captures.length > 0 ? (
<LemonMenu
items={[
+ {
+ label: captureLabel,
+ icon: <IconCamera />,
+ onClick: () => requestCapture(),
+ disabledReason: captureNowDisabledReason,
+ 'data-attr': 'heatmap-page-history-capture-now',
+ },
{
label: 'Refresh screenshots',
icon: <IconRefresh />,
@@ -169,6 +182,7 @@ export function PageHistoryStrip({ id }: { id: string }): JSX.Element {
<LemonButton
size="small"
icon={<IconEllipsis />}
+ loading={capturing}
aria-label="Screenshot actions"
data-attr="heatmap-page-history-actions"
/>
@@ -210,6 +224,48 @@ export function PageHistoryStrip({ id }: { id: string }): JSX.Element {
</LemonBanner>
) : null}
<div role="status" aria-live="polite">
+ {captureStatusUnknown ? (
+ <LemonBanner
+ type="warning"
+ className="mt-2"
+ action={{ children: 'Check capture', onClick: () => loadHistory(), loading: historyLoading }}
+ >
+ Couldn't check the capture's status. It may still be running. Check again before starting
+ another.
+ </LemonBanner>
+ ) : captureError ? (
+ <LemonBanner
+ type="error"
+ className="mt-2"
+ action={{
+ children: 'Try again',
+ onClick: () => requestCapture(),
+ disabledReason: captureNowDisabledReason,
+ }}
+ >
+ {captureError}
+ </LemonBanner>
+ ) : capturing ? (
+ <div className="flex items-center gap-2 text-sm mt-2">
+ <Spinner className="shrink-0" />
+ <span>Capturing today's page. You can keep exploring history.</span>
+ </div>
+ ) : completedCapture ? (
+ <LemonBanner
+ type="success"
+ className="mt-2"
+ onClose={() => setCompletedRequestId(null)}
+ action={{
+ children: 'View capture',
+ onClick: () => {
+ browseCapture(completedCapture.id)
+ setCompletedRequestId(null)
+ },
+ }}
+ >
+ <span>{`Your ${dayjs(completedCapture.captured_on).format('MMM D')} screenshot is ready.`}</span>
+ </LemonBanner>
+ ) : null}
{navigationNotice ? <p className="text-xs text-muted mt-2 mb-0">{navigationNotice}</p> : null}
</div>
{missingCaptureDate ? (
@@ -246,6 +302,17 @@ export function PageHistoryStrip({ id }: { id: string }): JSX.Element {
? "Automatic captures build history for recently viewed pages. Earlier page designs can't be recovered."
: 'Screenshot storage is unavailable on this installation. Ask your administrator to configure it.'}
</p>
+ <LemonButton
+ size="small"
+ type="primary"
+ icon={<IconCamera />}
+ onClick={requestCapture}
+ loading={capturing}
+ disabledReason={captureNowDisabledReason}
+ data-attr="heatmap-page-history-capture-now"
+ >
+ Capture today's screenshot
+ </LemonButton>
<p className="text-xs text-muted mb-0 mt-2">
<span>{`Saved screenshots are kept for ${history.retention_days} days. Some days may be missing.`}</span>
</p>
diff --git a/products/web_analytics/frontend/heatmaps/history/pageHistoryCaptureLogic.ts b/products/web_analytics/frontend/heatmaps/history/pageHistoryCaptureLogic.ts
new file mode 100644
index 000000000000..c04afb4dd2c0
--- /dev/null
+++ b/products/web_analytics/frontend/heatmaps/history/pageHistoryCaptureLogic.ts
@@ -0,0 +1,346 @@
+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import posthog from 'posthog-js'
+
+import { ApiError } from 'lib/api-error'
+import { dayjs } from 'lib/dayjs'
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import { teamLogic } from 'scenes/teamLogic'
+
+import {
+ savedScreenshotHistoryCaptureCreate,
+ savedScreenshotHistoryRequestsRetrieve,
+} from 'products/web_analytics/frontend/generated/api'
+import type {
+ HeatmapScreenshotHistoryItemApi,
+ HeatmapScreenshotHistoryResponseApi,
+} from 'products/web_analytics/frontend/generated/api.schemas'
+
+import { heatmapLogic } from '../scenes/heatmap/heatmapLogic'
+import { PageHistoryLogicProps, isUsableCapture, pageHistoryLogic } from './pageHistoryLogic'
+
+function pendingRequestId(history: HeatmapScreenshotHistoryResponseApi | null): string | null {
+ const pending = history?.results
+ .map((capture) => capture.latest_request)
+ .find((request) => request && ['queued', 'running'].includes(request.state))
+ return pending?.request_id ?? null
+}
+
+function requestOutcome(history: HeatmapScreenshotHistoryResponseApi, requestId: string): string | null {
+ for (const capture of history.results) {
+ if (capture.revision === requestId && isUsableCapture(capture)) {
+ return 'succeeded'
+ }
+ if (capture.latest_request?.request_id === requestId) {
+ return capture.latest_request.state
+ }
+ }
+ return null
+}
+
+function captureFailureMessage(state: string): string {
+ return state === 'cancelled'
+ ? 'The capture was canceled. Existing screenshots are kept.'
+ : "The capture couldn't finish. Existing screenshots are kept. Try again later."
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface pageHistoryCaptureLogicValues {
+ editDisabledReason: string | null // heatmapLogic
+ hasUnsavedChanges: boolean // heatmapLogic
+ captures: HeatmapScreenshotHistoryItemApi[] // pageHistoryLogic
+ history: HeatmapScreenshotHistoryResponseApi | null // pageHistoryLogic
+ timezone: string // teamLogic
+ captureError: string | null
+ captureNowDisabledReason: string | null
+ captureStatusUnknown: boolean
+ capturing: boolean
+ completedCapture: HeatmapScreenshotHistoryItemApi | null
+ completedRequestId: string | null
+ todaysCapture: HeatmapScreenshotHistoryItemApi | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface pageHistoryCaptureLogicActions {
+ loadHistory: (_?: void | undefined) => void // pageHistoryLogic
+ loadHistorySuccess: (
+ history: HeatmapScreenshotHistoryResponseApi,
+ payload?: void | undefined
+ ) => {
+ history: HeatmapScreenshotHistoryResponseApi
+ payload?: void | undefined
+ } // pageHistoryLogic
+ pageChanged: () => {
+ value: true
+ } // pageHistoryLogic
+ captureNow: () => {
+ value: true
+ }
+ pollRequest: (requestId: string) => {
+ requestId: string
+ }
+ requestCapture: () => {
+ value: true
+ }
+ setCaptureError: (error: string | null) => {
+ error: string | null
+ }
+ setCaptureStatusUnknown: (unknown: boolean) => {
+ unknown: boolean
+ }
+ setCapturing: (capturing: boolean) => {
+ capturing: boolean
+ }
+ setCompletedRequestId: (requestId: string | null) => {
+ requestId: string | null
+ }
+ stopPolling: () => {
+ value: true
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface pageHistoryCaptureLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ completedCapture: (
+ captures: HeatmapScreenshotHistoryItemApi[],
+ completedRequestId: string | null
+ ) => HeatmapScreenshotHistoryItemApi | null
+ todaysCapture: (
+ captures: HeatmapScreenshotHistoryItemApi[],
+ timezone: string
+ ) => HeatmapScreenshotHistoryItemApi | null
+ captureNowDisabledReason: (
+ editDisabledReason: string | null,
+ capturing: boolean,
+ history: HeatmapScreenshotHistoryResponseApi | null,
+ hasUnsavedChanges: boolean,
+ captureStatusUnknown: boolean
+ ) => string | null
+ }
+}
+
+export type pageHistoryCaptureLogicType = MakeLogicType<
+ pageHistoryCaptureLogicValues,
+ pageHistoryCaptureLogicActions,
+ PageHistoryLogicProps,
+ pageHistoryCaptureLogicMeta
+>
+
+export const pageHistoryCaptureLogic = kea<pageHistoryCaptureLogicType>([
+ path((key) => ['products', 'web_analytics', 'heatmaps', 'history', 'pageHistoryCaptureLogic', key]),
+ props({} as PageHistoryLogicProps),
+ key((props) => `${props.teamId ?? teamLogic.values.currentTeamIdStrict}:${props.id}`),
+ connect((props: PageHistoryLogicProps) => ({
+ values: [
+ pageHistoryLogic(props),
+ ['captures', 'history'],
+ heatmapLogic({ id: props.id }),
+ ['editDisabledReason', 'hasUnsavedChanges'],
+ teamLogic,
+ ['timezone'],
+ ],
+ actions: [pageHistoryLogic(props), ['loadHistory', 'loadHistorySuccess', 'pageChanged']],
+ })),
+ actions({
+ requestCapture: true,
+ captureNow: true,
+ setCapturing: (capturing: boolean) => ({ capturing }),
+ setCaptureError: (error: string | null) => ({ error }),
+ setCaptureStatusUnknown: (unknown: boolean) => ({ unknown }),
+ setCompletedRequestId: (requestId: string | null) => ({ requestId }),
+ pollRequest: (requestId: string) => ({ requestId }),
+ stopPolling: true,
+ }),
+ reducers({
+ captureError: [
+ null as string | null,
+ {
+ setCaptureError: (_, { error }) => error,
+ setCapturing: (state, { capturing }) => (capturing ? null : state),
+ },
+ ],
+ captureStatusUnknown: [false, { setCaptureStatusUnknown: (_, { unknown }) => unknown }],
+ completedRequestId: [
+ null as string | null,
+ {
+ setCompletedRequestId: (_, { requestId }) => requestId,
+ setCapturing: (state, { capturing }) => (capturing ? null : state),
+ },
+ ],
+ capturing: [false, { setCapturing: (_, { capturing }) => capturing, stopPolling: () => false }],
+ }),
+ selectors({
+ completedCapture: [
+ (s) => [s.captures, s.completedRequestId],
+ (
+ captures: HeatmapScreenshotHistoryItemApi[],
+ requestId: string | null
+ ): HeatmapScreenshotHistoryItemApi | null =>
+ requestId
+ ? (captures.find((capture) => capture.revision === requestId && isUsableCapture(capture)) ?? null)
+ : null,
+ ],
+ todaysCapture: [
+ (s) => [s.captures, s.timezone],
+ (captures: HeatmapScreenshotHistoryItemApi[], timezone: string): HeatmapScreenshotHistoryItemApi | null => {
+ const today = dayjs().tz(timezone).format('YYYY-MM-DD')
+ return captures.find((capture) => capture.captured_on === today && isUsableCapture(capture)) ?? null
+ },
+ ],
+ captureNowDisabledReason: [
+ (s) => [s.editDisabledReason, s.capturing, s.history, s.hasUnsavedChanges, s.captureStatusUnknown],
+ (
+ editDisabledReason: string | null,
+ capturing: boolean,
+ history: HeatmapScreenshotHistoryResponseApi | null,
+ hasUnsavedChanges: boolean,
+ captureStatusUnknown: boolean
+ ): string | null =>
+ editDisabledReason ||
+ (hasUnsavedChanges
+ ? 'Save your page settings before capturing.'
+ : captureStatusUnknown
+ ? 'Check the current capture before starting another.'
+ : !history
+ ? 'Load page history before capturing.'
+ : history.storage_available === false
+ ? 'Screenshot storage is unavailable on this installation.'
+ : capturing
+ ? 'Capturing the page'
+ : null),
+ ],
+ }),
+ listeners(({ actions, values, props, cache }) => ({
+ pageChanged: () => {
+ cache.pageGeneration = (cache.pageGeneration ?? 0) + 1
+ cache.interruptedRequestId = null
+ actions.stopPolling()
+ actions.setCaptureError(null)
+ actions.setCompletedRequestId(null)
+ },
+ loadHistorySuccess: ({ history }) => {
+ const interrupted: string | null = cache.interruptedRequestId ?? null
+ cache.interruptedRequestId = null
+ const outcome = interrupted ? requestOutcome(history, interrupted) : null
+ if (interrupted && outcome === 'succeeded') {
+ actions.setCompletedRequestId(interrupted)
+ } else if (outcome === 'failed' || outcome === 'cancelled') {
+ actions.setCaptureError(captureFailureMessage(outcome))
+ }
+ const pending = pendingRequestId(history)
+ actions.setCaptureStatusUnknown(false)
+ if (pending && !values.capturing) {
+ actions.pollRequest(pending)
+ }
+ },
+ requestCapture: () => {
+ if (values.captureNowDisabledReason) {
+ return
+ }
+ if (values.todaysCapture) {
+ LemonDialog.open({
+ title: "Replace today's capture?",
+ description:
+ "Only one screenshot is kept per day. A successful update replaces today's image; earlier interactions today may not match the new layout. Your previous screenshot stays available if the update fails.",
+ primaryButton: { children: 'Replace capture', onClick: () => actions.captureNow() },
+ secondaryButton: { children: 'Keep existing capture' },
+ })
+ } else {
+ actions.captureNow()
+ }
+ },
+ stopPolling: () => cache.disposables.dispose('history-poll'),
+ pollRequest: ({ requestId }) => {
+ actions.setCaptureStatusUnknown(false)
+ actions.setCapturing(true)
+ const giveUpAt = Date.now() + 30 * 60_000
+ cache.disposables.add(() => {
+ let cancelled = false
+ let timer: ReturnType<typeof setTimeout> | undefined
+ const poll = async (): Promise<void> => {
+ try {
+ const request = await savedScreenshotHistoryRequestsRetrieve(
+ String(cache.teamId),
+ props.id,
+ requestId
+ )
+ if (cancelled) {
+ return
+ }
+ if (['succeeded', 'failed', 'cancelled'].includes(request.state)) {
+ actions.stopPolling()
+ actions.loadHistory()
+ if (request.state === 'succeeded') {
+ actions.setCompletedRequestId(requestId)
+ } else {
+ actions.setCaptureError(captureFailureMessage(request.state))
+ }
+ return
+ }
+ if (Date.now() >= giveUpAt) {
+ throw new Error('Capture did not finish')
+ }
+ timer = setTimeout(poll, 10_000)
+ } catch {
+ if (!cancelled) {
+ cache.interruptedRequestId = requestId
+ actions.stopPolling()
+ actions.setCaptureStatusUnknown(true)
+ }
+ }
+ }
+ timer = setTimeout(poll, 10_000)
+ return () => {
+ cancelled = true
+ clearTimeout(timer)
+ }
+ }, 'history-poll')
+ },
+ captureNow: async (_, breakpoint) => {
+ if (values.captureNowDisabledReason) {
+ return
+ }
+ const pageGeneration = cache.pageGeneration
+ actions.setCapturing(true)
+ try {
+ const request = await savedScreenshotHistoryCaptureCreate(String(cache.teamId), props.id)
+ breakpoint()
+ if (cache.disposables.isDisposed) {
+ return
+ }
+ if (cache.pageGeneration !== pageGeneration) {
+ actions.setCapturing(false)
+ return
+ }
+ actions.pollRequest(request.request_id)
+ actions.loadHistory()
+ posthog.capture('heatmap page history capture requested', { heatmap_id: props.id })
+ } catch (error) {
+ if (cache.disposables.isDisposed) {
+ return
+ }
+ actions.setCapturing(false)
+ if (cache.pageGeneration !== pageGeneration) {
+ return
+ }
+ const rateLimited = error instanceof ApiError && error.status === 429
+ actions.setCaptureError(
+ rateLimited
+ ? `A capture was requested recently. Try again in ${Math.max(1, Math.ceil(Number(error.headers?.get('Retry-After') ?? 600) / 60))} minutes.`
+ : 'Could not start a capture. Try again later.'
+ )
+ if (!rateLimited) {
+ actions.loadHistory()
+ }
+ }
+ },
+ })),
+ afterMount(({ actions, values, props, cache }) => {
+ cache.teamId = props.teamId ?? teamLogic.values.currentTeamIdStrict
+ const pending = pendingRequestId(values.history)
+ if (pending) {
+ actions.pollRequest(pending)
+ }
+ }),
+])
diff --git a/products/web_analytics/frontend/heatmaps/history/pageHistoryLogic.test.ts b/products/web_analytics/frontend/heatmaps/history/pageHistoryLogic.test.ts
index 36e6f45c03d3..f95fd876cdeb 100644
--- a/products/web_analytics/frontend/heatmaps/history/pageHistoryLogic.test.ts
+++ b/products/web_analytics/frontend/heatmaps/history/pageHistoryLogic.test.ts
@@ -4,6 +4,7 @@ import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import api from 'lib/api'
+import { ApiError } from 'lib/api-error'
import { heatmapDataLogic } from 'lib/components/heatmaps/heatmapDataLogic'
import { FEATURE_FLAGS } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
@@ -20,6 +21,7 @@ import type {
} from 'products/web_analytics/frontend/generated/api.schemas'
import { heatmapLogic } from '../scenes/heatmap/heatmapLogic'
+import { pageHistoryCaptureLogic } from './pageHistoryCaptureLogic'
import { pageHistoryLogic, selectCapturesBetween } from './pageHistoryLogic'
const saved: HeatmapScreenshotResponseApi = {
@@ -110,6 +112,7 @@ describe('pageHistoryLogic', () => {
describe('selecting history', () => {
let logic: ReturnType<typeof pageHistoryLogic>
+ let captureLogic: ReturnType<typeof pageHistoryCaptureLogic>
const dataLogic = heatmapDataLogic({ context: 'in-app' })
beforeEach(async () => {
@@ -134,6 +137,8 @@ describe('pageHistoryLogic', () => {
dataLogic.actions.setWindowWidthOverride(1440)
logic = pageHistoryLogic({ id: 'hm_test' })
logic.mount()
+ captureLogic = pageHistoryCaptureLogic({ id: 'hm_test' })
+ captureLogic.mount()
await expectLogic(logic, () => logic.actions.loadHistory()).toFinishAllListeners()
})
@@ -143,6 +148,7 @@ describe('pageHistoryLogic', () => {
})
it('scopes the overlay to the day, shows that day on its screenshot and locks the width', async () => {
+ expect(captureLogic.values.completedCapture).toBeNull()
await expectLogic(logic, () => logic.actions.selectCapture('cap-3')).toFinishAllListeners()
expect(dataLogic.values.effectiveCommonFilters).toMatchObject({
@@ -296,6 +302,161 @@ describe('pageHistoryLogic', () => {
expect(exportAction).not.toHaveBeenCalled()
})
+ it.each([
+ ['no record of the request', null, null],
+ ['a capture that finished', 'cap-3', null],
+ ['a capture that failed', null, "couldn't finish"],
+ ])(
+ 'clears loading when a request status poll fails, then reconciles %s',
+ async (_label, completedId, error) => {
+ jest.useFakeTimers()
+ const poll = jest
+ .spyOn(heatmapApi, 'savedScreenshotHistoryRequestsRetrieve')
+ .mockRejectedValue(new Error('unavailable'))
+ captureLogic.actions.pollRequest('request-1')
+ expect(captureLogic.values.capturing).toBe(true)
+ await jest.advanceTimersByTimeAsync(10000)
+ expect(poll).toHaveBeenCalledWith('997', 'hm_test', 'request-1')
+ expect(captureLogic.values.capturing).toBe(false)
+ expect(captureLogic.values.captureStatusUnknown).toBe(true)
+ expect(captureLogic.values.captureNowDisabledReason).toContain('Check the current capture')
+
+ jest.useRealTimers()
+ const reconciled =
+ completedId !== null
+ ? capture('cap-3', '2024-05-03', { revision: 'request-1' })
+ : error !== null
+ ? capture('cap-3', '2024-05-03', {
+ latest_request: {
+ request_id: 'request-1',
+ state: 'failed',
+ failure_cause: 'browserless_timeout',
+ page_status: null,
+ deadline: '2024-05-03T12:30:00Z',
+ completed_at: '2024-05-03T12:05:00Z',
+ },
+ })
+ : captures[0]
+ jest.spyOn(heatmapApi, 'savedScreenshotHistoryRetrieve').mockResolvedValue(
+ historyResponse([reconciled, ...captures.slice(1)])
+ )
+ await expectLogic(logic, () => logic.actions.loadHistory()).toFinishAllListeners()
+ expect(captureLogic.values.captureStatusUnknown).toBe(false)
+ expect(captureLogic.values.completedCapture?.id ?? null).toBe(completedId)
+ if (error) {
+ expect(captureLogic.values.captureError).toContain(error)
+ } else {
+ expect(captureLogic.values.captureError).toBeNull()
+ }
+ }
+ )
+
+ it('offers a completed capture without changing the historical date being analyzed', async () => {
+ await expectLogic(logic, () => logic.actions.selectCapture('cap-1')).toFinishAllListeners()
+ jest.useFakeTimers()
+ const completed = capture('cap-3', '2024-05-03', { revision: 'request-1' })
+ jest.spyOn(heatmapApi, 'savedScreenshotHistoryRequestsRetrieve').mockResolvedValue({
+ request_id: 'request-1',
+ state: 'succeeded',
+ deadline: '2024-05-03T12:30:00Z',
+ completed_at: '2024-05-03T12:00:00Z',
+ failure_cause: null,
+ page_status: 200,
+ })
+ jest.spyOn(heatmapApi, 'savedScreenshotHistoryRetrieve').mockResolvedValue(
+ historyResponse([completed, ...captures.slice(1)])
+ )
+ captureLogic.actions.pollRequest('request-1')
+ await jest.advanceTimersByTimeAsync(10000)
+ await jest.advanceTimersByTimeAsync(1000)
+ expect(captureLogic.values.completedCapture?.id).toBe('cap-3')
+ expect(logic.values.selectedBackground?.id).toBe('cap-1')
+ expect(captureLogic.values.capturing).toBe(false)
+ })
+
+ it.each([
+ ['rate limited', new ApiError('Throttled', 429, new Headers({ 'Retry-After': '600' })), '10 minutes'],
+ ['unavailable', new Error('Unavailable'), 'Try again later'],
+ ])('clears capture loading and explains a creation failure: %s', async (_label, error, message) => {
+ jest.spyOn(heatmapApi, 'savedScreenshotHistoryCaptureCreate').mockRejectedValue(error)
+ await expectLogic(captureLogic, () => captureLogic.actions.captureNow()).toFinishAllListeners()
+ expect(captureLogic.values.capturing).toBe(false)
+ expect(captureLogic.values.captureError).toContain(message)
+ })
+
+ it('resumes polling a pending capture when the strip mounts after history loaded', async () => {
+ const pending = capture('cap-3', '2024-05-03', {
+ latest_request: {
+ request_id: 'request-1',
+ state: 'running',
+ failure_cause: null,
+ page_status: null,
+ deadline: '2024-05-03T12:30:00Z',
+ completed_at: null,
+ },
+ })
+ captureLogic.unmount()
+ await expectLogic(logic, () =>
+ logic.actions.loadHistorySuccess(historyResponse([pending, ...captures.slice(1)]))
+ ).toFinishAllListeners()
+
+ captureLogic = pageHistoryCaptureLogic({ id: 'hm_test' })
+ captureLogic.mount()
+
+ expect(captureLogic.values.capturing).toBe(true)
+ })
+
+ it('ignores a capture request that resolves after the page changed', async () => {
+ let resolveCreate: (
+ value: Awaited<ReturnType<typeof heatmapApi.savedScreenshotHistoryCaptureCreate>>
+ ) => void
+ jest.spyOn(heatmapApi, 'savedScreenshotHistoryCaptureCreate').mockImplementation(
+ () => new Promise((resolve) => (resolveCreate = resolve))
+ )
+ captureLogic.actions.captureNow()
+ expect(captureLogic.values.capturing).toBe(true)
+
+ logic.actions.pageChanged()
+ resolveCreate!({ request_id: 'request-old' } as Awaited<
+ ReturnType<typeof heatmapApi.savedScreenshotHistoryCaptureCreate>
+ >)
+ await expectLogic(captureLogic).toFinishAllListeners()
+
+ expect(captureLogic.values.capturing).toBe(false)
+ })
+
+ it('picks up a capture the server accepted when the create response was lost', async () => {
+ const accepted = capture('cap-3', '2024-05-03', {
+ latest_request: {
+ request_id: 'request-1',
+ state: 'queued',
+ failure_cause: null,
+ page_status: null,
+ deadline: '2024-05-03T12:30:00Z',
+ completed_at: null,
+ },
+ })
+ jest.spyOn(heatmapApi, 'savedScreenshotHistoryCaptureCreate').mockRejectedValue(new Error('Network error'))
+ jest.spyOn(heatmapApi, 'savedScreenshotHistoryRetrieve').mockResolvedValue(
+ historyResponse([accepted, ...captures.slice(1)])
+ )
+
+ await expectLogic(captureLogic, () => captureLogic.actions.captureNow()).toFinishAllListeners()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(captureLogic.values.capturing).toBe(true)
+ expect(captureLogic.values.captureError).toBeNull()
+ })
+
+ it('stops polling when navigation unmounts the history logic', async () => {
+ jest.useFakeTimers()
+ const poll = jest.spyOn(heatmapApi, 'savedScreenshotHistoryRequestsRetrieve')
+ captureLogic.actions.pollRequest('request-1')
+ captureLogic.unmount()
+ await jest.advanceTimersByTimeAsync(10000)
+ expect(poll).not.toHaveBeenCalled()
+ })
+
it('keeps history selections separate between projects', async () => {
const other = pageHistoryLogic({ id: 'hm_test', teamId: 998 })
other.mount()