: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(exports): show immediate feedback when preparing a CSV export (#70759)
ruby childsc770220c025b
diff --git a/frontend/src/lib/components/ExportButton/exportsLogic.test.ts b/frontend/src/lib/components/ExportButton/exportsLogic.test.tsindex 92959aa26737..3c8f5c110667 100644--- a/frontend/src/lib/components/ExportButton/exportsLogic.test.ts+++ b/frontend/src/lib/components/ExportButton/exportsLogic.test.ts@@ -8,7 +8,14 @@ import { downloadExportedAsset } from './exporter'import { exportsLogic, pickPollDelayMs } from './exportsLogic'jest.mock('lib/lemon-ui/LemonToast', () => ({- lemonToast: { info: jest.fn(), success: jest.fn(), error: jest.fn(), dismiss: jest.fn() },+ // promise() passes the underlying promise straight through so the loader's side effects still run.+ lemonToast: {+ info: jest.fn(),+ success: jest.fn(),+ error: jest.fn(),+ dismiss: jest.fn(),+ promise: jest.fn((p) => p),+ },}))jest.mock('./exporter', () => ({...jest.requireActual('./exporter'),@@ -100,7 +107,7 @@ describe('exportsLogic', () => {logic.unmount()})- // Let the fire-and-forget IIFE in the createExport loader run to its toast.+ // Let the fire-and-forget IIFE in the createExport loader run to settlement.const flush = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0))const createCases: {@@ -108,48 +115,45 @@ describe('exportsLogic', () => {response?: ExportedAssetTyperejectWith?: Errorformat: ExporterFormat- toast: { fn: 'success' | 'error'; args: any[] }+ settles: { resolved: string } | { rejected: string }expectsDownload: booleanfreshIds: number[]}[] = [{- label: 'async export is acknowledged immediately and tracked as undownloaded',+ label: 'async export resolves to "Export started" and is tracked as undownloaded',response: asset({ id: 11, export_format: ExporterFormat.MP4, has_content: false }),format: ExporterFormat.MP4,- toast: {- fn: 'success',- args: ['Export started', expect.objectContaining({ button: expect.any(Object) })],- },+ settles: { resolved: 'Export started' },expectsDownload: false,freshIds: [11],},{- label: 'blocking export with content is downloaded and confirmed',+ label: 'blocking export with content is downloaded and resolves to "Export complete!"',response: asset({ id: 12, export_format: ExporterFormat.CSV, has_content: true }),format: ExporterFormat.CSV,- toast: { fn: 'success', args: ['Export complete!'] },+ settles: { resolved: 'Export complete!' },expectsDownload: true,freshIds: [],},{- label: 'export that failed in the request surfaces the error',+ label: 'export that failed in the request rejects with the error',response: asset({ id: 13, export_format: ExporterFormat.MP4, exception: 'boom' }),format: ExporterFormat.MP4,- toast: { fn: 'error', args: ['Export failed: boom'] },+ settles: { rejected: 'Export failed: boom' },expectsDownload: false,freshIds: [],},{- label: 'create request that throws surfaces the error from the catch',+ label: 'create request that throws rejects with the error',rejectWith: new Error('network down'),format: ExporterFormat.MP4,- toast: { fn: 'error', args: ['Export failed: network down'] },+ settles: { rejected: 'Export failed: network down' },expectsDownload: false,freshIds: [],},]- it.each(createCases)('$label', async ({ response, rejectWith, format, toast, expectsDownload, freshIds }) => {+ it.each(createCases)('$label', async ({ response, rejectWith, format, settles, expectsDownload, freshIds }) => {const createSpy = jest.spyOn(api.exports, 'create')if (rejectWith) {createSpy.mockRejectedValue(rejectWith)@@ -160,9 +164,37 @@ describe('exportsLogic', () => {logic.actions.createExport({ exportData: { export_format: format } })await flush()- expect(lemonToast[toast.fn]).toHaveBeenCalledWith(...toast.args)+ // The loading spinner is driven by lemonToast.promise, so the user always sees "Preparing export…".+ expect(lemonToast.promise).toHaveBeenCalledWith(+ expect.any(Promise),+ expect.objectContaining({ pending: 'Preparing export…' }),+ expect.objectContaining({ toastId: expect.any(String) })+ )+ const runPromise = jest.mocked(lemonToast.promise).mock.calls[0][0]+ if ('resolved' in settles) {+ await expect(runPromise).resolves.toBe(settles.resolved)+ } else {+ await expect(runPromise).rejects.toThrow(settles.rejected)+ }expect(jest.mocked(downloadExportedAsset).mock.calls).toEqual(expectsDownload ? [[response]] : [])expect(logic.values.freshUndownloadedExports.map((a) => a.id)).toEqual(freshIds)})++ it('replaces the failure toast with the upsell survey when the export limit is reached', async () => {+ jest.spyOn(api.exports, 'create').mockRejectedValue({+ data: { attr: 'export_limit_exceeded', detail: 'You hit the cap' },+ })++ logic.actions.createExport({ exportData: { export_format: ExporterFormat.MP4 } })+ await flush()++ expect(logic.values.hasReachedExportFullVideoLimit).toBe(true)+ expect(lemonToast.dismiss).toHaveBeenCalled()+ expect(lemonToast.error).toHaveBeenCalledWith(+ 'You hit the cap',+ expect.objectContaining({ button: expect.objectContaining({ label: 'I want more' }) })+ )+ expect(jest.mocked(downloadExportedAsset).mock.calls).toEqual([])+ })})})diff --git a/frontend/src/lib/components/ExportButton/exportsLogic.ts b/frontend/src/lib/components/ExportButton/exportsLogic.tsindex 03e8a9e93dab..f1dd75a38da7 100644--- a/frontend/src/lib/components/ExportButton/exportsLogic.ts+++ b/frontend/src/lib/components/ExportButton/exportsLogic.ts@@ -8,7 +8,7 @@ import { isLongRunningExportFormat } from 'lib/components/ExportButton/exportStaimport { dayjs } from 'lib/dayjs'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { delay } from 'lib/utils/async'-import { newInternalTab } from 'lib/utils/newInternalTab'+import { uuid } from 'lib/utils/dom'import type { SessionRecordingPlayerMode } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'import { urls } from 'scenes/urls'@@ -207,41 +207,66 @@ export const exportsLogic = kea<exportsLogicType>([[] as ExportedAssetType[],{createExport: ({ exportData }) => {- void (async () => {+ // Non-video exports (CSV/XLSX/PNG) run synchronously on the backend, so this+ // request can block for a while. lemonToast.promise shows a spinner immediately+ // and swaps to the success/failure message when it settles, so the user always+ // gets feedback instead of a menu that looks like it did nothing.+ const runExport = async (): Promise<string> => {+ let response: ExportedAssetTypetry {- const response = await api.exports.create({+ response = await api.exports.create({export_format: exportData.export_format,dashboard: exportData.dashboard,insight: exportData.insight,export_context: exportData.export_context,expires_after: dayjs().add(6, 'hour').toJSON(),})+ } catch (error) {+ // Preserve the export-limit error so the caller can show the upsell;+ // give everything else a friendly message for the failure toast.+ if ((error as { data?: APIErrorType })?.data?.attr === 'export_limit_exceeded') {+ throw error+ }+ const message = error instanceof Error ? error.message : String(error)+ throw new Error('Export failed: ' + message)+ }- const currentExports = values.exports- const updatedExports = [response, ...currentExports.filter((e) => e.id !== response.id)]- actions.loadExportsSuccess(updatedExports)+ const currentExports = values.exports+ const updatedExports = [response, ...currentExports.filter((e) => e.id !== response.id)]+ actions.loadExportsSuccess(updatedExports)- if (response && response.has_content) {- // Blocking export already finished in the request — download and confirm.- await downloadExportedAsset(response)- lemonToast.success('Export complete!')- } else if (response && response.exception) {- lemonToast.error('Export failed: ' + response.exception)- } else if (response) {- // Async export (e.g. video render) is a background job: acknowledge the- // kickoff right away. It surfaces in the Exports panel once the render finishes.- lemonToast.success('Export started', {- button: {- label: 'View exports',- action: () => newInternalTab(urls.exports()),- },- })- actions.addFresh(response)- }+ if (response.has_content) {+ // Blocking export already finished in the request — download and confirm.+ downloadExportedAsset(response)+ return 'Export complete!'+ }+ if (response.exception) {+ throw new Error('Export failed: ' + response.exception)+ }+ // Async export (e.g. video render) is a background job: acknowledge the+ // kickoff. It surfaces in the Exports panel once the render finishes.+ actions.addFresh(response)+ return 'Export started'+ }++ const exportToastId = 'export-' + uuid()+ void (async () => {+ try {+ await lemonToast.promise(+ runExport(),+ {+ pending: 'Preparing export…',+ success: 'Export complete!',+ error: 'Export failed',+ },+ { toastId: exportToastId }+ )} catch (error) {const apiError = error as { data?: APIErrorType }- // Show a survey when the user reaches the export limit+ // 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') {+ lemonToast.dismiss(exportToastId)actions.setHasReachedExportFullVideoLimit(true)lemonToast.error(apiError?.data?.detail || 'You reached your export limit.', {autoClose: false,@@ -252,9 +277,6 @@ export const exportsLogic = kea<exportsLogicType>([dataAttr: 'export-limit-reached-button',},})- } else {- const message = error instanceof Error ? error.message : String(error)- lemonToast.error('Export failed: ' + message)}}})()