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(exports): trigger export download inside the user gesture (#75343)

Xanderec4dd0fe5eb3
diff --git a/frontend/src/lib/components/ExportButton/exporter.test.ts b/frontend/src/lib/components/ExportButton/exporter.test.ts
index 76fa59332e25..827d43348338 100644
--- a/frontend/src/lib/components/ExportButton/exporter.test.ts
+++ b/frontend/src/lib/components/ExportButton/exporter.test.ts
@@ -1,5 +1,3 @@
-import { lemonToast } from 'lib/lemon-ui/LemonToast'
-
import { ExportedAssetType } from '~/types'
import { downloadExportedAsset } from './exporter'
@@ -16,16 +14,13 @@ jest.mock('lib/api', () => ({
},
}))
-jest.mock('lib/lemon-ui/LemonToast', () => ({
- lemonToast: { error: jest.fn() },
-}))
-
describe('downloadExportedAsset', () => {
let fakeAnchor: HTMLAnchorElement
let appendSpy: jest.SpyInstance
let removeSpy: jest.SpyInstance
beforeEach(() => {
+ jest.useFakeTimers()
fakeAnchor = { style: {}, click: jest.fn() } as unknown as HTMLAnchorElement
jest.spyOn(document, 'createElement').mockReturnValue(fakeAnchor)
appendSpy = jest.spyOn(document.body, 'appendChild').mockImplementation((node) => node)
@@ -33,36 +28,25 @@ describe('downloadExportedAsset', () => {
})
afterEach(() => {
+ jest.runOnlyPendingTimers()
+ jest.useRealTimers()
jest.restoreAllMocks()
getResponse.mockReset()
- ;(lemonToast.error as jest.Mock).mockReset()
})
- it('navigates via anchor once the content endpoint responds successfully', async () => {
- // Cancelable body so we don't buffer large files in memory before the streaming download.
- const cancel = jest.fn().mockResolvedValue(undefined)
- getResponse.mockResolvedValue({ body: { cancel } })
+ it('navigates via a synchronous anchor click with no preflight fetch', () => {
+ downloadExportedAsset({ id: 123 } as ExportedAssetType)
- const result = await downloadExportedAsset({ id: 123 } as ExportedAssetType)
-
- expect(result).toBe(true)
- expect(getResponse).toHaveBeenCalledWith('/api/environments/1/exports/123/content?download=true')
- expect(cancel).toHaveBeenCalled()
+ // The click must fire synchronously with no await before it (no preflight fetch), or Safari
+ // drops the download once the user gesture expires.
+ expect(getResponse).not.toHaveBeenCalled()
expect((fakeAnchor as any).href).toBe('/api/environments/1/exports/123/content?download=true')
expect((fakeAnchor as any).click).toHaveBeenCalled()
expect(appendSpy).toHaveBeenCalledWith(fakeAnchor)
- expect(removeSpy).toHaveBeenCalledWith(fakeAnchor)
- })
-
- it('shows an error toast and does not navigate when retrieval fails', async () => {
- // A failed content retrieval (e.g. an access-control 404) must not navigate the tab to the raw
- // JSON error — that renders as a blank/black page. It should surface a toast instead.
- getResponse.mockRejectedValue(new Error('Not found.'))
- const result = await downloadExportedAsset({ id: 123 } as ExportedAssetType)
-
- expect(result).toBe(false)
- expect((fakeAnchor as any).click).not.toHaveBeenCalled()
- expect(lemonToast.error).toHaveBeenCalledWith('Export download failed: Not found.')
+ // Removal is deferred — removing the anchor synchronously can cancel the download in Firefox.
+ expect(removeSpy).not.toHaveBeenCalled()
+ jest.runOnlyPendingTimers()
+ expect(removeSpy).toHaveBeenCalledWith(fakeAnchor)
})
})
diff --git a/frontend/src/lib/components/ExportButton/exporter.tsx b/frontend/src/lib/components/ExportButton/exporter.tsx
index 57539489e834..1ad9f19d5d22 100644
--- a/frontend/src/lib/components/ExportButton/exporter.tsx
+++ b/frontend/src/lib/components/ExportButton/exporter.tsx
@@ -1,5 +1,4 @@
import api from 'lib/api'
-import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { ExportedAssetType } from '~/types'
@@ -25,30 +24,22 @@ export async function exportedAssetBlob(asset: ExportedAssetType): Promise<Blob>
return await response.blob()
}
-export async function downloadExportedAsset(asset: ExportedAssetType): Promise<boolean> {
+export function downloadExportedAsset(asset: ExportedAssetType): void {
const downloadUrl = api.exports.determineExportUrl(asset.id)
- // Probe the content endpoint before navigating to it. If retrieval fails (e.g. an access-control
- // 404), the raw JSON error would otherwise render as a blank/black page. api.getResponse throws on
- // a non-2xx status, so we can surface an error toast and keep the user where they are. We read only
- // the headers and cancel the body — the anchor navigation below streams the actual download to disk
- // without buffering large files (e.g. video exports) in memory.
- try {
- const response = await api.getResponse(downloadUrl)
- await response.body?.cancel()
- } catch (error) {
- const message = error instanceof Error ? error.message : String(error)
- lemonToast.error('Export download failed: ' + message)
- return false
- }
-
+ // Trigger the download synchronously so it runs inside the click's user gesture. Safari only
+ // performs a programmatic download while transient activation is live (~5s from the click), so any
+ // await before this point causes it to silently drop the download.
const anchor = document.createElement('a')
anchor.style.display = 'none'
anchor.href = downloadUrl
document.body.appendChild(anchor)
anchor.click()
- document.body.removeChild(anchor)
- return true
+ // Removing the anchor synchronously after click() can cancel the download in Firefox — defer it,
+ // matching downloadBlob and downloadFile in lib/utils/dom.ts.
+ setTimeout(() => {
+ document.body.removeChild(anchor)
+ }, 0)
}
export type TriggerExportProps = Pick<ExportedAssetType, 'export_format' | 'dashboard' | 'insight' | 'export_context'>
diff --git a/frontend/src/lib/components/ExportButton/exportsLogic.test.ts b/frontend/src/lib/components/ExportButton/exportsLogic.test.ts
index 70ae280b97cb..c198bcd18017 100644
--- a/frontend/src/lib/components/ExportButton/exportsLogic.test.ts
+++ b/frontend/src/lib/components/ExportButton/exportsLogic.test.ts
@@ -20,7 +20,7 @@ jest.mock('lib/lemon-ui/LemonToast', () => ({
}))
jest.mock('./exporter', () => ({
...jest.requireActual('./exporter'),
- downloadExportedAsset: jest.fn().mockResolvedValue(true),
+ downloadExportedAsset: jest.fn(),
}))
const asset = (overrides: Partial<ExportedAssetType> = {}): ExportedAssetType => ({
@@ -211,23 +211,35 @@ describe('exportsLogic', () => {
}
)
- it('does not confirm completion when the content download fails', async () => {
- // The export toast must not settle as "Export complete!" if retrieval failed — otherwise
- // the user sees success followed by a broken download (the reported black-screen symptom).
- jest.mocked(downloadExportedAsset).mockResolvedValueOnce(false)
- jest.spyOn(api.exports, 'create').mockResolvedValue(
- asset({ id: 14, export_format: ExporterFormat.PNG, has_content: true })
- )
+ it('offers a Download button when the create call outlived the user gesture', async () => {
+ // A slow synchronous render outlives Safari's user-activation window, so an auto-download
+ // would be silently dropped. The export must instead surface a Download button (a fresh
+ // click) and stay highlighted as undownloaded until the user clicks it.
+ const original = Object.getOwnPropertyDescriptor(navigator, 'userActivation')
+ Object.defineProperty(navigator, 'userActivation', { value: { isActive: false }, configurable: true })
+ try {
+ const response = asset({ id: 15, export_format: ExporterFormat.CSV, has_content: true })
+ jest.spyOn(api.exports, 'create').mockResolvedValue(response)
+ const downloadExportSpy = jest.spyOn(logic.actions, 'downloadExport')
- logic.actions.createExport({ exportData: { export_format: ExporterFormat.PNG } })
- await flush()
+ logic.actions.createExport({ exportData: { export_format: ExporterFormat.CSV } })
+ await flush()
- // The export promise rejects instead of resolving to "Export complete!"...
- const runPromise = jest.mocked(lemonToast.promise).mock.calls[0][0]
- await expect(runPromise).rejects.toThrow('Export download failed')
- // ...and the generic failure toast is dismissed, since downloadExportedAsset
- // already surfaced the specific error.
- expect(lemonToast.dismiss).toHaveBeenCalled()
+ expect(jest.mocked(downloadExportedAsset)).not.toHaveBeenCalled()
+ expect(logic.values.freshUndownloadedExports.map((a) => a.id)).toEqual([15])
+ expect(lemonToast.success).toHaveBeenCalledWith(
+ 'Export complete!',
+ expect.objectContaining({ button: expect.objectContaining({ label: 'Download' }) })
+ )
+ jest.mocked(lemonToast.success).mock.calls.at(-1)![1]!.button!.action()
+ expect(downloadExportSpy).toHaveBeenCalledWith(response)
+ } finally {
+ if (original) {
+ Object.defineProperty(navigator, 'userActivation', original)
+ } else {
+ delete (navigator as any).userActivation
+ }
+ }
})
it('notifies once with a Download button that routes through downloadExport', async () => {
@@ -257,37 +269,16 @@ describe('exportsLogic', () => {
expect(downloadExportSpy).toHaveBeenCalledWith(finished)
})
- it.each([
- {
- label: 'clears the highlight when the download succeeds',
- downloadOk: true,
- remainingIds: [] as number[],
- expectsDismiss: false,
- },
- {
- label: 'keeps the highlight and drops the generic toast when the download fails',
- downloadOk: false,
- remainingIds: [41],
- expectsDismiss: true,
- },
- ])('downloadExport $label', async ({ downloadOk, remainingIds, expectsDismiss }) => {
+ it('downloadExport triggers the download, clears the highlight, and confirms', async () => {
const tracked = asset({ id: 41, export_format: ExporterFormat.MP4, has_content: true })
logic.actions.addFresh(tracked)
- jest.mocked(downloadExportedAsset).mockResolvedValueOnce(downloadOk)
logic.actions.downloadExport(tracked)
await flush()
expect(jest.mocked(downloadExportedAsset).mock.calls).toEqual([[tracked]])
- expect(logic.values.freshUndownloadedExports.map((a) => a.id)).toEqual(remainingIds)
- // The spinner is shown immediately so the button doesn't look dead during the blocking probe.
- expect(lemonToast.promise).toHaveBeenCalledWith(
- expect.any(Promise),
- expect.objectContaining({ pending: 'Preparing download…' }),
- expect.objectContaining({ toastId: expect.any(String) })
- )
- // On failure downloadExportedAsset shows its own specific toast, so the generic one is dismissed.
- expect(jest.mocked(lemonToast.dismiss).mock.calls.length > 0).toBe(expectsDismiss)
+ expect(logic.values.freshUndownloadedExports.map((a) => a.id)).toEqual([])
+ expect(lemonToast.success).toHaveBeenCalledWith('Download started')
})
it('surfaces the failure and stops tracking when a tracked async export fails', async () => {
diff --git a/frontend/src/lib/components/ExportButton/exportsLogic.ts b/frontend/src/lib/components/ExportButton/exportsLogic.ts
index 72f131192e15..c6c082e3e5e1 100644
--- a/frontend/src/lib/components/ExportButton/exportsLogic.ts
+++ b/frontend/src/lib/components/ExportButton/exportsLogic.ts
@@ -25,10 +25,6 @@ import {
SidePanelTab,
} from '~/types'
-// Sentinel for a synchronous export whose content download failed after creation succeeded —
-// downloadExportedAsset has already shown the specific error toast by the time this is thrown.
-const EXPORT_DOWNLOAD_FAILED = 'Export download failed'
-
const POLL_DELAY_MS = 10000
// Long-running formats (e.g. MP4 session-replay renders) can take 30+ minutes,
// so polling every 10s produces unhelpful timeout noise. Back off when the
@@ -59,6 +55,20 @@ export const pickPollDelayMs = (pendingAssets: ExportedAssetType[]): number => {
const isLocalExport = (context: ExportContext | undefined): context is LocalExportContext =>
!!(context && 'localData' in context)
+// Thrown when a synchronous export finished but the create request outlived the click's user
+// activation, so the download must wait for a fresh gesture (a Download button) rather than
+// auto-download — Safari silently drops programmatic downloads once activation has expired.
+class ExportAwaitingDownload extends Error {
+ constructor(public readonly asset: ExportedAssetType) {
+ super('Export awaiting user download')
+ }
+}
+
+// The user gesture that started the export is still live, so an auto-download will fire. Falls back
+// to true where navigator.userActivation is unavailable (older Firefox), which tolerates a delayed
+// click anyway.
+const isUserActivationLive = (): boolean => navigator.userActivation?.isActive ?? true
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface exportsLogicValues {
assetFormat: ExporterFormat | null
@@ -263,36 +273,13 @@ export const exportsLogic = kea<exportsLogicType>([
createExportSuccess: () => {
actions.loadExports()
},
- downloadExport: async ({ exportedAsset }) => {
- // Downloading a synchronous export blocks server-side while the content is generated,
- // and downloadExportedAsset probes the endpoint before navigating — that wait can run
- // for a minute or more. Drive it through lemonToast.promise so the user sees a spinner
- // immediately instead of a button that looks like it did nothing until the download starts.
- const downloadToastId = 'download-' + uuid()
- try {
- await lemonToast.promise(
- (async (): Promise<string> => {
- // Only drop the "not downloaded" highlight once the file actually downloads, so a
- // failed retrieval leaves the user a retry cue instead of a silent dead end.
- if (!(await downloadExportedAsset(exportedAsset))) {
- throw new Error(EXPORT_DOWNLOAD_FAILED)
- }
- actions.removeFresh(exportedAsset)
- return 'Download started'
- })(),
- {
- pending: 'Preparing download…',
- success: 'Download started',
- error: 'Download failed',
- },
- { toastId: downloadToastId }
- )
- } catch (error) {
- if (error instanceof Error && error.message === EXPORT_DOWNLOAD_FAILED) {
- // downloadExportedAsset already surfaced a specific error toast — drop the generic one.
- lemonToast.dismiss(downloadToastId)
- }
- }
+ downloadExport: ({ exportedAsset }) => {
+ // Content already exists for this asset, so trigger the download synchronously — the click
+ // has to run inside the user gesture or Safari silently drops it. Drop the "not downloaded"
+ // highlight now that the download has been triggered.
+ downloadExportedAsset(exportedAsset)
+ actions.removeFresh(exportedAsset)
+ lemonToast.success('Download started')
},
loadExportsSuccess: async ({ exports: exportsList }, breakpoint) => {
// Surface async exports we kicked off that have now finished: the render completes long
@@ -442,13 +429,16 @@ export const exportsLogic = kea<exportsLogicType>([
actions.loadExportsSuccess(updatedExports)
if (response.has_content) {
- // Blocking export already finished in the request — download and confirm.
- // Only celebrate once the content actually downloads; downloadExportedAsset
- // surfaces its own error toast if retrieval fails (e.g. an access-control 404).
- if (!(await downloadExportedAsset(response))) {
- throw new Error(EXPORT_DOWNLOAD_FAILED)
+ // Blocking export already finished in the request. Auto-download while the
+ // click's activation is still live; if the create call outlived it (a slow
+ // synchronous render), Safari would drop the download, so hand off to a
+ // Download button whose click is a fresh gesture.
+ if (isUserActivationLive()) {
+ downloadExportedAsset(response)
+ return 'Export complete!'
}
- return 'Export complete!'
+ actions.addFresh(response)
+ throw new ExportAwaitingDownload(response)
}
if (response.exception) {
throw new Error('Export failed: ' + response.exception)
@@ -485,13 +475,19 @@ export const exportsLogic = kea<exportsLogicType>([
}
)
} catch (error) {
- const apiError = error as { data?: APIErrorType }
- if (error instanceof Error && error.message === EXPORT_DOWNLOAD_FAILED) {
- // downloadExportedAsset already surfaced a specific error toast —
- // drop the generic failure toast so the user isn't told twice.
+ if (error instanceof ExportAwaitingDownload) {
+ // Content is ready but the auto-download would have been dropped —
+ // replace the spinner with a Download button the user can click.
lemonToast.dismiss(exportToastId)
+ lemonToast.success('Export complete!', {
+ button: {
+ label: 'Download',
+ action: () => actions.downloadExport(error.asset),
+ },
+ })
return
}
+ const apiError = error as { data?: APIErrorType }
// Show a survey when the user reaches the export limit, replacing the
// generic failure toast with the upsell.
if (apiError?.data?.attr === 'export_limit_exceeded') {